diff --git a/packages/test-utils/.npmignore b/deprecated/packages/wallet-ts/.npmignore similarity index 100% rename from packages/test-utils/.npmignore rename to deprecated/packages/wallet-ts/.npmignore diff --git a/packages/wallet-ts/CHANGELOG.md b/deprecated/packages/wallet-ts/CHANGELOG.md similarity index 100% rename from packages/wallet-ts/CHANGELOG.md rename to deprecated/packages/wallet-ts/CHANGELOG.md diff --git a/packages/test-utils/LICENSE b/deprecated/packages/wallet-ts/LICENSE similarity index 100% rename from packages/test-utils/LICENSE rename to deprecated/packages/wallet-ts/LICENSE diff --git a/packages/wallet-ts/README.md b/deprecated/packages/wallet-ts/README.md similarity index 100% rename from packages/wallet-ts/README.md rename to deprecated/packages/wallet-ts/README.md diff --git a/packages/test-utils/jest.config.js b/deprecated/packages/wallet-ts/jest.config.js similarity index 100% rename from packages/test-utils/jest.config.js rename to deprecated/packages/wallet-ts/jest.config.js diff --git a/packages/wallet-ts/package.json b/deprecated/packages/wallet-ts/package.json similarity index 100% rename from packages/wallet-ts/package.json rename to deprecated/packages/wallet-ts/package.json diff --git a/packages/wallet-ts/src/broadcaster/MsgBroadcaster.ts b/deprecated/packages/wallet-ts/src/broadcaster/MsgBroadcaster.ts similarity index 100% rename from packages/wallet-ts/src/broadcaster/MsgBroadcaster.ts rename to deprecated/packages/wallet-ts/src/broadcaster/MsgBroadcaster.ts diff --git a/packages/wallet-ts/src/broadcaster/Web3Broadcaster.ts b/deprecated/packages/wallet-ts/src/broadcaster/Web3Broadcaster.ts similarity index 100% rename from packages/wallet-ts/src/broadcaster/Web3Broadcaster.ts rename to deprecated/packages/wallet-ts/src/broadcaster/Web3Broadcaster.ts diff --git a/packages/wallet-ts/src/broadcaster/helper.ts b/deprecated/packages/wallet-ts/src/broadcaster/helper.ts similarity index 100% rename from packages/wallet-ts/src/broadcaster/helper.ts rename to deprecated/packages/wallet-ts/src/broadcaster/helper.ts diff --git a/packages/wallet-ts/src/broadcaster/index.ts b/deprecated/packages/wallet-ts/src/broadcaster/index.ts similarity index 100% rename from packages/wallet-ts/src/broadcaster/index.ts rename to deprecated/packages/wallet-ts/src/broadcaster/index.ts diff --git a/packages/wallet-ts/src/broadcaster/types.ts b/deprecated/packages/wallet-ts/src/broadcaster/types.ts similarity index 100% rename from packages/wallet-ts/src/broadcaster/types.ts rename to deprecated/packages/wallet-ts/src/broadcaster/types.ts diff --git a/packages/wallet-ts/src/exports.ts b/deprecated/packages/wallet-ts/src/exports.ts similarity index 100% rename from packages/wallet-ts/src/exports.ts rename to deprecated/packages/wallet-ts/src/exports.ts diff --git a/packages/wallet-ts/src/index.ts b/deprecated/packages/wallet-ts/src/index.ts similarity index 100% rename from packages/wallet-ts/src/index.ts rename to deprecated/packages/wallet-ts/src/index.ts diff --git a/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/CosmosWalletStrategy.ts b/deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/CosmosWalletStrategy.ts similarity index 100% rename from packages/wallet-ts/src/strategies/cosmos-wallet-strategy/CosmosWalletStrategy.ts rename to deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/CosmosWalletStrategy.ts diff --git a/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/index.ts b/deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/index.ts similarity index 100% rename from packages/wallet-ts/src/strategies/cosmos-wallet-strategy/index.ts rename to deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/index.ts diff --git a/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Cosmostation.ts b/deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Cosmostation.ts similarity index 100% rename from packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Cosmostation.ts rename to deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Cosmostation.ts diff --git a/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Keplr.ts b/deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Keplr.ts similarity index 100% rename from packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Keplr.ts rename to deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Keplr.ts diff --git a/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Leap.ts b/deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Leap.ts similarity index 100% rename from packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Leap.ts rename to deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Leap.ts diff --git a/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Ninji.ts b/deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Ninji.ts similarity index 100% rename from packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Ninji.ts rename to deprecated/packages/wallet-ts/src/strategies/cosmos-wallet-strategy/strategies/Ninji.ts diff --git a/packages/wallet-ts/src/strategies/index.ts b/deprecated/packages/wallet-ts/src/strategies/index.ts similarity index 100% rename from packages/wallet-ts/src/strategies/index.ts rename to deprecated/packages/wallet-ts/src/strategies/index.ts diff --git a/packages/wallet-ts/src/strategies/types/index.ts b/deprecated/packages/wallet-ts/src/strategies/types/index.ts similarity index 100% rename from packages/wallet-ts/src/strategies/types/index.ts rename to deprecated/packages/wallet-ts/src/strategies/types/index.ts diff --git a/packages/wallet-ts/src/strategies/types/strategy.ts b/deprecated/packages/wallet-ts/src/strategies/types/strategy.ts similarity index 100% rename from packages/wallet-ts/src/strategies/types/strategy.ts rename to deprecated/packages/wallet-ts/src/strategies/types/strategy.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/WalletStrategy.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/WalletStrategy.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/WalletStrategy.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/WalletStrategy.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/constants.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/constants.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/constants.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/constants.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/index.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/index.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Base.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Base.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Base.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Base.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/index.ts similarity index 97% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/index.ts index 2943d2e3b..7d04012ce 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/index.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/index.ts @@ -64,7 +64,7 @@ export default class BitGet extends BaseConcreteStrategy implements ConcreteWall try { return await ethereum.request({ method: 'eth_requestAccounts', - }) + }) as string[] } catch (e: unknown) { throw new BitGetException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -93,7 +93,7 @@ export default class BitGet extends BaseConcreteStrategy implements ConcreteWall return await ethereum.request({ method: 'eth_sendTransaction', params: [transaction], - }) + }) as string } catch (e: unknown) { throw new BitGetException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -149,7 +149,7 @@ export default class BitGet extends BaseConcreteStrategy implements ConcreteWall return await ethereum.request({ method: 'eth_signTypedData_v4', params: [address, eip712json], - }) + }) as string } catch (e: unknown) { throw new BitGetException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -204,7 +204,7 @@ export default class BitGet extends BaseConcreteStrategy implements ConcreteWall params: [toUtf8(data), signer], }) - return signature + return signature as string } catch (e: unknown) { throw new BitGetException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -218,7 +218,7 @@ export default class BitGet extends BaseConcreteStrategy implements ConcreteWall const ethereum = await this.getEthereum() try { - return ethereum.request({ method: 'eth_chainId' }) + return ethereum.request({ method: 'eth_chainId' }) as Promise } catch (e: unknown) { throw new BitGetException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -236,7 +236,7 @@ export default class BitGet extends BaseConcreteStrategy implements ConcreteWall const receipt = await ethereum.request({ method: 'eth_getTransactionReceipt', params: [txHash], - }) + }) as string if (!receipt) { await sleep(interval) @@ -275,7 +275,7 @@ export default class BitGet extends BaseConcreteStrategy implements ConcreteWall } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const ethereum = await this.getEthereum() diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/utils.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/utils.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/utils.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/BitGet/utils.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Cosmostation.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Cosmostation.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Cosmostation.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Cosmostation.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Keplr.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Keplr.ts similarity index 99% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Keplr.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Keplr.ts index c6141e8a5..f981c33aa 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Keplr.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Keplr.ts @@ -244,7 +244,7 @@ export default class Keplr extends BaseConcreteStrategy implements ConcreteWalle } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const listener = async () => { const [account] = await this.getAddresses() diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Leap.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Leap.ts similarity index 99% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Leap.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Leap.ts index a9f4d1d9d..8a7fac79b 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Leap.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Leap.ts @@ -244,7 +244,7 @@ export default class Leap extends BaseConcreteStrategy implements ConcreteWallet } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const listener = async () => { const [account] = await this.getAddresses() diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/Base.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/Base.ts similarity index 99% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/Base.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/Base.ts index 31dd69837..bfef4221a 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/Base.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/Base.ts @@ -320,7 +320,7 @@ export default class LedgerBase const ledger = await this.ledger.getInstance() const { derivationPath } = await this.getWalletForAddress(options.address) const ledgerService = await import( - '@ledgerhq/hw-app-eth/lib/services/ledger/index.js' + '@ledgerhq/hw-app-eth/lib-es/services/ledger/index.js' ) const resolution = await ledgerService.default.resolveTransaction( encodedMessageHex, diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/LedgerLegacy.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/LedgerLegacy.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/LedgerLegacy.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/LedgerLegacy.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/LedgerLive.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/LedgerLive.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/LedgerLive.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/LedgerLive.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/AccountManager.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/AccountManager.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/AccountManager.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/AccountManager.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/index.ts similarity index 95% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/index.ts index c04612876..1043040da 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/index.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/hw/index.ts @@ -1,7 +1,7 @@ import TransportWebHID from '@ledgerhq/hw-transport-webhid' import TransportWebUSB from '@ledgerhq/hw-transport-webusb' -import type EthereumApp from '@ledgerhq/hw-app-eth' -import type Transport from '@ledgerhq/hw-transport' +import EthereumApp from '@ledgerhq/hw-app-eth' +import Transport from '@ledgerhq/hw-transport' import { LedgerException } from '@injectivelabs/exceptions' import AccountManager from './AccountManager.js' diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/utils.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/utils.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/utils.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/utils.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/hw/AccountManager.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/hw/AccountManager.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/hw/AccountManager.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/hw/AccountManager.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/hw/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/hw/index.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/hw/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/hw/index.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/index.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/LedgerCosmos/index.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Magic.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Magic.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Magic.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Magic.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/index.ts similarity index 97% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/index.ts index c31fc7e92..61d0ed1a8 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/index.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/index.ts @@ -67,7 +67,7 @@ export default class Metamask try { return await ethereum.request({ method: 'eth_requestAccounts', - }) + }) as string[] } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -96,7 +96,7 @@ export default class Metamask return await ethereum.request({ method: 'eth_sendTransaction', params: [transaction], - }) + }) as string } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -152,7 +152,7 @@ export default class Metamask return await ethereum.request({ method: 'eth_signTypedData_v4', params: [address, eip712json], - }) + }) as string } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -207,7 +207,7 @@ export default class Metamask params: [toUtf8(data), signer], }) - return signature + return signature as string } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -221,7 +221,7 @@ export default class Metamask const ethereum = await this.getEthereum() try { - return ethereum.request({ method: 'eth_chainId' }) + return ethereum.request({ method: 'eth_chainId' }) as Promise } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -239,7 +239,7 @@ export default class Metamask const receipt = await ethereum.request({ method: 'eth_getTransactionReceipt', params: [txHash], - }) + }) as string if (!receipt) { await sleep(interval) @@ -278,7 +278,7 @@ export default class Metamask } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const ethereum = await this.getEthereum() diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/utils.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/utils.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/utils.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Metamask/utils.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ninji.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ninji.ts similarity index 99% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ninji.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ninji.ts index 05f72ce7a..b0ad37ec7 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ninji.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ninji.ts @@ -242,7 +242,7 @@ export default class Ninji extends BaseConcreteStrategy implements ConcreteWalle } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const listener = async () => { const [account] = await this.getAddresses() diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/index.ts similarity index 93% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/index.ts index 996e1355a..ff9e4d785 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/index.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/index.ts @@ -23,7 +23,10 @@ import { } from '../../../../types/enums.js' import { getOkxWalletProvider } from './utils.js' -export default class OkxWallet extends BaseConcreteStrategy implements ConcreteWalletStrategy { +export default class OkxWallet + extends BaseConcreteStrategy + implements ConcreteWalletStrategy +{ constructor(args: EthereumWalletStrategyArgs) { super(args) } @@ -62,9 +65,9 @@ export default class OkxWallet extends BaseConcreteStrategy implements ConcreteW const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_requestAccounts', - }) + })) as string[] } catch (e: unknown) { throw new OkxWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -90,10 +93,10 @@ export default class OkxWallet extends BaseConcreteStrategy implements ConcreteW const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_sendTransaction', params: [transaction], - }) + })) as string } catch (e: unknown) { throw new OkxWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -146,10 +149,10 @@ export default class OkxWallet extends BaseConcreteStrategy implements ConcreteW const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_signTypedData_v4', params: [address, eip712json], - }) + })) as string } catch (e: unknown) { throw new OkxWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -204,7 +207,7 @@ export default class OkxWallet extends BaseConcreteStrategy implements ConcreteW params: [toUtf8(data), signer], }) - return signature + return signature as string } catch (e: unknown) { throw new OkxWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -218,7 +221,7 @@ export default class OkxWallet extends BaseConcreteStrategy implements ConcreteW const ethereum = await this.getEthereum() try { - return ethereum.request({ method: 'eth_chainId' }) + return ethereum.request({ method: 'eth_chainId' }) as Promise } catch (e: unknown) { throw new OkxWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -233,10 +236,10 @@ export default class OkxWallet extends BaseConcreteStrategy implements ConcreteW const interval = 1000 const transactionReceiptRetry = async () => { - const receipt = await ethereum.request({ + const receipt = (await ethereum.request({ method: 'eth_getTransactionReceipt', params: [txHash], - }) + })) as string if (!receipt) { await sleep(interval) @@ -275,7 +278,7 @@ export default class OkxWallet extends BaseConcreteStrategy implements ConcreteW } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const ethereum = await this.getEthereum() diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/utils.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/utils.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/utils.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Okx/utils.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/index.ts similarity index 94% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/index.ts index a96e5a031..99a6b34cb 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/index.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/index.ts @@ -23,7 +23,10 @@ import { } from '../../../../types/enums.js' import { getPhantomProvider } from './utils.js' -export default class Phantom extends BaseConcreteStrategy implements ConcreteWalletStrategy { +export default class Phantom + extends BaseConcreteStrategy + implements ConcreteWalletStrategy +{ constructor(args: EthereumWalletStrategyArgs) { super(args) } @@ -64,9 +67,9 @@ export default class Phantom extends BaseConcreteStrategy implements ConcreteWal const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_requestAccounts', - }) + })) as string[] } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -92,10 +95,10 @@ export default class Phantom extends BaseConcreteStrategy implements ConcreteWal const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_sendTransaction', params: [transaction], - }) + })) as string } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -148,10 +151,10 @@ export default class Phantom extends BaseConcreteStrategy implements ConcreteWal const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_signTypedData_v4', params: [address, eip712json], - }) + })) as string } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -206,7 +209,7 @@ export default class Phantom extends BaseConcreteStrategy implements ConcreteWal params: [toUtf8(data), signer], }) - return signature + return signature as string } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -220,7 +223,7 @@ export default class Phantom extends BaseConcreteStrategy implements ConcreteWal const ethereum = await this.getEthereum() try { - return ethereum.request({ method: 'eth_chainId' }) + return ethereum.request({ method: 'eth_chainId' }) as Promise } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -235,10 +238,10 @@ export default class Phantom extends BaseConcreteStrategy implements ConcreteWal const interval = 1000 const transactionReceiptRetry = async () => { - const receipt = await ethereum.request({ + const receipt = (await ethereum.request({ method: 'eth_getTransactionReceipt', params: [txHash], - }) + })) as string if (!receipt) { await sleep(interval) @@ -277,7 +280,7 @@ export default class Phantom extends BaseConcreteStrategy implements ConcreteWal } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const ethereum = await this.getEthereum() diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/utils.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/utils.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/utils.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Phantom/utils.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/PrivateKey.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/PrivateKey.ts similarity index 99% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/PrivateKey.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/PrivateKey.ts index 86a845130..76c9a2a09 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/PrivateKey.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/PrivateKey.ts @@ -251,7 +251,7 @@ export default class PrivateKey } async onAccountChange( - _callback: (account: AccountAddress) => void, + _callback: (account: AccountAddress | string[]) => void, ): Promise { // } diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Torus.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Torus.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Torus.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Torus.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/hw/AccountManager.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/hw/AccountManager.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/hw/AccountManager.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/hw/AccountManager.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/hw/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/hw/index.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/hw/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/hw/index.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/index.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/index.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/utils.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/utils.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/utils.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/Trezor/utils.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/index.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/index.ts similarity index 94% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/index.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/index.ts index 7a3ef0dab..0c89f3619 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/index.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/index.ts @@ -1,9 +1,6 @@ /* eslint-disable class-methods-use-this */ import { sleep } from '@injectivelabs/utils' -import { - AccountAddress, - EthereumChainId, -} from '@injectivelabs/ts-types' +import { AccountAddress, EthereumChainId } from '@injectivelabs/ts-types' import { ErrorType, WalletException, @@ -42,9 +39,9 @@ export default class TrustWallet const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_requestAccounts', - }) + })) as string[] } catch (e: unknown) { throw new TrustWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -70,10 +67,10 @@ export default class TrustWallet const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_sendTransaction', params: [transaction], - }) + })) as string } catch (e: unknown) { throw new TrustWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -126,10 +123,10 @@ export default class TrustWallet const ethereum = await this.getEthereum() try { - return await ethereum.request({ + return (await ethereum.request({ method: 'eth_signTypedData_v4', params: [eip712json, address], - }) + })) as Promise } catch (e: unknown) { throw new TrustWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -184,7 +181,7 @@ export default class TrustWallet params: [toUtf8(data), signer], }) - return signature + return signature as string } catch (e: unknown) { throw new TrustWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -198,7 +195,7 @@ export default class TrustWallet const ethereum = await this.getEthereum() try { - return ethereum.request({ method: 'eth_chainId' }) + return ethereum.request({ method: 'eth_chainId' }) as Promise } catch (e: unknown) { throw new TrustWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -213,10 +210,10 @@ export default class TrustWallet const interval = 1000 const transactionReceiptRetry = async () => { - const receipt = await ethereum.request({ + const receipt = (await ethereum.request({ method: 'eth_getTransactionReceipt', params: [txHash], - }) + })) as string if (!receipt) { await sleep(interval) diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/utils.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/utils.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/utils.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/TrustWallet/utils.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/WalletConnect.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/WalletConnect.ts similarity index 99% rename from packages/wallet-ts/src/strategies/wallet-strategy/strategies/WalletConnect.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/WalletConnect.ts index 1fc765c92..bc34e991d 100644 --- a/packages/wallet-ts/src/strategies/wallet-strategy/strategies/WalletConnect.ts +++ b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/strategies/WalletConnect.ts @@ -278,7 +278,7 @@ export default class WalletConnect } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const wc = await this.getConnectedWalletConnect() diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/types.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/types.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/types.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/types.ts diff --git a/packages/wallet-ts/src/strategies/wallet-strategy/utils.ts b/deprecated/packages/wallet-ts/src/strategies/wallet-strategy/utils.ts similarity index 100% rename from packages/wallet-ts/src/strategies/wallet-strategy/utils.ts rename to deprecated/packages/wallet-ts/src/strategies/wallet-strategy/utils.ts diff --git a/packages/wallet-ts/src/types/enums.ts b/deprecated/packages/wallet-ts/src/types/enums.ts similarity index 100% rename from packages/wallet-ts/src/types/enums.ts rename to deprecated/packages/wallet-ts/src/types/enums.ts diff --git a/packages/wallet-ts/src/types/index.ts b/deprecated/packages/wallet-ts/src/types/index.ts similarity index 100% rename from packages/wallet-ts/src/types/index.ts rename to deprecated/packages/wallet-ts/src/types/index.ts diff --git a/packages/wallet-ts/src/utils/alchemy.ts b/deprecated/packages/wallet-ts/src/utils/alchemy.ts similarity index 100% rename from packages/wallet-ts/src/utils/alchemy.ts rename to deprecated/packages/wallet-ts/src/utils/alchemy.ts diff --git a/packages/wallet-ts/src/utils/constants.ts b/deprecated/packages/wallet-ts/src/utils/constants.ts similarity index 100% rename from packages/wallet-ts/src/utils/constants.ts rename to deprecated/packages/wallet-ts/src/utils/constants.ts diff --git a/packages/wallet-ts/src/utils/cosmos.ts b/deprecated/packages/wallet-ts/src/utils/cosmos.ts similarity index 100% rename from packages/wallet-ts/src/utils/cosmos.ts rename to deprecated/packages/wallet-ts/src/utils/cosmos.ts diff --git a/packages/wallet-ts/src/utils/index.ts b/deprecated/packages/wallet-ts/src/utils/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/index.ts rename to deprecated/packages/wallet-ts/src/utils/index.ts diff --git a/packages/wallet-ts/src/utils/utils.ts b/deprecated/packages/wallet-ts/src/utils/utils.ts similarity index 100% rename from packages/wallet-ts/src/utils/utils.ts rename to deprecated/packages/wallet-ts/src/utils/utils.ts diff --git a/packages/wallet-ts/src/utils/wallets/bitget/BitGet.ts b/deprecated/packages/wallet-ts/src/utils/wallets/bitget/BitGet.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/bitget/BitGet.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/bitget/BitGet.ts diff --git a/packages/wallet-ts/src/utils/wallets/bitget/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/bitget/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/bitget/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/bitget/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/cosmos/endpoints.ts b/deprecated/packages/wallet-ts/src/utils/wallets/cosmos/endpoints.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/cosmos/endpoints.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/cosmos/endpoints.ts diff --git a/packages/wallet-ts/src/utils/wallets/cosmos/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/cosmos/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/cosmos/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/cosmos/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/cosmos/utils.ts b/deprecated/packages/wallet-ts/src/utils/wallets/cosmos/utils.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/cosmos/utils.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/cosmos/utils.ts diff --git a/packages/wallet-ts/src/utils/wallets/cosmostation/CosmostationWallet.ts b/deprecated/packages/wallet-ts/src/utils/wallets/cosmostation/CosmostationWallet.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/cosmostation/CosmostationWallet.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/cosmostation/CosmostationWallet.ts diff --git a/packages/wallet-ts/src/utils/wallets/cosmostation/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/cosmostation/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/cosmostation/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/cosmostation/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/keplr/KeplrWallet.ts b/deprecated/packages/wallet-ts/src/utils/wallets/keplr/KeplrWallet.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/keplr/KeplrWallet.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/keplr/KeplrWallet.ts diff --git a/packages/wallet-ts/src/utils/wallets/keplr/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/keplr/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/keplr/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/keplr/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/keplr/keplr.d.ts b/deprecated/packages/wallet-ts/src/utils/wallets/keplr/keplr.d.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/keplr/keplr.d.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/keplr/keplr.d.ts diff --git a/packages/wallet-ts/src/utils/wallets/keplr/utils/helpers.ts b/deprecated/packages/wallet-ts/src/utils/wallets/keplr/utils/helpers.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/keplr/utils/helpers.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/keplr/utils/helpers.ts diff --git a/packages/wallet-ts/src/utils/wallets/keplr/utils/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/keplr/utils/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/keplr/utils/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/keplr/utils/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/leap/LeapWallet.ts b/deprecated/packages/wallet-ts/src/utils/wallets/leap/LeapWallet.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/leap/LeapWallet.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/leap/LeapWallet.ts diff --git a/packages/wallet-ts/src/utils/wallets/leap/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/leap/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/leap/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/leap/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/leap/leap.d.ts b/deprecated/packages/wallet-ts/src/utils/wallets/leap/leap.d.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/leap/leap.d.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/leap/leap.d.ts diff --git a/packages/wallet-ts/src/utils/wallets/metamask/Metamask.ts b/deprecated/packages/wallet-ts/src/utils/wallets/metamask/Metamask.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/metamask/Metamask.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/metamask/Metamask.ts diff --git a/packages/wallet-ts/src/utils/wallets/metamask/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/metamask/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/metamask/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/metamask/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/ninji/NinjiWallet.ts b/deprecated/packages/wallet-ts/src/utils/wallets/ninji/NinjiWallet.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/ninji/NinjiWallet.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/ninji/NinjiWallet.ts diff --git a/packages/wallet-ts/src/utils/wallets/ninji/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/ninji/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/ninji/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/ninji/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/ninji/leap.d.ts b/deprecated/packages/wallet-ts/src/utils/wallets/ninji/leap.d.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/ninji/leap.d.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/ninji/leap.d.ts diff --git a/packages/wallet-ts/src/utils/wallets/okx/Okx.ts b/deprecated/packages/wallet-ts/src/utils/wallets/okx/Okx.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/okx/Okx.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/okx/Okx.ts diff --git a/packages/wallet-ts/src/utils/wallets/okx/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/okx/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/okx/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/okx/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/phantom/PhantomWallet.ts b/deprecated/packages/wallet-ts/src/utils/wallets/phantom/PhantomWallet.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/phantom/PhantomWallet.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/phantom/PhantomWallet.ts diff --git a/packages/wallet-ts/src/utils/wallets/phantom/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/phantom/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/phantom/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/phantom/index.ts diff --git a/packages/wallet-ts/src/utils/wallets/trust-wallet/TrustWallet.ts b/deprecated/packages/wallet-ts/src/utils/wallets/trust-wallet/TrustWallet.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/trust-wallet/TrustWallet.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/trust-wallet/TrustWallet.ts diff --git a/packages/wallet-ts/src/utils/wallets/trust-wallet/index.ts b/deprecated/packages/wallet-ts/src/utils/wallets/trust-wallet/index.ts similarity index 100% rename from packages/wallet-ts/src/utils/wallets/trust-wallet/index.ts rename to deprecated/packages/wallet-ts/src/utils/wallets/trust-wallet/index.ts diff --git a/packages/wallet-ts/tsconfig.build.esm.json b/deprecated/packages/wallet-ts/tsconfig.build.esm.json similarity index 100% rename from packages/wallet-ts/tsconfig.build.esm.json rename to deprecated/packages/wallet-ts/tsconfig.build.esm.json diff --git a/packages/wallet-ts/tsconfig.build.json b/deprecated/packages/wallet-ts/tsconfig.build.json similarity index 100% rename from packages/wallet-ts/tsconfig.build.json rename to deprecated/packages/wallet-ts/tsconfig.build.json diff --git a/packages/wallet-ts/tsconfig.json b/deprecated/packages/wallet-ts/tsconfig.json similarity index 100% rename from packages/wallet-ts/tsconfig.json rename to deprecated/packages/wallet-ts/tsconfig.json diff --git a/etc/replacements-ledger.js b/etc/replacements-ledger.js deleted file mode 100644 index f75de2c0b..000000000 --- a/etc/replacements-ledger.js +++ /dev/null @@ -1,47 +0,0 @@ -const { readFile, writeFile } = require('fs') - -const isCJS = process.env.BUILD_MODE.includes('cjs') -const isESM = process.env.BUILD_MODE.includes('esm') - -const REPLACEMENT_PAIRS = [ - { - path: './src/strategy/Ledger/Base.ts', - cjs: '@ledgerhq/hw-app-eth/lib/services/ledger/index.js', - esm: '@ledgerhq/hw-app-eth/lib-es/services/ledger/index.js', - }, -] - -for (const pair of REPLACEMENT_PAIRS) { - readFile(pair.path, 'utf8', (err, data) => { - if (err) { - console.error('Error reading file:', err) - return - } - - if (isCJS) { - const updatedData = data.replace(new RegExp(pair.esm, 'g'), pair.cjs) - - writeFile(pair.path, updatedData, 'utf8', (err) => { - if (err) { - console.error('Error writing file:', err) - return - } - - console.log(`Replaced in ${pair.path} for CJS`) - }) - } - - if (isESM) { - const updatedData = data.replace(new RegExp(pair.cjs, 'g'), pair.esm) - - writeFile(pair.path, updatedData, 'utf8', (err) => { - if (err) { - console.error('Error writing file:', err) - return - } - - console.log(`Replaced in ${pair.path} for ESM`) - }) - } - }) -} diff --git a/etc/replacements.js b/etc/replacements.js deleted file mode 100644 index e9c9716a2..000000000 --- a/etc/replacements.js +++ /dev/null @@ -1,47 +0,0 @@ -const { readFile, writeFile } = require('fs') - -const isCJS = process.env.BUILD_MODE.includes('cjs') -const isESM = process.env.BUILD_MODE.includes('esm') - -const REPLACEMENT_PAIRS = [ - { - path: './src/strategies/wallet-strategy/strategies/Ledger/Base.ts', - cjs: '@ledgerhq/hw-app-eth/lib/services/ledger', - esm: '@ledgerhq/hw-app-eth/lib-es/services/ledger', - }, -] - -for (const pair of REPLACEMENT_PAIRS) { - readFile(pair.path, 'utf8', (err, data) => { - if (err) { - console.error('Error reading file:', err) - return - } - - if (isCJS) { - const updatedData = data.replace(new RegExp(pair.esm, 'g'), pair.cjs) - - writeFile(pair.path, updatedData, 'utf8', (err) => { - if (err) { - console.error('Error writing file:', err) - return - } - - console.log(`Replaced in ${pair.path} for CJS`) - }) - } - - if (isESM) { - const updatedData = data.replace(new RegExp(pair.cjs, 'g'), pair.esm) - - writeFile(pair.path, updatedData, 'utf8', (err) => { - if (err) { - console.error('Error writing file:', err) - return - } - - console.log(`Replaced in ${pair.path} for ESM`) - }) - } - }) -} diff --git a/jest.config.js b/jest.config.js index 0bd19dd98..098611927 100644 --- a/jest.config.js +++ b/jest.config.js @@ -87,6 +87,7 @@ module.exports = { moduleNameMapper: { ...pathsToModuleNameMapper(packagePaths, { prefix: '/' }), ...pathsToModuleNameMapper(directoryPaths), + // '^crypto-es$': 'crypto-js' }, // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader @@ -181,7 +182,10 @@ module.exports = { extensionsToTreatAsEsm: ['.ts'], // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - transformIgnorePatterns: ['^.+\\.json$', 'node_modules/(?!(eth-crypto)/)'], + transformIgnorePatterns: [ + '^.+\\.json$', + 'node_modules/(?!' + ['@noble/secp256k1'].join('|') + ')', + ], // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them // unmockedModulePathPatterns: undefined, diff --git a/lerna.json b/lerna.json index d2873e7f5..342a0a547 100644 --- a/lerna.json +++ b/lerna.json @@ -3,7 +3,6 @@ "name": "injective-ts", "packages": ["packages/*", "packages/wallets/*"], "version": "independent", - "useWorkspaces": true, "command": { "version": { "message": "chore: release" diff --git a/package.json b/package.json index 03a6f9ba2..15edc4059 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ }, "scripts": { "postinstall": "node etc/bootstrapEnv", - "build": "node etc/bootstrapEnv && lerna run build", + "build": "node etc/bootstrapEnv && patch-package && lerna run build", "generate:core-proto-ts": "./proto/core/gen.sh", "publish:core-proto-ts": "./proto/core/publish.sh", "generate:indexer-proto-ts": "./proto/indexer/gen.sh", @@ -35,10 +35,11 @@ "build:patch:publish": "yarn build:fresh && yarn patch && yarn lerna:publish", "patch": "lerna version patch", "clean-up": "lerna run clean && shx rm -rf .build-cache *.log coverage junit.xml", - "bootstrap": "yarn clean-up && yarn install", + "bootstrap": "yarn clean-up && yarn install && patch-package", "test": "jest", "test:sdk-ts:core:stargate": "jest ./packages/sdk-ts/src/core/stargate", "test:sdk-ts:core:modules": "jest ./packages/sdk-ts/src/core/modules", + "test:sdk-ts:core:account": "jest ./packages/sdk-ts/src/core/account", "test:sdk-ts:core": "jest ./packages/sdk-ts/src/core", "test:sdk-ts:utils": "jest ./packages/sdk-ts/src/utils", "test:sdk-ts:client": "jest ./packages/sdk-ts/src/client", @@ -70,8 +71,8 @@ "@babel/preset-env": "^7.19.0", "@commitlint/cli": "^13.1.0", "@commitlint/config-conventional": "^13.1.0", - "@types/jest": "^29.4.0", - "@types/node": "^22.9.0", + "@types/jest": "^29.5.14", + "@types/node": "^22.10.1", "@typescript-eslint/eslint-plugin": "^6.0.0", "@typescript-eslint/parser": "^6.0.0", "babel-jest": "^29.4.3", @@ -89,13 +90,14 @@ "eslint-plugin-markdown": "^2.2.1", "eslint-plugin-prettier": "^4.0.0", "husky": "^7.0.2", - "jest": "^29.4.3", + "jest": "^29.7.0", "jest-junit": "^15.0.0", "jest-resolve": "^29.7.0", - "lerna": "6.6.1", + "lerna": "8.1.9", "lint-staged": "^11.1.2", "live-server": "^1.2.1", "markdownlint-cli": "^0.28.1", + "patch-package": "^8.0.0", "prettier": "^2.4.1", "serve": "^12.0.1", "shx": "^0.3.4", @@ -107,11 +109,6 @@ "tsconfig-paths": "^4.2.0", "typedoc": "^0.25.11", "typedoc-monorepo-link-types": "^0.0.4", - "typescript": "^5.1.1" - }, - "resolutions": { - "@ethereumjs/tx": "^4.1.1", - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" + "typescript": "^5.7.2" } } diff --git a/packages/exceptions/jest.config.js b/packages/exceptions/jest.config.js index 95cbf1481..9679ba054 100644 --- a/packages/exceptions/jest.config.js +++ b/packages/exceptions/jest.config.js @@ -1,6 +1,6 @@ -const baseConfig = require('../../jest.config.js') +import baseConfig from '../../jest.config.js' -module.exports = { +export default { ...baseConfig, globals: { 'ts-jest': { diff --git a/packages/exceptions/package.json b/packages/exceptions/package.json index 68fcf1da6..1dc20819f 100644 --- a/packages/exceptions/package.json +++ b/packages/exceptions/package.json @@ -4,6 +4,7 @@ "version": "1.14.34-beta.0", "sideEffects": false, "license": "Apache-2.0", + "type": "module", "types": "dist/cjs/index.d.ts", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", @@ -55,9 +56,9 @@ "start": "node dist/index.js" }, "dependencies": { - "@injectivelabs/grpc-web": "^0.0.1", - "@injectivelabs/ts-types": "^1.14.33", - "http-status-codes": "^2.2.0", + "http-status-codes": "^2.2.0" + }, + "devDependencies": { "shx": "^0.3.2" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" diff --git a/packages/exceptions/src/exceptions/types/codes.ts b/packages/exceptions/src/exceptions/types/codes.ts index 053cf0489..da8277448 100644 --- a/packages/exceptions/src/exceptions/types/codes.ts +++ b/packages/exceptions/src/exceptions/types/codes.ts @@ -1,6 +1,31 @@ -import * as grpc from '@injectivelabs/grpc-web' import { StatusCodes } from 'http-status-codes' +export enum GrpcErrorCode { + OK = 0, + Canceled = 1, + Unknown = 2, + InvalidArgument = 3, + DeadlineExceeded = 4, + NotFound = 5, + AlreadyExists = 6, + PermissionDenied = 7, + ResourceExhausted = 8, + FailedPrecondition = 9, + Aborted = 10, + OutOfRange = 11, + Unimplemented = 12, + Internal = 13, + Unavailable = 14, + DataLoss = 15, + Unauthenticated = 16, +} + +export const grpcErrorCodeToErrorCode = ( + grpcErrorCode: T, +): GrpcErrorCode => { + return grpcErrorCode as GrpcErrorCode +} + export enum TransactionChainErrorModule { Auction = 'auction', CosmosSdk = 'sdk', @@ -770,8 +795,8 @@ export const UnspecifiedErrorCode = -1 export type ErrorCode = | StatusCodes | typeof UnspecifiedErrorCode - | grpc.grpc.Code -export const GRPC_REQUEST_FAILED = grpc.grpc.Code.Unavailable + | GrpcErrorCode +export const GRPC_REQUEST_FAILED = GrpcErrorCode.Unavailable export type ErrorContextCode = | ChainAuctionErrorCodes diff --git a/packages/exceptions/tsconfig.build.esm.json b/packages/exceptions/tsconfig.build.esm.json index 7103f7078..d4d2fde6b 100644 --- a/packages/exceptions/tsconfig.build.esm.json +++ b/packages/exceptions/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../.build-cache/exceptions.esm.tsbuildinfo" } } diff --git a/packages/exceptions/tsconfig.build.json b/packages/exceptions/tsconfig.build.json index 15e66c278..a4d30305c 100644 --- a/packages/exceptions/tsconfig.build.json +++ b/packages/exceptions/tsconfig.build.json @@ -2,14 +2,11 @@ "extends": "../../tsconfig.build.json", "compilerOptions": { "rootDir": "./src", + "module": "commonjs", + "moduleResolution": "node", "outDir": "./dist/cjs", "tsBuildInfoFile": "../../.build-cache/exceptions.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ], + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/networks/jest.config.js b/packages/networks/jest.config.js index 95cbf1481..9679ba054 100644 --- a/packages/networks/jest.config.js +++ b/packages/networks/jest.config.js @@ -1,6 +1,6 @@ -const baseConfig = require('../../jest.config.js') +import baseConfig from '../../jest.config.js' -module.exports = { +export default { ...baseConfig, globals: { 'ts-jest': { diff --git a/packages/networks/package.json b/packages/networks/package.json index 1e04c8a01..8a1be757e 100644 --- a/packages/networks/package.json +++ b/packages/networks/package.json @@ -3,6 +3,7 @@ "description": "Endpoints, networks, etc. Can be reused throughout Injective's projects.", "version": "1.14.34-beta.0", "sideEffects": false, + "type": "module", "license": "Apache-2.0", "author": { "name": "InjectiveLabs", @@ -55,9 +56,9 @@ "start": "node dist/index.js" }, "dependencies": { - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", + "@injectivelabs/ts-types": "^1.14.33" + }, + "devDependencies": { "shx": "^0.3.2" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" diff --git a/packages/networks/src/chainInfos.ts b/packages/networks/src/chainInfos.ts index f5e046561..833385b0d 100644 --- a/packages/networks/src/chainInfos.ts +++ b/packages/networks/src/chainInfos.ts @@ -1,7 +1,8 @@ import { ChainId, EthereumChainId } from '@injectivelabs/ts-types' -import { INJ_DENOM } from '@injectivelabs/utils' import { ChainInfo } from './types.js' +const INJ_DENOM = 'inj' + export const mainnetChainInfo: ChainInfo = { feeDenom: INJ_DENOM, chainId: ChainId.Mainnet, diff --git a/packages/networks/tsconfig.build.esm.json b/packages/networks/tsconfig.build.esm.json index bc701ff9a..8a95352da 100644 --- a/packages/networks/tsconfig.build.esm.json +++ b/packages/networks/tsconfig.build.esm.json @@ -1,24 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../.build-cache/networks.esm.tsbuildinfo" - }, - "references": [ - { - "path": "../exceptions/tsconfig.build.esm.json" - }, - { - "path": "../ts-types/tsconfig.build.esm.json" - }, - { - "path": "../utils/tsconfig.build.esm.json" - } - ] + } } diff --git a/packages/networks/tsconfig.build.json b/packages/networks/tsconfig.build.json index 6cab4c21e..5358c2489 100644 --- a/packages/networks/tsconfig.build.json +++ b/packages/networks/tsconfig.build.json @@ -2,14 +2,11 @@ "extends": "../../tsconfig.build.json", "compilerOptions": { "rootDir": "./src", + "module": "commonjs", + "moduleResolution": "node", "outDir": "./dist/cjs", "tsBuildInfoFile": "../../.build-cache/networks.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/sdk-ts/jest.config.js b/packages/sdk-ts/jest.config.js index 95cbf1481..9679ba054 100644 --- a/packages/sdk-ts/jest.config.js +++ b/packages/sdk-ts/jest.config.js @@ -1,6 +1,6 @@ -const baseConfig = require('../../jest.config.js') +import baseConfig from '../../jest.config.js' -module.exports = { +export default { ...baseConfig, globals: { 'ts-jest': { diff --git a/packages/sdk-ts/package.json b/packages/sdk-ts/package.json index 3e7492482..85ee6868d 100644 --- a/packages/sdk-ts/package.json +++ b/packages/sdk-ts/package.json @@ -8,6 +8,7 @@ "name": "InjectiveLabs", "email": "admin@injectivelabs.org" }, + "type": "module", "types": "dist/cjs/index.d.ts", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", @@ -131,11 +132,11 @@ "@injectivelabs/mito-proto-ts": "1.13.2", "@injectivelabs/networks": "^1.14.34-beta.0", "@injectivelabs/olp-proto-ts": "1.13.1", - "@injectivelabs/test-utils": "^1.14.34-beta.3", "@injectivelabs/ts-types": "^1.14.33", "@injectivelabs/utils": "^1.14.34-beta.0", "@metamask/eth-sig-util": "^4.0.0", - "@noble/curves": "^1.4.0", + "@noble/curves": "^1.7.0", + "@noble/hashes": "^1.6.1", "axios": "^1.6.4", "bech32": "^2.0.0", "bip39": "^3.0.4", diff --git a/packages/sdk-ts/src/client/abacus/grpc/AbacusGrpcApi.ts b/packages/sdk-ts/src/client/abacus/grpc/AbacusGrpcApi.ts index db77a140e..d7b7b4dea 100644 --- a/packages/sdk-ts/src/client/abacus/grpc/AbacusGrpcApi.ts +++ b/packages/sdk-ts/src/client/abacus/grpc/AbacusGrpcApi.ts @@ -1,6 +1,7 @@ import { IndexerErrorModule, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveAbacusRpc } from '@injectivelabs/abacus-proto-ts' @@ -35,7 +36,7 @@ export class AbacusGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAbacusRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'PointsStatsLatestForAccount', contextModule: this.module, }) @@ -71,7 +72,7 @@ export class AbacusGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAbacusRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'PointsStatsDailyForAccount', contextModule: this.module, }) @@ -107,7 +108,7 @@ export class AbacusGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAbacusRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'PointsStatsWeeklyForAccount', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuctionApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuctionApi.ts index 73d59feb3..5794a06a1 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuctionApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuctionApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveAuctionV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -39,7 +40,7 @@ export class ChainGrpcAuctionApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAuctionV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AuctionParams', contextModule: this.module, }) @@ -69,7 +70,7 @@ export class ChainGrpcAuctionApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAuctionV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AuctionModuleState', contextModule: this.module, }) @@ -99,7 +100,7 @@ export class ChainGrpcAuctionApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAuctionV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'CurrentAuctionBasket', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthApi.spec.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthApi.spec.ts index 4e7b29f94..d49d6646e 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthApi.spec.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { ChainGrpcAuthApi } from './ChainGrpcAuthApi.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { ChainGrpcAuthTransformer } from '../transformers/ChainGrpcAuthTransformer.js' const injectiveAddress = mockFactory.injectiveAddress diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthApi.ts index 7ff23f19d..3668bd87c 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { CosmosAuthV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -40,7 +41,7 @@ export class ChainGrpcAuthApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosAuthV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', contextModule: this.module, }) @@ -69,7 +70,7 @@ export class ChainGrpcAuthApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosAuthV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Account', contextModule: this.module, }) @@ -101,7 +102,7 @@ export class ChainGrpcAuthApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosAuthV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Accounts', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthZApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthZApi.ts index 8ce234d35..236bc4301 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthZApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcAuthZApi.ts @@ -1,5 +1,6 @@ import { UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { CosmosAuthzV1Beta1Query } from '@injectivelabs/core-proto-ts' @@ -66,7 +67,7 @@ export class ChainGrpcAuthZApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosAuthzV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Grants', contextModule: this.module, }) @@ -105,7 +106,7 @@ export class ChainGrpcAuthZApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosAuthzV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GranterGrants', contextModule: this.module, }) @@ -144,7 +145,7 @@ export class ChainGrpcAuthZApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosAuthzV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GranteeGrants', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcBankApi.spec.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcBankApi.spec.ts index 4105c1f9f..dc7aa2581 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcBankApi.spec.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcBankApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { ChainGrpcBankApi } from './ChainGrpcBankApi.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { ChainGrpcBankTransformer } from '../transformers/index.js' import { CosmosBaseV1Beta1Coin } from '@injectivelabs/core-proto-ts' diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcBankApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcBankApi.ts index 7f5c03718..f7bb57369 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcBankApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcBankApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { CosmosBankV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -45,7 +46,7 @@ export class ChainGrpcBankApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBankV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', contextModule: this.module, }) @@ -81,7 +82,7 @@ export class ChainGrpcBankApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBankV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Balance', contextModule: this.module, }) @@ -116,7 +117,7 @@ export class ChainGrpcBankApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBankV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AllBalances', contextModule: this.module, }) @@ -148,7 +149,7 @@ export class ChainGrpcBankApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBankV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TotalSupply', contextModule: this.module, }) @@ -184,7 +185,7 @@ export class ChainGrpcBankApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBankV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'fetchSupplyOf', contextModule: this.module, }) @@ -218,7 +219,7 @@ export class ChainGrpcBankApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBankV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DenomsMetadata', contextModule: this.module, }) @@ -247,7 +248,7 @@ export class ChainGrpcBankApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBankV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DenomMetadata', contextModule: this.module, }) @@ -284,7 +285,7 @@ export class ChainGrpcBankApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBankV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DenomOwners', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcDistributionApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcDistributionApi.ts index ac7b06fcc..8bd6cea8a 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcDistributionApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcDistributionApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { Coin } from '@injectivelabs/ts-types' import { CosmosDistributionV1Beta1Query } from '@injectivelabs/core-proto-ts' @@ -39,7 +40,7 @@ export class ChainGrpcDistributionApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosDistributionV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', contextModule: this.module, }) @@ -78,7 +79,7 @@ export class ChainGrpcDistributionApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosDistributionV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DelegationRewards', contextModule: this.module, }) @@ -124,7 +125,7 @@ export class ChainGrpcDistributionApi extends BaseGrpcConsumer { if (e instanceof CosmosDistributionV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DelegationRewards', contextModule: this.module, }) @@ -156,7 +157,7 @@ export class ChainGrpcDistributionApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosDistributionV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DelegationTotalRewards', contextModule: this.module, }) @@ -192,7 +193,7 @@ export class ChainGrpcDistributionApi extends BaseGrpcConsumer { if (e instanceof CosmosDistributionV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DelegationTotalRewards', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcExchangeApi.spec.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcExchangeApi.spec.ts index 3a7dee1ef..be898006e 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcExchangeApi.spec.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcExchangeApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { ChainGrpcExchangeApi } from './ChainGrpcExchangeApi.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { ChainGrpcExchangeTransformer } from '../transformers/index.js' import { InjectiveExchangeV1Beta1Query } from '@injectivelabs/core-proto-ts' diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcExchangeApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcExchangeApi.ts index 2010ca317..1435c619e 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcExchangeApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcExchangeApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveExchangeV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -39,7 +40,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'QueryExchangeParams', contextModule: this.module, }) @@ -67,7 +68,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ExchangeModuleState', contextModule: this.module, }) @@ -97,7 +98,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FeeDiscountSchedule', contextModule: this.module, @@ -130,7 +131,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FeeDiscountAccountInfo', contextModule: this.module, }) @@ -160,7 +161,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TradeRewardCampaign', contextModule: this.module, }) @@ -190,7 +191,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TradeRewardPoints', contextModule: this.module, }) @@ -227,7 +228,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'PendingTradeRewardPoints', contextModule: this.module, }) @@ -254,7 +255,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Positions', contextModule: this.module, }) @@ -284,7 +285,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountTradeNonce', contextModule: this.module, }) @@ -316,7 +317,7 @@ export class ChainGrpcExchangeApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof InjectiveExchangeV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'IsOptedOutOfRewards', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcGovApi.spec.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcGovApi.spec.ts index 4f1c8553a..0755fb2c0 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcGovApi.spec.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcGovApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { ChainGrpcGovApi } from './ChainGrpcGovApi.js' -// import { mockFactory } from '@injectivelabs/test-utils' +// import { mockFactory } from '@injectivelabs/utils/test-utils' import { ChainGrpcGovTransformer } from '../transformers/index.js' import { CosmosGovV1Gov } from '@injectivelabs/core-proto-ts' diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcGovApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcGovApi.ts index 1a4517d34..0e6ffc7ea 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcGovApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcGovApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { CosmosGovV1Gov, CosmosGovV1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -48,7 +49,7 @@ export class ChainGrpcGovApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosGovV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', contextModule: this.module, }) @@ -89,7 +90,7 @@ export class ChainGrpcGovApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosGovV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Proposals', contextModule: this.module, }) @@ -117,7 +118,7 @@ export class ChainGrpcGovApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosGovV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Proposal', contextModule: this.module, }) @@ -157,7 +158,7 @@ export class ChainGrpcGovApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosGovV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Deposits', contextModule: this.module, }) @@ -196,7 +197,7 @@ export class ChainGrpcGovApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosGovV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Votes', contextModule: this.module, }) @@ -224,7 +225,7 @@ export class ChainGrpcGovApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof CosmosGovV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TallyResult', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcIbcApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcIbcApi.ts index e1f2169dc..ba79540ff 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcIbcApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcIbcApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { IbcApplicationsTransferV1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -40,7 +41,7 @@ export class ChainGrpcIbcApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof IbcApplicationsTransferV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DenomTrace', contextModule: this.module, }) @@ -74,7 +75,7 @@ export class ChainGrpcIbcApi extends BaseGrpcConsumer { } catch (e: any) { if (e instanceof IbcApplicationsTransferV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DenomTraces', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcInsuranceFundApi.spec.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcInsuranceFundApi.spec.ts index 515cd0fa5..ca4110956 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcInsuranceFundApi.spec.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcInsuranceFundApi.spec.ts @@ -1,7 +1,7 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { ChainGrpcInsuranceFundApi } from './ChainGrpcInsuranceFundApi.js' import { ChainGrpcInsuranceFundTransformer } from '../transformers/index.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { IndexerGrpcDerivativesApi } from '../../indexer/index.js' const endpoints = getNetworkEndpoints(Network.MainnetSentry) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcInsuranceFundApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcInsuranceFundApi.ts index 7fcd2471a..dbb2f3681 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcInsuranceFundApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcInsuranceFundApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveInsuranceV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -39,7 +40,7 @@ export class ChainGrpcInsuranceFundApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveInsuranceV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'InsuranceParams', contextModule: this.module, }) @@ -69,7 +70,7 @@ export class ChainGrpcInsuranceFundApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveInsuranceV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'InsuranceFunds', contextModule: this.module, }) @@ -101,7 +102,7 @@ export class ChainGrpcInsuranceFundApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveInsuranceV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'InsuranceFund', contextModule: this.module, }) @@ -140,7 +141,7 @@ export class ChainGrpcInsuranceFundApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveInsuranceV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'EstimatedRedemptions', contextModule: this.module, }) @@ -179,7 +180,7 @@ export class ChainGrpcInsuranceFundApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveInsuranceV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'PendingRedemptions', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcMintApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcMintApi.ts index d1eecbea6..50bdb18e7 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcMintApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcMintApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { CosmosMintV1Beta1Query } from '@injectivelabs/core-proto-ts' import { cosmosSdkDecToBigNumber, uint8ArrayToString } from '../../../utils/index.js' @@ -41,7 +42,7 @@ export class ChainGrpcMintApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosMintV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', contextModule: this.module, }) @@ -72,7 +73,7 @@ export class ChainGrpcMintApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosMintV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Inflation', contextModule: this.module, }) @@ -103,7 +104,7 @@ export class ChainGrpcMintApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosMintV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AnnualProvisions', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcOracleApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcOracleApi.ts index 233fad526..8e6364691 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcOracleApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcOracleApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveOracleV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -35,7 +36,7 @@ export class ChainGrpcOracleApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveOracleV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPeggyApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPeggyApi.ts index 704344744..3a16b6b1b 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPeggyApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPeggyApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectivePeggyV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -38,7 +39,7 @@ export class ChainGrpcPeggyApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectivePeggyV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPermissionsApi.spec.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPermissionsApi.spec.ts index 1699813da..d9a23b7af 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPermissionsApi.spec.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPermissionsApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { ChainGrpcPermissionsTransformer } from '../transformers/index.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { ChainGrpcPermissionsApi } from './ChainGrpcPermissionsApi.js' import { INJ_DENOM } from '@injectivelabs/utils' diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPermissionsApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPermissionsApi.ts index e23593a19..e799da106 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPermissionsApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcPermissionsApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectivePermissionsV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -42,7 +43,7 @@ export class ChainGrpcPermissionsApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectivePermissionsV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AddressesByRole', }) } @@ -79,7 +80,7 @@ export class ChainGrpcPermissionsApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectivePermissionsV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AddressRoles', }) } @@ -107,7 +108,7 @@ export class ChainGrpcPermissionsApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectivePermissionsV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AllNamespaces', }) } @@ -134,7 +135,7 @@ export class ChainGrpcPermissionsApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectivePermissionsV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', }) } @@ -171,7 +172,7 @@ export class ChainGrpcPermissionsApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectivePermissionsV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'NamespaceByDenom', }) } @@ -201,7 +202,7 @@ export class ChainGrpcPermissionsApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectivePermissionsV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'VouchersForAddress', }) } diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcStakingApi.spec.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcStakingApi.spec.ts index 99656bc52..86193659a 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcStakingApi.spec.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcStakingApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { ChainGrpcStakingApi } from './ChainGrpcStakingApi.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { ChainGrpcStakingTransformer } from '../transformers/index.js' import { Delegation, Validator } from '../types/index.js' diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcStakingApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcStakingApi.ts index a1d5dcdb0..63b49f9a6 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcStakingApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcStakingApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { CosmosStakingV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -40,7 +41,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Params', contextModule: this.module, }) @@ -67,7 +68,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Pool', contextModule: this.module, }) @@ -102,7 +103,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Validators', contextModule: this.module, }) @@ -131,7 +132,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Validator', contextModule: this.module, }) @@ -175,7 +176,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ValidatorDelegations', contextModule: this.module, }) @@ -223,7 +224,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ValidatorDelegations', contextModule: this.module, }) @@ -267,7 +268,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ValidatorUnbondingDelegations', contextModule: this.module, }) @@ -315,7 +316,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ValidatorUnbondingDelegations', contextModule: this.module, }) @@ -353,7 +354,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Delegation', contextModule: this.module, }) @@ -397,7 +398,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Delegations', contextModule: this.module, }) @@ -445,7 +446,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Delegation', contextModule: this.module, }) @@ -489,7 +490,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ValidatorDelegations', contextModule: this.module, }) @@ -537,7 +538,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ValidatorDelegations', contextModule: this.module, }) @@ -581,7 +582,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DelegatorUnbondingDelegations', contextModule: this.module, }) @@ -629,7 +630,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DelegatorUnbondingDelegations', contextModule: this.module, }) @@ -672,7 +673,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Redelegations', contextModule: this.module, }) @@ -719,7 +720,7 @@ export class ChainGrpcStakingApi extends BaseGrpcConsumer { if (e instanceof CosmosStakingV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Redelegations', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcTendermintApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcTendermintApi.ts index 5e7e8fad2..3fe76b696 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcTendermintApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcTendermintApi.ts @@ -2,8 +2,9 @@ import { CosmosBaseTendermintV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' import { ChainModule } from '../types/index.js' import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' /** * @category Chain Grpc API @@ -35,7 +36,7 @@ export class ChainGrpcTendermintApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmosBaseTendermintV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TendermintApi.fetchLatestBlock', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcTokenFactoryApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcTokenFactoryApi.ts index d1ffbbcb6..56898e58f 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcTokenFactoryApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcTokenFactoryApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveTokenFactoryV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -41,7 +42,7 @@ export class ChainGrpcTokenFactoryApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveTokenFactoryV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TokenFactoryDenomsFromCreator', contextModule: this.module, }) @@ -74,7 +75,7 @@ export class ChainGrpcTokenFactoryApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveTokenFactoryV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TokenFactoryDenomsFromCreator', contextModule: this.module, }) @@ -104,7 +105,7 @@ export class ChainGrpcTokenFactoryApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveTokenFactoryV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TokenFactoryParams', contextModule: this.module, }) @@ -134,7 +135,7 @@ export class ChainGrpcTokenFactoryApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveTokenFactoryV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TokenFactoryModuleState', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcWasmApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcWasmApi.ts index d1432f858..e32424b05 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcWasmApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcWasmApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { CosmwasmWasmV1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -55,7 +56,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AllContractState', contextModule: this.module, }) @@ -98,7 +99,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AllContractState', contextModule: this.module, }) @@ -135,7 +136,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ContractInfo', contextModule: this.module, }) @@ -166,7 +167,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ContractHistory', contextModule: this.module, }) @@ -205,7 +206,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SmartContractState', contextModule: this.module, }) @@ -238,7 +239,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'RawContractState', contextModule: this.module, }) @@ -272,7 +273,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Codes', contextModule: this.module, }) @@ -302,7 +303,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Code', contextModule: this.module, }) @@ -342,7 +343,7 @@ export class ChainGrpcWasmApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof CosmwasmWasmV1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ContractsByCode', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcWasmXApi.ts b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcWasmXApi.ts index 81f291b57..f94a85a3e 100644 --- a/packages/sdk-ts/src/client/chain/grpc/ChainGrpcWasmXApi.ts +++ b/packages/sdk-ts/src/client/chain/grpc/ChainGrpcWasmXApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveWasmxV1Beta1Query } from '@injectivelabs/core-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -35,7 +36,7 @@ export class ChainGrpcWasmXApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveWasmxV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'WasmxParams', contextModule: this.module, }) @@ -62,7 +63,7 @@ export class ChainGrpcWasmXApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveWasmxV1Beta1Query.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'WasmxModuleState', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAccountApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAccountApi.spec.ts index fa8283ce4..4be21f8b2 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAccountApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAccountApi.spec.ts @@ -1,5 +1,5 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { getDefaultSubaccountId } from '../../../utils/address.js' import { INJ_DENOM } from '@injectivelabs/utils' import { IndexerGrpcAccountTransformer } from '../transformers/index.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAccountApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAccountApi.ts index 97ada8515..be066b3df 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAccountApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAccountApi.ts @@ -1,6 +1,7 @@ import { GeneralException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveAccountRpc } from '@injectivelabs/indexer-proto-ts' @@ -56,7 +57,7 @@ export class IndexerGrpcAccountApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAccountRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Rewards', contextModule: this.module, }) @@ -85,7 +86,7 @@ export class IndexerGrpcAccountApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAccountRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountsList', contextModule: this.module, }) @@ -116,7 +117,7 @@ export class IndexerGrpcAccountApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAccountRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountBalanceEndpoint', contextModule: this.module, }) @@ -145,7 +146,7 @@ export class IndexerGrpcAccountApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAccountRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountBalancesList', contextModule: this.module, }) @@ -208,7 +209,7 @@ export class IndexerGrpcAccountApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAccountRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountHistory', contextModule: this.module, }) @@ -253,7 +254,7 @@ export class IndexerGrpcAccountApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAccountRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountOrderSummary', contextModule: this.module, }) @@ -287,7 +288,7 @@ export class IndexerGrpcAccountApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAccountRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'OrderStates', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcArchiverApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcArchiverApi.spec.ts index 1da2adf78..97b38dba9 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcArchiverApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcArchiverApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { INJ_DENOM } from '@injectivelabs/utils' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { IndexerGrpcArchiverTransformer } from '../transformers/index.js' import { IndexerGrpcArchiverApi } from './IndexerGrpcArchiverApi.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcArchiverApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcArchiverApi.ts index 145667781..863816cc3 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcArchiverApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcArchiverApi.ts @@ -1,5 +1,6 @@ import { UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveArchiverRpc } from '@injectivelabs/indexer-proto-ts' @@ -46,7 +47,7 @@ export class IndexerGrpcArchiverApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveArchiverRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Historical Balance', contextModule: this.module, }) @@ -83,7 +84,7 @@ export class IndexerGrpcArchiverApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveArchiverRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Historical Rpnl', contextModule: this.module, }) @@ -120,7 +121,7 @@ export class IndexerGrpcArchiverApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveArchiverRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Historical Volumes', contextModule: this.module, }) @@ -170,7 +171,7 @@ export class IndexerGrpcArchiverApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveArchiverRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Pnl Leaderboard', contextModule: this.module, }) @@ -220,7 +221,7 @@ export class IndexerGrpcArchiverApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveArchiverRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Vol Leaderboard', contextModule: this.module, }) @@ -268,7 +269,7 @@ export class IndexerGrpcArchiverApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveArchiverRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Pnl Leaderboard Fixed Resolution', contextModule: this.module, }) @@ -316,7 +317,7 @@ export class IndexerGrpcArchiverApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveArchiverRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Vol Leaderboard Fixed Resolution', contextModule: this.module, }) @@ -363,7 +364,7 @@ export class IndexerGrpcArchiverApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveArchiverRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'DenomHolders', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAuctionApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAuctionApi.ts index 20ea0539c..db6a181af 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAuctionApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcAuctionApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveAuctionRpc } from '@injectivelabs/indexer-proto-ts' import BaseGrpcConsumer from '../../base/BaseIndexerGrpcConsumer.js' @@ -44,7 +45,7 @@ export class IndexerGrpcAuctionApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAuctionRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AuctionEndpoint', contextModule: this.module, }) @@ -70,7 +71,7 @@ export class IndexerGrpcAuctionApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveAuctionRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Auctions', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcCampaignApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcCampaignApi.spec.ts index 19b947e88..397e6defe 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcCampaignApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcCampaignApi.spec.ts @@ -1,4 +1,4 @@ -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { IndexerCampaignTransformer } from '../transformers/index.js' import { IndexerGrpcCampaignApi } from './IndexerGrpcCampaignApi.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcCampaignApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcCampaignApi.ts index 232d2729c..1b4a59571 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcCampaignApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcCampaignApi.ts @@ -1,5 +1,6 @@ import { UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveMetaRpc } from '@injectivelabs/indexer-proto-ts' @@ -71,7 +72,7 @@ export class IndexerGrpcCampaignApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FetchCampaign', contextModule: this.module, }) @@ -130,7 +131,7 @@ export class IndexerGrpcCampaignApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FetchCampaigns', contextModule: this.module, }) @@ -182,7 +183,7 @@ export class IndexerGrpcCampaignApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveCampaignRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Campaigns', contextModule: this.module, }) @@ -230,7 +231,7 @@ export class IndexerGrpcCampaignApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FetchGuilds', contextModule: this.module, }) @@ -268,7 +269,7 @@ export class IndexerGrpcCampaignApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FetchGuildMember', contextModule: this.module, }) @@ -327,7 +328,7 @@ export class IndexerGrpcCampaignApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FetchGuildMembers', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcDerivativesApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcDerivativesApi.spec.ts index c7ad33e3d..cde5d4ee1 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcDerivativesApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcDerivativesApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { getDefaultSubaccountId } from '../../../utils/address.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { IndexerGrpcDerivativeTransformer } from '../transformers/index.js' import { DerivativeMarket } from '../types/index.js' import { IndexerGrpcDerivativesApi } from './IndexerGrpcDerivativesApi.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcDerivativesApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcDerivativesApi.ts index 3a310f6c9..92eb2de8d 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcDerivativesApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcDerivativesApi.ts @@ -1,6 +1,7 @@ import { GeneralException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { OrderSide, OrderState } from '@injectivelabs/ts-types' @@ -63,7 +64,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Markets', contextModule: this.module, }) @@ -92,7 +93,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Market', contextModule: this.module, }) @@ -146,7 +147,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'BinaryOptionsMarkets', contextModule: this.module, }) @@ -178,7 +179,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'BinaryOptionsMarket', contextModule: this.module, }) @@ -264,7 +265,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Orders', contextModule: this.module, }) @@ -365,7 +366,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'OrdersHistory', contextModule: this.module, }) @@ -437,7 +438,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Positions', contextModule: this.module, }) @@ -520,7 +521,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Positions', contextModule: this.module, }) @@ -631,7 +632,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Trades', contextModule: this.module, }) @@ -694,7 +695,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FundingPayments', contextModule: this.module, }) @@ -742,7 +743,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'FundingRates', contextModule: this.module, }) @@ -794,7 +795,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountOrdersList', contextModule: this.module, }) @@ -859,7 +860,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountTradesList', contextModule: this.module, }) @@ -897,7 +898,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'OrderbooksV2', contextModule: this.module, }) @@ -928,7 +929,7 @@ export class IndexerGrpcDerivativesApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDerivativeExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'OrderbookV2', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcExplorerApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcExplorerApi.spec.ts index d3eeb1038..f2f95500c 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcExplorerApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcExplorerApi.spec.ts @@ -1,5 +1,5 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { IndexerRestExplorerApi } from '../rest/index.js' import { IndexerGrpcExplorerTransformer } from '../transformers/index.js' import { ExplorerValidator } from '../types/index.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcExplorerApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcExplorerApi.ts index 79d6bd074..d999635ea 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcExplorerApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcExplorerApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveExplorerRpc } from '@injectivelabs/indexer-proto-ts' import BaseGrpcConsumer from '../../base/BaseIndexerGrpcConsumer.js' @@ -35,7 +36,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetTxByTxHash', contextModule: this.module, }) @@ -110,7 +111,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetAccountTxs', contextModule: this.module, }) @@ -141,7 +142,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetValidator', contextModule: this.module, }) @@ -172,7 +173,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetValidatorUptime', contextModule: this.module, }) @@ -227,7 +228,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetPeggyDepositTxs', contextModule: this.module, }) @@ -282,7 +283,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetPeggyWithdrawalTxs', contextModule: this.module, }) @@ -340,7 +341,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetBlocks', contextModule: this.module, }) @@ -368,7 +369,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetBlock', contextModule: this.module, }) @@ -448,7 +449,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetTxs', contextModule: this.module, }) @@ -527,7 +528,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetIBCTransferTxs', contextModule: this.module, }) @@ -555,7 +556,7 @@ export class IndexerGrpcExplorerApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveExplorerRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetExplorerStats', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcInsuranceFundApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcInsuranceFundApi.spec.ts index 31a4345ac..142a3f0ce 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcInsuranceFundApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcInsuranceFundApi.spec.ts @@ -1,5 +1,5 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { IndexerGrpcInsuranceFundTransformer } from '../transformers/index.js' import { IndexerGrpcInsuranceFundApi } from './IndexerGrpcInsuranceFundApi.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcInsuranceFundApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcInsuranceFundApi.ts index 268a9a6f8..c67f3167b 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcInsuranceFundApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcInsuranceFundApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveInsuranceRpc } from '@injectivelabs/indexer-proto-ts' import BaseGrpcConsumer from '../../base/BaseIndexerGrpcConsumer.js' @@ -56,7 +57,7 @@ export class IndexerGrpcInsuranceFundApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveInsuranceRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Redemptions', contextModule: this.module, }) @@ -84,7 +85,7 @@ export class IndexerGrpcInsuranceFundApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveInsuranceRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Funds', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMetaApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMetaApi.ts index 5acfffc84..59e69b871 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMetaApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMetaApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveMetaRpc } from '@injectivelabs/indexer-proto-ts' import BaseGrpcConsumer from '../../base/BaseIndexerGrpcConsumer.js' @@ -34,7 +35,7 @@ export class IndexerGrpcMetaApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Ping', contextModule: this.module, }) @@ -60,7 +61,7 @@ export class IndexerGrpcMetaApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Version', contextModule: this.module, }) @@ -88,7 +89,7 @@ export class IndexerGrpcMetaApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Info', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMitoApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMitoApi.spec.ts index 48fe5ba13..53bd17a28 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMitoApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMitoApi.spec.ts @@ -1,4 +1,4 @@ -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { IndexerGrpcMitoTransformer } from '../transformers/index.js' import { IndexerGrpcMitoApi } from './IndexerGrpcMitoApi.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMitoApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMitoApi.ts index 34dcf46c7..ab8931af2 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMitoApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcMitoApi.ts @@ -1,5 +1,6 @@ import { UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { MitoApi } from '@injectivelabs/mito-proto-ts' @@ -48,7 +49,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetVault', contextModule: this.module, }) @@ -94,7 +95,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetVaults', contextModule: this.module, }) @@ -140,7 +141,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'LPTokenPriceChart', contextModule: this.module, }) @@ -186,7 +187,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TVLChart', contextModule: this.module, }) @@ -238,7 +239,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'VaultsByHolderAddress', contextModule: this.module, }) @@ -285,7 +286,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'LPHolders', contextModule: this.module, }) @@ -320,7 +321,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Portfolio', contextModule: this.module, }) @@ -352,7 +353,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Leaderboard', contextModule: this.module, }) @@ -412,7 +413,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TransfersHistory', contextModule: this.module, }) @@ -460,7 +461,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'LeaderboardEpochs', contextModule: this.module, }) @@ -500,7 +501,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetStakingPools', contextModule: this.module, }) @@ -554,7 +555,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'StakingHistory', contextModule: this.module, }) @@ -591,7 +592,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'StakingReward', contextModule: this.module, }) @@ -619,7 +620,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Missions', contextModule: this.module, }) @@ -651,7 +652,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'MissionLeaderboard', contextModule: this.module, }) @@ -689,7 +690,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetIDO', contextModule: this.module, }) @@ -747,7 +748,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'ListIDOs', contextModule: this.module, }) @@ -799,7 +800,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetIDOSubscribers', contextModule: this.module, }) @@ -836,7 +837,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetIDOSubscription', contextModule: this.module, }) @@ -890,7 +891,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetIDOActivities', contextModule: this.module, }) @@ -936,7 +937,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetWhitelist', contextModule: this.module, }) @@ -985,7 +986,7 @@ export class IndexerGrpcMitoApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveMetaRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetClaimReferences', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcOracleApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcOracleApi.ts index 7a17f1c81..e578a4917 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcOracleApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcOracleApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveOracleRpc } from '@injectivelabs/indexer-proto-ts' import BaseGrpcConsumer from '../../base/BaseIndexerGrpcConsumer.js' @@ -35,7 +36,7 @@ export class IndexerGrpcOracleApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveOracleRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'OracleList', contextModule: this.module, }) @@ -79,7 +80,7 @@ export class IndexerGrpcOracleApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveOracleRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Price', contextModule: this.module, }) @@ -129,7 +130,7 @@ export class IndexerGrpcOracleApi extends BaseGrpcConsumer { if (e instanceof InjectiveOracleRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Price', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcPortfolioApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcPortfolioApi.spec.ts index b0edc8cfb..257c5758f 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcPortfolioApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcPortfolioApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' // import { INJ_DENOM } from '@injectivelabs/utils' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { IndexerGrpcAccountPortfolioTransformer } from '../transformers/index.js' import { IndexerGrpcAccountPortfolioApi } from './IndexerGrpcPortfolioApi.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcPortfolioApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcPortfolioApi.ts index bd4f42299..76809e809 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcPortfolioApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcPortfolioApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectivePortfolioRpc } from '@injectivelabs/indexer-proto-ts' import BaseGrpcConsumer from '../../base/BaseIndexerGrpcConsumer.js' @@ -50,7 +51,7 @@ export class IndexerGrpcAccountPortfolioApi extends BaseGrpcConsumer { if (e instanceof InjectivePortfolioRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AccountPortfolio', contextModule: this.module, }) @@ -91,7 +92,7 @@ export class IndexerGrpcAccountPortfolioApi extends BaseGrpcConsumer { if (e instanceof InjectivePortfolioRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AccountPortfolio', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcSpotApi.spec.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcSpotApi.spec.ts index 4e8a2f6cc..8571f2420 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcSpotApi.spec.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcSpotApi.spec.ts @@ -1,6 +1,6 @@ import { getNetworkEndpoints, Network } from '@injectivelabs/networks' import { getDefaultSubaccountId } from '../../../utils/address.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { IndexerGrpcSpotTransformer } from '../transformers/index.js' import { SpotMarket } from '../types/index.js' import { IndexerGrpcSpotApi } from './IndexerGrpcSpotApi.js' diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcSpotApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcSpotApi.ts index 4313ad123..c7e734a2e 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcSpotApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcSpotApi.ts @@ -1,6 +1,7 @@ import { GeneralException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { OrderSide, OrderState } from '@injectivelabs/ts-types' @@ -66,7 +67,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Markets', contextModule: this.module, }) @@ -95,7 +96,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Market', contextModule: this.module, }) @@ -176,7 +177,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Orders', contextModule: this.module, }) @@ -278,7 +279,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'OrdersHistory', contextModule: this.module, }) @@ -389,7 +390,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'Trades', contextModule: this.module, }) @@ -440,7 +441,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountOrdersList', contextModule: this.module, }) @@ -504,7 +505,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'SubaccountTradesList', contextModule: this.module, }) @@ -542,7 +543,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'OrderbooksV2', contextModule: this.module, }) @@ -573,7 +574,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'OrderbookV2', contextModule: this.module, }) @@ -628,7 +629,7 @@ export class IndexerGrpcSpotApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveSpotExchangeRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'AtomicSwapHistory', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcTradingApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcTradingApi.ts index 4a85ec79b..b33848a2d 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcTradingApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcTradingApi.ts @@ -1,6 +1,7 @@ import { - GrpcUnaryRequestException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { InjectiveTradingRpc } from '@injectivelabs/indexer-proto-ts' import BaseGrpcConsumer from '../../base/BaseIndexerGrpcConsumer.js' @@ -35,7 +36,7 @@ export class IndexerGrpcTradingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveTradingRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'TradingStats', contextModule: this.module, }) @@ -154,7 +155,7 @@ export class IndexerGrpcTradingApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveTradingRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GridStrategies', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcTransactionApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcTransactionApi.ts index 10b22c6e5..8e00ff5e9 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcTransactionApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcTransactionApi.ts @@ -9,9 +9,10 @@ import { recoverTypedSignaturePubKey } from '../../../utils/transaction.js' import { IndexerModule } from '../types/index.js' import { ErrorType, - GrpcUnaryRequestException, - TransactionException, UnspecifiedErrorCode, + TransactionException, + grpcErrorCodeToErrorCode, + GrpcUnaryRequestException, } from '@injectivelabs/exceptions' import { getGrpcIndexerWebImpl } from '../../base/BaseIndexerGrpcWebConsumer.js' import { InjectiveExchangeRpc } from '@injectivelabs/indexer-proto-ts' @@ -97,7 +98,7 @@ export class IndexerGrpcTransactionApi { } catch (e: unknown) { if (e instanceof InjectiveExchangeRpc.GrpcWebError) { throw new TransactionException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'PrepareTx', contextModule: 'Web3Gateway', type: e.type, @@ -177,7 +178,7 @@ export class IndexerGrpcTransactionApi { } catch (e: unknown) { if (e instanceof InjectiveExchangeRpc.GrpcWebError) { throw new TransactionException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), type: e.type, context: 'CosmosPrepareTx', contextModule: 'Web3Gateway', @@ -248,7 +249,7 @@ export class IndexerGrpcTransactionApi { } catch (e: unknown) { if (e instanceof InjectiveExchangeRpc.GrpcWebError) { throw new TransactionException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), type: e.type, context: 'BroadcastTx', contextModule: 'Web3Gateway', @@ -306,7 +307,7 @@ export class IndexerGrpcTransactionApi { } catch (e: unknown) { if (e instanceof GrpcUnaryRequestException) { throw new TransactionException(e.toOriginalError(), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), type: e.type, context: 'BroadcastTx', contextModule: 'Web3Gateway', @@ -332,7 +333,7 @@ export class IndexerGrpcTransactionApi { } catch (e: unknown) { if (e instanceof InjectiveExchangeRpc.GrpcWebError) { throw new TransactionException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), type: e.type, context: 'FeePayer', contextModule: 'Web3Gateway', diff --git a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcWeb3GwApi.ts b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcWeb3GwApi.ts index 12fac3889..608eda7fa 100644 --- a/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcWeb3GwApi.ts +++ b/packages/sdk-ts/src/client/indexer/grpc/IndexerGrpcWeb3GwApi.ts @@ -9,6 +9,7 @@ import { ErrorType, TransactionException, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, } from '@injectivelabs/exceptions' import { InjectiveExchangeRpc } from '@injectivelabs/indexer-proto-ts' import { CosmosBaseV1Beta1Coin } from '@injectivelabs/core-proto-ts' @@ -101,7 +102,7 @@ export class IndexerGrpcWeb3GwApi extends IndexerGrpcTransactionApi { } catch (e: unknown) { if (e instanceof InjectiveExchangeRpc.GrpcWebError) { throw new TransactionException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'PrepareEip712', contextModule: 'Web3Gateway', type: e.type, diff --git a/packages/sdk-ts/src/client/olp/grpc/OLPGrpcApi.spec.ts b/packages/sdk-ts/src/client/olp/grpc/OLPGrpcApi.spec.ts index 59d377d11..277301fbe 100644 --- a/packages/sdk-ts/src/client/olp/grpc/OLPGrpcApi.spec.ts +++ b/packages/sdk-ts/src/client/olp/grpc/OLPGrpcApi.spec.ts @@ -1,4 +1,4 @@ -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { OLPGrpcApi } from './OLPGrpcApi.js' import { DmmGrpcTransformer } from './transformers/index.js' diff --git a/packages/sdk-ts/src/client/olp/grpc/OLPGrpcApi.ts b/packages/sdk-ts/src/client/olp/grpc/OLPGrpcApi.ts index f6b8e99f9..b82deb5d2 100644 --- a/packages/sdk-ts/src/client/olp/grpc/OLPGrpcApi.ts +++ b/packages/sdk-ts/src/client/olp/grpc/OLPGrpcApi.ts @@ -1,7 +1,8 @@ import { + IndexerErrorModule, UnspecifiedErrorCode, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, - IndexerErrorModule, } from '@injectivelabs/exceptions' import { InjectiveDmmRpc } from '@injectivelabs/olp-proto-ts' import BaseGrpcConsumer from '../../base/BaseGrpcConsumer.js' @@ -36,7 +37,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetEpochs', contextModule: this.module, }) @@ -65,7 +66,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetMarketRewards', contextModule: this.module, }) @@ -106,7 +107,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetEligibleAddresses', contextModule: this.module, }) @@ -144,7 +145,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetEpochScores', contextModule: this.module, }) @@ -188,7 +189,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetEpochScoresHistory', contextModule: this.module, }) @@ -229,7 +230,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetTotalScores', contextModule: this.module, }) @@ -276,7 +277,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetTotalScoresHistory', contextModule: this.module, }) @@ -323,7 +324,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetRewardsDistribution', contextModule: this.module, }) @@ -359,7 +360,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetAccountVolumes', contextModule: this.module, }) @@ -402,7 +403,7 @@ export class OLPGrpcApi extends BaseGrpcConsumer { } catch (e: unknown) { if (e instanceof InjectiveDmmRpc.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), context: 'GetRewardsEligibility', contextModule: this.module, }) diff --git a/packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts b/packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts index 8f19b4a64..fbc273121 100644 --- a/packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts +++ b/packages/sdk-ts/src/core/accounts/PrivateKey.spec.ts @@ -1,5 +1,5 @@ import { verifyMessage, Wallet } from 'ethers' -import { toUtf8 } from '../../utils' +import { toUtf8 } from '../../utils/utf8.js' import { PrivateKey } from './PrivateKey.js' import { generateArbitrarySignDoc } from '../tx/index.js' @@ -128,17 +128,16 @@ describe('PrivateKey', () => { const privateKey = PrivateKey.fromHex(pk) const publicKey = privateKey.toHex() - const privKeySignatureArray = privateKey.sign( + const ethersVerifiedSigner = verifyMessage(message, ethersSignature) + const ethersSignatureVerifiedCorrectly = ethersVerifiedSigner === publicKey + expect(ethersSignatureVerifiedCorrectly).toBe(true) + + const privKeySignatureArray = privateKey.signHashed( Buffer.from(toUtf8(message), 'utf-8'), ) const privKeySignature = `0x${Buffer.from(privKeySignatureArray).toString( 'hex', )}` - - const ethersVerifiedSigner = verifyMessage(message, ethersSignature) - const ethersSignatureVerifiedCorrectly = ethersVerifiedSigner === publicKey - expect(ethersSignatureVerifiedCorrectly).toBe(true) - const privKeyVerifiedSigner = verifyMessage(message, privKeySignature) const privKeySignatureVerifiedCorrectly = privKeyVerifiedSigner === publicKey diff --git a/packages/sdk-ts/src/core/modules/auction/msgs/MsgBid.spec.ts b/packages/sdk-ts/src/core/modules/auction/msgs/MsgBid.spec.ts index 64d385c64..301227a6c 100644 --- a/packages/sdk-ts/src/core/modules/auction/msgs/MsgBid.spec.ts +++ b/packages/sdk-ts/src/core/modules/auction/msgs/MsgBid.spec.ts @@ -1,5 +1,5 @@ import { BigNumberInBase } from '@injectivelabs/utils' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import MsgBid from './MsgBid.js' import snakecaseKeys from 'snakecase-keys' diff --git a/packages/sdk-ts/src/core/modules/authz/msgs/MsgExec.spec.ts b/packages/sdk-ts/src/core/modules/authz/msgs/MsgExec.spec.ts index 586ff0d5c..6ba841822 100644 --- a/packages/sdk-ts/src/core/modules/authz/msgs/MsgExec.spec.ts +++ b/packages/sdk-ts/src/core/modules/authz/msgs/MsgExec.spec.ts @@ -1,5 +1,5 @@ import MsgExec from './MsgExec' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { BigNumberInBase } from '@injectivelabs/utils' import MsgSend from '../../bank/msgs/MsgSend.js' diff --git a/packages/sdk-ts/src/core/modules/authz/msgs/MsgGrant.spec.ts b/packages/sdk-ts/src/core/modules/authz/msgs/MsgGrant.spec.ts index 322fe4171..6cffa2a43 100644 --- a/packages/sdk-ts/src/core/modules/authz/msgs/MsgGrant.spec.ts +++ b/packages/sdk-ts/src/core/modules/authz/msgs/MsgGrant.spec.ts @@ -1,5 +1,5 @@ import MsgGrant from './MsgGrant.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const { injectiveAddress, injectiveAddress2 } = mockFactory diff --git a/packages/sdk-ts/src/core/modules/authz/msgs/MsgGrantWithAuthorization.spec.ts b/packages/sdk-ts/src/core/modules/authz/msgs/MsgGrantWithAuthorization.spec.ts index 78d8e6dfc..fc71603f2 100644 --- a/packages/sdk-ts/src/core/modules/authz/msgs/MsgGrantWithAuthorization.spec.ts +++ b/packages/sdk-ts/src/core/modules/authz/msgs/MsgGrantWithAuthorization.spec.ts @@ -1,5 +1,5 @@ import MsgGrantWithAuthorization from './MsgGrantWithAuthorization.js' -import { mockFactory, prepareEip712 } from '@injectivelabs/test-utils' +import { mockFactory, prepareEip712 } from '@injectivelabs/utils/test-utils' import GenericAuthorization from './authorizations/GenericAuthorization.js' import ContractExecutionAuthorization from './authorizations/ContractExecutionAuthorization.js' import { getEip712TypedData, getEip712TypedDataV2 } from '../../../tx/index.js' diff --git a/packages/sdk-ts/src/core/modules/authz/msgs/MsgRevoke.spec.ts b/packages/sdk-ts/src/core/modules/authz/msgs/MsgRevoke.spec.ts index f0621de07..7cfd63761 100644 --- a/packages/sdk-ts/src/core/modules/authz/msgs/MsgRevoke.spec.ts +++ b/packages/sdk-ts/src/core/modules/authz/msgs/MsgRevoke.spec.ts @@ -1,5 +1,5 @@ import MsgRevoke from './MsgRevoke.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const { injectiveAddress, injectiveAddress2 } = mockFactory diff --git a/packages/sdk-ts/src/core/modules/bank/msgs/MsgSend.spec.ts b/packages/sdk-ts/src/core/modules/bank/msgs/MsgSend.spec.ts index 572ba0695..162690797 100644 --- a/packages/sdk-ts/src/core/modules/bank/msgs/MsgSend.spec.ts +++ b/packages/sdk-ts/src/core/modules/bank/msgs/MsgSend.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgSend from './MsgSend.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' const params: MsgSend['params'] = { dstInjectiveAddress: mockFactory.injectiveAddress, diff --git a/packages/sdk-ts/src/core/modules/distribution/msgs/MsgWithdrawDelegatorReward.spec.ts b/packages/sdk-ts/src/core/modules/distribution/msgs/MsgWithdrawDelegatorReward.spec.ts index aa47a3daf..172d88dcd 100644 --- a/packages/sdk-ts/src/core/modules/distribution/msgs/MsgWithdrawDelegatorReward.spec.ts +++ b/packages/sdk-ts/src/core/modules/distribution/msgs/MsgWithdrawDelegatorReward.spec.ts @@ -1,5 +1,5 @@ import MsgWithdrawDelegatorReward from './MsgWithdrawDelegatorReward.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgWithdrawDelegatorReward['params'] = { diff --git a/packages/sdk-ts/src/core/modules/distribution/msgs/MsgWithdrawValidatorCommission.spec.ts b/packages/sdk-ts/src/core/modules/distribution/msgs/MsgWithdrawValidatorCommission.spec.ts index 7e737c33a..48c525e4b 100644 --- a/packages/sdk-ts/src/core/modules/distribution/msgs/MsgWithdrawValidatorCommission.spec.ts +++ b/packages/sdk-ts/src/core/modules/distribution/msgs/MsgWithdrawValidatorCommission.spec.ts @@ -1,5 +1,5 @@ import MsgWithdrawValidatorCommission from './MsgWithdrawValidatorCommission.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgWithdrawValidatorCommission['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelBinaryOptionsOrders.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelBinaryOptionsOrders.spec.ts index c1273d4f6..4afa5554b 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelBinaryOptionsOrders.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelBinaryOptionsOrders.spec.ts @@ -1,5 +1,5 @@ import MsgBatchCancelDerivativeOrders from './MsgBatchCancelDerivativeOrders.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgBatchCancelDerivativeOrders['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelDerivativeOrders.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelDerivativeOrders.spec.ts index c1273d4f6..4afa5554b 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelDerivativeOrders.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelDerivativeOrders.spec.ts @@ -1,5 +1,5 @@ import MsgBatchCancelDerivativeOrders from './MsgBatchCancelDerivativeOrders.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgBatchCancelDerivativeOrders['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelSpotOrders.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelSpotOrders.spec.ts index fa201f3a2..846bea1a3 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelSpotOrders.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgBatchCancelSpotOrders.spec.ts @@ -1,5 +1,5 @@ import MsgBatchCancelSpotOrders from './MsgBatchCancelSpotOrders.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' // import { Network, getNetworkEndpoints } from '@injectivelabs/networks' import snakecaseKeys from 'snakecase-keys' // import { getEthereumAddress } from '../../../../utils/address' diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelBinaryOptionsOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelBinaryOptionsOrder.spec.ts index 41aeb1e60..de7dcd961 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelBinaryOptionsOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelBinaryOptionsOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCancelBinaryOptionsOrder from './MsgCancelBinaryOptionsOrder.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCancelBinaryOptionsOrder['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelDerivativeOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelDerivativeOrder.spec.ts index e8799386d..07938dca1 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelDerivativeOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelDerivativeOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCancelDerivativeOrder from './MsgCancelDerivativeOrder.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCancelDerivativeOrder['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelSpotOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelSpotOrder.spec.ts index 415deba19..b328510fe 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelSpotOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCancelSpotOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCancelSpotOrder from './MsgCancelSpotOrder' -import { mockFactory, prepareEip712 } from '@injectivelabs/test-utils' +import { mockFactory, prepareEip712 } from '@injectivelabs/utils/test-utils' import { IndexerGrpcWeb3GwApi } from '../../../../client/indexer/grpc/IndexerGrpcWeb3GwApi.js' import snakecaseKeys from 'snakecase-keys' import { getEip712TypedData, getEip712TypedDataV2 } from '../../../tx/index.js' diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateBinaryOptionsLimitOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateBinaryOptionsLimitOrder.spec.ts index 7455595d8..8f3e05b62 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateBinaryOptionsLimitOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateBinaryOptionsLimitOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCreateBinaryOptionsLimitOrder from './MsgCreateBinaryOptionsLimitOrder.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCreateBinaryOptionsLimitOrder['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateBinaryOptionsMarketOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateBinaryOptionsMarketOrder.spec.ts index 10bcd16ac..f82f471f1 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateBinaryOptionsMarketOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateBinaryOptionsMarketOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCreateBinaryOptionsMarketOrder from './MsgCreateBinaryOptionsMarketOrder.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCreateBinaryOptionsMarketOrder['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateDerivativeLimitOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateDerivativeLimitOrder.spec.ts index 3fdb3eddc..17fbeaa45 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateDerivativeLimitOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateDerivativeLimitOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCreateDerivativeLimitOrder from './MsgCreateDerivativeLimitOrder.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCreateDerivativeLimitOrder['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateDerivativeMarketOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateDerivativeMarketOrder.spec.ts index d0fbe6cc1..ae5fc4004 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateDerivativeMarketOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateDerivativeMarketOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCreateDerivativeMarketOrder from './MsgCreateDerivativeMarketOrder.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCreateDerivativeMarketOrder['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateSpotLimitOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateSpotLimitOrder.spec.ts index 194ba4948..44bdf0835 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateSpotLimitOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateSpotLimitOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCreateSpotLimitOrder from './MsgCreateSpotLimitOrder.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCreateSpotLimitOrder['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateSpotMarketOrder.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateSpotMarketOrder.spec.ts index c9aaa56e4..41ddef77e 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateSpotMarketOrder.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgCreateSpotMarketOrder.spec.ts @@ -1,5 +1,5 @@ import MsgCreateSpotMarketOrder from './MsgCreateSpotMarketOrder.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCreateSpotMarketOrder['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgDeposit.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgDeposit.spec.ts index e76a8c6e6..8934d5154 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgDeposit.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgDeposit.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgDeposit from './MsgDeposit.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgDeposit['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgExternalTransfer.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgExternalTransfer.spec.ts index c7ecee89d..207a292f0 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgExternalTransfer.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgExternalTransfer.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgExternalTransfer from './MsgExternalTransfer.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgExternalTransfer['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgIncreasePositionMargin.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgIncreasePositionMargin.spec.ts index a57f24d35..3e1fc6c4b 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgIncreasePositionMargin.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgIncreasePositionMargin.spec.ts @@ -1,5 +1,5 @@ import MsgIncreasePositionMargin from './MsgIncreasePositionMargin.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgIncreasePositionMargin['params'] = { diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgInstantSpotMarketLaunch.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgInstantSpotMarketLaunch.spec.ts index 59537407a..c374320d8 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgInstantSpotMarketLaunch.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgInstantSpotMarketLaunch.spec.ts @@ -1,5 +1,5 @@ import MsgInstantSpotMarketLaunch from './MsgInstantSpotMarketLaunch.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const market = mockFactory.injUsdtSpotMarket diff --git a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgWithdraw.spec.ts b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgWithdraw.spec.ts index b11df4f69..7e4db1204 100644 --- a/packages/sdk-ts/src/core/modules/exchange/msgs/MsgWithdraw.spec.ts +++ b/packages/sdk-ts/src/core/modules/exchange/msgs/MsgWithdraw.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgWithdraw from './MsgWithdraw.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgWithdraw['params'] = { diff --git a/packages/sdk-ts/src/core/modules/feegrant/msgs/MsgGrantAllowance.spec.ts b/packages/sdk-ts/src/core/modules/feegrant/msgs/MsgGrantAllowance.spec.ts index 3b1c9c35e..c7a417838 100644 --- a/packages/sdk-ts/src/core/modules/feegrant/msgs/MsgGrantAllowance.spec.ts +++ b/packages/sdk-ts/src/core/modules/feegrant/msgs/MsgGrantAllowance.spec.ts @@ -1,5 +1,5 @@ import MsgGrantAllowance from './MsgGrantAllowance.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { CosmosFeegrantV1Beta1Feegrant } from '@injectivelabs/core-proto-ts' import snakecaseKeys from 'snakecase-keys' diff --git a/packages/sdk-ts/src/core/modules/feegrant/msgs/MsgRevokeAllowance.spec.ts b/packages/sdk-ts/src/core/modules/feegrant/msgs/MsgRevokeAllowance.spec.ts index dc6005e0b..880655dcc 100644 --- a/packages/sdk-ts/src/core/modules/feegrant/msgs/MsgRevokeAllowance.spec.ts +++ b/packages/sdk-ts/src/core/modules/feegrant/msgs/MsgRevokeAllowance.spec.ts @@ -1,5 +1,5 @@ import MsgRevokeAllowance from './MsgRevokeAllowance.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const { injectiveAddress, injectiveAddress2 } = mockFactory diff --git a/packages/sdk-ts/src/core/modules/gov/msgs/MsgDeposit.spec.ts b/packages/sdk-ts/src/core/modules/gov/msgs/MsgDeposit.spec.ts index c0efea8a3..782b51a0a 100644 --- a/packages/sdk-ts/src/core/modules/gov/msgs/MsgDeposit.spec.ts +++ b/packages/sdk-ts/src/core/modules/gov/msgs/MsgDeposit.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgDeposit from './MsgDeposit.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgDeposit['params'] = { diff --git a/packages/sdk-ts/src/core/modules/gov/msgs/MsgVote.spec.ts b/packages/sdk-ts/src/core/modules/gov/msgs/MsgVote.spec.ts index 995514d36..7c5c570bc 100644 --- a/packages/sdk-ts/src/core/modules/gov/msgs/MsgVote.spec.ts +++ b/packages/sdk-ts/src/core/modules/gov/msgs/MsgVote.spec.ts @@ -1,5 +1,5 @@ import MsgVote from './MsgVote.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgVote['params'] = { diff --git a/packages/sdk-ts/src/core/modules/insurance/msgs/MsgCreateInsuranceFund.spec.ts b/packages/sdk-ts/src/core/modules/insurance/msgs/MsgCreateInsuranceFund.spec.ts index 1e3703a59..32627a9f2 100644 --- a/packages/sdk-ts/src/core/modules/insurance/msgs/MsgCreateInsuranceFund.spec.ts +++ b/packages/sdk-ts/src/core/modules/insurance/msgs/MsgCreateInsuranceFund.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgCreateInsuranceFund from './MsgCreateInsuranceFund.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const market = mockFactory.injUsdtDerivativeMarket diff --git a/packages/sdk-ts/src/core/modules/insurance/msgs/MsgRequestRedemption.spec.ts b/packages/sdk-ts/src/core/modules/insurance/msgs/MsgRequestRedemption.spec.ts index 0dfa897b9..bc2f35975 100644 --- a/packages/sdk-ts/src/core/modules/insurance/msgs/MsgRequestRedemption.spec.ts +++ b/packages/sdk-ts/src/core/modules/insurance/msgs/MsgRequestRedemption.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgRequestRedemption from './MsgRequestRedemption.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgRequestRedemption['params'] = { diff --git a/packages/sdk-ts/src/core/modules/insurance/msgs/MsgUnderwrite.spec.ts b/packages/sdk-ts/src/core/modules/insurance/msgs/MsgUnderwrite.spec.ts index b710b29f0..1fe0faf8e 100644 --- a/packages/sdk-ts/src/core/modules/insurance/msgs/MsgUnderwrite.spec.ts +++ b/packages/sdk-ts/src/core/modules/insurance/msgs/MsgUnderwrite.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgUnderwrite from './MsgUnderwrite.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgUnderwrite['params'] = { diff --git a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgClaimVoucher.spec.ts b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgClaimVoucher.spec.ts index 1d83e4109..0cac75922 100644 --- a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgClaimVoucher.spec.ts +++ b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgClaimVoucher.spec.ts @@ -1,6 +1,6 @@ import snakecaseKeys from 'snakecase-keys' import MsgClaimVoucher from './MsgClaimVoucher.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' const params: MsgClaimVoucher['params'] = { sender: mockFactory.injectiveAddress, diff --git a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgCreateNamespace.spec.ts b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgCreateNamespace.spec.ts index 9b2417776..3f75ab941 100644 --- a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgCreateNamespace.spec.ts +++ b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgCreateNamespace.spec.ts @@ -1,6 +1,6 @@ import snakecaseKeys from 'snakecase-keys' import MsgCreateNamespace from './MsgCreateNamespace.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' const params: MsgCreateNamespace['params'] = { sender: mockFactory.injectiveAddress, diff --git a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgDeleteNamespace.spec.ts b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgDeleteNamespace.spec.ts index f6335b345..0e17ffd50 100644 --- a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgDeleteNamespace.spec.ts +++ b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgDeleteNamespace.spec.ts @@ -1,6 +1,6 @@ import snakecaseKeys from 'snakecase-keys' import MsgDeleteNamespace from './MsgDeleteNamespace.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' const params: MsgDeleteNamespace['params'] = { sender: mockFactory.injectiveAddress, diff --git a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgRevokeNamespaceRoles.spec.ts b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgRevokeNamespaceRoles.spec.ts index dbfe9a8f3..420cfcc4d 100644 --- a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgRevokeNamespaceRoles.spec.ts +++ b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgRevokeNamespaceRoles.spec.ts @@ -1,6 +1,6 @@ import snakecaseKeys from 'snakecase-keys' import MsgRevokeNamespaceRoles from './MsgRevokeNamespaceRoles.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' const params: MsgRevokeNamespaceRoles['params'] = { sender: mockFactory.injectiveAddress, diff --git a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateNamespace.spec.ts b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateNamespace.spec.ts index aa3da4519..e33b94aed 100644 --- a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateNamespace.spec.ts +++ b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateNamespace.spec.ts @@ -1,6 +1,6 @@ import snakecaseKeys from 'snakecase-keys' import MsgUpdateNamespace from './MsgUpdateNamespace.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' const params: MsgUpdateNamespace['params'] = { sender: mockFactory.injectiveAddress, diff --git a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateNamespaceRoles.spec.ts b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateNamespaceRoles.spec.ts index bd7fc5b8a..24400b791 100644 --- a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateNamespaceRoles.spec.ts +++ b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateNamespaceRoles.spec.ts @@ -1,6 +1,6 @@ import snakecaseKeys from 'snakecase-keys' import MsgUpdateNamespaceRoles from './MsgUpdateNamespaceRoles.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' const params: MsgUpdateNamespaceRoles['params'] = { sender: mockFactory.injectiveAddress, diff --git a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateParams.spec.ts b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateParams.spec.ts index ef24d3ec2..580b0352c 100644 --- a/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateParams.spec.ts +++ b/packages/sdk-ts/src/core/modules/permissions/msgs/MsgUpdateParams.spec.ts @@ -1,6 +1,6 @@ import snakecaseKeys from 'snakecase-keys' import MsgUpdateParams from './MsgUpdateParams.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' const params: MsgUpdateParams['params'] = { authority: mockFactory.injectiveAddress, diff --git a/packages/sdk-ts/src/core/modules/staking/msgs/MsgBeginRedelegate.spec.ts b/packages/sdk-ts/src/core/modules/staking/msgs/MsgBeginRedelegate.spec.ts index f40baa4c1..02f759f8c 100644 --- a/packages/sdk-ts/src/core/modules/staking/msgs/MsgBeginRedelegate.spec.ts +++ b/packages/sdk-ts/src/core/modules/staking/msgs/MsgBeginRedelegate.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgBeginRedelegate from './MsgBeginRedelegate.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgBeginRedelegate['params'] = { diff --git a/packages/sdk-ts/src/core/modules/staking/msgs/MsgCancelUnbondingDelegation.spec.ts b/packages/sdk-ts/src/core/modules/staking/msgs/MsgCancelUnbondingDelegation.spec.ts index 7949d2845..ffcbcda1c 100644 --- a/packages/sdk-ts/src/core/modules/staking/msgs/MsgCancelUnbondingDelegation.spec.ts +++ b/packages/sdk-ts/src/core/modules/staking/msgs/MsgCancelUnbondingDelegation.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgCancelUnbondingDelegation from './MsgCancelUnbondingDelegation.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCancelUnbondingDelegation['params'] = { diff --git a/packages/sdk-ts/src/core/modules/staking/msgs/MsgDelegate.spec.ts b/packages/sdk-ts/src/core/modules/staking/msgs/MsgDelegate.spec.ts index ed81ab592..6b7103ebd 100644 --- a/packages/sdk-ts/src/core/modules/staking/msgs/MsgDelegate.spec.ts +++ b/packages/sdk-ts/src/core/modules/staking/msgs/MsgDelegate.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgDelegate from './MsgDelegate.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgDelegate['params'] = { diff --git a/packages/sdk-ts/src/core/modules/staking/msgs/MsgEditValidator.spec.ts b/packages/sdk-ts/src/core/modules/staking/msgs/MsgEditValidator.spec.ts index 74d03f1d6..c5245772b 100644 --- a/packages/sdk-ts/src/core/modules/staking/msgs/MsgEditValidator.spec.ts +++ b/packages/sdk-ts/src/core/modules/staking/msgs/MsgEditValidator.spec.ts @@ -1,5 +1,5 @@ import MsgEditValidator from './MsgEditValidator.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgEditValidator['params'] = { diff --git a/packages/sdk-ts/src/core/modules/staking/msgs/MsgUndelegate.spec.ts b/packages/sdk-ts/src/core/modules/staking/msgs/MsgUndelegate.spec.ts index 3316beae4..5673c5f5a 100644 --- a/packages/sdk-ts/src/core/modules/staking/msgs/MsgUndelegate.spec.ts +++ b/packages/sdk-ts/src/core/modules/staking/msgs/MsgUndelegate.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgUndelegate from './MsgUndelegate.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgUndelegate['params'] = { diff --git a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgBurn.spec.ts b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgBurn.spec.ts index 47199ff82..e8d5eba4b 100644 --- a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgBurn.spec.ts +++ b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgBurn.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgBurn from './MsgBurn.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgBurn['params'] = { diff --git a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgChangeAdmin.spec.ts b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgChangeAdmin.spec.ts index a5e12c8c3..cf1c7e3ab 100644 --- a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgChangeAdmin.spec.ts +++ b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgChangeAdmin.spec.ts @@ -1,5 +1,5 @@ import MsgChangeAdmin from './MsgChangeAdmin.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgChangeAdmin['params'] = { diff --git a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgCreateDenom.spec.ts b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgCreateDenom.spec.ts index 9c988ec23..1a8a69822 100644 --- a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgCreateDenom.spec.ts +++ b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgCreateDenom.spec.ts @@ -1,5 +1,5 @@ import MsgCreateDenom from './MsgCreateDenom.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgCreateDenom['params'] = { diff --git a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgMint.spec.ts b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgMint.spec.ts index e718c9eff..e23b78500 100644 --- a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgMint.spec.ts +++ b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgMint.spec.ts @@ -1,6 +1,6 @@ import { BigNumberInBase } from '@injectivelabs/utils' import MsgMint from './MsgMint.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgMint['params'] = { diff --git a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgSetDenomMetadata.spec.ts b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgSetDenomMetadata.spec.ts index 2a91dae4a..301a7459a 100644 --- a/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgSetDenomMetadata.spec.ts +++ b/packages/sdk-ts/src/core/modules/tokenfactory/msgs/MsgSetDenomMetadata.spec.ts @@ -1,5 +1,5 @@ import MsgSetDenomMetadata from './MsgSetDenomMetadata.js' -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import snakecaseKeys from 'snakecase-keys' const params: MsgSetDenomMetadata['params'] = { diff --git a/packages/sdk-ts/src/core/tx/api/TxGrpcApi.ts b/packages/sdk-ts/src/core/tx/api/TxGrpcApi.ts index ef277fc48..6a53c95b2 100644 --- a/packages/sdk-ts/src/core/tx/api/TxGrpcApi.ts +++ b/packages/sdk-ts/src/core/tx/api/TxGrpcApi.ts @@ -4,9 +4,10 @@ import { TxClientBroadcastResponse, } from '../types/tx.js' import { + GeneralException, TransactionException, + grpcErrorCodeToErrorCode, GrpcUnaryRequestException, - GeneralException, } from '@injectivelabs/exceptions' import { BigNumberInBase, @@ -76,7 +77,7 @@ export class TxGrpcApi implements TxConcreteApi { // Failed to query the transaction on the chain if (e instanceof CosmosTxV1Beta1Service.GrpcWebError) { throw new GrpcUnaryRequestException(new Error(e.toString()), { - code: e.code, + code: grpcErrorCodeToErrorCode(e.code), }) } diff --git a/packages/sdk-ts/src/core/tx/broadcaster/MsgBroadcasterWithPk.spec.ts b/packages/sdk-ts/src/core/tx/broadcaster/MsgBroadcasterWithPk.spec.ts index 6524fe08a..22f1c2929 100644 --- a/packages/sdk-ts/src/core/tx/broadcaster/MsgBroadcasterWithPk.spec.ts +++ b/packages/sdk-ts/src/core/tx/broadcaster/MsgBroadcasterWithPk.spec.ts @@ -4,7 +4,8 @@ import { MsgSend } from '../../modules/bank/index.js' import { MsgBroadcasterWithPk } from './MsgBroadcasterWithPk.js' import { EthereumChainId } from '@injectivelabs/ts-types' -describe('MsgBroadcasterWithPk', () => { +// TODO +describe.skip('MsgBroadcasterWithPk', () => { test('prepares, simulates, signs and broadcasts a transaction', async () => { const privateKey = PrivateKey.fromHex( process.env.TEST_PRIVATE_KEY as string, diff --git a/packages/sdk-ts/src/core/tx/eip712/eip712.spec.ts b/packages/sdk-ts/src/core/tx/eip712/eip712.spec.ts index c6a3fb06e..adb4a4a46 100644 --- a/packages/sdk-ts/src/core/tx/eip712/eip712.spec.ts +++ b/packages/sdk-ts/src/core/tx/eip712/eip712.spec.ts @@ -1,4 +1,4 @@ -import { mockFactory } from '@injectivelabs/test-utils' +import { mockFactory } from '@injectivelabs/utils/test-utils' import { BigNumberInBase, DEFAULT_STD_FEE } from '@injectivelabs/utils' import { MsgSend } from '@injectivelabs/sdk-ts' import { getEip712TypedDataV2 } from './eip712.js' diff --git a/packages/sdk-ts/src/utils/address.ts b/packages/sdk-ts/src/utils/address.ts index f5b459318..8924092e5 100644 --- a/packages/sdk-ts/src/utils/address.ts +++ b/packages/sdk-ts/src/utils/address.ts @@ -103,3 +103,9 @@ export const getChecksumAddress = (ethAddress: string) => { export const isCw20ContractAddress = (address: string) => address.length === 42 && address.startsWith('inj') + +export const addHexPrefix = (hex: string) => + hex.startsWith('0x') ? hex : `0x${hex}` + +export const removeHexPrefix = (hex: string) => + hex.startsWith('0x') ? hex.slice(2) : hex diff --git a/packages/sdk-ts/src/utils/crypto.ts b/packages/sdk-ts/src/utils/crypto.ts index 06a91a3b9..a98cc1c36 100644 --- a/packages/sdk-ts/src/utils/crypto.ts +++ b/packages/sdk-ts/src/utils/crypto.ts @@ -1,27 +1,31 @@ -import SHA256 from 'crypto-js/sha256' -import RIPEMD160 from 'crypto-js/ripemd160' -import Base64 from 'crypto-js/enc-base64' -import * as secp256k1 from 'secp256k1' +// import CryptoEs from 'crypto-es' +import CryptoEs from 'crypto-js' +import { secp256k1 } from '@noble/curves/secp256k1' +import keccak256 from 'keccak256' import { SignTypedDataVersion, TypedDataUtils } from '@metamask/eth-sig-util' export const hashToHex = (data: string): string => { - return SHA256(Base64.parse(data)).toString().toUpperCase() + return CryptoEs.SHA256(CryptoEs.enc.Base64.parse(data)) + .toString() + .toUpperCase() } export const sha256 = (data: Uint8Array): Uint8Array => { - const dataInUtf8 = Buffer.from(data).toString('utf-8') + const wordArray = CryptoEs.lib.WordArray.create(data) + const hash = CryptoEs.SHA256(wordArray) - return Uint8Array.from(Buffer.from(SHA256(dataInUtf8).toString(), 'hex')) + return Uint8Array.from(Buffer.from(hash.toString(), 'hex')) } export const ripemd160 = (data: Uint8Array): Uint8Array => { - const dataInUtf8 = Buffer.from(data).toString('utf-8') + const wordArray = CryptoEs.lib.WordArray.create(data) + const hash = CryptoEs.RIPEMD160(wordArray) - return Uint8Array.from(Buffer.from(RIPEMD160(dataInUtf8).toString(), 'hex')) + return Uint8Array.from(Buffer.from(hash.toString(), 'hex')) } export const privateKeyToPublicKey = (privateKey: Uint8Array): Uint8Array => { - return secp256k1.publicKeyCreate(privateKey, true) + return secp256k1.getPublicKey(privateKey, true) } export const privateKeyHashToPublicKey = ( @@ -31,7 +35,7 @@ export const privateKeyHashToPublicKey = ( ? privateKeyHash.slice(2) : privateKeyHash - return secp256k1.publicKeyCreate(Buffer.from(privateKey, 'hex'), true) + return secp256k1.getPublicKey(Buffer.from(privateKey, 'hex'), true) } export const privateKeyToPublicKeyBase64 = (privateKey: Uint8Array): string => { @@ -71,17 +75,34 @@ export function hexToUnit8Array(str: string) { } export function decompressPubKey(startsWith02Or03: string) { - // if already decompressed an not has trailing 04 const testBuffer = Buffer.from(startsWith02Or03, 'hex') if (testBuffer.length === 64) startsWith02Or03 = '04' + startsWith02Or03 - let decompressed = uint8ArrayToHex( - secp256k1.publicKeyConvert(hexToUnit8Array(startsWith02Or03), false), + const point = secp256k1.ProjectivePoint.fromHex( + Buffer.from(testBuffer).toString('hex'), ) - // remove trailing 04 - decompressed = decompressed.substring(2) + const decompressed = point.toHex(false) - return decompressed + if (!decompressed.startsWith('04')) return decompressed + + return decompressed.slice(2) +} + +export const publicKeyToAddress = function ( + pubKey: Uint8Array, + sanitize: boolean = false, +): Uint8Array { + if (sanitize && pubKey.length !== 64) { + pubKey = secp256k1.ProjectivePoint.fromHex(pubKey) + .toRawBytes(false) + .slice(1) + } + + if (pubKey.length !== 64) { + throw new Error('Expected pubKey to be of length 64') + } + + return keccak256(Buffer.from(pubKey)).subarray(-20) } diff --git a/packages/sdk-ts/tsconfig.build.esm.json b/packages/sdk-ts/tsconfig.build.esm.json index a7b22cee7..16628b192 100644 --- a/packages/sdk-ts/tsconfig.build.esm.json +++ b/packages/sdk-ts/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../.build-cache/sdk-ts.esm.tsbuildinfo" } } diff --git a/packages/sdk-ts/tsconfig.build.json b/packages/sdk-ts/tsconfig.build.json index d81c19433..ab0f5a25f 100644 --- a/packages/sdk-ts/tsconfig.build.json +++ b/packages/sdk-ts/tsconfig.build.json @@ -2,14 +2,11 @@ "extends": "../../tsconfig.build.json", "compilerOptions": { "rootDir": "./src", + "module": "commonjs", + "moduleResolution": "node", "outDir": "./dist/cjs", - "tsBuildInfoFile": "../../.build-cache/sdk-ts.tsbuildinfo", + "tsBuildInfoFile": "../../.build-cache/sdk-ts.tsbuildinfo" }, - "include": [ - "./src/**/*.ts" - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/test-utils/CHANGELOG.md b/packages/test-utils/CHANGELOG.md deleted file mode 100644 index 82fce610c..000000000 --- a/packages/test-utils/CHANGELOG.md +++ /dev/null @@ -1,352 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. - -## [1.14.33](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.33-beta.1...@injectivelabs/test-utils@1.14.33) (2024-11-29) - -**Note:** Version bump only for package @injectivelabs/test-utils - - - - - -## [1.14.32](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.30...@injectivelabs/test-utils@1.14.32) (2024-11-25) - -**Note:** Version bump only for package @injectivelabs/test-utils - - - - - -## [1.14.30](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.21...@injectivelabs/test-utils@1.14.30) (2024-11-25) - - -### Bug Fixes - -* version ([24f63c9](https://github.com/InjectiveLabs/injective-ts/commit/24f63c9d175507982ac77ce24e5cbce4cab96804)) - - - - - -## [1.14.21](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.20...@injectivelabs/test-utils@1.14.21) (2024-11-25) - -**Note:** Version bump only for package @injectivelabs/test-utils - - - - - -## [1.14.20](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.19...@injectivelabs/test-utils@1.14.20) (2024-11-25) - -**Note:** Version bump only for package @injectivelabs/test-utils - - - - - -## [1.14.19](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.17...@injectivelabs/test-utils@1.14.19) (2024-11-11) - -**Note:** Version bump only for package @injectivelabs/test-utils - - - - - -## [1.14.17](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.17-beta.2...@injectivelabs/test-utils@1.14.17) (2024-11-11) - -**Note:** Version bump only for package @injectivelabs/test-utils - - - - - -## [1.14.16](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.16-beta.0...@injectivelabs/test-utils@1.14.16) (2024-10-29) - -**Note:** Version bump only for package @injectivelabs/test-utils - - - - - -## [1.14.15](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.15-beta.0...@injectivelabs/test-utils@1.14.15) (2024-10-29) - -**Note:** Version bump only for package @injectivelabs/test-utils - - - - - -## [1.14.14](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.14-dev.0...@injectivelabs/test-utils@1.14.14) (2024-09-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.14.13](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.13-beta.0...@injectivelabs/test-utils@1.14.13) (2024-07-02) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.14.6](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.6-beta.0...@injectivelabs/test-utils@1.14.6) (2024-06-18) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.14.5](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.5-beta.2...@injectivelabs/test-utils@1.14.5) (2024-06-10) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.14.4](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.4-beta.2...@injectivelabs/test-utils@1.14.4) (2024-03-01) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.14.3](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.3-beta.0...@injectivelabs/test-utils@1.14.3) (2023-11-20) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.14.2](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.2-beta.0...@injectivelabs/test-utils@1.14.2) (2023-11-17) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.14.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.1-beta.5...@injectivelabs/test-utils@1.14.1) (2023-10-27) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.14.1-beta.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.0-beta.1...@injectivelabs/test-utils@1.14.1-beta.0) (2023-09-23) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.14.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.14.0-beta.1...@injectivelabs/test-utils@1.14.0) (2023-09-22) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.14.0-beta.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.13.1-beta.1...@injectivelabs/test-utils@1.14.0-beta.1) (2023-09-22) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.13.1-beta.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.13.0...@injectivelabs/test-utils@1.13.1-beta.1) (2023-09-22) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.13.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.12.1...@injectivelabs/test-utils@1.13.0) (2023-09-22) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.12.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.12.0...@injectivelabs/test-utils@1.12.1) (2023-08-31) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.12.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.12.0-beta.1...@injectivelabs/test-utils@1.12.0) (2023-08-31) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.12.0-beta.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.2-beta.0...@injectivelabs/test-utils@1.12.0-beta.1) (2023-05-31) - -### Bug Fixes - -- versions ([b7770bf](https://github.com/InjectiveLabs/injective-ts/commit/b7770bf382619115063ecdee2a9bd39b520e70de)) - -## [1.11.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.1-beta.1...@injectivelabs/test-utils@1.11.1) (2023-05-30) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.11.1-beta.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.1-beta.0...@injectivelabs/test-utils@1.11.1-beta.1) (2023-05-30) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.11.1-beta.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.10...@injectivelabs/test-utils@1.11.1-beta.0) (2023-05-29) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.10...@injectivelabs/test-utils@1.11.0) (2023-05-29) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.10](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.9...@injectivelabs/test-utils@1.11.0-beta.10) (2023-05-29) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.9](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.0...@injectivelabs/test-utils@1.11.0-beta.9) (2023-05-28) - -### Bug Fixes - -- change log ([e039b61](https://github.com/InjectiveLabs/injective-ts/commit/e039b6173a1037bafb026c71f82cb08a073fad6a)) -- package version ([f861fbf](https://github.com/InjectiveLabs/injective-ts/commit/f861fbf21f5f78d1b840930a67b05c578087a3b8)) - -# [1.11.0-beta.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.0...@injectivelabs/test-utils@1.11.0-beta.1) (2023-05-28) - -### Bug Fixes - -- change log ([e039b61](https://github.com/InjectiveLabs/injective-ts/commit/e039b6173a1037bafb026c71f82cb08a073fad6a)) - -# [1.11.0-beta.8](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.7...@injectivelabs/test-utils@1.11.0-beta.8) (2023-05-26) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.7](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.6...@injectivelabs/test-utils@1.11.0-beta.7) (2023-05-26) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.6](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.5...@injectivelabs/test-utils@1.11.0-beta.6) (2023-05-26) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.5](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.4...@injectivelabs/test-utils@1.11.0-beta.5) (2023-05-26) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.4](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.3...@injectivelabs/test-utils@1.11.0-beta.4) (2023-05-26) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.3](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.2...@injectivelabs/test-utils@1.11.0-beta.3) (2023-05-26) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.2](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.11.0-beta.1...@injectivelabs/test-utils@1.11.0-beta.2) (2023-05-26) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.11.0-beta.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.13-beta.3...@injectivelabs/test-utils@1.11.0-beta.1) (2023-05-26) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.13-beta.3](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.13-beta.2...@injectivelabs/test-utils@1.10.13-beta.3) (2023-05-10) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.13-beta.2](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.13-beta.1...@injectivelabs/test-utils@1.10.13-beta.2) (2023-05-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.13-beta.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.13-beta.0...@injectivelabs/test-utils@1.10.13-beta.1) (2023-05-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.13-beta.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.12...@injectivelabs/test-utils@1.10.13-beta.0) (2023-05-05) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.12](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.11...@injectivelabs/test-utils@1.10.12) (2023-04-30) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.11](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.4...@injectivelabs/test-utils@1.10.11) (2023-04-30) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.4](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.4-beta.0...@injectivelabs/test-utils@1.10.4) (2023-04-30) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.4-beta.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.3...@injectivelabs/test-utils@1.10.4-beta.0) (2023-04-28) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.3](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.2...@injectivelabs/test-utils@1.10.3) (2023-04-18) - -### Bug Fixes - -- build script ([6e8c15f](https://github.com/InjectiveLabs/injective-ts/commit/6e8c15f5d0c0d61e15766abb6217f3fa34cdf791)) - -## [1.10.2](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.1...@injectivelabs/test-utils@1.10.2) (2023-04-15) - -### Bug Fixes - -- script minor ([adb7c76](https://github.com/InjectiveLabs/injective-ts/commit/adb7c764ad00a0cfa38223cecf9b221873cd31b8)) - -## [1.10.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.1-alpha.0...@injectivelabs/test-utils@1.10.1) (2023-04-04) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.10.1-alpha.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.0...@injectivelabs/test-utils@1.10.1-alpha.0) (2023-04-04) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.10.0](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.0-alpha.1...@injectivelabs/test-utils@1.10.0) (2023-03-23) - -**Note:** Version bump only for package @injectivelabs/test-utils - -# [1.10.0-alpha.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.10.0-alpha.0...@injectivelabs/test-utils@1.10.0-alpha.1) (2023-03-17) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.19](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.18...@injectivelabs/test-utils@1.0.19) (2023-03-15) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.18](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.17...@injectivelabs/test-utils@1.0.18) (2023-03-15) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.17](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.16...@injectivelabs/test-utils@1.0.17) (2023-03-15) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.16](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.15...@injectivelabs/test-utils@1.0.16) (2023-01-12) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.15](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.14...@injectivelabs/test-utils@1.0.15) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.14](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.13...@injectivelabs/test-utils@1.0.14) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.13](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.12...@injectivelabs/test-utils@1.0.13) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.12](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.11...@injectivelabs/test-utils@1.0.12) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.11](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.10...@injectivelabs/test-utils@1.0.11) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.10](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.9...@injectivelabs/test-utils@1.0.10) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.9](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.8...@injectivelabs/test-utils@1.0.9) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.8](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.7...@injectivelabs/test-utils@1.0.8) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.7](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.6...@injectivelabs/test-utils@1.0.7) (2023-01-09) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.6](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.5...@injectivelabs/test-utils@1.0.6) (2022-11-14) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.5](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.4...@injectivelabs/test-utils@1.0.5) (2022-11-14) - -### Features - -- bridge-ts initial ([4320b1c](https://github.com/InjectiveLabs/injective-ts/commit/4320b1c256b58caec7a08c33854f0bdde9681c3c)) - -## [1.0.4](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.3...@injectivelabs/test-utils@1.0.4) (2022-11-06) - -**Note:** Version bump only for package @injectivelabs/test-utils - -## [1.0.3](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@1.0.2...@injectivelabs/test-utils@1.0.3) (2022-09-15) - -### Features - -- add unit test for remaining eip 712 messages ([#77](https://github.com/InjectiveLabs/injective-ts/issues/77)) ([2584aa0](https://github.com/InjectiveLabs/injective-ts/commit/2584aa09eb3f410f911509a23aca753ba696d773)) - -## [1.0.2](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@0.5.0...@injectivelabs/test-utils@1.0.2) (2022-09-14) - -### Features - -- add unit test coverage for eip712 messages ([#75](https://github.com/InjectiveLabs/injective-ts/issues/75)) ([cf7e2fd](https://github.com/InjectiveLabs/injective-ts/commit/cf7e2fde727979fcf2187385d72b96efbed6d61a)) - -## [1.0.1](https://github.com/InjectiveLabs/injective-ts/compare/@injectivelabs/test-utils@0.5.0...@injectivelabs/test-utils@1.0.1) (2022-09-14) - -**Note:** Version bump only for package @injectivelabs/test-utils diff --git a/packages/test-utils/README.md b/packages/test-utils/README.md deleted file mode 100644 index e9bcc07cd..000000000 --- a/packages/test-utils/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# 🌟 Injective Protocol - Testing Utils - -Utilities and mock data for testing purposes. - ---- - -## 📚 Installation - -```bash -yarn add @injectivelabs/test-utils -``` - ---- - -## ⛑ Support - -Reach out to us at one of the following places! - -- Website at `injective.com` -- Twitter at `@Injective` -- Discord at `Discord` -- Telegram at `Telegram` - ---- - -## 🔓 License - -Copyright © 2021 - 2022 Injective Labs Inc. (https://injectivelabs.org/) - - - -Originally released by Injective Labs Inc. under:
-Apache License
-Version 2.0, January 2004
-http://www.apache.org/licenses/ - - -

 

-
- Powering the future of decentralized finance. -
diff --git a/packages/test-utils/package.json b/packages/test-utils/package.json deleted file mode 100644 index 72972f863..000000000 --- a/packages/test-utils/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "@injectivelabs/test-utils", - "description": "List of test-utils and helper functions that can be reused throughout Injective's projects.", - "version": "1.14.34-beta.3", - "sideEffects": false, - "author": { - "name": "InjectiveLabs", - "email": "admin@injectivelabs.org" - }, - "license": "Apache-2.0", - "types": "dist/cjs/index.d.ts", - "main": "dist/cjs/index.js", - "module": "dist/esm/index.js", - "files": [ - "dist" - ], - "exports": { - ".": { - "react-native": { - "import": "./dist/esm/index.js", - "require": "./dist/cjs/index.js", - "types": "./dist/cjs/index.d.ts", - "default": "./dist/cjs/index.js" - }, - "require": { - "types": "./dist/cjs/index.d.ts", - "default": "./dist/cjs/index.js" - }, - "import": { - "types": "./dist/esm/index.d.ts", - "default": "./dist/esm/index.js" - }, - "default": { - "types": "./dist/cjs/index.d.ts", - "default": "./dist/cjs/index.js" - } - } - }, - "_moduleAliases": { - "~test-utils": "dist" - }, - "scripts": { - "build": "yarn build:cjs && yarn build:esm && yarn build:post", - "build:cjs": "tsc --build --force tsconfig.build.json", - "build:esm": "tsc --build --force tsconfig.build.esm.json", - "build:watch": "tsc --build -w tsconfig.build.json && tsc -w --build tsconfig.build.esm.json && yarn build:post", - "build:post": "shx cp ../../etc/stub/package.json.stub dist/cjs/package.json && shx cp ../../etc/stub/package.esm.json.stub dist/esm/package.json", - "clean": "tsc --build tsconfig.build.json --clean && tsc --build tsconfig.build.esm.json --clean && shx rm -rf coverage *.log junit.xml dist && jest --clearCache && shx mkdir -p dist", - "test": "jest", - "test:watch": "jest --watch", - "test:ci": "jest --coverage --ci --reporters='jest-junit'", - "coverage": "jest --coverage", - "coverage:show": "live-server coverage", - "dev": "ts-node -r tsconfig-paths/register src/index.ts", - "start": "node dist/index.js" - }, - "dependencies": { - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/networks": "^1.14.34-beta.0", - "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "axios": "^1.6.4", - "bignumber.js": "^9.0.1", - "shx": "^0.3.2", - "snakecase-keys": "^5.1.2", - "store2": "^2.12.0" - }, - "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" -} diff --git a/packages/test-utils/tsconfig.build.esm.json b/packages/test-utils/tsconfig.build.esm.json deleted file mode 100644 index 66996135f..000000000 --- a/packages/test-utils/tsconfig.build.esm.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "./tsconfig.build.json", - "compilerOptions": { - "module": "ESNext", - "outDir": "./dist/esm", - "rootDir": "./src", - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "target": "ESNext", - "moduleResolution": "Bundler", - "tsBuildInfoFile": "../../.build-cache/test-utils.esm.tsbuildinfo" - } -} diff --git a/packages/test-utils/tsconfig.build.json b/packages/test-utils/tsconfig.build.json deleted file mode 100644 index 1123555a3..000000000 --- a/packages/test-utils/tsconfig.build.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../tsconfig.build.json", - "compilerOptions": { - "rootDir": "./src", - "outDir": "./dist/cjs", - "tsBuildInfoFile": "../../.build-cache/test-utils.tsbuildinfo" - }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] -} diff --git a/packages/test-utils/tsconfig.json b/packages/test-utils/tsconfig.json deleted file mode 100644 index 6f83eb665..000000000 --- a/packages/test-utils/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../../tsconfig.json", -} diff --git a/packages/ts-types/jest.config.js b/packages/ts-types/jest.config.js index 95cbf1481..9679ba054 100644 --- a/packages/ts-types/jest.config.js +++ b/packages/ts-types/jest.config.js @@ -1,6 +1,6 @@ -const baseConfig = require('../../jest.config.js') +import baseConfig from '../../jest.config.js' -module.exports = { +export default { ...baseConfig, globals: { 'ts-jest': { diff --git a/packages/ts-types/package.json b/packages/ts-types/package.json index 35e72fa0f..bae527db2 100644 --- a/packages/ts-types/package.json +++ b/packages/ts-types/package.json @@ -4,6 +4,7 @@ "version": "1.14.33", "sideEffects": false, "license": "Apache-2.0", + "type": "module", "types": "dist/cjs/index.d.ts", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", @@ -54,7 +55,7 @@ "dev": "ts-node -r tsconfig-paths/register src/index.ts", "start": "node dist/index.js" }, - "dependencies": { + "devDependencies": { "shx": "^0.3.2" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" diff --git a/packages/ts-types/tsconfig.build.esm.json b/packages/ts-types/tsconfig.build.esm.json index 2b7c526d7..89305a3ed 100644 --- a/packages/ts-types/tsconfig.build.esm.json +++ b/packages/ts-types/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../.build-cache/ts-types.esm.tsbuildinfo" } } diff --git a/packages/ts-types/tsconfig.build.json b/packages/ts-types/tsconfig.build.json index 2318a9e2d..d69770163 100644 --- a/packages/ts-types/tsconfig.build.json +++ b/packages/ts-types/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../.build-cache/ts-types.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ], + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/utils/jest.config.js b/packages/utils/jest.config.js index 95cbf1481..9679ba054 100644 --- a/packages/utils/jest.config.js +++ b/packages/utils/jest.config.js @@ -1,6 +1,6 @@ -const baseConfig = require('../../jest.config.js') +import baseConfig from '../../jest.config.js' -module.exports = { +export default { ...baseConfig, globals: { 'ts-jest': { diff --git a/packages/utils/package.json b/packages/utils/package.json index eb93f3976..913aad541 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -3,6 +3,7 @@ "description": "List of utils and helper functions that can be reused throughout Injective's projects.", "version": "1.14.34-beta.0", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -34,6 +35,26 @@ "types": "./dist/cjs/index.d.ts", "default": "./dist/cjs/index.js" } + }, + "./test-utils": { + "react-native": { + "import": "./dist/esm/test-utils/index.js", + "require": "./dist/cjs/test-utils/index.js", + "types": "./dist/cjs/test-utils/index.d.ts", + "default": "./dist/cjs/test-utils/index.js" + }, + "require": { + "types": "./dist/cjs/test-utils/index.d.ts", + "default": "./dist/cjs/test-utils/index.js" + }, + "import": { + "types": "./dist/esm/test-utils/index.d.ts", + "default": "./dist/esm/test-utils/index.js" + }, + "default": { + "types": "./dist/cjs/test-utils/index.d.ts", + "default": "./dist/cjs/test-utils/index.js" + } } }, "_moduleAliases": { @@ -55,14 +76,16 @@ "start": "node dist/index.js" }, "dependencies": { - "@injectivelabs/exceptions": "^1.14.34-beta.0", + "@injectivelabs/exceptions": "^1.14.33", + "@injectivelabs/networks": "^1.14.33", "@injectivelabs/ts-types": "^1.14.33", "axios": "^1.6.4", "bignumber.js": "^9.0.1", "http-status-codes": "^2.2.0", - "shx": "^0.3.2", - "snakecase-keys": "^5.1.2", - "store2": "^2.12.0" + "store2": "^2.14.3" + }, + "devDependencies": { + "shx": "^0.3.2" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" } diff --git a/packages/utils/src/classes/LocalStorage.ts b/packages/utils/src/classes/LocalStorage.ts index 8949117bb..a1617f17d 100644 --- a/packages/utils/src/classes/LocalStorage.ts +++ b/packages/utils/src/classes/LocalStorage.ts @@ -1,4 +1,4 @@ -import store, { StoreAPI } from 'store2' +import { store, StoreAPI } from 'store2' export default class LocalStorage { private storage: StoreAPI diff --git a/packages/utils/src/helpers.ts b/packages/utils/src/helpers.ts index d1977dde6..11b0379a4 100644 --- a/packages/utils/src/helpers.ts +++ b/packages/utils/src/helpers.ts @@ -1,4 +1,3 @@ -import BigNumber from 'bignumber.js' import { DEFAULT_STD_FEE, DEFAULT_GAS_LIMIT, @@ -78,7 +77,9 @@ export const getStdFeeForToken = ( const gasPriceScaled = new BigNumberInBase(gasPriceInBase) .toWei(token.decimals) .toFixed(0) - const gasNormalized = new BigNumber(gasLimit || DEFAULT_GAS_LIMIT).toFixed(0) + const gasNormalized = new BigNumberInBase( + gasLimit || DEFAULT_GAS_LIMIT, + ).toFixed(0) return { amount: [ @@ -111,19 +112,19 @@ export const getStdFeeFromObject = (args?: { granter, feePayer, } = args - const gasNormalized = new BigNumber(gas).toFixed(0) - const gasPriceNormalized = new BigNumber(gasPrice).toFixed(0) + const gasNormalized = new BigNumberInBase(gas).toFixed(0) + const gasPriceNormalized = new BigNumberInBase(gasPrice).toFixed(0) return { amount: [ { denom: 'inj', - amount: new BigNumber(gasNormalized) + amount: new BigNumberInBase(gasNormalized) .times(gasPriceNormalized) .toFixed(), }, ], - gas: new BigNumber(gasNormalized).toFixed(), + gas: new BigNumberInBase(gasNormalized).toFixed(), payer /** for Web3Gateway fee delegation */, granter, feePayer, diff --git a/packages/test-utils/src/index.ts b/packages/utils/src/test-utils/index.ts similarity index 100% rename from packages/test-utils/src/index.ts rename to packages/utils/src/test-utils/index.ts diff --git a/packages/test-utils/src/mocks/index.ts b/packages/utils/src/test-utils/mocks/index.ts similarity index 100% rename from packages/test-utils/src/mocks/index.ts rename to packages/utils/src/test-utils/mocks/index.ts diff --git a/packages/test-utils/src/msgs.ts b/packages/utils/src/test-utils/msgs.ts similarity index 92% rename from packages/test-utils/src/msgs.ts rename to packages/utils/src/test-utils/msgs.ts index 555e0e0f7..71decfe09 100644 --- a/packages/test-utils/src/msgs.ts +++ b/packages/utils/src/test-utils/msgs.ts @@ -1,8 +1,5 @@ -import { - BigNumber, - DEFAULT_GAS_LIMIT, - DEFAULT_GAS_PRICE, -} from '@injectivelabs/utils' +import { DEFAULT_GAS_LIMIT, DEFAULT_GAS_PRICE } from '../constants.js' +import { BigNumberInBase } from '../classes/index.js' import { Network, getNetworkInfo, @@ -75,7 +72,7 @@ export const prepareEip712 = ({ amount: [ { denom: 'inj', - amount: new BigNumber(gas.toString()) + amount: new BigNumberInBase(gas.toString()) .times(DEFAULT_GAS_PRICE) .toFixed(), }, diff --git a/packages/utils/tsconfig.build.esm.json b/packages/utils/tsconfig.build.esm.json index 1622eaf85..184b4394b 100644 --- a/packages/utils/tsconfig.build.esm.json +++ b/packages/utils/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../.build-cache/utils.esm.tsbuildinfo" } } diff --git a/packages/utils/tsconfig.build.json b/packages/utils/tsconfig.build.json index 93e3af8be..d04ade507 100644 --- a/packages/utils/tsconfig.build.json +++ b/packages/utils/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../.build-cache/utils.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallet-ts/.npmignore b/packages/wallet-ts/.npmignore deleted file mode 100644 index 48ac5271b..000000000 --- a/packages/wallet-ts/.npmignore +++ /dev/null @@ -1,8 +0,0 @@ -# Blacklist all files -.* -* -src - -# Whitelist dist -!dist/**/*.d.ts -!dist/**/*.js diff --git a/packages/wallet-ts/LICENSE b/packages/wallet-ts/LICENSE deleted file mode 100644 index 52bccb7e3..000000000 --- a/packages/wallet-ts/LICENSE +++ /dev/null @@ -1,203 +0,0 @@ -Copyright © 2021 - 2022 Injective Labs Inc. (https://injectivelabs.org/) - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [2022] [InjectiveLabs] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/packages/wallet-ts/jest.config.js b/packages/wallet-ts/jest.config.js deleted file mode 100644 index 95cbf1481..000000000 --- a/packages/wallet-ts/jest.config.js +++ /dev/null @@ -1,10 +0,0 @@ -const baseConfig = require('../../jest.config.js') - -module.exports = { - ...baseConfig, - globals: { - 'ts-jest': { - tsConfig: 'tsconfig.build.esm.json', - }, - }, -} diff --git a/packages/wallets/wallet-base/package.json b/packages/wallets/wallet-base/package.json index 047bbbc87..e9177df56 100644 --- a/packages/wallets/wallet-base/package.json +++ b/packages/wallets/wallet-base/package.json @@ -3,6 +3,7 @@ "description": "Base wallet strategy for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -55,30 +56,14 @@ "start": "node dist/index.js" }, "dependencies": { - "@ethereumjs/common": "^3.1.1", - "@ethereumjs/tx": "^4.1.1", - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/networks": "^1.14.34-beta.0", - "@injectivelabs/sdk-ts": "^1.14.34-beta.5", + "@injectivelabs/exceptions": "^1.14.33", + "@injectivelabs/sdk-ts": "^1.14.34-beta.4", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "alchemy-sdk": "^3.4.7", - "eip1193-provider": "^1.0.1", - "eth-sig-util": "^3.0.1", - "ethereumjs-util": "^7.1.0", - "ethers": "^6.5.1", - "hdkey": "^2.0.1", - "long": "^5.2.1", - "shx": "^0.3.3" + "@injectivelabs/utils": "^1.14.33", + "eip1193-provider": "^1.0.1" }, "devDependencies": { - "@types/eth-sig-util": "^2.1.1", - "@types/ethereumjs-util": "^6.1.0", - "@types/hdkey": "^2.0.1" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" + "shx": "^0.3.3" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" } diff --git a/packages/wallets/wallet-base/src/types/enums.ts b/packages/wallets/wallet-base/src/types/enums.ts index cbfb99842..500188534 100644 --- a/packages/wallets/wallet-base/src/types/enums.ts +++ b/packages/wallets/wallet-base/src/types/enums.ts @@ -5,7 +5,6 @@ export enum Wallet { Keplr = 'keplr', Ninji = 'ninji', Magic = 'magic', - Torus = 'torus', Ledger = 'ledger', BitGet = 'BitGet', Trezor = 'trezor', diff --git a/packages/wallets/wallet-base/src/types/provider.ts b/packages/wallets/wallet-base/src/types/provider.ts index 0cf98d34e..8268a5f85 100644 --- a/packages/wallets/wallet-base/src/types/provider.ts +++ b/packages/wallets/wallet-base/src/types/provider.ts @@ -1,6 +1,6 @@ -import Eip1993Provider from 'eip1193-provider' +import { type EIP1193Provider } from 'eip1193-provider' -export interface BrowserEip1993Provider extends Eip1993Provider { +export interface BrowserEip1993Provider extends EIP1193Provider { removeAllListeners(): void isMetaMask: boolean isTrustWallet: boolean diff --git a/packages/wallets/wallet-base/src/types/strategy.ts b/packages/wallets/wallet-base/src/types/strategy.ts index 13a3a85ab..1a0eeb328 100644 --- a/packages/wallets/wallet-base/src/types/strategy.ts +++ b/packages/wallets/wallet-base/src/types/strategy.ts @@ -13,7 +13,7 @@ import type { import { StdSignDoc } from '@keplr-wallet/types' import { WalletDeviceType, Wallet } from './enums.js' -export type onAccountChangeCallback = (account: string) => void +export type onAccountChangeCallback = (account: string | string[]) => void export type onChainIdChangeCallback = () => void export type CosmosWalletAbstraction = { diff --git a/packages/wallets/wallet-base/src/utils/wallet.ts b/packages/wallets/wallet-base/src/utils/wallet.ts index a10eae65f..b32bdbf8f 100644 --- a/packages/wallets/wallet-base/src/utils/wallet.ts +++ b/packages/wallets/wallet-base/src/utils/wallet.ts @@ -3,7 +3,6 @@ import { Wallet } from './../types/enums.js' export const isEvmWallet = (wallet: Wallet): boolean => [ Wallet.Magic, - Wallet.Torus, Wallet.BitGet, Wallet.Ledger, Wallet.Trezor, diff --git a/packages/wallets/wallet-base/tsconfig.build.esm.json b/packages/wallets/wallet-base/tsconfig.build.esm.json index 741ef02a0..28aa44045 100644 --- a/packages/wallets/wallet-base/tsconfig.build.esm.json +++ b/packages/wallets/wallet-base/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-base.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-base/tsconfig.build.json b/packages/wallets/wallet-base/tsconfig.build.json index 8fc34b66a..80c67d837 100644 --- a/packages/wallets/wallet-base/tsconfig.build.json +++ b/packages/wallets/wallet-base/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-base.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-core/package.json b/packages/wallets/wallet-core/package.json index 5571740dc..a8ddd0d87 100644 --- a/packages/wallets/wallet-core/package.json +++ b/packages/wallets/wallet-core/package.json @@ -3,6 +3,7 @@ "description": "Core wallet strategy", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -59,18 +60,12 @@ "@injectivelabs/networks": "^1.14.34-beta.0", "@injectivelabs/sdk-ts": "^1.14.34-beta.5", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5", - "eip1193-provider": "^1.0.1" + "@injectivelabs/utils": "^1.14.33", + "@injectivelabs/wallet-base": "^1.14.34-beta.4", + "@keplr-wallet/types": "^0.12.159" }, "devDependencies": { - "@types/eth-sig-util": "^2.1.1", - "@types/ethereumjs-util": "^6.1.0", - "@types/hdkey": "^2.0.1" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" + "shx": "^0.3.3" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" } diff --git a/packages/wallets/wallet-core/src/broadcaster/MsgBroadcaster.ts b/packages/wallets/wallet-core/src/broadcaster/MsgBroadcaster.ts index 6e3c459cc..921b968b9 100644 --- a/packages/wallets/wallet-core/src/broadcaster/MsgBroadcaster.ts +++ b/packages/wallets/wallet-core/src/broadcaster/MsgBroadcaster.ts @@ -8,6 +8,7 @@ import { ofacWallets, SIGN_EIP712_V2, SIGN_EIP712, + DirectSignResponse, ChainGrpcAuthApi, CosmosTxV1Beta1Tx, createTxRawEIP712, @@ -24,7 +25,6 @@ import { recoverTypedSignaturePubKey, CreateTransactionWithSignersArgs, } from '@injectivelabs/sdk-ts' -import type { DirectSignResponse } from '@cosmjs/proto-signing' import { getStdFee, BigNumberInBase, diff --git a/packages/wallets/wallet-core/tsconfig.build.esm.json b/packages/wallets/wallet-core/tsconfig.build.esm.json index 4bcbc8521..36bcce0cf 100644 --- a/packages/wallets/wallet-core/tsconfig.build.esm.json +++ b/packages/wallets/wallet-core/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-core.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-core/tsconfig.build.json b/packages/wallets/wallet-core/tsconfig.build.json index a7720d357..d1b8b36ce 100644 --- a/packages/wallets/wallet-core/tsconfig.build.json +++ b/packages/wallets/wallet-core/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-core.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-cosmos-strategy/package.json b/packages/wallets/wallet-cosmos-strategy/package.json index a71661d05..bdb2a975c 100644 --- a/packages/wallets/wallet-cosmos-strategy/package.json +++ b/packages/wallets/wallet-cosmos-strategy/package.json @@ -3,6 +3,7 @@ "description": "Wallet Cosmos Strategy with instantiated wallets", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -55,34 +56,14 @@ "start": "node dist/index.js" }, "dependencies": { - "@ethereumjs/common": "^3.1.1", - "@ethereumjs/tx": "^4.1.1", - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/networks": "^1.14.34-beta.0", - "@injectivelabs/sdk-ts": "^1.14.34-beta.5", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5", - "@injectivelabs/wallet-core": "^1.14.34-beta.5", - "@injectivelabs/wallet-cosmos": "^1.14.34-beta.5", - "@injectivelabs/wallet-cosmostation": "^1.14.34-beta.5", - "alchemy-sdk": "^3.4.7", - "eip1193-provider": "^1.0.1", - "eth-sig-util": "^3.0.1", - "ethereumjs-util": "^7.1.0", - "ethers": "^6.5.1", - "hdkey": "^2.0.1", - "long": "^5.2.1", - "shx": "^0.3.3" + "@injectivelabs/wallet-base": "^1.14.34-beta.4", + "@injectivelabs/wallet-core": "^1.14.34-beta.4", + "@injectivelabs/wallet-cosmos": "^1.14.34-beta.4", + "@injectivelabs/wallet-cosmostation": "^1.14.34-beta.4" }, "devDependencies": { - "@types/eth-sig-util": "^2.1.1", - "@types/ethereumjs-util": "^6.1.0", - "@types/hdkey": "^2.0.1" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" + "shx": "^0.3.3" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" } diff --git a/packages/wallets/wallet-cosmos-strategy/tsconfig.build.esm.json b/packages/wallets/wallet-cosmos-strategy/tsconfig.build.esm.json index fc2b98fd1..1d5fce764 100644 --- a/packages/wallets/wallet-cosmos-strategy/tsconfig.build.esm.json +++ b/packages/wallets/wallet-cosmos-strategy/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-strategy.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-cosmos-strategy/tsconfig.build.json b/packages/wallets/wallet-cosmos-strategy/tsconfig.build.json index eaba8aec7..d67c6a5a8 100644 --- a/packages/wallets/wallet-cosmos-strategy/tsconfig.build.json +++ b/packages/wallets/wallet-cosmos-strategy/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-strategy.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-cosmos/README.md b/packages/wallets/wallet-cosmos/README.md index 2f429aead..f5cebd3fb 100644 --- a/packages/wallets/wallet-cosmos/README.md +++ b/packages/wallets/wallet-cosmos/README.md @@ -2,8 +2,8 @@ -[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) -[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) +[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-cosmos.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-cosmos) +[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-cosmos.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-cosmos) [![license](https://img.shields.io/npm/l/express.svg)]() _Package to use Cosmos Wallets on Injective via the wallet strategy._ diff --git a/packages/wallets/wallet-cosmos/package.json b/packages/wallets/wallet-cosmos/package.json index 9692605d7..f41d98540 100644 --- a/packages/wallets/wallet-cosmos/package.json +++ b/packages/wallets/wallet-cosmos/package.json @@ -3,6 +3,7 @@ "description": "Cosmos wallet strategies for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -55,18 +56,17 @@ "start": "node dist/index.js" }, "dependencies": { - "@cosmjs/amino": "^0.32.3", "@cosmjs/launchpad": "0.27.1", "@cosmjs/proto-signing": "^0.32.3", "@cosmjs/stargate": "^0.32.3", - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/networks": "^1.14.34-beta.0", - "@injectivelabs/sdk-ts": "^1.14.34-beta.5", + "@injectivelabs/exceptions": "^1.14.33", + "@injectivelabs/sdk-ts": "^1.14.34-beta.4", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5", - "@keplr-wallet/cosmos": "^0.12.71", - "@keplr-wallet/types": "^0.12.71", + "@injectivelabs/utils": "^1.14.33", + "@injectivelabs/wallet-base": "^1.14.34-beta.4", + "@keplr-wallet/types": "^0.12.71" + }, + "devDependencies": { "shx": "^0.3.3" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445", @@ -74,9 +74,5 @@ "entryPoint": "./src/index.ts", "readmeFile": "./README.md", "displayName": "wallet-cosmos API Documentation" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" } } diff --git a/packages/wallets/wallet-cosmos/src/strategy/strategy.ts b/packages/wallets/wallet-cosmos/src/strategy/strategy.ts index 84b968597..1dec933d8 100644 --- a/packages/wallets/wallet-cosmos/src/strategy/strategy.ts +++ b/packages/wallets/wallet-cosmos/src/strategy/strategy.ts @@ -292,7 +292,7 @@ export class CosmosWalletStrategy } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const { wallet } = this diff --git a/packages/wallets/wallet-cosmos/tsconfig.build.esm.json b/packages/wallets/wallet-cosmos/tsconfig.build.esm.json index 9b8bb55e1..80c4b05c8 100644 --- a/packages/wallets/wallet-cosmos/tsconfig.build.esm.json +++ b/packages/wallets/wallet-cosmos/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-cosmos.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-cosmos/tsconfig.build.json b/packages/wallets/wallet-cosmos/tsconfig.build.json index a0473b852..8d3d2d0a3 100644 --- a/packages/wallets/wallet-cosmos/tsconfig.build.json +++ b/packages/wallets/wallet-cosmos/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-cosmos.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-cosmostation/README.md b/packages/wallets/wallet-cosmostation/README.md index 9b86ffd10..2e29b0e95 100644 --- a/packages/wallets/wallet-cosmostation/README.md +++ b/packages/wallets/wallet-cosmostation/README.md @@ -2,8 +2,8 @@ -[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) -[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) +[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-cosmostation.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-cosmostation) +[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-cosmostation.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-cosmostation) [![license](https://img.shields.io/npm/l/express.svg)]() _Package to use Magic Wallets on Injective via the wallet strategy._ diff --git a/packages/wallets/wallet-cosmostation/package.json b/packages/wallets/wallet-cosmostation/package.json index d54494d3a..1233009a6 100644 --- a/packages/wallets/wallet-cosmostation/package.json +++ b/packages/wallets/wallet-cosmostation/package.json @@ -3,6 +3,7 @@ "description": "Cosmostation strategy for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -60,18 +61,12 @@ "@injectivelabs/exceptions": "^1.14.34-beta.0", "@injectivelabs/sdk-ts": "^1.14.34-beta.5", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5", - "@walletconnect/ethereum-provider": "^2.12.2" + "@injectivelabs/wallet-base": "^1.14.34-beta.4" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445", "typedoc": { "entryPoint": "./src/index.ts", "readmeFile": "./README.md", "displayName": "wallet-cosmostation API Documentation" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" } } diff --git a/packages/wallets/wallet-cosmostation/tsconfig.build.esm.json b/packages/wallets/wallet-cosmostation/tsconfig.build.esm.json index b10b4bc0c..526639b12 100644 --- a/packages/wallets/wallet-cosmostation/tsconfig.build.esm.json +++ b/packages/wallets/wallet-cosmostation/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-connect.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-cosmostation/tsconfig.build.json b/packages/wallets/wallet-cosmostation/tsconfig.build.json index d9f47369b..feeb16a2c 100644 --- a/packages/wallets/wallet-cosmostation/tsconfig.build.json +++ b/packages/wallets/wallet-cosmostation/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-connect.tsbuildinfo" }, - "include": [ - "./src/**/*.ts" - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-evm/README.md b/packages/wallets/wallet-evm/README.md index 675429830..f216b33db 100644 --- a/packages/wallets/wallet-evm/README.md +++ b/packages/wallets/wallet-evm/README.md @@ -2,8 +2,8 @@ -[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) -[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) +[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-evm.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-evm) +[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-evm.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-evm) [![license](https://img.shields.io/npm/l/express.svg)]() _Package to use Wallets EVM on Injective via the wallet strategy._ diff --git a/packages/wallets/wallet-evm/package.json b/packages/wallets/wallet-evm/package.json index a2610f2fd..e14c31df4 100644 --- a/packages/wallets/wallet-evm/package.json +++ b/packages/wallets/wallet-evm/package.json @@ -3,6 +3,7 @@ "description": "EVM wallet strategies for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -55,29 +56,19 @@ "start": "node dist/index.js" }, "dependencies": { - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/networks": "^1.14.34-beta.0", - "@injectivelabs/sdk-ts": "^1.14.34-beta.5", + "@injectivelabs/exceptions": "^1.14.33", + "@injectivelabs/sdk-ts": "^1.14.34-beta.4", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5", - "ethers": "^6.5.1", - "long": "^5.2.1", - "shx": "^0.3.3" + "@injectivelabs/utils": "^1.14.33", + "@injectivelabs/wallet-base": "^1.14.34-beta.4" }, "devDependencies": { - "@types/eth-sig-util": "^2.1.1", - "@types/ethereumjs-util": "^6.1.0", - "@types/hdkey": "^2.0.1" + "shx": "^0.3.3" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445", "typedoc": { "entryPoint": "./src/index.ts", "readmeFile": "./README.md", "displayName": "wallet-evm API Documentation" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" } } diff --git a/packages/wallets/wallet-evm/src/strategy/strategy.ts b/packages/wallets/wallet-evm/src/strategy/strategy.ts index bfb786f1a..9a18ae43a 100644 --- a/packages/wallets/wallet-evm/src/strategy/strategy.ts +++ b/packages/wallets/wallet-evm/src/strategy/strategy.ts @@ -130,7 +130,7 @@ export class EvmWallet try { return await ethereum.request({ method: 'eth_requestAccounts', - }) + }) as string[] } catch (e: unknown) { throw this.EvmWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -159,7 +159,7 @@ export class EvmWallet return await ethereum.request({ method: 'eth_sendTransaction', params: [transaction], - }) + }) as string } catch (e: unknown) { throw this.EvmWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -207,7 +207,7 @@ export class EvmWallet return await ethereum.request({ method: 'eth_signTypedData_v4', params: [address, eip712json], - }) + }) as string } catch (e: unknown) { throw new MetamaskException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -260,7 +260,7 @@ export class EvmWallet params: [toUtf8(data), signer], }) - return signature + return signature as string } catch (e: unknown) { throw this.EvmWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -274,7 +274,7 @@ export class EvmWallet const ethereum = await this.getEthereum() try { - return ethereum.request({ method: 'eth_chainId' }) + return ethereum.request({ method: 'eth_chainId' }) as Promise } catch (e: unknown) { throw this.EvmWalletException(new Error((e as any).message), { code: UnspecifiedErrorCode, @@ -292,7 +292,7 @@ export class EvmWallet const receipt = await ethereum.request({ method: 'eth_getTransactionReceipt', params: [txHash], - }) + }) as string if (!receipt) { await sleep(interval) @@ -331,7 +331,7 @@ export class EvmWallet } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const ethereum = await this.getEthereum() diff --git a/packages/wallets/wallet-evm/src/utils/index.ts b/packages/wallets/wallet-evm/src/utils/index.ts index b8bd831a8..55db185fd 100644 --- a/packages/wallets/wallet-evm/src/utils/index.ts +++ b/packages/wallets/wallet-evm/src/utils/index.ts @@ -85,7 +85,7 @@ export const updateEvmNetwork = async ( params: [{ chainId: `0x${chainIdToHex}` }], }), new Promise((resolve) => - provider.on('change', ({ chain }: any) => { + provider.on('chainChanged', ({ chain }: any) => { if (chain?.id === chainIdToHex) { resolve() } diff --git a/packages/wallets/wallet-evm/tsconfig.build.esm.json b/packages/wallets/wallet-evm/tsconfig.build.esm.json index 6e4e94f6e..d5c9cebf5 100644 --- a/packages/wallets/wallet-evm/tsconfig.build.esm.json +++ b/packages/wallets/wallet-evm/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-evm.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-evm/tsconfig.build.json b/packages/wallets/wallet-evm/tsconfig.build.json index ab5466cfe..189c419d3 100644 --- a/packages/wallets/wallet-evm/tsconfig.build.json +++ b/packages/wallets/wallet-evm/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-evm.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-ledger/README.md b/packages/wallets/wallet-ledger/README.md index 5cc33b315..d2d9a1a7f 100644 --- a/packages/wallets/wallet-ledger/README.md +++ b/packages/wallets/wallet-ledger/README.md @@ -2,8 +2,8 @@ -[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) -[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) +[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ledger.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ledger) +[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ledger.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ledger) [![license](https://img.shields.io/npm/l/express.svg)]() _Package to use Ledger Wallets on Injective via the wallet strategy._ diff --git a/packages/wallets/wallet-ledger/package.json b/packages/wallets/wallet-ledger/package.json index 0240f363c..0a097731e 100644 --- a/packages/wallets/wallet-ledger/package.json +++ b/packages/wallets/wallet-ledger/package.json @@ -3,6 +3,7 @@ "description": "Ledger wallet strategy for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -41,8 +42,8 @@ }, "scripts": { "build": "yarn build:esm && yarn build:cjs && yarn build:post", - "build:cjs": "BUILD_MODE=cjs node ./../../../etc/replacements-ledger.js && tsc --build --force tsconfig.build.json", - "build:esm": "BUILD_MODE=esm node ./../../../etc/replacements-ledger.js && tsc --build --force tsconfig.build.esm.json", + "build:cjs": "tsc --build --force tsconfig.build.json", + "build:esm": "tsc --build --force tsconfig.build.esm.json", "build:watch": "tsc --build -w tsconfig.build.json && tsc -w --build tsconfig.build.esm.json && yarn build:post", "build:post": "shx cp ../../../etc/stub/package.json.stub dist/cjs/package.json && shx cp ../../../etc/stub/package.esm.json.stub dist/esm/package.json", "clean": "tsc --build tsconfig.build.json --clean && tsc --build tsconfig.build.esm.json --clean && shx rm -rf coverage *.log junit.xml dist && jest --clearCache && shx mkdir -p dist", @@ -57,21 +58,19 @@ "dependencies": { "@ethereumjs/common": "^3.1.1", "@ethereumjs/tx": "^4.1.1", - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/networks": "^1.14.34-beta.0", - "@injectivelabs/sdk-ts": "^1.14.34-beta.5", + "@injectivelabs/exceptions": "^1.14.33", + "@injectivelabs/sdk-ts": "^1.14.34-beta.4", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5", - "@ledgerhq/hw-app-cosmos": "^6.29.5", - "@ledgerhq/hw-app-eth": "6.35.6", - "@ledgerhq/hw-transport": "6.30.4", - "@ledgerhq/hw-transport-webhid": "6.28.4", - "@ledgerhq/hw-transport-webusb": "6.28.4", + "@injectivelabs/wallet-base": "^1.14.34-beta.4", + "@ledgerhq/hw-app-cosmos": "^6.30.4", + "@ledgerhq/hw-app-eth": "6.42.0", + "@ledgerhq/hw-transport": "6.31.4", + "@ledgerhq/hw-transport-webhid": "6.29.4", + "@ledgerhq/hw-transport-webusb": "6.29.4", "alchemy-sdk": "^3.4.7", "eth-sig-util": "^3.0.1", "ethereumjs-util": "^7.1.0", - "hdkey": "^2.0.1" + "hdkey": "^2.1.0" }, "devDependencies": { "@types/eth-sig-util": "^2.1.1", @@ -79,9 +78,5 @@ "@types/hdkey": "^2.0.1", "@types/ledgerhq__hw-transport-webusb": "^4.70.1" }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" - }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" } diff --git a/packages/wallets/wallet-ledger/src/strategy/Ledger/Base.ts b/packages/wallets/wallet-ledger/src/strategy/Ledger/Base.ts index b5da5216b..5683000c1 100644 --- a/packages/wallets/wallet-ledger/src/strategy/Ledger/Base.ts +++ b/packages/wallets/wallet-ledger/src/strategy/Ledger/Base.ts @@ -3,6 +3,7 @@ import { AccountAddress, EthereumChainId } from '@injectivelabs/ts-types' import { bufferToHex, addHexPrefix } from 'ethereumjs-util' import { Common, Chain, Hardfork } from '@ethereumjs/common' import { FeeMarketEIP1559Transaction } from '@ethereumjs/tx' +import { ledgerService } from '@ledgerhq/hw-app-eth' import { ErrorType, GeneralException, @@ -312,10 +313,7 @@ export default class LedgerBase try { const ledger = await this.ledger.getInstance() const { derivationPath } = await this.getWalletForAddress(options.address) - const ledgerService = await import( - '@ledgerhq/hw-app-eth/lib/services/ledger/index.js' - ) - const resolution = await ledgerService.default.resolveTransaction( + const resolution = await ledgerService.resolveTransaction( encodedMessageHex, {}, {}, diff --git a/packages/wallets/wallet-ledger/src/strategy/Ledger/hw/AccountManager.ts b/packages/wallets/wallet-ledger/src/strategy/Ledger/hw/AccountManager.ts index 2390f96a7..b555843f5 100644 --- a/packages/wallets/wallet-ledger/src/strategy/Ledger/hw/AccountManager.ts +++ b/packages/wallets/wallet-ledger/src/strategy/Ledger/hw/AccountManager.ts @@ -1,7 +1,7 @@ import { AccountAddress } from '@injectivelabs/ts-types' import { publicToAddress, addHexPrefix } from 'ethereumjs-util' import HDNode from 'hdkey' -import type EthereumApp from '@ledgerhq/hw-app-eth' +import { Eth as EthereumApp } from '@ledgerhq/hw-app-eth' import { LedgerDerivationPathType, LedgerWalletInfo } from '../../../types.js' import { DEFAULT_NUM_ADDRESSES_TO_FETCH } from '@injectivelabs/wallet-base' diff --git a/packages/wallets/wallet-ledger/src/strategy/Ledger/hw/index.ts b/packages/wallets/wallet-ledger/src/strategy/Ledger/hw/index.ts index 5329774d4..4657fc4c0 100644 --- a/packages/wallets/wallet-ledger/src/strategy/Ledger/hw/index.ts +++ b/packages/wallets/wallet-ledger/src/strategy/Ledger/hw/index.ts @@ -1,7 +1,7 @@ -import TransportWebHID from '@ledgerhq/hw-transport-webhid' -import TransportWebUSB from '@ledgerhq/hw-transport-webusb' -import type EthereumApp from '@ledgerhq/hw-app-eth' -import type Transport from '@ledgerhq/hw-transport' +import { TransportWebHID } from '@ledgerhq/hw-transport-webhid' +import { TransportWebUSB } from '@ledgerhq/hw-transport-webusb' +import { Eth as EthereumApp } from '@ledgerhq/hw-app-eth' +import { Transport } from '@ledgerhq/hw-transport' import { LedgerException } from '@injectivelabs/exceptions' import AccountManager from './AccountManager.js' @@ -47,9 +47,8 @@ export default class LedgerTransport { async getInstance(): Promise { if (!this.ledger) { const transport = await LedgerTransport.getTransport() - const EthereumApp = await import('@ledgerhq/hw-app-eth') - this.ledger = new EthereumApp.default(transport) + this.ledger = new EthereumApp(transport) transport.on('disconnect', () => { this.ledger = null diff --git a/packages/wallets/wallet-ledger/src/strategy/LedgerCosmos/hw/AccountManager.ts b/packages/wallets/wallet-ledger/src/strategy/LedgerCosmos/hw/AccountManager.ts index e5bef25ed..859d5624e 100644 --- a/packages/wallets/wallet-ledger/src/strategy/LedgerCosmos/hw/AccountManager.ts +++ b/packages/wallets/wallet-ledger/src/strategy/LedgerCosmos/hw/AccountManager.ts @@ -1,5 +1,5 @@ import { AccountAddress } from '@injectivelabs/ts-types' -import type CosmosApp from '@ledgerhq/hw-app-cosmos' +import { Cosmos as CosmosApp } from '@ledgerhq/hw-app-cosmos' import { LedgerWalletInfo } from '../../../types.js' import { DEFAULT_NUM_ADDRESSES_TO_FETCH } from '@injectivelabs/wallet-base' diff --git a/packages/wallets/wallet-ledger/src/strategy/LedgerCosmos/hw/index.ts b/packages/wallets/wallet-ledger/src/strategy/LedgerCosmos/hw/index.ts index d2b7b5c7f..a0fce7e45 100644 --- a/packages/wallets/wallet-ledger/src/strategy/LedgerCosmos/hw/index.ts +++ b/packages/wallets/wallet-ledger/src/strategy/LedgerCosmos/hw/index.ts @@ -1,7 +1,7 @@ -import TransportWebUSB from '@ledgerhq/hw-transport-webusb' -import TransportWebHID from '@ledgerhq/hw-transport-webhid' -import CosmosApp from '@ledgerhq/hw-app-cosmos' -import type Transport from '@ledgerhq/hw-transport' +import { TransportWebUSB } from '@ledgerhq/hw-transport-webusb' +import { TransportWebHID } from '@ledgerhq/hw-transport-webhid' +import { Cosmos as CosmosApp } from '@ledgerhq/hw-app-cosmos' +import { Transport } from '@ledgerhq/hw-transport' import { LedgerCosmosException } from '@injectivelabs/exceptions' import AccountManager from './AccountManager.js' diff --git a/packages/wallets/wallet-ledger/tsconfig.build.esm.json b/packages/wallets/wallet-ledger/tsconfig.build.esm.json index 0c9774fd1..10c74ff3d 100644 --- a/packages/wallets/wallet-ledger/tsconfig.build.esm.json +++ b/packages/wallets/wallet-ledger/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-ledger.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-ledger/tsconfig.build.json b/packages/wallets/wallet-ledger/tsconfig.build.json index 6f5460f07..267c4d99a 100644 --- a/packages/wallets/wallet-ledger/tsconfig.build.json +++ b/packages/wallets/wallet-ledger/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-ledger.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-magic/README.md b/packages/wallets/wallet-magic/README.md index be5199ff5..7dfc36e4a 100644 --- a/packages/wallets/wallet-magic/README.md +++ b/packages/wallets/wallet-magic/README.md @@ -2,8 +2,8 @@ -[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) -[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) +[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-magic.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-magic) +[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-magic.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-magic) [![license](https://img.shields.io/npm/l/express.svg)]() _Package to use Magic Wallets on Injective via the wallet strategy._ diff --git a/packages/wallets/wallet-magic/package.json b/packages/wallets/wallet-magic/package.json index 5a1a3d3b8..e2a69fceb 100644 --- a/packages/wallets/wallet-magic/package.json +++ b/packages/wallets/wallet-magic/package.json @@ -3,6 +3,7 @@ "description": "Magic wallet strategy for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -69,9 +70,5 @@ "entryPoint": "./src/index.ts", "readmeFile": "./README.md", "displayName": "wallet-magic API Documentation" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" } } diff --git a/packages/wallets/wallet-magic/tsconfig.build.esm.json b/packages/wallets/wallet-magic/tsconfig.build.esm.json index 68970b702..88abff07f 100644 --- a/packages/wallets/wallet-magic/tsconfig.build.esm.json +++ b/packages/wallets/wallet-magic/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-magic.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-magic/tsconfig.build.json b/packages/wallets/wallet-magic/tsconfig.build.json index 4cc3a1747..f6c84cd48 100644 --- a/packages/wallets/wallet-magic/tsconfig.build.json +++ b/packages/wallets/wallet-magic/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-magic.tsbuildinfo" }, - "include": [ - "./src/**/*.ts" - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-private-key/README.md b/packages/wallets/wallet-private-key/README.md index c3719bfda..e501c5db5 100644 --- a/packages/wallets/wallet-private-key/README.md +++ b/packages/wallets/wallet-private-key/README.md @@ -2,8 +2,8 @@ -[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) -[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) +[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-private-key.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-private-key) +[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-private-key.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-private-key) [![license](https://img.shields.io/npm/l/express.svg)]() _Package to use Private Wallet on Injective via the wallet strategy._ diff --git a/packages/wallets/wallet-private-key/package.json b/packages/wallets/wallet-private-key/package.json index 4596d43a7..955c7edff 100644 --- a/packages/wallets/wallet-private-key/package.json +++ b/packages/wallets/wallet-private-key/package.json @@ -3,6 +3,7 @@ "description": "Private key wallet strategy for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -58,17 +59,12 @@ "@injectivelabs/exceptions": "^1.14.34-beta.0", "@injectivelabs/sdk-ts": "^1.14.34-beta.5", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5" + "@injectivelabs/wallet-base": "^1.14.34-beta.4" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445", "typedoc": { "entryPoint": "./src/index.ts", "readmeFile": "./README.md", "displayName": "wallet-private-key API Documentation" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" } } diff --git a/packages/wallets/wallet-private-key/src/strategy/strategy.ts b/packages/wallets/wallet-private-key/src/strategy/strategy.ts index bf1b5b79c..730a8c2ce 100644 --- a/packages/wallets/wallet-private-key/src/strategy/strategy.ts +++ b/packages/wallets/wallet-private-key/src/strategy/strategy.ts @@ -247,7 +247,7 @@ export class PrivateKeyWallet } async onAccountChange( - _callback: (account: AccountAddress) => void, + _callback: (account: AccountAddress | string[]) => void, ): Promise { // } diff --git a/packages/wallets/wallet-private-key/tsconfig.build.esm.json b/packages/wallets/wallet-private-key/tsconfig.build.esm.json index 1685b7e1f..d580502d6 100644 --- a/packages/wallets/wallet-private-key/tsconfig.build.esm.json +++ b/packages/wallets/wallet-private-key/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-private-key.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-private-key/tsconfig.build.json b/packages/wallets/wallet-private-key/tsconfig.build.json index 77d82bf57..d1d5a0525 100644 --- a/packages/wallets/wallet-private-key/tsconfig.build.json +++ b/packages/wallets/wallet-private-key/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-private-key.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-strategy/package.json b/packages/wallets/wallet-strategy/package.json index bea706a41..bb4aedd2b 100644 --- a/packages/wallets/wallet-strategy/package.json +++ b/packages/wallets/wallet-strategy/package.json @@ -3,6 +3,7 @@ "description": "Wallet strategy with instantiated wallets", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -77,18 +78,13 @@ "eth-sig-util": "^3.0.1", "ethereumjs-util": "^7.1.0", "ethers": "^6.5.1", - "hdkey": "^2.0.1", - "long": "^5.2.1", - "shx": "^0.3.3" + "hdkey": "^2.1.0" }, "devDependencies": { + "shx": "^0.3.3", "@types/eth-sig-util": "^2.1.1", "@types/ethereumjs-util": "^6.1.0", "@types/hdkey": "^2.0.1" }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" - }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" } diff --git a/packages/wallets/wallet-strategy/tsconfig.build.esm.json b/packages/wallets/wallet-strategy/tsconfig.build.esm.json index fc2b98fd1..1d5fce764 100644 --- a/packages/wallets/wallet-strategy/tsconfig.build.esm.json +++ b/packages/wallets/wallet-strategy/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-strategy.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-strategy/tsconfig.build.json b/packages/wallets/wallet-strategy/tsconfig.build.json index eaba8aec7..d67c6a5a8 100644 --- a/packages/wallets/wallet-strategy/tsconfig.build.json +++ b/packages/wallets/wallet-strategy/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-strategy.tsbuildinfo" }, - "include": [ - "./src/**/*.ts", - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-trezor/README.md b/packages/wallets/wallet-trezor/README.md index c0f3e4cec..79829ae48 100644 --- a/packages/wallets/wallet-trezor/README.md +++ b/packages/wallets/wallet-trezor/README.md @@ -2,8 +2,8 @@ -[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) -[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) +[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-trezor.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-trezor) +[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-trezor.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-trezor) [![license](https://img.shields.io/npm/l/express.svg)]() _Package to use Trezor Wallets on Injective via the wallet strategy._ diff --git a/packages/wallets/wallet-trezor/package.json b/packages/wallets/wallet-trezor/package.json index a226f8a4f..245719c49 100644 --- a/packages/wallets/wallet-trezor/package.json +++ b/packages/wallets/wallet-trezor/package.json @@ -3,6 +3,7 @@ "description": "Trezor wallet strategy for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -55,32 +56,22 @@ "start": "node dist/index.js" }, "dependencies": { - "@ethereumjs/common": "^3.1.1", + "@trezor/connect-web": "^9.4.5", + "@ethereumjs/common": "3.1.1", "@ethereumjs/tx": "^4.1.1", - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/networks": "^1.14.34-beta.0", - "@injectivelabs/sdk-ts": "^1.14.34-beta.5", + "@injectivelabs/exceptions": "^1.14.33", + "@injectivelabs/sdk-ts": "^1.14.34-beta.4", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5", - "@trezor/connect-web": "9.2.1", + "@injectivelabs/wallet-base": "^1.14.34-beta.4", + "@metamask/eth-sig-util": "^8.0.0", "alchemy-sdk": "^3.4.7", - "eip1193-provider": "^1.0.1", - "eth-sig-util": "^3.0.1", - "ethereumjs-util": "^7.1.0", - "ethers": "^6.5.1", - "hdkey": "^2.0.1", - "long": "^5.2.1", - "shx": "^0.3.3" + "hdkey": "^2.1.0" }, "devDependencies": { - "@types/eth-sig-util": "^2.1.1", - "@types/ethereumjs-util": "^6.1.0", - "@types/hdkey": "^2.0.1" + "shx": "^0.3.3" }, "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" + "@ethereumjs/common": "3.1.1" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445" } diff --git a/packages/wallets/wallet-trezor/src/strategy/hw/AccountManager.ts b/packages/wallets/wallet-trezor/src/strategy/hw/AccountManager.ts index 6fbfe82ba..1a800a872 100644 --- a/packages/wallets/wallet-trezor/src/strategy/hw/AccountManager.ts +++ b/packages/wallets/wallet-trezor/src/strategy/hw/AccountManager.ts @@ -1,8 +1,8 @@ /* eslint-disable class-methods-use-this */ import { AccountAddress } from '@injectivelabs/ts-types' import HDNode from 'hdkey' -import { addHexPrefix, publicToAddress } from 'ethereumjs-util' import { TrezorWalletInfo } from '../../types.js' +import { addHexPrefix, publicKeyToAddress } from '@injectivelabs/sdk-ts' import { DEFAULT_NUM_ADDRESSES_TO_FETCH, DEFAULT_BASE_DERIVATION_PATH, @@ -11,9 +11,8 @@ import { const addressOfHDKey = (hdKey: HDNode): string => { const shouldSanitizePublicKey = true const derivedPublicKey = hdKey.publicKey - const ethereumAddressWithoutPrefix = publicToAddress( - derivedPublicKey, - shouldSanitizePublicKey, + const ethereumAddressWithoutPrefix = Buffer.from( + publicKeyToAddress(derivedPublicKey, shouldSanitizePublicKey), ).toString('hex') const address = addHexPrefix(ethereumAddressWithoutPrefix) diff --git a/packages/wallets/wallet-trezor/src/strategy/hw/index.ts b/packages/wallets/wallet-trezor/src/strategy/hw/index.ts index a7a058499..ec4c5a820 100644 --- a/packages/wallets/wallet-trezor/src/strategy/hw/index.ts +++ b/packages/wallets/wallet-trezor/src/strategy/hw/index.ts @@ -1,12 +1,9 @@ -import TrezorConnect from '@trezor/connect-web' +import { TrezorConnect } from '@trezor/connect-web' import HDNode from 'hdkey' import { DEFAULT_BASE_DERIVATION_PATH } from '@injectivelabs/wallet-base' import AccountManager from './AccountManager.js' import { WalletException } from '@injectivelabs/exceptions' -// @ts-ignore -const trezorConnect = TrezorConnect.default || TrezorConnect - const TREZOR_CONNECT_MANIFEST = { email: 'contact@injectivelabs.org', appUrl: 'https://injectivelabs.org', @@ -19,7 +16,10 @@ export default class TrezorTransport { constructor() { try { - trezorConnect.init({ lazyLoad: true, manifest: TREZOR_CONNECT_MANIFEST }) + TrezorConnect.init({ + lazyLoad: true, + manifest: TREZOR_CONNECT_MANIFEST, + }) } catch (e) { throw new WalletException(e as Error) } diff --git a/packages/wallets/wallet-trezor/src/strategy/strategy.ts b/packages/wallets/wallet-trezor/src/strategy/strategy.ts index b1edab2e1..356d4fcb0 100644 --- a/packages/wallets/wallet-trezor/src/strategy/strategy.ts +++ b/packages/wallets/wallet-trezor/src/strategy/strategy.ts @@ -5,7 +5,7 @@ import { Alchemy, Network as AlchemyNetwork } from 'alchemy-sdk' import { addHexPrefix } from 'ethereumjs-util' import { FeeMarketEIP1559Transaction } from '@ethereumjs/tx' import { Common, Chain, Hardfork } from '@ethereumjs/common' -import TrezorConnect from '@trezor/connect-web' +import { TrezorConnect } from '@trezor/connect-web' import { ErrorType, WalletException, diff --git a/packages/wallets/wallet-trezor/tsconfig.build.esm.json b/packages/wallets/wallet-trezor/tsconfig.build.esm.json index 7c542d7b9..e907fe8ff 100644 --- a/packages/wallets/wallet-trezor/tsconfig.build.esm.json +++ b/packages/wallets/wallet-trezor/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", - "esModuleInterop": true, + "esModuleInterop": false, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-trezor.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-trezor/tsconfig.build.json b/packages/wallets/wallet-trezor/tsconfig.build.json index 55af62253..0cd5116d9 100644 --- a/packages/wallets/wallet-trezor/tsconfig.build.json +++ b/packages/wallets/wallet-trezor/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-trezor.tsbuildinfo" }, - "include": [ - "./src/**/*.ts" - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/packages/wallets/wallet-wallet-connect/README.md b/packages/wallets/wallet-wallet-connect/README.md index eecee08ce..34b9cacb4 100644 --- a/packages/wallets/wallet-wallet-connect/README.md +++ b/packages/wallets/wallet-wallet-connect/README.md @@ -2,8 +2,8 @@ -[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) -[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-ts.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-ts) +[![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-wallet-connect.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-wallet-connect) +[![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-wallet-connect.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-wallet-connect) [![license](https://img.shields.io/npm/l/express.svg)]() _Package to use Wallet Connect Wallets on Injective via the wallet strategy._ diff --git a/packages/wallets/wallet-wallet-connect/package.json b/packages/wallets/wallet-wallet-connect/package.json index 9b80b6135..c9dca976d 100644 --- a/packages/wallets/wallet-wallet-connect/package.json +++ b/packages/wallets/wallet-wallet-connect/package.json @@ -3,6 +3,7 @@ "description": "Wallet connect strategy for use with @injectivelabs/wallet-core.", "version": "1.14.34-beta.5", "sideEffects": false, + "type": "module", "author": { "name": "InjectiveLabs", "email": "admin@injectivelabs.org" @@ -55,21 +56,17 @@ "start": "node dist/index.js" }, "dependencies": { - "@injectivelabs/exceptions": "^1.14.34-beta.0", - "@injectivelabs/sdk-ts": "^1.14.34-beta.5", + "@bangjelkoski/wallet-connect-ethereum-provider": "^2.17.2", + "@injectivelabs/exceptions": "^1.14.33", + "@injectivelabs/sdk-ts": "^1.14.34-beta.4", "@injectivelabs/ts-types": "^1.14.33", - "@injectivelabs/utils": "^1.14.34-beta.0", - "@injectivelabs/wallet-base": "^1.14.34-beta.5", - "@walletconnect/ethereum-provider": "^2.12.2" + "@injectivelabs/wallet-base": "^1.14.34-beta.4", + "@walletconnect/ethereum-provider": "^2.17.2" }, "gitHead": "6442ae377bbfb3459d2fb3a44c650630a5b7f445", "typedoc": { "entryPoint": "./src/index.ts", "readmeFile": "./README.md", "displayName": "wallet-connect API Documentation" - }, - "resolutions": { - "**/libsodium": "npm:@bangjelkoski/noop", - "**/libsodium-wrappers": "npm:@bangjelkoski/noop" } } diff --git a/packages/wallets/wallet-wallet-connect/src/strategy/strategy.ts b/packages/wallets/wallet-wallet-connect/src/strategy/strategy.ts index b2f364ced..9b33c4e34 100644 --- a/packages/wallets/wallet-wallet-connect/src/strategy/strategy.ts +++ b/packages/wallets/wallet-wallet-connect/src/strategy/strategy.ts @@ -17,7 +17,8 @@ import { SendTransactionOptions, ConcreteEthereumWalletStrategyArgs, } from '@injectivelabs/wallet-base' -import Provider, { +import { + Provider, EthereumProvider, EthereumProviderOptions, } from '@walletconnect/ethereum-provider' @@ -277,7 +278,7 @@ export class WalletConnect } async onAccountChange( - callback: (account: AccountAddress) => void, + callback: (account: AccountAddress | string[]) => void, ): Promise { const wc = await this.getConnectedWalletConnect() @@ -288,7 +289,7 @@ export class WalletConnect wc.on('accountsChanged', (accounts) => callback(accounts[0])) } - private async getWalletConnect(): Promise { + private async getWalletConnect() { if (this.provider) { return this.provider } @@ -346,7 +347,7 @@ export class WalletConnect }, }) - return this.provider + return this.provider as Provider } catch (e) { throw new WalletException( new Error('WalletConnect not supported for this wallet'), diff --git a/packages/wallets/wallet-wallet-connect/tsconfig.build.esm.json b/packages/wallets/wallet-wallet-connect/tsconfig.build.esm.json index aee43480f..e4dfebd6a 100644 --- a/packages/wallets/wallet-wallet-connect/tsconfig.build.esm.json +++ b/packages/wallets/wallet-wallet-connect/tsconfig.build.esm.json @@ -1,13 +1,13 @@ { "extends": "./tsconfig.build.json", "compilerOptions": { - "module": "ESNext", + "module": "NodeNext", "outDir": "./dist/esm", "rootDir": "./src", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", - "moduleResolution": "Bundler", + "moduleResolution": "NodeNext", "tsBuildInfoFile": "../../../.build-cache/wallet-wallet-connect.esm.tsbuildinfo" } } diff --git a/packages/wallets/wallet-wallet-connect/tsconfig.build.json b/packages/wallets/wallet-wallet-connect/tsconfig.build.json index 34041077d..e3ae7a681 100644 --- a/packages/wallets/wallet-wallet-connect/tsconfig.build.json +++ b/packages/wallets/wallet-wallet-connect/tsconfig.build.json @@ -3,13 +3,10 @@ "compilerOptions": { "rootDir": "./src", "outDir": "./dist/cjs", + "module": "commonjs", + "moduleResolution": "node", "tsBuildInfoFile": "../../../.build-cache/wallet-wallet-connect.tsbuildinfo" }, - "include": [ - "./src/**/*.ts" - ], - "exclude": [ - "./src/**/*.spec.ts", - "./src/**/*.test.ts" - ] + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"] } diff --git a/patches/@ledgerhq+hw-app-cosmos+6.30.4.patch b/patches/@ledgerhq+hw-app-cosmos+6.30.4.patch new file mode 100644 index 000000000..f79c81c5f --- /dev/null +++ b/patches/@ledgerhq+hw-app-cosmos+6.30.4.patch @@ -0,0 +1,95 @@ +diff --git a/node_modules/@ledgerhq/hw-app-cosmos/.DS_Store b/node_modules/@ledgerhq/hw-app-cosmos/.DS_Store +new file mode 100644 +index 0000000..be5febd +Binary files /dev/null and b/node_modules/@ledgerhq/hw-app-cosmos/.DS_Store differ +diff --git a/node_modules/@ledgerhq/hw-app-cosmos/lib-es/Cosmos.d.ts b/node_modules/@ledgerhq/hw-app-cosmos/lib-es/Cosmos.d.ts +index 0317ca3..a6d0ffa 100644 +--- a/node_modules/@ledgerhq/hw-app-cosmos/lib-es/Cosmos.d.ts ++++ b/node_modules/@ledgerhq/hw-app-cosmos/lib-es/Cosmos.d.ts +@@ -23,7 +23,7 @@ import type Transport from "@ledgerhq/hw-transport"; + * import Cosmos from "@ledgerhq/hw-app-cosmos"; + * const cosmos = new Cosmos(transport) + */ +-export default class Cosmos { ++declare class Cosmos { + transport: Transport; + constructor(transport: Transport, scrambleKey?: string); + getAppConfiguration(): Promise<{ +@@ -53,4 +53,6 @@ export default class Cosmos { + return_code: number | string; + }>; + } ++export { Cosmos }; ++export default Cosmos; + //# sourceMappingURL=Cosmos.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-app-cosmos/lib-es/Cosmos.js b/node_modules/@ledgerhq/hw-app-cosmos/lib-es/Cosmos.js +index 1b0b463..49c69b2 100644 +--- a/node_modules/@ledgerhq/hw-app-cosmos/lib-es/Cosmos.js ++++ b/node_modules/@ledgerhq/hw-app-cosmos/lib-es/Cosmos.js +@@ -27,7 +27,7 @@ const SW_CANCEL = 0x6986; + * import Cosmos from "@ledgerhq/hw-app-cosmos"; + * const cosmos = new Cosmos(transport) + */ +-export default class Cosmos { ++class Cosmos { + constructor(transport, scrambleKey = APP_KEY) { + this.transport = transport; + transport.decorateAppAPIMethods(this, ["getAddress", "sign", "getAppConfiguration"], scrambleKey); +@@ -140,4 +140,6 @@ export default class Cosmos { + }); + } + } ++export { Cosmos }; ++export default Cosmos; + //# sourceMappingURL=Cosmos.js.map +diff --git a/node_modules/@ledgerhq/hw-app-cosmos/lib/Cosmos.d.ts b/node_modules/@ledgerhq/hw-app-cosmos/lib/Cosmos.d.ts +index 0317ca3..a6d0ffa 100644 +--- a/node_modules/@ledgerhq/hw-app-cosmos/lib/Cosmos.d.ts ++++ b/node_modules/@ledgerhq/hw-app-cosmos/lib/Cosmos.d.ts +@@ -23,7 +23,7 @@ import type Transport from "@ledgerhq/hw-transport"; + * import Cosmos from "@ledgerhq/hw-app-cosmos"; + * const cosmos = new Cosmos(transport) + */ +-export default class Cosmos { ++declare class Cosmos { + transport: Transport; + constructor(transport: Transport, scrambleKey?: string); + getAppConfiguration(): Promise<{ +@@ -53,4 +53,6 @@ export default class Cosmos { + return_code: number | string; + }>; + } ++export { Cosmos }; ++export default Cosmos; + //# sourceMappingURL=Cosmos.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-app-cosmos/lib/Cosmos.js b/node_modules/@ledgerhq/hw-app-cosmos/lib/Cosmos.js +index c91196d..7acc3d7 100644 +--- a/node_modules/@ledgerhq/hw-app-cosmos/lib/Cosmos.js ++++ b/node_modules/@ledgerhq/hw-app-cosmos/lib/Cosmos.js +@@ -145,5 +145,6 @@ class Cosmos { + }); + } + } ++exports.Cosmos = Cosmos; + exports.default = Cosmos; + //# sourceMappingURL=Cosmos.js.map +diff --git a/node_modules/@ledgerhq/hw-app-cosmos/src/Cosmos.ts b/node_modules/@ledgerhq/hw-app-cosmos/src/Cosmos.ts +index 34ade2e..767bbd6 100644 +--- a/node_modules/@ledgerhq/hw-app-cosmos/src/Cosmos.ts ++++ b/node_modules/@ledgerhq/hw-app-cosmos/src/Cosmos.ts +@@ -36,7 +36,7 @@ const SW_CANCEL = 0x6986; + * const cosmos = new Cosmos(transport) + */ + +-export default class Cosmos { ++class Cosmos { + transport: Transport; + + constructor(transport: Transport, scrambleKey: string = APP_KEY) { +@@ -194,3 +194,6 @@ export default class Cosmos { + }); + } + } ++ ++export { Cosmos }; ++export default Cosmos; diff --git a/patches/@ledgerhq+hw-app-eth+6.42.0.patch b/patches/@ledgerhq+hw-app-eth+6.42.0.patch new file mode 100644 index 000000000..3180f2456 --- /dev/null +++ b/patches/@ledgerhq+hw-app-eth+6.42.0.patch @@ -0,0 +1,94 @@ +diff --git a/node_modules/@ledgerhq/hw-app-eth/.DS_Store b/node_modules/@ledgerhq/hw-app-eth/.DS_Store +new file mode 100644 +index 0000000..6538df2 +Binary files /dev/null and b/node_modules/@ledgerhq/hw-app-eth/.DS_Store differ +diff --git a/node_modules/@ledgerhq/hw-app-eth/lib-es/Eth.d.ts b/node_modules/@ledgerhq/hw-app-eth/lib-es/Eth.d.ts +index b1044d5..6ff52af 100644 +--- a/node_modules/@ledgerhq/hw-app-eth/lib-es/Eth.d.ts ++++ b/node_modules/@ledgerhq/hw-app-eth/lib-es/Eth.d.ts +@@ -14,7 +14,7 @@ export type StarkQuantizationType = "eth" | "erc20" | "erc721" | "erc20mintable" + * import Eth from "@ledgerhq/hw-app-eth"; + * const eth = new Eth(transport) + */ +-export default class Eth { ++declare class Eth { + transport: Transport; + loadConfig: LoadConfig; + setLoadConfig(loadConfig: LoadConfig): void; +@@ -353,4 +353,6 @@ export default class Eth { + */ + provideDomainName(data: string): Promise; + } ++export { Eth }; ++export default Eth; + //# sourceMappingURL=Eth.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-app-eth/lib-es/Eth.js b/node_modules/@ledgerhq/hw-app-eth/lib-es/Eth.js +index 05972b0..64c9a6f 100644 +--- a/node_modules/@ledgerhq/hw-app-eth/lib-es/Eth.js ++++ b/node_modules/@ledgerhq/hw-app-eth/lib-es/Eth.js +@@ -38,7 +38,7 @@ const remapTransactionRelatedErrors = e => { + * import Eth from "@ledgerhq/hw-app-eth"; + * const eth = new Eth(transport) + */ +-export default class Eth { ++class Eth { + setLoadConfig(loadConfig) { + this.loadConfig = loadConfig; + } +@@ -959,4 +959,6 @@ export default class Eth { + }); + } + } ++export { Eth }; ++export default Eth; + //# sourceMappingURL=Eth.js.map +diff --git a/node_modules/@ledgerhq/hw-app-eth/lib/Eth.d.ts b/node_modules/@ledgerhq/hw-app-eth/lib/Eth.d.ts +index b1044d5..6ff52af 100644 +--- a/node_modules/@ledgerhq/hw-app-eth/lib/Eth.d.ts ++++ b/node_modules/@ledgerhq/hw-app-eth/lib/Eth.d.ts +@@ -14,7 +14,7 @@ export type StarkQuantizationType = "eth" | "erc20" | "erc721" | "erc20mintable" + * import Eth from "@ledgerhq/hw-app-eth"; + * const eth = new Eth(transport) + */ +-export default class Eth { ++declare class Eth { + transport: Transport; + loadConfig: LoadConfig; + setLoadConfig(loadConfig: LoadConfig): void; +@@ -353,4 +353,6 @@ export default class Eth { + */ + provideDomainName(data: string): Promise; + } ++export { Eth }; ++export default Eth; + //# sourceMappingURL=Eth.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-app-eth/lib/Eth.js b/node_modules/@ledgerhq/hw-app-eth/lib/Eth.js +index 7fd2adf..6b2b5f1 100644 +--- a/node_modules/@ledgerhq/hw-app-eth/lib/Eth.js ++++ b/node_modules/@ledgerhq/hw-app-eth/lib/Eth.js +@@ -979,5 +979,6 @@ class Eth { + }); + } + } ++exports.Eth = Eth; + exports.default = Eth; + //# sourceMappingURL=Eth.js.map +diff --git a/node_modules/@ledgerhq/hw-app-eth/src/Eth.ts b/node_modules/@ledgerhq/hw-app-eth/src/Eth.ts +index 42c1e7a..7123b39 100644 +--- a/node_modules/@ledgerhq/hw-app-eth/src/Eth.ts ++++ b/node_modules/@ledgerhq/hw-app-eth/src/Eth.ts +@@ -50,7 +50,7 @@ const remapTransactionRelatedErrors = e => { + * const eth = new Eth(transport) + */ + +-export default class Eth { ++class Eth { + transport: Transport; + loadConfig: LoadConfig; + +@@ -1265,3 +1265,5 @@ export default class Eth { + return true; + } + } ++export { Eth }; ++export default Eth; diff --git a/patches/@ledgerhq+hw-transport+6.31.4.patch b/patches/@ledgerhq+hw-transport+6.31.4.patch new file mode 100644 index 000000000..8565af5ec --- /dev/null +++ b/patches/@ledgerhq+hw-transport+6.31.4.patch @@ -0,0 +1,86 @@ +diff --git a/node_modules/@ledgerhq/hw-transport/.DS_Store b/node_modules/@ledgerhq/hw-transport/.DS_Store +new file mode 100644 +index 0000000..5ebd040 +Binary files /dev/null and b/node_modules/@ledgerhq/hw-transport/.DS_Store differ +diff --git a/node_modules/@ledgerhq/hw-transport/lib-es/Transport.d.ts b/node_modules/@ledgerhq/hw-transport/lib-es/Transport.d.ts +index 9099450..33d84ac 100644 +--- a/node_modules/@ledgerhq/hw-transport/lib-es/Transport.d.ts ++++ b/node_modules/@ledgerhq/hw-transport/lib-es/Transport.d.ts +@@ -40,7 +40,7 @@ export type Observer = Readonly<{ + * There are different kind of transports based on the technology (channels like U2F, HID, Bluetooth, Webusb) and environment (Node, Web,...). + * It is an abstract class that needs to be implemented. + */ +-export default class Transport { ++declare class Transport { + exchangeTimeout: number; + unresponsiveTimeout: number; + deviceModel: DeviceModel | null | undefined; +@@ -220,4 +220,6 @@ export default class Transport { + static ErrorMessage_ListenTimeout: string; + static ErrorMessage_NoDeviceFound: string; + } ++export { Transport }; ++export default Transport; + //# sourceMappingURL=Transport.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-transport/lib-es/Transport.js b/node_modules/@ledgerhq/hw-transport/lib-es/Transport.js +index 2dfe25c..ac10991 100644 +--- a/node_modules/@ledgerhq/hw-transport/lib-es/Transport.js ++++ b/node_modules/@ledgerhq/hw-transport/lib-es/Transport.js +@@ -297,5 +297,6 @@ class Transport { + } + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; ++export { Transport }; + export default Transport; + //# sourceMappingURL=Transport.js.map +diff --git a/node_modules/@ledgerhq/hw-transport/lib/Transport.d.ts b/node_modules/@ledgerhq/hw-transport/lib/Transport.d.ts +index 9099450..33d84ac 100644 +--- a/node_modules/@ledgerhq/hw-transport/lib/Transport.d.ts ++++ b/node_modules/@ledgerhq/hw-transport/lib/Transport.d.ts +@@ -40,7 +40,7 @@ export type Observer = Readonly<{ + * There are different kind of transports based on the technology (channels like U2F, HID, Bluetooth, Webusb) and environment (Node, Web,...). + * It is an abstract class that needs to be implemented. + */ +-export default class Transport { ++declare class Transport { + exchangeTimeout: number; + unresponsiveTimeout: number; + deviceModel: DeviceModel | null | undefined; +@@ -220,4 +220,6 @@ export default class Transport { + static ErrorMessage_ListenTimeout: string; + static ErrorMessage_NoDeviceFound: string; + } ++export { Transport }; ++export default Transport; + //# sourceMappingURL=Transport.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-transport/lib/Transport.js b/node_modules/@ledgerhq/hw-transport/lib/Transport.js +index 2d23d92..e485bc2 100644 +--- a/node_modules/@ledgerhq/hw-transport/lib/Transport.js ++++ b/node_modules/@ledgerhq/hw-transport/lib/Transport.js +@@ -306,5 +306,6 @@ class Transport { + } + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; ++exports.Transport = Transport; + exports.default = Transport; + //# sourceMappingURL=Transport.js.map +diff --git a/node_modules/@ledgerhq/hw-transport/src/Transport.ts b/node_modules/@ledgerhq/hw-transport/src/Transport.ts +index d44d282..74068fc 100644 +--- a/node_modules/@ledgerhq/hw-transport/src/Transport.ts ++++ b/node_modules/@ledgerhq/hw-transport/src/Transport.ts +@@ -51,7 +51,7 @@ export type Observer = Readonly<{ + * There are different kind of transports based on the technology (channels like U2F, HID, Bluetooth, Webusb) and environment (Node, Web,...). + * It is an abstract class that needs to be implemented. + */ +-export default class Transport { ++class Transport { + exchangeTimeout = 30000; + unresponsiveTimeout = 15000; + deviceModel: DeviceModel | null | undefined = null; +@@ -445,3 +445,6 @@ export default class Transport { + static ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + static ErrorMessage_NoDeviceFound = "No Ledger device found"; + } ++ ++export { Transport }; ++export default Transport; diff --git a/patches/@ledgerhq+hw-transport-webhid+6.29.4.patch b/patches/@ledgerhq+hw-transport-webhid+6.29.4.patch new file mode 100644 index 000000000..e9bbffb35 --- /dev/null +++ b/patches/@ledgerhq+hw-transport-webhid+6.29.4.patch @@ -0,0 +1,87 @@ +diff --git a/node_modules/@ledgerhq/hw-transport-webhid/.DS_Store b/node_modules/@ledgerhq/hw-transport-webhid/.DS_Store +new file mode 100644 +index 0000000..5ebd040 +Binary files /dev/null and b/node_modules/@ledgerhq/hw-transport-webhid/.DS_Store differ +diff --git a/node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.d.ts b/node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.d.ts +index fcaad75..f552bf7 100644 +--- a/node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.d.ts ++++ b/node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.d.ts +@@ -11,7 +11,7 @@ declare function getLedgerDevices(): Promise; + * ... + * TransportWebHID.create().then(transport => ...) + */ +-export default class TransportWebHID extends Transport { ++declare class TransportWebHID extends Transport { + device: HIDDevice; + deviceModel: DeviceModel | null | undefined; + channel: number; +@@ -62,5 +62,6 @@ export default class TransportWebHID extends Transport { + exchange: (apdu: Buffer) => Promise; + setScrambleKey(): void; + } +-export {}; ++export { TransportWebHID }; ++export default TransportWebHID; + //# sourceMappingURL=TransportWebHID.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.js b/node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.js +index 8246e08..3310fd1 100644 +--- a/node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.js ++++ b/node_modules/@ledgerhq/hw-transport-webhid/lib-es/TransportWebHID.js +@@ -216,5 +216,6 @@ TransportWebHID.listen = (observer) => { + unsubscribe, + }; + }; ++export { TransportWebHID }; + export default TransportWebHID; + //# sourceMappingURL=TransportWebHID.js.map +diff --git a/node_modules/@ledgerhq/hw-transport-webhid/lib/TransportWebHID.d.ts b/node_modules/@ledgerhq/hw-transport-webhid/lib/TransportWebHID.d.ts +index fcaad75..f552bf7 100644 +--- a/node_modules/@ledgerhq/hw-transport-webhid/lib/TransportWebHID.d.ts ++++ b/node_modules/@ledgerhq/hw-transport-webhid/lib/TransportWebHID.d.ts +@@ -11,7 +11,7 @@ declare function getLedgerDevices(): Promise; + * ... + * TransportWebHID.create().then(transport => ...) + */ +-export default class TransportWebHID extends Transport { ++declare class TransportWebHID extends Transport { + device: HIDDevice; + deviceModel: DeviceModel | null | undefined; + channel: number; +@@ -62,5 +62,6 @@ export default class TransportWebHID extends Transport { + exchange: (apdu: Buffer) => Promise; + setScrambleKey(): void; + } +-export {}; ++export { TransportWebHID }; ++export default TransportWebHID; + //# sourceMappingURL=TransportWebHID.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-transport-webhid/lib/TransportWebHID.js b/node_modules/@ledgerhq/hw-transport-webhid/lib/TransportWebHID.js +index 0d1228c..d3c3f3e 100644 +--- a/node_modules/@ledgerhq/hw-transport-webhid/lib/TransportWebHID.js ++++ b/node_modules/@ledgerhq/hw-transport-webhid/lib/TransportWebHID.js +@@ -221,5 +221,6 @@ TransportWebHID.listen = (observer) => { + unsubscribe, + }; + }; ++exports.TransportWebHID = TransportWebHID; + exports.default = TransportWebHID; + //# sourceMappingURL=TransportWebHID.js.map +diff --git a/node_modules/@ledgerhq/hw-transport-webhid/src/TransportWebHID.ts b/node_modules/@ledgerhq/hw-transport-webhid/src/TransportWebHID.ts +index 0ddb4eb..6052cd4 100644 +--- a/node_modules/@ledgerhq/hw-transport-webhid/src/TransportWebHID.ts ++++ b/node_modules/@ledgerhq/hw-transport-webhid/src/TransportWebHID.ts +@@ -53,7 +53,7 @@ async function getFirstLedgerDevice(): Promise { + * TransportWebHID.create().then(transport => ...) + */ + +-export default class TransportWebHID extends Transport { ++class TransportWebHID extends Transport { + device: HIDDevice; + deviceModel: DeviceModel | null | undefined; + channel = Math.floor(Math.random() * 0xffff); +@@ -232,3 +232,5 @@ export default class TransportWebHID extends Transport { + + setScrambleKey() {} + } ++export { TransportWebHID }; ++export default TransportWebHID; diff --git a/patches/@ledgerhq+hw-transport-webusb+6.29.4.patch b/patches/@ledgerhq+hw-transport-webusb+6.29.4.patch new file mode 100644 index 000000000..f184fe079 --- /dev/null +++ b/patches/@ledgerhq+hw-transport-webusb+6.29.4.patch @@ -0,0 +1,91 @@ +diff --git a/node_modules/@ledgerhq/hw-transport-webusb/.DS_Store b/node_modules/@ledgerhq/hw-transport-webusb/.DS_Store +new file mode 100644 +index 0000000..a0f42bc +Binary files /dev/null and b/node_modules/@ledgerhq/hw-transport-webusb/.DS_Store differ +diff --git a/node_modules/@ledgerhq/hw-transport-webusb/lib-es/TransportWebUSB.d.ts b/node_modules/@ledgerhq/hw-transport-webusb/lib-es/TransportWebUSB.d.ts +index d90d860..b8810fa 100644 +--- a/node_modules/@ledgerhq/hw-transport-webusb/lib-es/TransportWebUSB.d.ts ++++ b/node_modules/@ledgerhq/hw-transport-webusb/lib-es/TransportWebUSB.d.ts +@@ -11,7 +11,7 @@ import { getLedgerDevices } from "./webusb"; + * ... + * TransportWebUSB.create().then(transport => ...) + */ +-export default class TransportWebUSB extends Transport { ++declare class TransportWebUSB extends Transport { + device: USBDevice; + deviceModel: DeviceModel | null | undefined; + channel: number; +@@ -59,4 +59,6 @@ export default class TransportWebUSB extends Transport { + exchange(apdu: Buffer): Promise; + setScrambleKey(): void; + } ++export { TransportWebUSB }; ++export default TransportWebUSB; + //# sourceMappingURL=TransportWebUSB.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-transport-webusb/lib-es/TransportWebUSB.js b/node_modules/@ledgerhq/hw-transport-webusb/lib-es/TransportWebUSB.js +index 830d2e2..5d958f1 100644 +--- a/node_modules/@ledgerhq/hw-transport-webusb/lib-es/TransportWebUSB.js ++++ b/node_modules/@ledgerhq/hw-transport-webusb/lib-es/TransportWebUSB.js +@@ -185,6 +185,7 @@ TransportWebUSB.listen = (observer) => { + unsubscribe, + }; + }; ++export { TransportWebUSB }; + export default TransportWebUSB; + function gracefullyResetDevice(device) { + return __awaiter(this, void 0, void 0, function* () { +diff --git a/node_modules/@ledgerhq/hw-transport-webusb/lib/TransportWebUSB.d.ts b/node_modules/@ledgerhq/hw-transport-webusb/lib/TransportWebUSB.d.ts +index d90d860..b8810fa 100644 +--- a/node_modules/@ledgerhq/hw-transport-webusb/lib/TransportWebUSB.d.ts ++++ b/node_modules/@ledgerhq/hw-transport-webusb/lib/TransportWebUSB.d.ts +@@ -11,7 +11,7 @@ import { getLedgerDevices } from "./webusb"; + * ... + * TransportWebUSB.create().then(transport => ...) + */ +-export default class TransportWebUSB extends Transport { ++declare class TransportWebUSB extends Transport { + device: USBDevice; + deviceModel: DeviceModel | null | undefined; + channel: number; +@@ -59,4 +59,6 @@ export default class TransportWebUSB extends Transport { + exchange(apdu: Buffer): Promise; + setScrambleKey(): void; + } ++export { TransportWebUSB }; ++export default TransportWebUSB; + //# sourceMappingURL=TransportWebUSB.d.ts.map +diff --git a/node_modules/@ledgerhq/hw-transport-webusb/lib/TransportWebUSB.js b/node_modules/@ledgerhq/hw-transport-webusb/lib/TransportWebUSB.js +index b821c0b..acaee43 100644 +--- a/node_modules/@ledgerhq/hw-transport-webusb/lib/TransportWebUSB.js ++++ b/node_modules/@ledgerhq/hw-transport-webusb/lib/TransportWebUSB.js +@@ -190,6 +190,7 @@ TransportWebUSB.listen = (observer) => { + unsubscribe, + }; + }; ++exports.TransportWebUSB = TransportWebUSB; + exports.default = TransportWebUSB; + function gracefullyResetDevice(device) { + return __awaiter(this, void 0, void 0, function* () { +diff --git a/node_modules/@ledgerhq/hw-transport-webusb/src/TransportWebUSB.ts b/node_modules/@ledgerhq/hw-transport-webusb/src/TransportWebUSB.ts +index f215b88..887c0dd 100644 +--- a/node_modules/@ledgerhq/hw-transport-webusb/src/TransportWebUSB.ts ++++ b/node_modules/@ledgerhq/hw-transport-webusb/src/TransportWebUSB.ts +@@ -23,7 +23,7 @@ const endpointNumber = 3; + * ... + * TransportWebUSB.create().then(transport => ...) + */ +-export default class TransportWebUSB extends Transport { ++class TransportWebUSB extends Transport { + device: USBDevice; + deviceModel: DeviceModel | null | undefined; + channel = Math.floor(Math.random() * 0xffff); +@@ -211,7 +211,8 @@ export default class TransportWebUSB extends Transport { + + setScrambleKey() {} + } +- ++export { TransportWebUSB }; ++export default TransportWebUSB; + async function gracefullyResetDevice(device: USBDevice) { + try { + await device.reset(); diff --git a/patches/@trezor+connect-web+9.4.5.patch b/patches/@trezor+connect-web+9.4.5.patch new file mode 100644 index 000000000..d625bba02 --- /dev/null +++ b/patches/@trezor+connect-web+9.4.5.patch @@ -0,0 +1,25 @@ +diff --git a/node_modules/@trezor/connect-web/lib/index.d.ts b/node_modules/@trezor/connect-web/lib/index.d.ts +index 7a8e473..fdc76ea 100644 +--- a/node_modules/@trezor/connect-web/lib/index.d.ts ++++ b/node_modules/@trezor/connect-web/lib/index.d.ts +@@ -7,6 +7,6 @@ type ConnectWebExtraMethods = { + declare const TrezorConnect: Omit & { + init: import("@trezor/connect/lib/types/api/init").InitType; + } & ConnectWebExtraMethods; +-export default TrezorConnect; ++export { TrezorConnect }; + export * from '@trezor/connect/lib/exports'; + //# sourceMappingURL=index.d.ts.map +diff --git a/node_modules/@trezor/connect-web/lib/index.js b/node_modules/@trezor/connect-web/lib/index.js +index 63cf4e0..1b6ca1a 100644 +--- a/node_modules/@trezor/connect-web/lib/index.js ++++ b/node_modules/@trezor/connect-web/lib/index.js +@@ -72,6 +72,7 @@ const TrezorConnect = (0, factory_1.factory)({ + disableWebUSB: impl.getTarget().disableWebUSB.bind(impl), + requestWebUSBDevice: impl.getTarget().requestWebUSBDevice.bind(impl), + }); +-exports.default = TrezorConnect; ++// exports.default = TrezorConnect; ++exports.TrezorConnect = TrezorConnect; + tslib_1.__exportStar(require("@trezor/connect/lib/exports"), exports); + //# sourceMappingURL=index.js.map diff --git a/patches/@walletconnect+ethereum-provider+2.17.2.patch b/patches/@walletconnect+ethereum-provider+2.17.2.patch new file mode 100644 index 000000000..a0da23f2f --- /dev/null +++ b/patches/@walletconnect+ethereum-provider+2.17.2.patch @@ -0,0 +1,233 @@ +diff --git a/node_modules/@walletconnect/ethereum-provider/.DS_Store b/node_modules/@walletconnect/ethereum-provider/.DS_Store +new file mode 100644 +index 0000000..5008ddf +Binary files /dev/null and b/node_modules/@walletconnect/ethereum-provider/.DS_Store differ +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js b/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js +index 9b5b22d..49f7d4d 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js +@@ -1,2 +1,2 @@ +-"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var M=require("events"),p=require("@walletconnect/utils"),P=require("@walletconnect/universal-provider");function A(a){if(a&&a.__esModule)return a;var t=Object.create(null);return a&&Object.keys(a).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(a,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return a[e]}})}}),t.default=a,Object.freeze(t)}const T="wc",S="ethereum_provider",R=`${T}@2:${S}:`,j="https://rpc.walletconnect.org/v1/",g=["eth_sendTransaction","personal_sign"],_=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],m=["chainChanged","accountsChanged"],y=["chainChanged","accountsChanged","message","disconnect","connect"];var N=Object.defineProperty,q=Object.defineProperties,D=Object.getOwnPropertyDescriptors,O=Object.getOwnPropertySymbols,$=Object.prototype.hasOwnProperty,U=Object.prototype.propertyIsEnumerable,b=(a,t,e)=>t in a?N(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,u=(a,t)=>{for(var e in t||(t={}))$.call(t,e)&&b(a,e,t[e]);if(O)for(var e of O(t))U.call(t,e)&&b(a,e,t[e]);return a},E=(a,t)=>q(a,D(t));function v(a){return Number(a[0].split(":")[1])}function C(a){return`0x${a.toString(16)}`}function Q(a){const{chains:t,optionalChains:e,methods:s,optionalMethods:i,events:n,optionalEvents:o,rpcMap:c}=a;if(!p.isValidArray(t))throw new Error("Invalid chains");const r={chains:t,methods:s||g,events:n||m,rpcMap:u({},t.length?{[v(t)]:c[v(t)]}:{})},h=n?.filter(l=>!m.includes(l)),d=s?.filter(l=>!g.includes(l));if(!e&&!o&&!i&&!(h!=null&&h.length)&&!(d!=null&&d.length))return{required:t.length?r:void 0};const w=h?.length&&d?.length||!e,f={chains:[...new Set(w?r.chains.concat(e||[]):e)],methods:[...new Set(r.methods.concat(i!=null&&i.length?i:_))],events:[...new Set(r.events.concat(o!=null&&o.length?o:y))],rpcMap:c};return{required:t.length?r:void 0,optional:e.length?f:void 0}}class I{constructor(){this.events=new M.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=R,this.on=(t,e)=>(this.events.on(t,e),this),this.once=(t,e)=>(this.events.once(t,e),this),this.removeListener=(t,e)=>(this.events.removeListener(t,e),this),this.off=(t,e)=>(this.events.off(t,e),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const e=new I;return await e.initialize(t),e}async request(t,e){return await this.signer.request(t,this.formatChainId(this.chainId),e)}sendAsync(t,e,s){this.signer.sendAsync(t,e,this.formatChainId(this.chainId),s)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:e,optional:s}=Q(this.rpc);try{const i=await new Promise(async(o,c)=>{var r;this.rpc.showQrModal&&((r=this.modal)==null||r.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(E(u({namespaces:u({},e&&{[this.namespace]:e})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:t?.pairingTopic})).then(h=>{o(h)}).catch(h=>{c(new Error(h.message))})});if(!i)return;const n=p.getAccountsFromNamespaces(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:C(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async authenticate(t,e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const s=await new Promise(async(n,o)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(E(u({},t),{chains:this.rpc.chains}),e).then(r=>{n(r)}).catch(r=>{o(new Error(r.message))})}),i=s.session;if(i){const n=p.getAccountsFromNamespaces(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:C(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:e}=t,{event:s}=e;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const e=parseInt(t);this.chainId=e,this.events.emit("chainChanged",C(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",E(u({},p.getSdkError("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var e,s;this.rpc.showQrModal&&((e=this.modal)==null||e.closeModal(),(s=this.modal)==null||s.openModal({uri:t})),this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const e=t.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));e.length&&(this.chainId=e[0],this.events.emit("chainChanged",C(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const e=this.parseChainId(t);this.chainId=e,this.switchEthereumChain(e)}}parseAccountId(t){const[e,s,i]=t.split(":");return{chainId:`${e}:${s}`,address:i}}setAccounts(t){this.accounts=t.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var e,s;const i=(e=t?.chains)!=null?e:[],n=(s=t?.optionalChains)!=null?s:[],o=i.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const c=i.length?t?.methods||g:[],r=i.length?t?.events||m:[],h=t?.optionalMethods||[],d=t?.optionalEvents||[],w=t?.rpcMap||this.buildRpcMap(o,t.projectId),f=t?.qrModalOptions||void 0;return{chains:i?.map(l=>this.formatChainId(l)),optionalChains:n.map(l=>this.formatChainId(l)),methods:c,events:r,optionalMethods:h,optionalEvents:d,rpcMap:w,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:f,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,e){const s={};return t.forEach(i=>{s[i]=this.getRpcUrl(i,e)}),s}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?v(this.rpc.chains):v(this.rpc.optionalChains),this.signer=await P.UniversalProvider.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let e;try{const{WalletConnectModal:s}=await Promise.resolve().then(function(){return A(require("@walletconnect/modal"))});e=s}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(e)try{this.modal=new e(u({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:e,optionalChains:s,rpcMap:i}=t;e&&p.isValidArray(e)&&(this.rpc.chains=e.map(n=>this.formatChainId(n)),e.forEach(n=>{this.rpc.rpcMap[n]=i?.[n]||this.getRpcUrl(n)})),s&&p.isValidArray(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=i?.[n]||this.getRpcUrl(n)}))}getRpcUrl(t,e){var s;return((s=this.rpc.rpcMap)==null?void 0:s[t])||`${j}?chainId=eip155:${t}&projectId=${e||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),e=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:e?.accounts),this.setAccounts(e?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(e=>this.signer.logger.warn(e))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(e=>this.parseAccount(e))}}const L=I;exports.EthereumProvider=L,exports.OPTIONAL_EVENTS=y,exports.OPTIONAL_METHODS=_,exports.REQUIRED_EVENTS=m,exports.REQUIRED_METHODS=g,exports.default=I; ++"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var P=require("events"),p=require("@walletconnect/utils"),M=require("@walletconnect/universal-provider");function A(a){if(a&&a.__esModule)return a;var t=Object.create(null);return a&&Object.keys(a).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(a,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return a[e]}})}}),t.default=a,Object.freeze(t)}const T="wc",S="ethereum_provider",R=`${T}@2:${S}:`,j="https://rpc.walletconnect.org/v1/",g=["eth_sendTransaction","personal_sign"],_=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],m=["chainChanged","accountsChanged"],y=["chainChanged","accountsChanged","message","disconnect","connect"];var N=Object.defineProperty,q=Object.defineProperties,D=Object.getOwnPropertyDescriptors,O=Object.getOwnPropertySymbols,$=Object.prototype.hasOwnProperty,U=Object.prototype.propertyIsEnumerable,b=(a,t,e)=>t in a?N(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,u=(a,t)=>{for(var e in t||(t={}))$.call(t,e)&&b(a,e,t[e]);if(O)for(var e of O(t))U.call(t,e)&&b(a,e,t[e]);return a},f=(a,t)=>q(a,D(t));function v(a){return Number(a[0].split(":")[1])}function C(a){return`0x${a.toString(16)}`}function Q(a){const{chains:t,optionalChains:e,methods:s,optionalMethods:i,events:n,optionalEvents:o,rpcMap:c}=a;if(!p.isValidArray(t))throw new Error("Invalid chains");const r={chains:t,methods:s||g,events:n||m,rpcMap:u({},t.length?{[v(t)]:c[v(t)]}:{})},h=n?.filter(l=>!m.includes(l)),d=s?.filter(l=>!g.includes(l));if(!e&&!o&&!i&&!(h!=null&&h.length)&&!(d!=null&&d.length))return{required:t.length?r:void 0};const w=h?.length&&d?.length||!e,E={chains:[...new Set(w?r.chains.concat(e||[]):e)],methods:[...new Set(r.methods.concat(i!=null&&i.length?i:_))],events:[...new Set(r.events.concat(o!=null&&o.length?o:y))],rpcMap:c};return{required:t.length?r:void 0,optional:e.length?E:void 0}}class I{constructor(){this.events=new P.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=R,this.on=(t,e)=>(this.events.on(t,e),this),this.once=(t,e)=>(this.events.once(t,e),this),this.removeListener=(t,e)=>(this.events.removeListener(t,e),this),this.off=(t,e)=>(this.events.off(t,e),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const e=new I;return await e.initialize(t),e}async request(t,e){return await this.signer.request(t,this.formatChainId(this.chainId),e)}sendAsync(t,e,s){this.signer.sendAsync(t,e,this.formatChainId(this.chainId),s)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:e,optional:s}=Q(this.rpc);try{const i=await new Promise(async(o,c)=>{var r;this.rpc.showQrModal&&((r=this.modal)==null||r.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(f(u({namespaces:u({},e&&{[this.namespace]:e})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:t?.pairingTopic})).then(h=>{o(h)}).catch(h=>{c(new Error(h.message))})});if(!i)return;const n=p.getAccountsFromNamespaces(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:C(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async authenticate(t,e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const s=await new Promise(async(n,o)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(r=>{!r.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(f(u({},t),{chains:this.rpc.chains}),e).then(r=>{n(r)}).catch(r=>{o(new Error(r.message))})}),i=s.session;if(i){const n=p.getAccountsFromNamespaces(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:C(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:e}=t,{event:s}=e;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const e=parseInt(t);this.chainId=e,this.events.emit("chainChanged",C(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",f(u({},p.getSdkError("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var e,s;this.rpc.showQrModal&&((e=this.modal)==null||e.closeModal(),(s=this.modal)==null||s.openModal({uri:t})),this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const e=t.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));e.length&&(this.chainId=e[0],this.events.emit("chainChanged",C(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const e=this.parseChainId(t);this.chainId=e,this.switchEthereumChain(e)}}parseAccountId(t){const[e,s,i]=t.split(":");return{chainId:`${e}:${s}`,address:i}}setAccounts(t){this.accounts=t.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var e,s;const i=(e=t?.chains)!=null?e:[],n=(s=t?.optionalChains)!=null?s:[],o=i.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const c=i.length?t?.methods||g:[],r=i.length?t?.events||m:[],h=t?.optionalMethods||[],d=t?.optionalEvents||[],w=t?.rpcMap||this.buildRpcMap(o,t.projectId),E=t?.qrModalOptions||void 0;return{chains:i?.map(l=>this.formatChainId(l)),optionalChains:n.map(l=>this.formatChainId(l)),methods:c,events:r,optionalMethods:h,optionalEvents:d,rpcMap:w,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:E,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,e){const s={};return t.forEach(i=>{s[i]=this.getRpcUrl(i,e)}),s}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?v(this.rpc.chains):v(this.rpc.optionalChains),this.signer=await M.UniversalProvider.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let e;try{const{WalletConnectModal:s}=await Promise.resolve().then(function(){return A(require("@walletconnect/modal"))});e=s}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(e)try{this.modal=new e(u({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:e,optionalChains:s,rpcMap:i}=t;e&&p.isValidArray(e)&&(this.rpc.chains=e.map(n=>this.formatChainId(n)),e.forEach(n=>{this.rpc.rpcMap[n]=i?.[n]||this.getRpcUrl(n)})),s&&p.isValidArray(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=i?.[n]||this.getRpcUrl(n)}))}getRpcUrl(t,e){var s;return((s=this.rpc.rpcMap)==null?void 0:s[t])||`${j}?chainId=eip155:${t}&projectId=${e||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),e=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:e?.accounts),this.setAccounts(e?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(e=>this.signer.logger.warn(e))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(e=>this.parseAccount(e))}}const L=I;exports.EthereumProvider=L,exports.OPTIONAL_EVENTS=y,exports.OPTIONAL_METHODS=_,exports.Provider=I,exports.REQUIRED_EVENTS=m,exports.REQUIRED_METHODS=g; + //# sourceMappingURL=index.cjs.js.map +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js.map b/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js.map +index 34a86a6..86c1fac 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js.map ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.cjs.js.map +@@ -1 +1 @@ +-{"version":3,"file":"index.cjs.js","sources":["../src/constants/values.ts","../src/constants/rpc.ts","../src/EthereumProvider.ts","../src/index.ts"],"sourcesContent":["export const PROTOCOL = \"wc\";\nexport const WC_VERSION = 2;\nexport const CONTEXT = \"ethereum_provider\";\nexport const STORAGE_KEY = `${PROTOCOL}@${WC_VERSION}:${CONTEXT}:`;\nexport const RPC_URL = \"https://rpc.walletconnect.org/v1/\";\n","export const REQUIRED_METHODS = [\"eth_sendTransaction\", \"personal_sign\"];\nexport const OPTIONAL_METHODS = [\n \"eth_accounts\",\n \"eth_requestAccounts\",\n \"eth_sendRawTransaction\",\n \"eth_sign\",\n \"eth_signTransaction\",\n \"eth_signTypedData\",\n \"eth_signTypedData_v3\",\n \"eth_signTypedData_v4\",\n \"eth_sendTransaction\",\n \"personal_sign\",\n \"wallet_switchEthereumChain\",\n \"wallet_addEthereumChain\",\n \"wallet_getPermissions\",\n \"wallet_requestPermissions\",\n \"wallet_registerOnboarding\",\n \"wallet_watchAsset\",\n \"wallet_scanQRCode\",\n \"wallet_sendCalls\",\n \"wallet_getCapabilities\",\n \"wallet_getCallsStatus\",\n \"wallet_showCallsStatus\",\n];\nexport const REQUIRED_EVENTS = [\"chainChanged\", \"accountsChanged\"];\nexport const OPTIONAL_EVENTS = [\n \"chainChanged\",\n \"accountsChanged\",\n \"message\",\n \"disconnect\",\n \"connect\",\n];\n","import { EventEmitter } from \"events\";\nimport { getAccountsFromNamespaces, getSdkError, isValidArray } from \"@walletconnect/utils\";\nimport { KeyValueStorageOptions } from \"@walletconnect/keyvaluestorage\";\nimport {\n IEthereumProvider as IProvider,\n IEthereumProviderEvents,\n ProviderAccounts,\n RequestArguments,\n QrModalOptions,\n} from \"./types\";\nimport {\n Metadata,\n Namespace,\n UniversalProvider,\n UniversalProviderOpts,\n} from \"@walletconnect/universal-provider\";\nimport { AuthTypes, SessionTypes, SignClientTypes } from \"@walletconnect/types\";\nimport { JsonRpcResult } from \"@walletconnect/jsonrpc-types\";\nimport {\n STORAGE_KEY,\n REQUIRED_METHODS,\n REQUIRED_EVENTS,\n RPC_URL,\n OPTIONAL_METHODS,\n OPTIONAL_EVENTS,\n} from \"./constants\";\n\nexport type RpcMethod =\n | \"personal_sign\"\n | \"eth_sendTransaction\"\n | \"eth_accounts\"\n | \"eth_requestAccounts\"\n | \"eth_call\"\n | \"eth_getBalance\"\n | \"eth_sendRawTransaction\"\n | \"eth_sign\"\n | \"eth_signTransaction\"\n | \"eth_signTypedData\"\n | \"eth_signTypedData_v3\"\n | \"eth_signTypedData_v4\"\n | \"wallet_switchEthereumChain\"\n | \"wallet_addEthereumChain\"\n | \"wallet_getPermissions\"\n | \"wallet_requestPermissions\"\n | \"wallet_registerOnboarding\"\n | \"wallet_watchAsset\"\n | \"wallet_scanQRCode\"\n | \"wallet_sendCalls\"\n | \"wallet_getCapabilities\"\n | \"wallet_getCallsStatus\"\n | \"wallet_showCallsStatus\";\n\nexport type RpcEvent = \"accountsChanged\" | \"chainChanged\" | \"message\" | \"disconnect\" | \"connect\";\n\nexport interface EthereumRpcMap {\n [chainId: string]: string;\n}\n\nexport interface SessionEvent {\n event: { name: string; data: any };\n chainId: string;\n}\n\nexport interface EthereumRpcConfig {\n chains: string[];\n optionalChains: string[];\n methods: string[];\n optionalMethods?: string[];\n /**\n * @description Events that the wallet MUST support or the connection will be rejected\n */\n events: string[];\n optionalEvents?: string[];\n rpcMap: EthereumRpcMap;\n projectId: string;\n metadata?: Metadata;\n showQrModal: boolean;\n qrModalOptions?: QrModalOptions;\n}\nexport interface ConnectOps {\n chains?: number[];\n optionalChains?: number[];\n rpcMap?: EthereumRpcMap;\n pairingTopic?: string;\n}\n\nexport type AuthenticateParams = {\n chains?: number[];\n} & Omit;\n\nexport interface IEthereumProvider extends IProvider {\n connect(opts?: ConnectOps | undefined): Promise;\n}\n\nexport function getRpcUrl(chainId: string, rpc: EthereumRpcConfig): string | undefined {\n let rpcUrl: string | undefined;\n if (rpc.rpcMap) {\n rpcUrl = rpc.rpcMap[getEthereumChainId([chainId])];\n }\n return rpcUrl;\n}\n\nexport function getEthereumChainId(chains: string[]): number {\n return Number(chains[0].split(\":\")[1]);\n}\n\nexport function toHexChainId(chainId: number): string {\n return `0x${chainId.toString(16)}`;\n}\n\nexport type NamespacesParams = {\n chains: EthereumRpcConfig[\"chains\"];\n optionalChains: EthereumRpcConfig[\"optionalChains\"];\n methods?: EthereumRpcConfig[\"methods\"];\n optionalMethods?: EthereumRpcConfig[\"methods\"];\n events?: EthereumRpcConfig[\"events\"];\n rpcMap: EthereumRpcConfig[\"rpcMap\"];\n optionalEvents?: EthereumRpcConfig[\"events\"];\n};\n\nexport function buildNamespaces(params: NamespacesParams): {\n required?: Namespace;\n optional?: Namespace;\n} {\n const { chains, optionalChains, methods, optionalMethods, events, optionalEvents, rpcMap } =\n params;\n if (!isValidArray(chains)) {\n throw new Error(\"Invalid chains\");\n }\n\n const required: Namespace = {\n chains,\n methods: methods || REQUIRED_METHODS,\n events: events || REQUIRED_EVENTS,\n rpcMap: {\n ...(chains.length\n ? { [getEthereumChainId(chains)]: rpcMap[getEthereumChainId(chains)] }\n : {}),\n },\n };\n\n // make a list of events and methods that require additional permissions\n // so we know if we should to include the required chains in the optional namespace\n const eventsRequiringPermissions = events?.filter((event) => !REQUIRED_EVENTS.includes(event));\n const methodsRequiringPermissions = methods?.filter((event) => !REQUIRED_METHODS.includes(event));\n\n if (\n !optionalChains &&\n !optionalEvents &&\n !optionalMethods &&\n !eventsRequiringPermissions?.length &&\n !methodsRequiringPermissions?.length\n ) {\n return { required: chains.length ? required : undefined };\n }\n\n /*\n * decides whether or not to include the required chains in the optional namespace\n * use case: if there is a single chain as required but additional methods/events as optional\n */\n const shouldIncludeRequiredChains =\n (eventsRequiringPermissions?.length && methodsRequiringPermissions?.length) || !optionalChains;\n\n const optional: Namespace = {\n chains: [\n ...new Set(\n shouldIncludeRequiredChains ? required.chains.concat(optionalChains || []) : optionalChains,\n ),\n ],\n methods: [\n ...new Set(\n required.methods.concat(optionalMethods?.length ? optionalMethods : OPTIONAL_METHODS),\n ),\n ],\n events: [\n ...new Set(required.events.concat(optionalEvents?.length ? optionalEvents : OPTIONAL_EVENTS)),\n ],\n rpcMap,\n };\n\n return {\n required: chains.length ? required : undefined,\n optional: optionalChains.length ? optional : undefined,\n };\n}\n\n// helper type to force setting at least one value in an array\ntype ArrayOneOrMore = {\n 0: T;\n} & Array;\n\n/**\n * @param {number[]} chains - The Chains your app intents to use and the peer MUST support. If the peer does not support these chains, the connection will be rejected.\n * @param {number[]} optionalChains - The Chains your app MAY attempt to use and the peer MAY support. If the peer does not support these chains, the connection will still be established.\n * @description either chains or optionalChains must be provided\n */\nexport type ChainsProps =\n | {\n chains: ArrayOneOrMore;\n optionalChains?: number[];\n }\n | {\n chains?: number[];\n optionalChains: ArrayOneOrMore;\n };\n\nexport type EthereumProviderOptions = {\n projectId: string;\n /**\n * @note Methods that your app intents to use and the peer MUST support. If the peer does not support these methods, the connection will be rejected.\n * @default [\"eth_sendTransaction\", \"personal_sign\"]\n */\n methods?: string[];\n /**\n * @note Methods that your app MAY attempt to use and the peer MAY support. If the peer does not support these methods, the connection will still be established.\n */\n optionalMethods?: string[];\n events?: string[];\n optionalEvents?: string[];\n rpcMap?: EthereumRpcMap;\n metadata?: Metadata;\n showQrModal: boolean;\n qrModalOptions?: QrModalOptions;\n disableProviderPing?: boolean;\n relayUrl?: string;\n storageOptions?: KeyValueStorageOptions;\n} & ChainsProps &\n UniversalProviderOpts;\n\nexport class EthereumProvider implements IEthereumProvider {\n public events = new EventEmitter();\n public namespace = \"eip155\";\n public accounts: string[] = [];\n public signer: InstanceType;\n public chainId = 1;\n public modal?: any;\n\n protected rpc: EthereumRpcConfig;\n protected readonly STORAGE_KEY = STORAGE_KEY;\n\n constructor() {\n // assigned during initialize\n this.signer = {} as InstanceType;\n this.rpc = {} as EthereumRpcConfig;\n }\n\n static async init(opts: EthereumProviderOptions): Promise {\n const provider = new EthereumProvider();\n await provider.initialize(opts);\n return provider;\n }\n\n public async request(args: RequestArguments, expiry?: number): Promise {\n return await this.signer.request(args, this.formatChainId(this.chainId), expiry);\n }\n\n public sendAsync(\n args: RequestArguments,\n callback: (error: Error | null, response: JsonRpcResult) => void,\n expiry?: number,\n ): void {\n this.signer.sendAsync(args, callback, this.formatChainId(this.chainId), expiry);\n }\n\n get connected(): boolean {\n if (!this.signer.client) return false;\n return this.signer.client.core.relayer.connected;\n }\n\n get connecting(): boolean {\n if (!this.signer.client) return false;\n return this.signer.client.core.relayer.connecting;\n }\n\n public async enable(): Promise {\n if (!this.session) await this.connect();\n const accounts = await this.request({ method: \"eth_requestAccounts\" });\n return accounts as ProviderAccounts;\n }\n\n public async connect(opts?: ConnectOps): Promise {\n if (!this.signer.client) {\n throw new Error(\"Provider not initialized. Call init() first\");\n }\n\n this.loadConnectOpts(opts);\n const { required, optional } = buildNamespaces(this.rpc);\n try {\n const session = await new Promise(\n async (resolve, reject) => {\n if (this.rpc.showQrModal) {\n this.modal?.subscribeModal((state: { open: boolean }) => {\n // the modal was closed so reject the promise\n if (!state.open && !this.signer.session) {\n this.signer.abortPairingAttempt();\n reject(new Error(\"Connection request reset. Please try again.\"));\n }\n });\n }\n await this.signer\n .connect({\n namespaces: {\n ...(required && {\n [this.namespace]: required,\n }),\n },\n ...(optional && {\n optionalNamespaces: {\n [this.namespace]: optional,\n },\n }),\n pairingTopic: opts?.pairingTopic,\n })\n .then((session?: SessionTypes.Struct) => {\n resolve(session);\n })\n .catch((error: Error) => {\n reject(new Error(error.message));\n });\n },\n );\n if (!session) return;\n\n const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);\n // if no required chains are set, use the approved accounts to fetch chainIds\n this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);\n this.setAccounts(accounts);\n this.events.emit(\"connect\", { chainId: toHexChainId(this.chainId) });\n } catch (error) {\n this.signer.logger.error(error);\n throw error;\n } finally {\n if (this.modal) this.modal.closeModal();\n }\n }\n\n public async authenticate(\n params: AuthenticateParams,\n walletUniversalLink?: string,\n ): Promise {\n if (!this.signer.client) {\n throw new Error(\"Provider not initialized. Call init() first\");\n }\n\n this.loadConnectOpts({\n chains: params?.chains,\n });\n\n try {\n const result = await new Promise(\n async (resolve, reject) => {\n if (this.rpc.showQrModal) {\n this.modal?.subscribeModal((state: { open: boolean }) => {\n // the modal was closed so reject the promise\n if (!state.open && !this.signer.session) {\n this.signer.abortPairingAttempt();\n reject(new Error(\"Connection request reset. Please try again.\"));\n }\n });\n }\n await this.signer\n .authenticate(\n {\n ...params,\n chains: this.rpc.chains,\n },\n walletUniversalLink,\n )\n .then((result: AuthTypes.AuthenticateResponseResult) => {\n resolve(result);\n })\n .catch((error: Error) => {\n reject(new Error(error.message));\n });\n },\n );\n\n const session = result.session;\n if (session) {\n const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);\n // if no required chains are set, use the approved accounts to fetch chainIds as both contain :\n this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);\n this.setAccounts(accounts);\n this.events.emit(\"connect\", { chainId: toHexChainId(this.chainId) });\n }\n return result;\n } catch (error) {\n this.signer.logger.error(error);\n throw error;\n } finally {\n if (this.modal) this.modal.closeModal();\n }\n }\n\n public async disconnect(): Promise {\n if (this.session) {\n await this.signer.disconnect();\n }\n this.reset();\n }\n\n public on: IEthereumProviderEvents[\"on\"] = (event, listener) => {\n this.events.on(event, listener);\n return this;\n };\n\n public once: IEthereumProviderEvents[\"once\"] = (event, listener) => {\n this.events.once(event, listener);\n return this;\n };\n\n public removeListener: IEthereumProviderEvents[\"removeListener\"] = (event, listener) => {\n this.events.removeListener(event, listener);\n return this;\n };\n\n public off: IEthereumProviderEvents[\"off\"] = (event, listener) => {\n this.events.off(event, listener);\n return this;\n };\n\n get isWalletConnect() {\n return true;\n }\n\n get session() {\n return this.signer.session;\n }\n\n // ---------- Protected --------------------------------------------- //\n\n protected registerEventListeners() {\n this.signer.on(\"session_event\", (payload: SignClientTypes.EventArguments[\"session_event\"]) => {\n const { params } = payload;\n const { event } = params;\n if (event.name === \"accountsChanged\") {\n this.accounts = this.parseAccounts(event.data);\n this.events.emit(\"accountsChanged\", this.accounts);\n } else if (event.name === \"chainChanged\") {\n this.setChainId(this.formatChainId(event.data));\n } else {\n this.events.emit(event.name as any, event.data);\n }\n this.events.emit(\"session_event\", payload);\n });\n\n this.signer.on(\"chainChanged\", (chainId: string) => {\n const chain = parseInt(chainId);\n this.chainId = chain;\n this.events.emit(\"chainChanged\", toHexChainId(this.chainId));\n this.persist();\n });\n\n this.signer.on(\n \"session_update\",\n (payload: SignClientTypes.EventArguments[\"session_update\"]) => {\n this.events.emit(\"session_update\", payload);\n },\n );\n\n this.signer.on(\n \"session_delete\",\n (payload: SignClientTypes.EventArguments[\"session_delete\"]) => {\n this.reset();\n this.events.emit(\"session_delete\", payload);\n this.events.emit(\"disconnect\", {\n ...getSdkError(\"USER_DISCONNECTED\"),\n data: payload.topic,\n name: \"USER_DISCONNECTED\",\n });\n },\n );\n\n this.signer.on(\"display_uri\", (uri: string) => {\n if (this.rpc.showQrModal) {\n // to refresh the QR we have to close the modal and open it again\n // until proper API is provided by walletconnect modal\n this.modal?.closeModal();\n this.modal?.openModal({ uri });\n }\n this.events.emit(\"display_uri\", uri);\n });\n }\n\n protected switchEthereumChain(chainId: number): void {\n this.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: chainId.toString(16) }],\n });\n }\n\n protected isCompatibleChainId(chainId: string): boolean {\n return typeof chainId === \"string\" ? chainId.startsWith(`${this.namespace}:`) : false;\n }\n\n protected formatChainId(chainId: number): string {\n return `${this.namespace}:${chainId}`;\n }\n\n protected parseChainId(chainId: string): number {\n return Number(chainId.split(\":\")[1]);\n }\n\n protected setChainIds(chains: string[]) {\n const compatible = chains.filter((x) => this.isCompatibleChainId(x));\n const chainIds = compatible.map((c) => this.parseChainId(c));\n if (chainIds.length) {\n this.chainId = chainIds[0];\n this.events.emit(\"chainChanged\", toHexChainId(this.chainId));\n this.persist();\n }\n }\n\n protected setChainId(chain: string) {\n if (this.isCompatibleChainId(chain)) {\n const chainId = this.parseChainId(chain);\n this.chainId = chainId;\n this.switchEthereumChain(chainId);\n }\n }\n\n protected parseAccountId(account: string): { chainId: string; address: string } {\n const [namespace, reference, address] = account.split(\":\");\n const chainId = `${namespace}:${reference}`;\n return { chainId, address };\n }\n\n protected setAccounts(accounts: string[]) {\n this.accounts = accounts\n .filter((x) => this.parseChainId(this.parseAccountId(x).chainId) === this.chainId)\n .map((x) => this.parseAccountId(x).address);\n this.events.emit(\"accountsChanged\", this.accounts);\n }\n\n protected getRpcConfig(opts: EthereumProviderOptions): EthereumRpcConfig {\n const requiredChains = opts?.chains ?? [];\n const optionalChains = opts?.optionalChains ?? [];\n const allChains = requiredChains.concat(optionalChains);\n if (!allChains.length)\n throw new Error(\"No chains specified in either `chains` or `optionalChains`\");\n const requiredMethods = requiredChains.length ? opts?.methods || REQUIRED_METHODS : [];\n const requiredEvents = requiredChains.length ? opts?.events || REQUIRED_EVENTS : [];\n const optionalMethods = opts?.optionalMethods || [];\n const optionalEvents = opts?.optionalEvents || [];\n const rpcMap = opts?.rpcMap || this.buildRpcMap(allChains, opts.projectId);\n const qrModalOptions = opts?.qrModalOptions || undefined;\n return {\n chains: requiredChains?.map((chain) => this.formatChainId(chain)),\n optionalChains: optionalChains.map((chain) => this.formatChainId(chain)),\n methods: requiredMethods,\n events: requiredEvents,\n optionalMethods,\n optionalEvents,\n rpcMap,\n showQrModal: Boolean(opts?.showQrModal),\n qrModalOptions,\n projectId: opts.projectId,\n metadata: opts.metadata,\n };\n }\n\n protected buildRpcMap(chains: number[], projectId: string): EthereumRpcMap {\n const map: EthereumRpcMap = {};\n chains.forEach((chain) => {\n map[chain] = this.getRpcUrl(chain, projectId);\n });\n return map;\n }\n\n protected async initialize(opts: EthereumProviderOptions) {\n this.rpc = this.getRpcConfig(opts);\n\n this.chainId = this.rpc.chains.length\n ? getEthereumChainId(this.rpc.chains)\n : getEthereumChainId(this.rpc.optionalChains);\n this.signer = await UniversalProvider.init({\n projectId: this.rpc.projectId,\n metadata: this.rpc.metadata,\n disableProviderPing: opts.disableProviderPing,\n relayUrl: opts.relayUrl,\n storageOptions: opts.storageOptions,\n customStoragePrefix: opts.customStoragePrefix,\n telemetryEnabled: opts.telemetryEnabled,\n });\n this.registerEventListeners();\n await this.loadPersistedSession();\n if (this.rpc.showQrModal) {\n let WalletConnectModalClass;\n try {\n const { WalletConnectModal } = await import(\"@walletconnect/modal\");\n WalletConnectModalClass = WalletConnectModal;\n } catch {\n throw new Error(\"To use QR modal, please install @walletconnect/modal package\");\n }\n if (WalletConnectModalClass) {\n try {\n this.modal = new WalletConnectModalClass({\n projectId: this.rpc.projectId,\n ...this.rpc.qrModalOptions,\n });\n } catch (e) {\n this.signer.logger.error(e);\n throw new Error(\"Could not generate WalletConnectModal Instance\");\n }\n }\n }\n }\n\n protected loadConnectOpts(opts?: ConnectOps) {\n if (!opts) return;\n const { chains, optionalChains, rpcMap } = opts;\n if (chains && isValidArray(chains)) {\n this.rpc.chains = chains.map((chain) => this.formatChainId(chain));\n chains.forEach((chain) => {\n this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);\n });\n }\n if (optionalChains && isValidArray(optionalChains)) {\n this.rpc.optionalChains = [];\n this.rpc.optionalChains = optionalChains?.map((chain) => this.formatChainId(chain));\n optionalChains.forEach((chain) => {\n this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);\n });\n }\n }\n\n protected getRpcUrl(chainId: number, projectId?: string): string {\n const providedRpc = this.rpc.rpcMap?.[chainId];\n return (\n providedRpc ||\n `${RPC_URL}?chainId=eip155:${chainId}&projectId=${projectId || this.rpc.projectId}`\n );\n }\n\n protected async loadPersistedSession() {\n if (!this.session) return;\n try {\n const chainId = await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);\n\n // cater to both inline & nested namespace formats\n const namespace = this.session.namespaces[`${this.namespace}:${chainId}`]\n ? this.session.namespaces[`${this.namespace}:${chainId}`]\n : this.session.namespaces[this.namespace];\n\n this.setChainIds(chainId ? [this.formatChainId(chainId)] : namespace?.accounts);\n this.setAccounts(namespace?.accounts);\n } catch (error) {\n this.signer.logger.error(\"Failed to load persisted session, clearing state...\");\n this.signer.logger.error(error);\n await this.disconnect().catch((error) => this.signer.logger.warn(error));\n }\n }\n\n protected reset() {\n this.chainId = 1;\n this.accounts = [];\n }\n\n protected persist() {\n if (!this.session) return;\n this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`, this.chainId);\n }\n\n protected parseAccounts(payload: string | string[]): string[] {\n if (typeof payload === \"string\" || payload instanceof String) {\n return [this.parseAccount(payload)];\n }\n return payload.map((account: string) => this.parseAccount(account));\n }\n\n protected parseAccount = (payload: any): string => {\n return this.isCompatibleChainId(payload) ? this.parseAccountId(payload).address : payload;\n };\n}\n\nexport default EthereumProvider;\n","import { EthereumProvider as Provider } from \"./EthereumProvider\";\nexport const EthereumProvider = Provider;\nexport type { EthereumProviderOptions, RpcEvent, RpcMethod } from \"./EthereumProvider\";\nexport * from \"./constants/rpc\";\nexport default Provider;\n"],"names":["chains","chainId","params","optionalChains","methods","optionalMethods","events","optionalEvents","rpcMap","isValidArray","required","REQUIRED_METHODS","REQUIRED_EVENTS","__spreadValues","eventsRequiringPermissions","event","methodsRequiringPermissions","shouldIncludeRequiredChains","optional","OPTIONAL_METHODS","OPTIONAL_EVENTS","EthereumProvider","EventEmitter","STORAGE_KEY","listener","payload","opts","provider","args","expiry","callback","session","resolve","reject","_a","state","__spreadProps","error","accounts","getAccountsFromNamespaces","walletUniversalLink","result","chain","getSdkError","uri","_b","chainIds","x","c","account","namespace","reference","address","requiredChains","allChains","requiredMethods","requiredEvents","qrModalOptions","projectId","map","UniversalProvider","WalletConnectModalClass","WalletConnectModal","e","RPC_URL","Provider"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAa,MAAA,QAAA,CAAW,IACX,CACA,OAAA,CAAU,oBACV,WAAc,CAAA,CAAA,EAAG,QAA0B,CAAA,GAAA,EAAA,OAAA,CAAA,CAAA,CAAA,CAC3C,OAAU,CAAA;;ACJhB,MAAM,iBAAmB,CAAC,qBAAA,CAAuB,eAAe,CAC1D,CAAA,gBAAA,CAAmB,CAC9B,cACA,CAAA,qBAAA,CACA,wBACA,CAAA,UAAA,CACA,sBACA,mBACA,CAAA,sBAAA,CACA,uBACA,qBACA,CAAA,eAAA,CACA,6BACA,yBACA,CAAA,uBAAA,CACA,2BACA,CAAA,2BAAA,CACA,oBACA,mBACA,CAAA,kBAAA,CACA,yBACA,uBACA,CAAA,wBACF,EACa,eAAkB,CAAA,CAAC,cAAgB,CAAA,iBAAiB,EACpD,eAAkB,CAAA,CAC7B,eACA,iBACA,CAAA,SAAA,CACA,aACA,SACF;;6aCuEO,SAAS,kBAAmBA,CAAAA,CAAAA,CAA0B,CAC3D,OAAO,MAAA,CAAOA,EAAO,CAAC,CAAA,CAAE,MAAM,GAAG,CAAA,CAAE,CAAC,CAAC,CACvC,UAEgB,YAAaC,CAAAA,CAAAA,CAAyB,CACpD,OAAO,CAAKA,EAAAA,EAAAA,CAAAA,CAAQ,SAAS,EAAE,CAAA,CAAA,CACjC,CAYO,SAAS,eAAgBC,CAAAA,CAAAA,CAG9B,CACA,KAAM,CAAE,MAAAF,CAAAA,CAAAA,CAAQ,cAAAG,CAAAA,CAAAA,CAAgB,QAAAC,CAAS,CAAA,eAAA,CAAAC,CAAiB,CAAA,MAAA,CAAAC,CAAQ,CAAA,cAAA,CAAAC,EAAgB,MAAAC,CAAAA,CAAO,CACvFN,CAAAA,CAAAA,CACF,GAAI,CAACO,mBAAaT,CAAM,CAAA,CACtB,MAAM,IAAI,KAAM,CAAA,gBAAgB,EAGlC,MAAMU,CAAAA,CAAsB,CAC1B,MAAAV,CAAAA,CAAAA,CACA,QAASI,CAAWO,EAAAA,gBAAAA,CACpB,MAAQL,CAAAA,CAAAA,EAAUM,eAClB,CAAA,MAAA,CAAQC,EAAA,EACFb,CAAAA,CAAAA,CAAO,MACP,CAAA,CAAE,CAAC,kBAAA,CAAmBA,CAAM,CAAC,EAAGQ,CAAO,CAAA,kBAAA,CAAmBR,CAAM,CAAC,CAAE,CACnE,CAAA,EAER,CAAA,CAAA,CAIMc,CAA6BR,CAAAA,CAAAA,EAAA,YAAAA,CAAQ,CAAA,MAAA,CAAQS,CAAU,EAAA,CAACH,eAAgB,CAAA,QAAA,CAASG,CAAK,CACtFC,CAAAA,CAAAA,CAAAA,CAA8BZ,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAS,CAAA,MAAA,CAAQW,GAAU,CAACJ,gBAAAA,CAAiB,QAASI,CAAAA,CAAK,CAE/F,CAAA,CAAA,GACE,CAACZ,CACD,EAAA,CAACI,GACD,CAACF,CAAAA,EACD,EAACS,CAAA,EAAA,IAAA,EAAAA,CAA4B,CAAA,MAAA,CAAA,EAC7B,EAACE,CAAAA,EAAA,MAAAA,CAA6B,CAAA,MAAA,CAAA,CAE9B,OAAO,CAAE,QAAUhB,CAAAA,CAAAA,CAAO,OAASU,CAAW,CAAA,KAAA,CAAU,CAO1D,CAAA,MAAMO,CACHH,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAA4B,CAAA,MAAA,IAAUE,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAA6B,CAAA,MAAA,CAAA,EAAW,CAACb,CAE5Ee,CAAAA,CAAAA,CAAsB,CAC1B,MAAA,CAAQ,CACN,GAAG,IAAI,GACLD,CAAAA,CAAAA,CAA8BP,CAAS,CAAA,MAAA,CAAO,MAAOP,CAAAA,CAAAA,EAAkB,EAAE,CAAA,CAAIA,CAC/E,CACF,CACA,CAAA,OAAA,CAAS,CACP,GAAG,IAAI,IACLO,CAAS,CAAA,OAAA,CAAQ,OAAOL,CAAA,EAAA,IAAA,EAAAA,CAAiB,CAAA,MAAA,CAASA,CAAkBc,CAAAA,gBAAgB,CACtF,CACF,CAAA,CACA,MAAQ,CAAA,CACN,GAAG,IAAI,IAAIT,CAAS,CAAA,MAAA,CAAO,MAAOH,CAAAA,CAAAA,EAAA,IAAAA,EAAAA,CAAAA,CAAgB,OAASA,CAAiBa,CAAAA,eAAe,CAAC,CAC9F,CACA,CAAA,MAAA,CAAAZ,CACF,CAEA,CAAA,OAAO,CACL,QAAA,CAAUR,CAAO,CAAA,MAAA,CAASU,EAAW,KACrC,CAAA,CAAA,QAAA,CAAUP,CAAe,CAAA,MAAA,CAASe,CAAW,CAAA,KAAA,CAC/C,CACF,CA6CO,MAAMG,kBAA8C,CAWzD,WAAc,EAAA,CAVd,KAAO,MAAS,CAAA,IAAIC,oBACpB,IAAO,CAAA,SAAA,CAAY,SACnB,IAAO,CAAA,QAAA,CAAqB,EAAC,CAE7B,IAAO,CAAA,OAAA,CAAU,EAIjB,IAAmB,CAAA,WAAA,CAAcC,WAmKjC,CAAA,IAAA,CAAO,EAAoC,CAAA,CAACR,EAAOS,CACjD,IAAA,IAAA,CAAK,MAAO,CAAA,EAAA,CAAGT,CAAOS,CAAAA,CAAQ,EACvB,IAGT,CAAA,CAAA,IAAA,CAAO,IAAwC,CAAA,CAACT,CAAOS,CAAAA,CAAAA,IACrD,KAAK,MAAO,CAAA,IAAA,CAAKT,CAAOS,CAAAA,CAAQ,CACzB,CAAA,IAAA,CAAA,CAGT,KAAO,cAA4D,CAAA,CAACT,CAAOS,CAAAA,CAAAA,IACzE,IAAK,CAAA,MAAA,CAAO,eAAeT,CAAOS,CAAAA,CAAQ,CACnC,CAAA,IAAA,CAAA,CAGT,IAAO,CAAA,GAAA,CAAsC,CAACT,CAAOS,CAAAA,CAAAA,IACnD,KAAK,MAAO,CAAA,GAAA,CAAIT,EAAOS,CAAQ,CAAA,CACxB,IA4PT,CAAA,CAAA,IAAA,CAAU,YAAgBC,CAAAA,CAAAA,EACjB,KAAK,mBAAoBA,CAAAA,CAAO,CAAI,CAAA,IAAA,CAAK,cAAeA,CAAAA,CAAO,EAAE,OAAUA,CAAAA,CAAAA,CA7alF,IAAK,CAAA,MAAA,CAAS,EAAC,CACf,KAAK,GAAM,CAAA,GACb,CAEA,aAAa,IAAA,CAAKC,EAA0D,CAC1E,MAAMC,CAAW,CAAA,IAAIN,kBACrB,CAAA,OAAA,MAAMM,EAAS,UAAWD,CAAAA,CAAI,CACvBC,CAAAA,CACT,CAEA,MAAa,QAAqBC,CAAwBC,CAAAA,CAAAA,CAA6B,CACrF,OAAO,MAAM,IAAA,CAAK,OAAO,OAAQD,CAAAA,CAAAA,CAAM,KAAK,aAAc,CAAA,IAAA,CAAK,OAAO,CAAGC,CAAAA,CAAM,CACjF,CAEO,SACLD,CAAAA,CAAAA,CACAE,EACAD,CACM,CAAA,CACN,IAAK,CAAA,MAAA,CAAO,SAAUD,CAAAA,CAAAA,CAAME,EAAU,IAAK,CAAA,aAAA,CAAc,IAAK,CAAA,OAAO,CAAGD,CAAAA,CAAM,EAChF,CAEA,IAAI,SAAqB,EAAA,CACvB,OAAK,IAAA,CAAK,OAAO,MACV,CAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,UADP,CAElC,CAAA,CAEA,IAAI,UAAA,EAAsB,CACxB,OAAK,KAAK,MAAO,CAAA,MAAA,CACV,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,IAAA,CAAK,QAAQ,UADP,CAAA,CAAA,CAElC,CAEA,MAAa,MAAA,EAAoC,CAC/C,OAAK,IAAA,CAAK,OAAS,EAAA,MAAM,IAAK,CAAA,OAAA,GACb,MAAM,IAAA,CAAK,OAAQ,CAAA,CAAE,MAAQ,CAAA,qBAAsB,CAAC,CAEvE,CAEA,MAAa,OAAA,CAAQH,CAAkC,CAAA,CACrD,GAAI,CAAC,IAAA,CAAK,MAAO,CAAA,MAAA,CACf,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAG/D,IAAK,CAAA,eAAA,CAAgBA,CAAI,CAAA,CACzB,KAAM,CAAE,QAAA,CAAAhB,CAAU,CAAA,QAAA,CAAAQ,CAAS,CAAA,CAAI,gBAAgB,IAAK,CAAA,GAAG,CACvD,CAAA,GAAI,CACF,MAAMa,EAAU,MAAM,IAAI,QACxB,MAAOC,CAAAA,CAASC,IAAW,CAjSnC,IAAAC,CAkSc,CAAA,IAAA,CAAK,GAAI,CAAA,WAAA,GAAA,CACXA,EAAA,IAAK,CAAA,KAAA,GAAL,IAAAA,EAAAA,CAAAA,CAAY,cAAgBC,CAAAA,CAAAA,EAA6B,CAEnD,CAACA,CAAAA,CAAM,IAAQ,EAAA,CAAC,IAAK,CAAA,MAAA,CAAO,UAC9B,IAAK,CAAA,MAAA,CAAO,mBAAoB,EAAA,CAChCF,CAAO,CAAA,IAAI,MAAM,6CAA6C,CAAC,CAEnE,EAAA,CAAA,CAAA,CAAA,CAEF,MAAM,IAAA,CAAK,OACR,OAAQG,CAAAA,CAAAA,CAAAvB,CAAA,CAAA,CACP,UAAYA,CAAAA,CAAAA,CAAA,GACNH,CAAY,EAAA,CACd,CAAC,IAAA,CAAK,SAAS,EAAGA,CACpB,CAEEQ,CAAAA,CAAAA,CAAAA,CAAAA,EAAY,CACd,kBAAoB,CAAA,CAClB,CAAC,IAAK,CAAA,SAAS,EAAGA,CACpB,CACF,CAAA,CAAA,CAVO,CAWP,YAAcQ,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,YACtB,CAAA,CAAC,EACA,IAAMK,CAAAA,CAAAA,EAAkC,CACvCC,CAAAA,CAAQD,CAAO,EACjB,CAAC,CACA,CAAA,KAAA,CAAOM,CAAiB,EAAA,CACvBJ,CAAO,CAAA,IAAI,MAAMI,CAAM,CAAA,OAAO,CAAC,EACjC,CAAC,EACL,CACF,CACA,CAAA,GAAI,CAACN,CAAAA,CAAS,OAEd,MAAMO,EAAWC,+BAA0BR,CAAAA,CAAAA,CAAQ,UAAY,CAAA,CAAC,IAAK,CAAA,SAAS,CAAC,CAE/E,CAAA,IAAA,CAAK,YAAY,IAAK,CAAA,GAAA,CAAI,OAAO,MAAS,CAAA,IAAA,CAAK,GAAI,CAAA,MAAA,CAASO,CAAQ,CAAA,CACpE,KAAK,WAAYA,CAAAA,CAAQ,CACzB,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,UAAW,CAAE,OAAA,CAAS,YAAa,CAAA,IAAA,CAAK,OAAO,CAAE,CAAC,EACrE,CAAA,MAASD,CAAP,CAAA,CACA,MAAK,IAAA,CAAA,MAAA,CAAO,OAAO,KAAMA,CAAAA,CAAK,CACxBA,CAAAA,CACR,CAAE,OAAA,CACI,KAAK,KAAO,EAAA,IAAA,CAAK,KAAM,CAAA,UAAA,GAC7B,CACF,CAEA,MAAa,YAAA,CACXnC,CACAsC,CAAAA,CAAAA,CAC2D,CAC3D,GAAI,CAAC,IAAK,CAAA,MAAA,CAAO,OACf,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAG/D,IAAK,CAAA,eAAA,CAAgB,CACnB,MAAA,CAAQtC,GAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAQ,MAClB,CAAC,CAED,CAAA,GAAI,CACF,MAAMuC,CAAAA,CAAS,MAAM,IAAI,OACvB,CAAA,MAAOT,EAASC,CAAW,GAAA,CA9VnC,IAAAC,CAAAA,CA+Vc,IAAK,CAAA,GAAA,CAAI,eACXA,CAAA,CAAA,IAAA,CAAK,KAAL,GAAA,IAAA,EAAAA,CAAY,CAAA,cAAA,CAAgBC,GAA6B,CAEnD,CAACA,CAAM,CAAA,IAAA,EAAQ,CAAC,IAAA,CAAK,OAAO,OAC9B,GAAA,IAAA,CAAK,MAAO,CAAA,mBAAA,EACZF,CAAAA,CAAAA,CAAO,IAAI,KAAM,CAAA,6CAA6C,CAAC,CAEnE,EAAA,CAAA,CAAA,CAAA,CAEF,MAAM,IAAK,CAAA,MAAA,CACR,YACCG,CAAAA,CAAAA,CAAAvB,CAAA,CAAA,EAAA,CACKX,GADL,CAEE,MAAA,CAAQ,IAAK,CAAA,GAAA,CAAI,MACnB,CAAA,CAAA,CACAsC,CACF,CACC,CAAA,IAAA,CAAMC,CAAiD,EAAA,CACtDT,CAAQS,CAAAA,CAAM,EAChB,CAAC,CAAA,CACA,KAAOJ,CAAAA,CAAAA,EAAiB,CACvBJ,CAAAA,CAAO,IAAI,KAAMI,CAAAA,CAAAA,CAAM,OAAO,CAAC,EACjC,CAAC,EACL,CACF,CAAA,CAEMN,CAAUU,CAAAA,CAAAA,CAAO,OACvB,CAAA,GAAIV,EAAS,CACX,MAAMO,CAAWC,CAAAA,+BAAAA,CAA0BR,CAAQ,CAAA,UAAA,CAAY,CAAC,IAAK,CAAA,SAAS,CAAC,CAE/E,CAAA,IAAA,CAAK,YAAY,IAAK,CAAA,GAAA,CAAI,MAAO,CAAA,MAAA,CAAS,IAAK,CAAA,GAAA,CAAI,OAASO,CAAQ,CAAA,CACpE,IAAK,CAAA,WAAA,CAAYA,CAAQ,CAAA,CACzB,KAAK,MAAO,CAAA,IAAA,CAAK,SAAW,CAAA,CAAE,OAAS,CAAA,YAAA,CAAa,KAAK,OAAO,CAAE,CAAC,EAAA,CAErE,OAAOG,CACT,OAASJ,CAAP,CAAA,CACA,MAAK,IAAA,CAAA,MAAA,CAAO,MAAO,CAAA,KAAA,CAAMA,CAAK,CACxBA,CAAAA,CACR,CAAE,OAAA,CACI,IAAK,CAAA,KAAA,EAAO,KAAK,KAAM,CAAA,UAAA,GAC7B,CACF,CAEA,MAAa,YAA4B,CACnC,IAAA,CAAK,OACP,EAAA,MAAM,IAAK,CAAA,MAAA,CAAO,YAEpB,CAAA,IAAA,CAAK,KAAM,GACb,CAsBA,IAAI,iBAAkB,CACpB,OAAO,CACT,CAAA,CAEA,IAAI,OAAA,EAAU,CACZ,OAAO,IAAA,CAAK,MAAO,CAAA,OACrB,CAIU,sBAAA,EAAyB,CACjC,IAAK,CAAA,MAAA,CAAO,EAAG,CAAA,eAAA,CAAkBZ,CAA6D,EAAA,CAC5F,KAAM,CAAE,MAAA,CAAAvB,CAAO,CAAA,CAAIuB,CACb,CAAA,CAAE,MAAAV,CAAM,CAAA,CAAIb,CACda,CAAAA,CAAAA,CAAM,IAAS,GAAA,iBAAA,EACjB,KAAK,QAAW,CAAA,IAAA,CAAK,aAAcA,CAAAA,CAAAA,CAAM,IAAI,CAAA,CAC7C,KAAK,MAAO,CAAA,IAAA,CAAK,kBAAmB,IAAK,CAAA,QAAQ,GACxCA,CAAM,CAAA,IAAA,GAAS,cACxB,CAAA,IAAA,CAAK,UAAW,CAAA,IAAA,CAAK,cAAcA,CAAM,CAAA,IAAI,CAAC,CAAA,CAE9C,IAAK,CAAA,MAAA,CAAO,KAAKA,CAAM,CAAA,IAAA,CAAaA,CAAM,CAAA,IAAI,CAEhD,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,eAAA,CAAiBU,CAAO,EAC3C,CAAC,CAAA,CAED,KAAK,MAAO,CAAA,EAAA,CAAG,cAAiBxB,CAAAA,CAAAA,EAAoB,CAClD,MAAMyC,EAAQ,QAASzC,CAAAA,CAAO,CAC9B,CAAA,IAAA,CAAK,OAAUyC,CAAAA,CAAAA,CACf,KAAK,MAAO,CAAA,IAAA,CAAK,cAAgB,CAAA,YAAA,CAAa,IAAK,CAAA,OAAO,CAAC,CAC3D,CAAA,IAAA,CAAK,UACP,CAAC,EAED,IAAK,CAAA,MAAA,CAAO,EACV,CAAA,gBAAA,CACCjB,CAA8D,EAAA,CAC7D,KAAK,MAAO,CAAA,IAAA,CAAK,gBAAkBA,CAAAA,CAAO,EAC5C,CACF,EAEA,IAAK,CAAA,MAAA,CAAO,EACV,CAAA,gBAAA,CACCA,CAA8D,EAAA,CAC7D,KAAK,KAAM,EAAA,CACX,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,gBAAA,CAAkBA,CAAO,CAC1C,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,YAAcW,CAAAA,CAAAA,CAAAvB,EAAA,EAC1B8B,CAAAA,iBAAAA,CAAY,mBAAmB,CAAA,CAAA,CADL,CAE7B,IAAA,CAAMlB,EAAQ,KACd,CAAA,IAAA,CAAM,mBACR,CAAA,CAAC,EACH,CACF,EAEA,IAAK,CAAA,MAAA,CAAO,GAAG,aAAgBmB,CAAAA,CAAAA,EAAgB,CAzdnD,IAAAV,CAAAA,CAAAW,CA0dU,CAAA,IAAA,CAAK,GAAI,CAAA,WAAA,GAAA,CAGXX,EAAA,IAAK,CAAA,KAAA,GAAL,IAAAA,EAAAA,CAAAA,CAAY,UACZW,EAAAA,CAAAA,CAAAA,CAAAA,CAAA,KAAK,KAAL,GAAA,IAAA,EAAAA,CAAY,CAAA,SAAA,CAAU,CAAE,GAAA,CAAAD,CAAI,CAE9B,CAAA,CAAA,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,aAAeA,CAAAA,CAAG,EACrC,CAAC,EACH,CAEU,mBAAA,CAAoB3C,CAAuB,CAAA,CACnD,KAAK,OAAQ,CAAA,CACX,MAAQ,CAAA,4BAAA,CACR,MAAQ,CAAA,CAAC,CAAE,OAASA,CAAAA,CAAAA,CAAQ,QAAS,CAAA,EAAE,CAAE,CAAC,CAC5C,CAAC,EACH,CAEU,mBAAoBA,CAAAA,CAAAA,CAA0B,CACtD,OAAO,OAAOA,CAAY,EAAA,QAAA,CAAWA,CAAQ,CAAA,UAAA,CAAW,GAAG,IAAK,CAAA,SAAA,CAAA,CAAA,CAAY,CAAI,CAAA,CAAA,CAClF,CAEU,aAAA,CAAcA,EAAyB,CAC/C,OAAO,CAAG,EAAA,IAAA,CAAK,SAAaA,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,CAC9B,CAEU,YAAaA,CAAAA,CAAAA,CAAyB,CAC9C,OAAO,MAAOA,CAAAA,CAAAA,CAAQ,MAAM,GAAG,CAAA,CAAE,CAAC,CAAC,CACrC,CAEU,YAAYD,CAAkB,CAAA,CAEtC,MAAM8C,CAAAA,CADa9C,CAAO,CAAA,MAAA,CAAQ+C,GAAM,IAAK,CAAA,mBAAA,CAAoBA,CAAC,CAAC,CACvC,CAAA,GAAA,CAAKC,GAAM,IAAK,CAAA,YAAA,CAAaA,CAAC,CAAC,CAAA,CACvDF,EAAS,MACX,GAAA,IAAA,CAAK,OAAUA,CAAAA,CAAAA,CAAS,CAAC,CAAA,CACzB,KAAK,MAAO,CAAA,IAAA,CAAK,cAAgB,CAAA,YAAA,CAAa,IAAK,CAAA,OAAO,CAAC,CAC3D,CAAA,IAAA,CAAK,OAAQ,EAAA,EAEjB,CAEU,UAAA,CAAWJ,EAAe,CAClC,GAAI,IAAK,CAAA,mBAAA,CAAoBA,CAAK,CAAA,CAAG,CACnC,MAAMzC,CAAAA,CAAU,IAAK,CAAA,YAAA,CAAayC,CAAK,CAAA,CACvC,KAAK,OAAUzC,CAAAA,CAAAA,CACf,IAAK,CAAA,mBAAA,CAAoBA,CAAO,EAAA,CAEpC,CAEU,cAAegD,CAAAA,CAAAA,CAAuD,CAC9E,KAAM,CAACC,CAAAA,CAAWC,EAAWC,CAAO,CAAA,CAAIH,EAAQ,KAAM,CAAA,GAAG,EAEzD,OAAO,CAAE,OADO,CAAA,CAAA,EAAGC,CAAaC,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,CAAAA,CACd,QAAAC,CAAQ,CAC5B,CAEU,WAAA,CAAYd,CAAoB,CAAA,CACxC,KAAK,QAAWA,CAAAA,CAAAA,CACb,MAAQS,CAAAA,CAAAA,EAAM,IAAK,CAAA,YAAA,CAAa,KAAK,cAAeA,CAAAA,CAAC,CAAE,CAAA,OAAO,CAAM,GAAA,IAAA,CAAK,OAAO,CAChF,CAAA,GAAA,CAAKA,CAAM,EAAA,IAAA,CAAK,cAAeA,CAAAA,CAAC,EAAE,OAAO,CAAA,CAC5C,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,iBAAA,CAAmB,KAAK,QAAQ,EACnD,CAEU,YAAA,CAAarB,CAAkD,CAAA,CAthB3E,IAAAQ,CAAAW,CAAAA,CAAAA,CAuhBI,MAAMQ,CAAiBnB,CAAAA,CAAAA,CAAAA,CAAAR,GAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,MAAN,GAAA,IAAA,CAAAQ,CAAgB,CAAA,GACjC/B,CAAiB0C,CAAAA,CAAAA,CAAAA,CAAAnB,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,cAAA,GAAN,KAAAmB,CAAwB,CAAA,EACzCS,CAAAA,CAAAA,CAAYD,CAAe,CAAA,MAAA,CAAOlD,CAAc,CACtD,CAAA,GAAI,CAACmD,CAAAA,CAAU,MACb,CAAA,MAAM,IAAI,KAAM,CAAA,4DAA4D,CAC9E,CAAA,MAAMC,CAAkBF,CAAAA,CAAAA,CAAe,QAAS3B,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,OAAA,GAAWf,gBAAmB,CAAA,GAC9E6C,CAAiBH,CAAAA,CAAAA,CAAe,MAAS3B,CAAAA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,SAAUd,eAAkB,CAAA,GAC3EP,CAAkBqB,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAAM,CAAA,eAAA,GAAmB,EAAC,CAC5CnB,CAAiBmB,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAAM,CAAA,cAAA,GAAkB,EAAC,CAC1ClB,CAASkB,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAAM,CAAA,MAAA,GAAU,IAAK,CAAA,WAAA,CAAY4B,CAAW5B,CAAAA,CAAAA,CAAK,SAAS,CACnE+B,CAAAA,CAAAA,CAAAA,CAAiB/B,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,cAAA,GAAkB,OAC/C,OAAO,CACL,MAAQ2B,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAgB,IAAKX,CAAU,EAAA,IAAA,CAAK,aAAcA,CAAAA,CAAK,CAC/D,CAAA,CAAA,cAAA,CAAgBvC,EAAe,GAAKuC,CAAAA,CAAAA,EAAU,IAAK,CAAA,aAAA,CAAcA,CAAK,CAAC,EACvE,OAASa,CAAAA,CAAAA,CACT,OAAQC,CACR,CAAA,eAAA,CAAAnD,EACA,cAAAE,CAAAA,CAAAA,CACA,MAAAC,CAAAA,CAAAA,CACA,WAAa,CAAA,CAAA,EAAQkB,GAAA,IAAAA,EAAAA,CAAAA,CAAM,WAC3B,CAAA,CAAA,cAAA,CAAA+B,CACA,CAAA,SAAA,CAAW/B,EAAK,SAChB,CAAA,QAAA,CAAUA,CAAK,CAAA,QACjB,CACF,CAEU,YAAY1B,CAAkB0D,CAAAA,CAAAA,CAAmC,CACzE,MAAMC,CAAsB,CAAA,GAC5B,OAAA3D,CAAAA,CAAO,OAAS0C,CAAAA,CAAAA,EAAU,CACxBiB,CAAAA,CAAIjB,CAAK,CAAI,CAAA,IAAA,CAAK,SAAUA,CAAAA,CAAAA,CAAOgB,CAAS,EAC9C,CAAC,CACMC,CAAAA,CACT,CAEA,MAAgB,UAAWjC,CAAAA,CAAAA,CAA+B,CAiBxD,GAhBA,IAAA,CAAK,IAAM,IAAK,CAAA,YAAA,CAAaA,CAAI,CAEjC,CAAA,IAAA,CAAK,OAAU,CAAA,IAAA,CAAK,GAAI,CAAA,MAAA,CAAO,OAC3B,kBAAmB,CAAA,IAAA,CAAK,GAAI,CAAA,MAAM,CAClC,CAAA,kBAAA,CAAmB,KAAK,GAAI,CAAA,cAAc,CAC9C,CAAA,IAAA,CAAK,MAAS,CAAA,MAAMkC,oCAAkB,IAAK,CAAA,CACzC,SAAW,CAAA,IAAA,CAAK,GAAI,CAAA,SAAA,CACpB,SAAU,IAAK,CAAA,GAAA,CAAI,QACnB,CAAA,mBAAA,CAAqBlC,CAAK,CAAA,mBAAA,CAC1B,SAAUA,CAAK,CAAA,QAAA,CACf,cAAgBA,CAAAA,CAAAA,CAAK,cACrB,CAAA,mBAAA,CAAqBA,EAAK,mBAC1B,CAAA,gBAAA,CAAkBA,CAAK,CAAA,gBACzB,CAAC,CAAA,CACD,KAAK,sBAAuB,EAAA,CAC5B,MAAM,IAAK,CAAA,oBAAA,GACP,IAAK,CAAA,GAAA,CAAI,WAAa,CAAA,CACxB,IAAImC,CAAAA,CACJ,GAAI,CACF,KAAM,CAAE,kBAAA,CAAAC,CAAmB,CAAA,CAAI,MAAa,mFAAA,sBAAsB,MAClED,CAAAA,CAAAA,CAA0BC,EAC5B,CAAA,MAAQC,EAAN,CACA,MAAM,IAAI,KAAA,CAAM,8DAA8D,CAChF,CACA,GAAIF,CAAAA,CACF,GAAI,CACF,IAAK,CAAA,KAAA,CAAQ,IAAIA,CAAwBhD,CAAAA,CAAAA,CAAA,CACvC,SAAA,CAAW,IAAK,CAAA,GAAA,CAAI,WACjB,IAAK,CAAA,GAAA,CAAI,cACb,CAAA,EACH,CAASkD,MAAAA,CAAAA,CAAP,CACA,MAAK,IAAA,CAAA,MAAA,CAAO,OAAO,KAAMA,CAAAA,CAAC,EACpB,IAAI,KAAA,CAAM,gDAAgD,CAClE,CAGN,CAAA,CAEU,gBAAgBrC,CAAmB,CAAA,CAC3C,GAAI,CAACA,CAAM,CAAA,OACX,KAAM,CAAE,MAAA,CAAA1B,CAAQ,CAAA,cAAA,CAAAG,CAAgB,CAAA,MAAA,CAAAK,CAAO,CAAIkB,CAAAA,CAAAA,CACvC1B,CAAUS,EAAAA,kBAAAA,CAAaT,CAAM,CAAA,GAC/B,KAAK,GAAI,CAAA,MAAA,CAASA,CAAO,CAAA,GAAA,CAAK0C,CAAU,EAAA,IAAA,CAAK,cAAcA,CAAK,CAAC,CACjE1C,CAAAA,CAAAA,CAAO,OAAS0C,CAAAA,CAAAA,EAAU,CACxB,IAAK,CAAA,GAAA,CAAI,MAAOA,CAAAA,CAAK,CAAIlC,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAASkC,CAAAA,CAAAA,CAAAA,GAAU,KAAK,SAAUA,CAAAA,CAAK,EAClE,CAAC,CAAA,CAAA,CAECvC,CAAkBM,EAAAA,kBAAAA,CAAaN,CAAc,CAAA,GAC/C,KAAK,GAAI,CAAA,cAAA,CAAiB,EAAC,CAC3B,IAAK,CAAA,GAAA,CAAI,eAAiBA,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAgB,CAAA,GAAA,CAAKuC,CAAU,EAAA,IAAA,CAAK,cAAcA,CAAK,CAAA,CAAA,CACjFvC,CAAe,CAAA,OAAA,CAASuC,CAAU,EAAA,CAChC,KAAK,GAAI,CAAA,MAAA,CAAOA,CAAK,CAAA,CAAA,CAAIlC,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,EAASkC,CAAU,CAAA,GAAA,IAAA,CAAK,SAAUA,CAAAA,CAAK,EAClE,CAAC,GAEL,CAEU,SAAA,CAAUzC,CAAiByD,CAAAA,CAAAA,CAA4B,CAlnBnE,IAAAxB,EAonBI,OADoBA,CAAAA,CAAAA,CAAAA,CAAA,KAAK,GAAI,CAAA,MAAA,GAAT,YAAAA,CAAkBjC,CAAAA,CAAAA,CAAAA,GAGpC,CAAG+D,EAAAA,OAAAA,CAAAA,gBAAAA,EAA0B/D,CAAqByD,CAAAA,WAAAA,EAAAA,CAAAA,EAAa,KAAK,GAAI,CAAA,SAAA,CAAA,CAE5E,CAEA,MAAgB,oBAAuB,EAAA,CACrC,GAAK,IAAK,CAAA,OAAA,CACV,GAAI,CACF,MAAMzD,CAAAA,CAAU,MAAM,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,IAAA,CAAK,OAAQ,CAAA,OAAA,CAAQ,GAAG,IAAK,CAAA,WAAA,CAAA,QAAA,CAAqB,CAGrFiD,CAAAA,CAAAA,CAAY,IAAK,CAAA,OAAA,CAAQ,WAAW,CAAG,EAAA,IAAA,CAAK,SAAajD,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,CAAS,CACpE,CAAA,IAAA,CAAK,QAAQ,UAAW,CAAA,CAAA,EAAG,IAAK,CAAA,SAAA,CAAA,CAAA,EAAaA,CAAS,CAAA,CAAA,CAAA,CACtD,KAAK,OAAQ,CAAA,UAAA,CAAW,KAAK,SAAS,CAAA,CAE1C,KAAK,WAAYA,CAAAA,CAAAA,CAAU,CAAC,IAAA,CAAK,aAAcA,CAAAA,CAAO,CAAC,CAAIiD,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAW,QAAQ,CAAA,CAC9E,KAAK,WAAYA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAW,QAAQ,EACtC,OAASb,CAAP,CAAA,CACA,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,KAAA,CAAM,qDAAqD,CAC9E,CAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAMA,CAAAA,CAAK,EAC9B,MAAM,IAAA,CAAK,UAAW,EAAA,CAAE,KAAOA,CAAAA,CAAAA,EAAU,KAAK,MAAO,CAAA,MAAA,CAAO,IAAKA,CAAAA,CAAK,CAAC,EACzE,CACF,CAEU,KAAA,EAAQ,CAChB,IAAA,CAAK,OAAU,CAAA,CAAA,CACf,KAAK,QAAW,CAAA,GAClB,CAEU,OAAU,EAAA,CACb,KAAK,OACV,EAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,QAAQ,CAAG,EAAA,IAAA,CAAK,WAAuB,CAAA,QAAA,CAAA,CAAA,IAAA,CAAK,OAAO,EACrF,CAEU,aAAcZ,CAAAA,CAAAA,CAAsC,CAC5D,OAAI,OAAOA,CAAAA,EAAY,UAAYA,CAAmB,YAAA,MAAA,CAC7C,CAAC,IAAA,CAAK,YAAaA,CAAAA,CAAO,CAAC,CAE7BA,CAAAA,CAAAA,CAAQ,GAAKwB,CAAAA,CAAAA,EAAoB,IAAK,CAAA,YAAA,CAAaA,CAAO,CAAC,CACpE,CAKF;;AChqBO,MAAM,iBAAmBgB;;;;;;;;;"} +\ No newline at end of file ++{"version":3,"file":"index.cjs.js","sources":["../src/constants/values.ts","../src/constants/rpc.ts","../src/EthereumProvider.ts","../src/index.ts"],"sourcesContent":["export const PROTOCOL = \"wc\";\nexport const WC_VERSION = 2;\nexport const CONTEXT = \"ethereum_provider\";\nexport const STORAGE_KEY = `${PROTOCOL}@${WC_VERSION}:${CONTEXT}:`;\nexport const RPC_URL = \"https://rpc.walletconnect.org/v1/\";\n","export const REQUIRED_METHODS = [\"eth_sendTransaction\", \"personal_sign\"];\nexport const OPTIONAL_METHODS = [\n \"eth_accounts\",\n \"eth_requestAccounts\",\n \"eth_sendRawTransaction\",\n \"eth_sign\",\n \"eth_signTransaction\",\n \"eth_signTypedData\",\n \"eth_signTypedData_v3\",\n \"eth_signTypedData_v4\",\n \"eth_sendTransaction\",\n \"personal_sign\",\n \"wallet_switchEthereumChain\",\n \"wallet_addEthereumChain\",\n \"wallet_getPermissions\",\n \"wallet_requestPermissions\",\n \"wallet_registerOnboarding\",\n \"wallet_watchAsset\",\n \"wallet_scanQRCode\",\n \"wallet_sendCalls\",\n \"wallet_getCapabilities\",\n \"wallet_getCallsStatus\",\n \"wallet_showCallsStatus\",\n];\nexport const REQUIRED_EVENTS = [\"chainChanged\", \"accountsChanged\"];\nexport const OPTIONAL_EVENTS = [\n \"chainChanged\",\n \"accountsChanged\",\n \"message\",\n \"disconnect\",\n \"connect\",\n];\n","import { EventEmitter } from \"events\";\nimport { getAccountsFromNamespaces, getSdkError, isValidArray } from \"@walletconnect/utils\";\nimport { KeyValueStorageOptions } from \"@walletconnect/keyvaluestorage\";\nimport {\n IEthereumProvider as IProvider,\n IEthereumProviderEvents,\n ProviderAccounts,\n RequestArguments,\n QrModalOptions,\n} from \"./types\";\nimport {\n Metadata,\n Namespace,\n UniversalProvider,\n UniversalProviderOpts,\n} from \"@walletconnect/universal-provider\";\nimport { AuthTypes, SessionTypes, SignClientTypes } from \"@walletconnect/types\";\nimport { JsonRpcResult } from \"@walletconnect/jsonrpc-types\";\nimport {\n STORAGE_KEY,\n REQUIRED_METHODS,\n REQUIRED_EVENTS,\n RPC_URL,\n OPTIONAL_METHODS,\n OPTIONAL_EVENTS,\n} from \"./constants\";\n\nexport type RpcMethod =\n | \"personal_sign\"\n | \"eth_sendTransaction\"\n | \"eth_accounts\"\n | \"eth_requestAccounts\"\n | \"eth_call\"\n | \"eth_getBalance\"\n | \"eth_sendRawTransaction\"\n | \"eth_sign\"\n | \"eth_signTransaction\"\n | \"eth_signTypedData\"\n | \"eth_signTypedData_v3\"\n | \"eth_signTypedData_v4\"\n | \"wallet_switchEthereumChain\"\n | \"wallet_addEthereumChain\"\n | \"wallet_getPermissions\"\n | \"wallet_requestPermissions\"\n | \"wallet_registerOnboarding\"\n | \"wallet_watchAsset\"\n | \"wallet_scanQRCode\"\n | \"wallet_sendCalls\"\n | \"wallet_getCapabilities\"\n | \"wallet_getCallsStatus\"\n | \"wallet_showCallsStatus\";\n\nexport type RpcEvent = \"accountsChanged\" | \"chainChanged\" | \"message\" | \"disconnect\" | \"connect\";\n\nexport interface EthereumRpcMap {\n [chainId: string]: string;\n}\n\nexport interface SessionEvent {\n event: { name: string; data: any };\n chainId: string;\n}\n\nexport interface EthereumRpcConfig {\n chains: string[];\n optionalChains: string[];\n methods: string[];\n optionalMethods?: string[];\n /**\n * @description Events that the wallet MUST support or the connection will be rejected\n */\n events: string[];\n optionalEvents?: string[];\n rpcMap: EthereumRpcMap;\n projectId: string;\n metadata?: Metadata;\n showQrModal: boolean;\n qrModalOptions?: QrModalOptions;\n}\nexport interface ConnectOps {\n chains?: number[];\n optionalChains?: number[];\n rpcMap?: EthereumRpcMap;\n pairingTopic?: string;\n}\n\nexport type AuthenticateParams = {\n chains?: number[];\n} & Omit;\n\nexport interface IEthereumProvider extends IProvider {\n connect(opts?: ConnectOps | undefined): Promise;\n}\n\nexport function getRpcUrl(chainId: string, rpc: EthereumRpcConfig): string | undefined {\n let rpcUrl: string | undefined;\n if (rpc.rpcMap) {\n rpcUrl = rpc.rpcMap[getEthereumChainId([chainId])];\n }\n return rpcUrl;\n}\n\nexport function getEthereumChainId(chains: string[]): number {\n return Number(chains[0].split(\":\")[1]);\n}\n\nexport function toHexChainId(chainId: number): string {\n return `0x${chainId.toString(16)}`;\n}\n\nexport type NamespacesParams = {\n chains: EthereumRpcConfig[\"chains\"];\n optionalChains: EthereumRpcConfig[\"optionalChains\"];\n methods?: EthereumRpcConfig[\"methods\"];\n optionalMethods?: EthereumRpcConfig[\"methods\"];\n events?: EthereumRpcConfig[\"events\"];\n rpcMap: EthereumRpcConfig[\"rpcMap\"];\n optionalEvents?: EthereumRpcConfig[\"events\"];\n};\n\nexport function buildNamespaces(params: NamespacesParams): {\n required?: Namespace;\n optional?: Namespace;\n} {\n const { chains, optionalChains, methods, optionalMethods, events, optionalEvents, rpcMap } =\n params;\n if (!isValidArray(chains)) {\n throw new Error(\"Invalid chains\");\n }\n\n const required: Namespace = {\n chains,\n methods: methods || REQUIRED_METHODS,\n events: events || REQUIRED_EVENTS,\n rpcMap: {\n ...(chains.length\n ? { [getEthereumChainId(chains)]: rpcMap[getEthereumChainId(chains)] }\n : {}),\n },\n };\n\n // make a list of events and methods that require additional permissions\n // so we know if we should to include the required chains in the optional namespace\n const eventsRequiringPermissions = events?.filter((event) => !REQUIRED_EVENTS.includes(event));\n const methodsRequiringPermissions = methods?.filter((event) => !REQUIRED_METHODS.includes(event));\n\n if (\n !optionalChains &&\n !optionalEvents &&\n !optionalMethods &&\n !eventsRequiringPermissions?.length &&\n !methodsRequiringPermissions?.length\n ) {\n return { required: chains.length ? required : undefined };\n }\n\n /*\n * decides whether or not to include the required chains in the optional namespace\n * use case: if there is a single chain as required but additional methods/events as optional\n */\n const shouldIncludeRequiredChains =\n (eventsRequiringPermissions?.length && methodsRequiringPermissions?.length) || !optionalChains;\n\n const optional: Namespace = {\n chains: [\n ...new Set(\n shouldIncludeRequiredChains ? required.chains.concat(optionalChains || []) : optionalChains,\n ),\n ],\n methods: [\n ...new Set(\n required.methods.concat(optionalMethods?.length ? optionalMethods : OPTIONAL_METHODS),\n ),\n ],\n events: [\n ...new Set(required.events.concat(optionalEvents?.length ? optionalEvents : OPTIONAL_EVENTS)),\n ],\n rpcMap,\n };\n\n return {\n required: chains.length ? required : undefined,\n optional: optionalChains.length ? optional : undefined,\n };\n}\n\n// helper type to force setting at least one value in an array\ntype ArrayOneOrMore = {\n 0: T;\n} & Array;\n\n/**\n * @param {number[]} chains - The Chains your app intents to use and the peer MUST support. If the peer does not support these chains, the connection will be rejected.\n * @param {number[]} optionalChains - The Chains your app MAY attempt to use and the peer MAY support. If the peer does not support these chains, the connection will still be established.\n * @description either chains or optionalChains must be provided\n */\nexport type ChainsProps =\n | {\n chains: ArrayOneOrMore;\n optionalChains?: number[];\n }\n | {\n chains?: number[];\n optionalChains: ArrayOneOrMore;\n };\n\nexport type EthereumProviderOptions = {\n projectId: string;\n /**\n * @note Methods that your app intents to use and the peer MUST support. If the peer does not support these methods, the connection will be rejected.\n * @default [\"eth_sendTransaction\", \"personal_sign\"]\n */\n methods?: string[];\n /**\n * @note Methods that your app MAY attempt to use and the peer MAY support. If the peer does not support these methods, the connection will still be established.\n */\n optionalMethods?: string[];\n events?: string[];\n optionalEvents?: string[];\n rpcMap?: EthereumRpcMap;\n metadata?: Metadata;\n showQrModal: boolean;\n qrModalOptions?: QrModalOptions;\n disableProviderPing?: boolean;\n relayUrl?: string;\n storageOptions?: KeyValueStorageOptions;\n} & ChainsProps &\n UniversalProviderOpts;\n\nexport class EthereumProvider implements IEthereumProvider {\n public events = new EventEmitter();\n public namespace = \"eip155\";\n public accounts: string[] = [];\n public signer: InstanceType;\n public chainId = 1;\n public modal?: any;\n\n protected rpc: EthereumRpcConfig;\n protected readonly STORAGE_KEY = STORAGE_KEY;\n\n constructor() {\n // assigned during initialize\n this.signer = {} as InstanceType;\n this.rpc = {} as EthereumRpcConfig;\n }\n\n static async init(opts: EthereumProviderOptions): Promise {\n const provider = new EthereumProvider();\n await provider.initialize(opts);\n return provider;\n }\n\n public async request(args: RequestArguments, expiry?: number): Promise {\n return await this.signer.request(args, this.formatChainId(this.chainId), expiry);\n }\n\n public sendAsync(\n args: RequestArguments,\n callback: (error: Error | null, response: JsonRpcResult) => void,\n expiry?: number,\n ): void {\n this.signer.sendAsync(args, callback, this.formatChainId(this.chainId), expiry);\n }\n\n get connected(): boolean {\n if (!this.signer.client) return false;\n return this.signer.client.core.relayer.connected;\n }\n\n get connecting(): boolean {\n if (!this.signer.client) return false;\n return this.signer.client.core.relayer.connecting;\n }\n\n public async enable(): Promise {\n if (!this.session) await this.connect();\n const accounts = await this.request({ method: \"eth_requestAccounts\" });\n return accounts as ProviderAccounts;\n }\n\n public async connect(opts?: ConnectOps): Promise {\n if (!this.signer.client) {\n throw new Error(\"Provider not initialized. Call init() first\");\n }\n\n this.loadConnectOpts(opts);\n const { required, optional } = buildNamespaces(this.rpc);\n try {\n const session = await new Promise(\n async (resolve, reject) => {\n if (this.rpc.showQrModal) {\n this.modal?.subscribeModal((state: { open: boolean }) => {\n // the modal was closed so reject the promise\n if (!state.open && !this.signer.session) {\n this.signer.abortPairingAttempt();\n reject(new Error(\"Connection request reset. Please try again.\"));\n }\n });\n }\n await this.signer\n .connect({\n namespaces: {\n ...(required && {\n [this.namespace]: required,\n }),\n },\n ...(optional && {\n optionalNamespaces: {\n [this.namespace]: optional,\n },\n }),\n pairingTopic: opts?.pairingTopic,\n })\n .then((session?: SessionTypes.Struct) => {\n resolve(session);\n })\n .catch((error: Error) => {\n reject(new Error(error.message));\n });\n },\n );\n if (!session) return;\n\n const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);\n // if no required chains are set, use the approved accounts to fetch chainIds\n this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);\n this.setAccounts(accounts);\n this.events.emit(\"connect\", { chainId: toHexChainId(this.chainId) });\n } catch (error) {\n this.signer.logger.error(error);\n throw error;\n } finally {\n if (this.modal) this.modal.closeModal();\n }\n }\n\n public async authenticate(\n params: AuthenticateParams,\n walletUniversalLink?: string,\n ): Promise {\n if (!this.signer.client) {\n throw new Error(\"Provider not initialized. Call init() first\");\n }\n\n this.loadConnectOpts({\n chains: params?.chains,\n });\n\n try {\n const result = await new Promise(\n async (resolve, reject) => {\n if (this.rpc.showQrModal) {\n this.modal?.subscribeModal((state: { open: boolean }) => {\n // the modal was closed so reject the promise\n if (!state.open && !this.signer.session) {\n this.signer.abortPairingAttempt();\n reject(new Error(\"Connection request reset. Please try again.\"));\n }\n });\n }\n await this.signer\n .authenticate(\n {\n ...params,\n chains: this.rpc.chains,\n },\n walletUniversalLink,\n )\n .then((result: AuthTypes.AuthenticateResponseResult) => {\n resolve(result);\n })\n .catch((error: Error) => {\n reject(new Error(error.message));\n });\n },\n );\n\n const session = result.session;\n if (session) {\n const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);\n // if no required chains are set, use the approved accounts to fetch chainIds as both contain :\n this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);\n this.setAccounts(accounts);\n this.events.emit(\"connect\", { chainId: toHexChainId(this.chainId) });\n }\n return result;\n } catch (error) {\n this.signer.logger.error(error);\n throw error;\n } finally {\n if (this.modal) this.modal.closeModal();\n }\n }\n\n public async disconnect(): Promise {\n if (this.session) {\n await this.signer.disconnect();\n }\n this.reset();\n }\n\n public on: IEthereumProviderEvents[\"on\"] = (event, listener) => {\n this.events.on(event, listener);\n return this;\n };\n\n public once: IEthereumProviderEvents[\"once\"] = (event, listener) => {\n this.events.once(event, listener);\n return this;\n };\n\n public removeListener: IEthereumProviderEvents[\"removeListener\"] = (event, listener) => {\n this.events.removeListener(event, listener);\n return this;\n };\n\n public off: IEthereumProviderEvents[\"off\"] = (event, listener) => {\n this.events.off(event, listener);\n return this;\n };\n\n get isWalletConnect() {\n return true;\n }\n\n get session() {\n return this.signer.session;\n }\n\n // ---------- Protected --------------------------------------------- //\n\n protected registerEventListeners() {\n this.signer.on(\"session_event\", (payload: SignClientTypes.EventArguments[\"session_event\"]) => {\n const { params } = payload;\n const { event } = params;\n if (event.name === \"accountsChanged\") {\n this.accounts = this.parseAccounts(event.data);\n this.events.emit(\"accountsChanged\", this.accounts);\n } else if (event.name === \"chainChanged\") {\n this.setChainId(this.formatChainId(event.data));\n } else {\n this.events.emit(event.name as any, event.data);\n }\n this.events.emit(\"session_event\", payload);\n });\n\n this.signer.on(\"chainChanged\", (chainId: string) => {\n const chain = parseInt(chainId);\n this.chainId = chain;\n this.events.emit(\"chainChanged\", toHexChainId(this.chainId));\n this.persist();\n });\n\n this.signer.on(\n \"session_update\",\n (payload: SignClientTypes.EventArguments[\"session_update\"]) => {\n this.events.emit(\"session_update\", payload);\n },\n );\n\n this.signer.on(\n \"session_delete\",\n (payload: SignClientTypes.EventArguments[\"session_delete\"]) => {\n this.reset();\n this.events.emit(\"session_delete\", payload);\n this.events.emit(\"disconnect\", {\n ...getSdkError(\"USER_DISCONNECTED\"),\n data: payload.topic,\n name: \"USER_DISCONNECTED\",\n });\n },\n );\n\n this.signer.on(\"display_uri\", (uri: string) => {\n if (this.rpc.showQrModal) {\n // to refresh the QR we have to close the modal and open it again\n // until proper API is provided by walletconnect modal\n this.modal?.closeModal();\n this.modal?.openModal({ uri });\n }\n this.events.emit(\"display_uri\", uri);\n });\n }\n\n protected switchEthereumChain(chainId: number): void {\n this.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: chainId.toString(16) }],\n });\n }\n\n protected isCompatibleChainId(chainId: string): boolean {\n return typeof chainId === \"string\" ? chainId.startsWith(`${this.namespace}:`) : false;\n }\n\n protected formatChainId(chainId: number): string {\n return `${this.namespace}:${chainId}`;\n }\n\n protected parseChainId(chainId: string): number {\n return Number(chainId.split(\":\")[1]);\n }\n\n protected setChainIds(chains: string[]) {\n const compatible = chains.filter((x) => this.isCompatibleChainId(x));\n const chainIds = compatible.map((c) => this.parseChainId(c));\n if (chainIds.length) {\n this.chainId = chainIds[0];\n this.events.emit(\"chainChanged\", toHexChainId(this.chainId));\n this.persist();\n }\n }\n\n protected setChainId(chain: string) {\n if (this.isCompatibleChainId(chain)) {\n const chainId = this.parseChainId(chain);\n this.chainId = chainId;\n this.switchEthereumChain(chainId);\n }\n }\n\n protected parseAccountId(account: string): { chainId: string; address: string } {\n const [namespace, reference, address] = account.split(\":\");\n const chainId = `${namespace}:${reference}`;\n return { chainId, address };\n }\n\n protected setAccounts(accounts: string[]) {\n this.accounts = accounts\n .filter((x) => this.parseChainId(this.parseAccountId(x).chainId) === this.chainId)\n .map((x) => this.parseAccountId(x).address);\n this.events.emit(\"accountsChanged\", this.accounts);\n }\n\n protected getRpcConfig(opts: EthereumProviderOptions): EthereumRpcConfig {\n const requiredChains = opts?.chains ?? [];\n const optionalChains = opts?.optionalChains ?? [];\n const allChains = requiredChains.concat(optionalChains);\n if (!allChains.length)\n throw new Error(\"No chains specified in either `chains` or `optionalChains`\");\n const requiredMethods = requiredChains.length ? opts?.methods || REQUIRED_METHODS : [];\n const requiredEvents = requiredChains.length ? opts?.events || REQUIRED_EVENTS : [];\n const optionalMethods = opts?.optionalMethods || [];\n const optionalEvents = opts?.optionalEvents || [];\n const rpcMap = opts?.rpcMap || this.buildRpcMap(allChains, opts.projectId);\n const qrModalOptions = opts?.qrModalOptions || undefined;\n return {\n chains: requiredChains?.map((chain) => this.formatChainId(chain)),\n optionalChains: optionalChains.map((chain) => this.formatChainId(chain)),\n methods: requiredMethods,\n events: requiredEvents,\n optionalMethods,\n optionalEvents,\n rpcMap,\n showQrModal: Boolean(opts?.showQrModal),\n qrModalOptions,\n projectId: opts.projectId,\n metadata: opts.metadata,\n };\n }\n\n protected buildRpcMap(chains: number[], projectId: string): EthereumRpcMap {\n const map: EthereumRpcMap = {};\n chains.forEach((chain) => {\n map[chain] = this.getRpcUrl(chain, projectId);\n });\n return map;\n }\n\n protected async initialize(opts: EthereumProviderOptions) {\n this.rpc = this.getRpcConfig(opts);\n\n this.chainId = this.rpc.chains.length\n ? getEthereumChainId(this.rpc.chains)\n : getEthereumChainId(this.rpc.optionalChains);\n this.signer = await UniversalProvider.init({\n projectId: this.rpc.projectId,\n metadata: this.rpc.metadata,\n disableProviderPing: opts.disableProviderPing,\n relayUrl: opts.relayUrl,\n storageOptions: opts.storageOptions,\n customStoragePrefix: opts.customStoragePrefix,\n telemetryEnabled: opts.telemetryEnabled,\n logger: opts.logger,\n });\n this.registerEventListeners();\n await this.loadPersistedSession();\n if (this.rpc.showQrModal) {\n let WalletConnectModalClass;\n try {\n const { WalletConnectModal } = await import(\"@walletconnect/modal\");\n WalletConnectModalClass = WalletConnectModal;\n } catch {\n throw new Error(\"To use QR modal, please install @walletconnect/modal package\");\n }\n if (WalletConnectModalClass) {\n try {\n this.modal = new WalletConnectModalClass({\n projectId: this.rpc.projectId,\n ...this.rpc.qrModalOptions,\n });\n } catch (e) {\n this.signer.logger.error(e);\n throw new Error(\"Could not generate WalletConnectModal Instance\");\n }\n }\n }\n }\n\n protected loadConnectOpts(opts?: ConnectOps) {\n if (!opts) return;\n const { chains, optionalChains, rpcMap } = opts;\n if (chains && isValidArray(chains)) {\n this.rpc.chains = chains.map((chain) => this.formatChainId(chain));\n chains.forEach((chain) => {\n this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);\n });\n }\n if (optionalChains && isValidArray(optionalChains)) {\n this.rpc.optionalChains = [];\n this.rpc.optionalChains = optionalChains?.map((chain) => this.formatChainId(chain));\n optionalChains.forEach((chain) => {\n this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);\n });\n }\n }\n\n protected getRpcUrl(chainId: number, projectId?: string): string {\n const providedRpc = this.rpc.rpcMap?.[chainId];\n return (\n providedRpc ||\n `${RPC_URL}?chainId=eip155:${chainId}&projectId=${projectId || this.rpc.projectId}`\n );\n }\n\n protected async loadPersistedSession() {\n if (!this.session) return;\n try {\n const chainId = await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);\n\n // cater to both inline & nested namespace formats\n const namespace = this.session.namespaces[`${this.namespace}:${chainId}`]\n ? this.session.namespaces[`${this.namespace}:${chainId}`]\n : this.session.namespaces[this.namespace];\n\n this.setChainIds(chainId ? [this.formatChainId(chainId)] : namespace?.accounts);\n this.setAccounts(namespace?.accounts);\n } catch (error) {\n this.signer.logger.error(\"Failed to load persisted session, clearing state...\");\n this.signer.logger.error(error);\n await this.disconnect().catch((error) => this.signer.logger.warn(error));\n }\n }\n\n protected reset() {\n this.chainId = 1;\n this.accounts = [];\n }\n\n protected persist() {\n if (!this.session) return;\n this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`, this.chainId);\n }\n\n protected parseAccounts(payload: string | string[]): string[] {\n if (typeof payload === \"string\" || payload instanceof String) {\n return [this.parseAccount(payload)];\n }\n return payload.map((account: string) => this.parseAccount(account));\n }\n\n protected parseAccount = (payload: any): string => {\n return this.isCompatibleChainId(payload) ? this.parseAccountId(payload).address : payload;\n };\n}\n\nexport default EthereumProvider;\n","import { EthereumProvider as Provider } from \"./EthereumProvider\";\nexport const EthereumProvider = Provider;\nexport type { EthereumProviderOptions, RpcEvent, RpcMethod } from \"./EthereumProvider\";\nexport * from \"./constants/rpc\";\nexport { Provider };\n"],"names":["chains","chainId","params","optionalChains","methods","optionalMethods","events","optionalEvents","rpcMap","isValidArray","required","REQUIRED_METHODS","REQUIRED_EVENTS","__spreadValues","eventsRequiringPermissions","event","methodsRequiringPermissions","shouldIncludeRequiredChains","optional","OPTIONAL_METHODS","OPTIONAL_EVENTS","EthereumProvider","EventEmitter","STORAGE_KEY","listener","payload","opts","provider","args","expiry","callback","session","resolve","reject","_a","state","__spreadProps","error","accounts","getAccountsFromNamespaces","walletUniversalLink","result","chain","getSdkError","uri","_b","chainIds","x","c","account","namespace","reference","address","requiredChains","allChains","requiredMethods","requiredEvents","qrModalOptions","projectId","map","UniversalProvider","WalletConnectModalClass","WalletConnectModal","e","RPC_URL","Provider"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAa,MAAA,QAAA,CAAW,IACX,CACA,OAAA,CAAU,oBACV,WAAc,CAAA,CAAA,EAAG,QAA0B,CAAA,GAAA,EAAA,OAAA,CAAA,CAAA,CAAA,CAC3C,OAAU,CAAA;;ACJhB,MAAM,iBAAmB,CAAC,qBAAA,CAAuB,eAAe,CAC1D,CAAA,gBAAA,CAAmB,CAC9B,cACA,CAAA,qBAAA,CACA,wBACA,CAAA,UAAA,CACA,sBACA,mBACA,CAAA,sBAAA,CACA,uBACA,qBACA,CAAA,eAAA,CACA,6BACA,yBACA,CAAA,uBAAA,CACA,2BACA,CAAA,2BAAA,CACA,oBACA,mBACA,CAAA,kBAAA,CACA,yBACA,uBACA,CAAA,wBACF,EACa,eAAkB,CAAA,CAAC,cAAgB,CAAA,iBAAiB,EACpD,eAAkB,CAAA,CAC7B,eACA,iBACA,CAAA,SAAA,CACA,aACA,SACF;;6aCuEO,SAAS,kBAAmBA,CAAAA,CAAAA,CAA0B,CAC3D,OAAO,MAAA,CAAOA,EAAO,CAAC,CAAA,CAAE,MAAM,GAAG,CAAA,CAAE,CAAC,CAAC,CACvC,UAEgB,YAAaC,CAAAA,CAAAA,CAAyB,CACpD,OAAO,CAAKA,EAAAA,EAAAA,CAAAA,CAAQ,SAAS,EAAE,CAAA,CAAA,CACjC,CAYO,SAAS,eAAgBC,CAAAA,CAAAA,CAG9B,CACA,KAAM,CAAE,MAAAF,CAAAA,CAAAA,CAAQ,cAAAG,CAAAA,CAAAA,CAAgB,QAAAC,CAAS,CAAA,eAAA,CAAAC,CAAiB,CAAA,MAAA,CAAAC,CAAQ,CAAA,cAAA,CAAAC,EAAgB,MAAAC,CAAAA,CAAO,CACvFN,CAAAA,CAAAA,CACF,GAAI,CAACO,mBAAaT,CAAM,CAAA,CACtB,MAAM,IAAI,KAAM,CAAA,gBAAgB,EAGlC,MAAMU,CAAAA,CAAsB,CAC1B,MAAAV,CAAAA,CAAAA,CACA,QAASI,CAAWO,EAAAA,gBAAAA,CACpB,MAAQL,CAAAA,CAAAA,EAAUM,eAClB,CAAA,MAAA,CAAQC,EAAA,EACFb,CAAAA,CAAAA,CAAO,MACP,CAAA,CAAE,CAAC,kBAAA,CAAmBA,CAAM,CAAC,EAAGQ,CAAO,CAAA,kBAAA,CAAmBR,CAAM,CAAC,CAAE,CACnE,CAAA,EAER,CAAA,CAAA,CAIMc,CAA6BR,CAAAA,CAAAA,EAAA,YAAAA,CAAQ,CAAA,MAAA,CAAQS,CAAU,EAAA,CAACH,eAAgB,CAAA,QAAA,CAASG,CAAK,CACtFC,CAAAA,CAAAA,CAAAA,CAA8BZ,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAS,CAAA,MAAA,CAAQW,GAAU,CAACJ,gBAAAA,CAAiB,QAASI,CAAAA,CAAK,CAE/F,CAAA,CAAA,GACE,CAACZ,CACD,EAAA,CAACI,GACD,CAACF,CAAAA,EACD,EAACS,CAAA,EAAA,IAAA,EAAAA,CAA4B,CAAA,MAAA,CAAA,EAC7B,EAACE,CAAAA,EAAA,MAAAA,CAA6B,CAAA,MAAA,CAAA,CAE9B,OAAO,CAAE,QAAUhB,CAAAA,CAAAA,CAAO,OAASU,CAAW,CAAA,KAAA,CAAU,CAO1D,CAAA,MAAMO,CACHH,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAA4B,CAAA,MAAA,IAAUE,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAA6B,CAAA,MAAA,CAAA,EAAW,CAACb,CAE5Ee,CAAAA,CAAAA,CAAsB,CAC1B,MAAA,CAAQ,CACN,GAAG,IAAI,GACLD,CAAAA,CAAAA,CAA8BP,CAAS,CAAA,MAAA,CAAO,MAAOP,CAAAA,CAAAA,EAAkB,EAAE,CAAA,CAAIA,CAC/E,CACF,CACA,CAAA,OAAA,CAAS,CACP,GAAG,IAAI,IACLO,CAAS,CAAA,OAAA,CAAQ,OAAOL,CAAA,EAAA,IAAA,EAAAA,CAAiB,CAAA,MAAA,CAASA,CAAkBc,CAAAA,gBAAgB,CACtF,CACF,CAAA,CACA,MAAQ,CAAA,CACN,GAAG,IAAI,IAAIT,CAAS,CAAA,MAAA,CAAO,MAAOH,CAAAA,CAAAA,EAAA,IAAAA,EAAAA,CAAAA,CAAgB,OAASA,CAAiBa,CAAAA,eAAe,CAAC,CAC9F,CACA,CAAA,MAAA,CAAAZ,CACF,CAEA,CAAA,OAAO,CACL,QAAA,CAAUR,CAAO,CAAA,MAAA,CAASU,EAAW,KACrC,CAAA,CAAA,QAAA,CAAUP,CAAe,CAAA,MAAA,CAASe,CAAW,CAAA,KAAA,CAC/C,CACF,CA6CO,MAAMG,kBAA8C,CAWzD,WAAc,EAAA,CAVd,KAAO,MAAS,CAAA,IAAIC,oBACpB,IAAO,CAAA,SAAA,CAAY,SACnB,IAAO,CAAA,QAAA,CAAqB,EAAC,CAE7B,IAAO,CAAA,OAAA,CAAU,EAIjB,IAAmB,CAAA,WAAA,CAAcC,WAmKjC,CAAA,IAAA,CAAO,EAAoC,CAAA,CAACR,EAAOS,CACjD,IAAA,IAAA,CAAK,MAAO,CAAA,EAAA,CAAGT,CAAOS,CAAAA,CAAQ,EACvB,IAGT,CAAA,CAAA,IAAA,CAAO,IAAwC,CAAA,CAACT,CAAOS,CAAAA,CAAAA,IACrD,KAAK,MAAO,CAAA,IAAA,CAAKT,CAAOS,CAAAA,CAAQ,CACzB,CAAA,IAAA,CAAA,CAGT,KAAO,cAA4D,CAAA,CAACT,CAAOS,CAAAA,CAAAA,IACzE,IAAK,CAAA,MAAA,CAAO,eAAeT,CAAOS,CAAAA,CAAQ,CACnC,CAAA,IAAA,CAAA,CAGT,IAAO,CAAA,GAAA,CAAsC,CAACT,CAAOS,CAAAA,CAAAA,IACnD,KAAK,MAAO,CAAA,GAAA,CAAIT,EAAOS,CAAQ,CAAA,CACxB,IA6PT,CAAA,CAAA,IAAA,CAAU,YAAgBC,CAAAA,CAAAA,EACjB,KAAK,mBAAoBA,CAAAA,CAAO,CAAI,CAAA,IAAA,CAAK,cAAeA,CAAAA,CAAO,EAAE,OAAUA,CAAAA,CAAAA,CA9alF,IAAK,CAAA,MAAA,CAAS,EAAC,CACf,KAAK,GAAM,CAAA,GACb,CAEA,aAAa,IAAA,CAAKC,EAA0D,CAC1E,MAAMC,CAAW,CAAA,IAAIN,kBACrB,CAAA,OAAA,MAAMM,EAAS,UAAWD,CAAAA,CAAI,CACvBC,CAAAA,CACT,CAEA,MAAa,QAAqBC,CAAwBC,CAAAA,CAAAA,CAA6B,CACrF,OAAO,MAAM,IAAA,CAAK,OAAO,OAAQD,CAAAA,CAAAA,CAAM,IAAK,CAAA,aAAA,CAAc,IAAK,CAAA,OAAO,EAAGC,CAAM,CACjF,CAEO,SAAA,CACLD,CACAE,CAAAA,CAAAA,CACAD,EACM,CACN,IAAA,CAAK,MAAO,CAAA,SAAA,CAAUD,CAAME,CAAAA,CAAAA,CAAU,KAAK,aAAc,CAAA,IAAA,CAAK,OAAO,CAAA,CAAGD,CAAM,EAChF,CAEA,IAAI,SAAA,EAAqB,CACvB,OAAK,IAAK,CAAA,MAAA,CAAO,OACV,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,IAAA,CAAK,OAAQ,CAAA,SAAA,CADP,EAElC,CAEA,IAAI,UAAsB,EAAA,CACxB,OAAK,IAAA,CAAK,OAAO,MACV,CAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,WADP,CAElC,CAAA,CAEA,MAAa,MAAoC,EAAA,CAC/C,OAAK,IAAK,CAAA,OAAA,EAAS,MAAM,IAAA,CAAK,OAAQ,EAAA,CACrB,MAAM,IAAK,CAAA,OAAA,CAAQ,CAAE,MAAA,CAAQ,qBAAsB,CAAC,CAEvE,CAEA,MAAa,OAAQH,CAAAA,CAAAA,CAAkC,CACrD,GAAI,CAAC,IAAK,CAAA,MAAA,CAAO,MACf,CAAA,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAG/D,CAAA,IAAA,CAAK,eAAgBA,CAAAA,CAAI,CACzB,CAAA,KAAM,CAAE,QAAAhB,CAAAA,CAAAA,CAAU,QAAAQ,CAAAA,CAAS,CAAI,CAAA,eAAA,CAAgB,KAAK,GAAG,CAAA,CACvD,GAAI,CACF,MAAMa,CAAAA,CAAU,MAAM,IAAI,OAAA,CACxB,MAAOC,CAASC,CAAAA,CAAAA,GAAW,CAjSnC,IAAAC,CAAAA,CAkSc,IAAK,CAAA,GAAA,CAAI,WACXA,GAAAA,CAAAA,CAAAA,CAAA,KAAK,KAAL,GAAA,IAAA,EAAAA,CAAY,CAAA,cAAA,CAAgBC,CAA6B,EAAA,CAEnD,CAACA,CAAM,CAAA,IAAA,EAAQ,CAAC,IAAA,CAAK,MAAO,CAAA,OAAA,GAC9B,KAAK,MAAO,CAAA,mBAAA,EACZF,CAAAA,CAAAA,CAAO,IAAI,KAAA,CAAM,6CAA6C,CAAC,CAAA,EAEnE,CAEF,CAAA,CAAA,CAAA,MAAM,IAAK,CAAA,MAAA,CACR,QAAQG,CAAAvB,CAAAA,CAAAA,CAAA,CACP,UAAA,CAAYA,CAAA,CAAA,EAAA,CACNH,GAAY,CACd,CAAC,IAAK,CAAA,SAAS,EAAGA,CACpB,IAEEQ,CAAY,EAAA,CACd,mBAAoB,CAClB,CAAC,KAAK,SAAS,EAAGA,CACpB,CACF,CAVO,CAAA,CAAA,CAWP,aAAcQ,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,YACtB,CAAC,CAAA,CAAA,CACA,KAAMK,CAAkC,EAAA,CACvCC,CAAQD,CAAAA,CAAO,EACjB,CAAC,EACA,KAAOM,CAAAA,CAAAA,EAAiB,CACvBJ,CAAAA,CAAO,IAAI,KAAA,CAAMI,EAAM,OAAO,CAAC,EACjC,CAAC,EACL,CACF,EACA,GAAI,CAACN,CAAS,CAAA,OAEd,MAAMO,CAAAA,CAAWC,gCAA0BR,CAAQ,CAAA,UAAA,CAAY,CAAC,IAAA,CAAK,SAAS,CAAC,EAE/E,IAAK,CAAA,WAAA,CAAY,KAAK,GAAI,CAAA,MAAA,CAAO,OAAS,IAAK,CAAA,GAAA,CAAI,MAASO,CAAAA,CAAQ,CACpE,CAAA,IAAA,CAAK,YAAYA,CAAQ,CAAA,CACzB,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,SAAA,CAAW,CAAE,OAAS,CAAA,YAAA,CAAa,IAAK,CAAA,OAAO,CAAE,CAAC,EACrE,CAASD,MAAAA,CAAAA,CAAP,CACA,MAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,MAAMA,CAAK,CAAA,CACxBA,CACR,CAAA,OAAE,CACI,IAAA,CAAK,OAAO,IAAK,CAAA,KAAA,CAAM,UAAW,GACxC,CACF,CAEA,MAAa,YACXnC,CAAAA,CAAAA,CACAsC,CAC2D,CAAA,CAC3D,GAAI,CAAC,KAAK,MAAO,CAAA,MAAA,CACf,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAG/D,CAAA,IAAA,CAAK,eAAgB,CAAA,CACnB,MAAQtC,CAAAA,CAAAA,EAAA,YAAAA,CAAQ,CAAA,MAClB,CAAC,CAAA,CAED,GAAI,CACF,MAAMuC,CAAS,CAAA,MAAM,IAAI,OAAA,CACvB,MAAOT,CAAAA,CAASC,IAAW,CA9VnC,IAAAC,CA+Vc,CAAA,IAAA,CAAK,GAAI,CAAA,WAAA,GAAA,CACXA,EAAA,IAAK,CAAA,KAAA,GAAL,IAAAA,EAAAA,CAAAA,CAAY,cAAgBC,CAAAA,CAAAA,EAA6B,CAEnD,CAACA,CAAAA,CAAM,IAAQ,EAAA,CAAC,IAAK,CAAA,MAAA,CAAO,UAC9B,IAAK,CAAA,MAAA,CAAO,mBAAoB,EAAA,CAChCF,CAAO,CAAA,IAAI,MAAM,6CAA6C,CAAC,GAEnE,CAEF,CAAA,CAAA,CAAA,MAAM,KAAK,MACR,CAAA,YAAA,CACCG,CAAAvB,CAAAA,CAAAA,CAAA,EACKX,CAAAA,CAAAA,CAAAA,CADL,CAEE,MAAQ,CAAA,IAAA,CAAK,GAAI,CAAA,MACnB,CACAsC,CAAAA,CAAAA,CACF,EACC,IAAMC,CAAAA,CAAAA,EAAiD,CACtDT,CAAAA,CAAQS,CAAM,EAChB,CAAC,CACA,CAAA,KAAA,CAAOJ,CAAiB,EAAA,CACvBJ,CAAO,CAAA,IAAI,MAAMI,CAAM,CAAA,OAAO,CAAC,EACjC,CAAC,EACL,CACF,CAEMN,CAAAA,CAAAA,CAAUU,CAAO,CAAA,OAAA,CACvB,GAAIV,CAAAA,CAAS,CACX,MAAMO,CAAAA,CAAWC,+BAA0BR,CAAAA,CAAAA,CAAQ,UAAY,CAAA,CAAC,KAAK,SAAS,CAAC,EAE/E,IAAK,CAAA,WAAA,CAAY,KAAK,GAAI,CAAA,MAAA,CAAO,MAAS,CAAA,IAAA,CAAK,GAAI,CAAA,MAAA,CAASO,CAAQ,CACpE,CAAA,IAAA,CAAK,WAAYA,CAAAA,CAAQ,CACzB,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,SAAA,CAAW,CAAE,OAAA,CAAS,YAAa,CAAA,IAAA,CAAK,OAAO,CAAE,CAAC,EAErE,CAAA,OAAOG,CACT,CAAA,MAASJ,EAAP,CACA,MAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAMA,CAAAA,CAAK,EACxBA,CACR,CAAA,OAAE,CACI,IAAA,CAAK,KAAO,EAAA,IAAA,CAAK,MAAM,UAAW,GACxC,CACF,CAEA,MAAa,UAAA,EAA4B,CACnC,IAAK,CAAA,OAAA,EACP,MAAM,IAAA,CAAK,MAAO,CAAA,UAAA,GAEpB,IAAK,CAAA,KAAA,GACP,CAsBA,IAAI,eAAA,EAAkB,CACpB,OAAO,CAAA,CACT,CAEA,IAAI,OAAU,EAAA,CACZ,OAAO,IAAK,CAAA,MAAA,CAAO,OACrB,CAIU,sBAAyB,EAAA,CACjC,KAAK,MAAO,CAAA,EAAA,CAAG,eAAkBZ,CAAAA,CAAAA,EAA6D,CAC5F,KAAM,CAAE,MAAAvB,CAAAA,CAAO,CAAIuB,CAAAA,CAAAA,CACb,CAAE,KAAA,CAAAV,CAAM,CAAIb,CAAAA,CAAAA,CACda,CAAM,CAAA,IAAA,GAAS,iBACjB,EAAA,IAAA,CAAK,SAAW,IAAK,CAAA,aAAA,CAAcA,CAAM,CAAA,IAAI,CAC7C,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,iBAAA,CAAmB,KAAK,QAAQ,CAAA,EACxCA,EAAM,IAAS,GAAA,cAAA,CACxB,IAAK,CAAA,UAAA,CAAW,IAAK,CAAA,aAAA,CAAcA,EAAM,IAAI,CAAC,CAE9C,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAKA,EAAM,IAAaA,CAAAA,CAAAA,CAAM,IAAI,CAAA,CAEhD,IAAK,CAAA,MAAA,CAAO,KAAK,eAAiBU,CAAAA,CAAO,EAC3C,CAAC,CAED,CAAA,IAAA,CAAK,OAAO,EAAG,CAAA,cAAA,CAAiBxB,CAAoB,EAAA,CAClD,MAAMyC,CAAAA,CAAQ,SAASzC,CAAO,CAAA,CAC9B,IAAK,CAAA,OAAA,CAAUyC,CACf,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,cAAA,CAAgB,YAAa,CAAA,IAAA,CAAK,OAAO,CAAC,EAC3D,IAAK,CAAA,OAAA,GACP,CAAC,CAAA,CAED,KAAK,MAAO,CAAA,EAAA,CACV,gBACCjB,CAAAA,CAAAA,EAA8D,CAC7D,IAAA,CAAK,OAAO,IAAK,CAAA,gBAAA,CAAkBA,CAAO,EAC5C,CACF,CAAA,CAEA,KAAK,MAAO,CAAA,EAAA,CACV,gBACCA,CAAAA,CAAAA,EAA8D,CAC7D,IAAA,CAAK,OACL,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,gBAAkBA,CAAAA,CAAO,EAC1C,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,YAAA,CAAcW,CAAAvB,CAAAA,CAAAA,CAAA,GAC1B8B,iBAAY,CAAA,mBAAmB,CADL,CAAA,CAAA,CAE7B,IAAMlB,CAAAA,CAAAA,CAAQ,MACd,IAAM,CAAA,mBACR,CAAC,CAAA,EACH,CACF,CAAA,CAEA,KAAK,MAAO,CAAA,EAAA,CAAG,cAAgBmB,CAAgB,EAAA,CAzdnD,IAAAV,CAAAW,CAAAA,CAAAA,CA0dU,IAAK,CAAA,GAAA,CAAI,WAGXX,GAAAA,CAAAA,CAAAA,CAAA,KAAK,KAAL,GAAA,IAAA,EAAAA,CAAY,CAAA,UAAA,EAAA,CAAA,CACZW,CAAA,CAAA,IAAA,CAAK,QAAL,IAAAA,EAAAA,CAAAA,CAAY,SAAU,CAAA,CAAE,GAAAD,CAAAA,CAAI,IAE9B,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,aAAA,CAAeA,CAAG,EACrC,CAAC,EACH,CAEU,mBAAoB3C,CAAAA,CAAAA,CAAuB,CACnD,IAAA,CAAK,QAAQ,CACX,MAAA,CAAQ,4BACR,CAAA,MAAA,CAAQ,CAAC,CAAE,QAASA,CAAQ,CAAA,QAAA,CAAS,EAAE,CAAE,CAAC,CAC5C,CAAC,EACH,CAEU,oBAAoBA,CAA0B,CAAA,CACtD,OAAO,OAAOA,CAAAA,EAAY,QAAWA,CAAAA,CAAAA,CAAQ,UAAW,CAAA,CAAA,EAAG,KAAK,SAAY,CAAA,CAAA,CAAA,CAAA,CAAI,CAClF,CAAA,CAEU,aAAcA,CAAAA,CAAAA,CAAyB,CAC/C,OAAO,CAAA,EAAG,IAAK,CAAA,SAAA,CAAA,CAAA,EAAaA,CAC9B,CAAA,CAAA,CAEU,aAAaA,CAAyB,CAAA,CAC9C,OAAO,MAAA,CAAOA,CAAQ,CAAA,KAAA,CAAM,GAAG,CAAE,CAAA,CAAC,CAAC,CACrC,CAEU,WAAA,CAAYD,EAAkB,CAEtC,MAAM8C,CADa9C,CAAAA,CAAAA,CAAO,MAAQ+C,CAAAA,CAAAA,EAAM,KAAK,mBAAoBA,CAAAA,CAAC,CAAC,CAAA,CACvC,GAAKC,CAAAA,CAAAA,EAAM,KAAK,YAAaA,CAAAA,CAAC,CAAC,CACvDF,CAAAA,CAAAA,CAAS,SACX,IAAK,CAAA,OAAA,CAAUA,CAAS,CAAA,CAAC,CACzB,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,cAAA,CAAgB,YAAa,CAAA,IAAA,CAAK,OAAO,CAAC,EAC3D,IAAK,CAAA,OAAA,EAET,EAAA,CAEU,UAAWJ,CAAAA,CAAAA,CAAe,CAClC,GAAI,IAAA,CAAK,mBAAoBA,CAAAA,CAAK,CAAG,CAAA,CACnC,MAAMzC,CAAU,CAAA,IAAA,CAAK,YAAayC,CAAAA,CAAK,CACvC,CAAA,IAAA,CAAK,QAAUzC,CACf,CAAA,IAAA,CAAK,mBAAoBA,CAAAA,CAAO,EAEpC,CAAA,CAEU,eAAegD,CAAuD,CAAA,CAC9E,KAAM,CAACC,CAAWC,CAAAA,CAAAA,CAAWC,CAAO,CAAIH,CAAAA,CAAAA,CAAQ,MAAM,GAAG,CAAA,CAEzD,OAAO,CAAE,OAAA,CADO,CAAGC,EAAAA,CAAAA,CAAAA,CAAAA,EAAaC,CACd,CAAA,CAAA,CAAA,OAAA,CAAAC,CAAQ,CAC5B,CAEU,WAAYd,CAAAA,CAAAA,CAAoB,CACxC,IAAA,CAAK,SAAWA,CACb,CAAA,MAAA,CAAQS,CAAM,EAAA,IAAA,CAAK,YAAa,CAAA,IAAA,CAAK,eAAeA,CAAC,CAAA,CAAE,OAAO,CAAA,GAAM,IAAK,CAAA,OAAO,EAChF,GAAKA,CAAAA,CAAAA,EAAM,IAAK,CAAA,cAAA,CAAeA,CAAC,CAAA,CAAE,OAAO,CAC5C,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,iBAAmB,CAAA,IAAA,CAAK,QAAQ,EACnD,CAEU,YAAarB,CAAAA,CAAAA,CAAkD,CAthB3E,IAAAQ,EAAAW,CAuhBI,CAAA,MAAMQ,GAAiBnB,CAAAR,CAAAA,CAAAA,EAAA,YAAAA,CAAM,CAAA,MAAA,GAAN,IAAAQ,CAAAA,CAAAA,CAAgB,EAAC,CAClC/B,GAAiB0C,CAAAnB,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,cAAN,GAAA,IAAA,CAAAmB,EAAwB,EAAC,CAC1CS,CAAYD,CAAAA,CAAAA,CAAe,MAAOlD,CAAAA,CAAc,EACtD,GAAI,CAACmD,CAAU,CAAA,MAAA,CACb,MAAM,IAAI,MAAM,4DAA4D,CAAA,CAC9E,MAAMC,CAAAA,CAAkBF,CAAe,CAAA,MAAA,CAAA,CAAS3B,GAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,OAAWf,GAAAA,gBAAAA,CAAmB,EAAC,CAC/E6C,EAAiBH,CAAe,CAAA,MAAA,CAAA,CAAS3B,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,MAAA,GAAUd,gBAAkB,EAAC,CAC5EP,CAAkBqB,CAAAA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,kBAAmB,EAAC,CAC5CnB,CAAiBmB,CAAAA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,iBAAkB,EAAC,CAC1ClB,CAASkB,CAAAA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,SAAU,IAAK,CAAA,WAAA,CAAY4B,CAAW5B,CAAAA,CAAAA,CAAK,SAAS,CAAA,CACnE+B,GAAiB/B,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,cAAA,GAAkB,KAC/C,CAAA,CAAA,OAAO,CACL,MAAQ2B,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAgB,GAAKX,CAAAA,CAAAA,EAAU,KAAK,aAAcA,CAAAA,CAAK,CAC/D,CAAA,CAAA,cAAA,CAAgBvC,CAAe,CAAA,GAAA,CAAKuC,GAAU,IAAK,CAAA,aAAA,CAAcA,CAAK,CAAC,CACvE,CAAA,OAAA,CAASa,EACT,MAAQC,CAAAA,CAAAA,CACR,gBAAAnD,CACA,CAAA,cAAA,CAAAE,EACA,MAAAC,CAAAA,CAAAA,CACA,WAAa,CAAA,CAAA,EAAQkB,CAAA,EAAA,IAAA,EAAAA,EAAM,WAC3B,CAAA,CAAA,cAAA,CAAA+B,CACA,CAAA,SAAA,CAAW/B,CAAK,CAAA,SAAA,CAChB,SAAUA,CAAK,CAAA,QACjB,CACF,CAEU,WAAY1B,CAAAA,CAAAA,CAAkB0D,EAAmC,CACzE,MAAMC,CAAsB,CAAA,EAC5B,CAAA,OAAA3D,EAAO,OAAS0C,CAAAA,CAAAA,EAAU,CACxBiB,CAAAA,CAAIjB,CAAK,CAAA,CAAI,KAAK,SAAUA,CAAAA,CAAAA,CAAOgB,CAAS,EAC9C,CAAC,CAAA,CACMC,CACT,CAEA,MAAgB,UAAWjC,CAAAA,CAAAA,CAA+B,CAkBxD,GAjBA,KAAK,GAAM,CAAA,IAAA,CAAK,aAAaA,CAAI,CAAA,CAEjC,KAAK,OAAU,CAAA,IAAA,CAAK,GAAI,CAAA,MAAA,CAAO,MAC3B,CAAA,kBAAA,CAAmB,KAAK,GAAI,CAAA,MAAM,CAClC,CAAA,kBAAA,CAAmB,IAAK,CAAA,GAAA,CAAI,cAAc,CAC9C,CAAA,IAAA,CAAK,MAAS,CAAA,MAAMkC,mCAAkB,CAAA,IAAA,CAAK,CACzC,SAAW,CAAA,IAAA,CAAK,GAAI,CAAA,SAAA,CACpB,QAAU,CAAA,IAAA,CAAK,IAAI,QACnB,CAAA,mBAAA,CAAqBlC,CAAK,CAAA,mBAAA,CAC1B,QAAUA,CAAAA,CAAAA,CAAK,SACf,cAAgBA,CAAAA,CAAAA,CAAK,cACrB,CAAA,mBAAA,CAAqBA,CAAK,CAAA,mBAAA,CAC1B,iBAAkBA,CAAK,CAAA,gBAAA,CACvB,MAAQA,CAAAA,CAAAA,CAAK,MACf,CAAC,EACD,IAAK,CAAA,sBAAA,GACL,MAAM,IAAA,CAAK,sBACP,CAAA,IAAA,CAAK,GAAI,CAAA,WAAA,CAAa,CACxB,IAAImC,EACJ,GAAI,CACF,KAAM,CAAE,kBAAAC,CAAAA,CAAmB,EAAI,MAAM,mFAAO,sBAAsB,MAAA,CAClED,CAA0BC,CAAAA,EAC5B,OAAQC,CAAN,CAAA,CACA,MAAM,IAAI,KAAM,CAAA,8DAA8D,CAChF,CACA,GAAIF,CACF,CAAA,GAAI,CACF,IAAA,CAAK,MAAQ,IAAIA,CAAAA,CAAwBhD,CAAA,CAAA,CACvC,SAAW,CAAA,IAAA,CAAK,IAAI,SACjB,CAAA,CAAA,IAAA,CAAK,GAAI,CAAA,cAAA,CACb,EACH,CAAA,MAASkD,EAAP,CACA,MAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAMA,CAAAA,CAAC,EACpB,IAAI,KAAA,CAAM,gDAAgD,CAClE,CAGN,CAAA,CAEU,gBAAgBrC,CAAmB,CAAA,CAC3C,GAAI,CAACA,CAAM,CAAA,OACX,KAAM,CAAE,MAAA,CAAA1B,CAAQ,CAAA,cAAA,CAAAG,CAAgB,CAAA,MAAA,CAAAK,CAAO,CAAIkB,CAAAA,CAAAA,CACvC1B,CAAUS,EAAAA,kBAAAA,CAAaT,CAAM,CAAA,GAC/B,KAAK,GAAI,CAAA,MAAA,CAASA,CAAO,CAAA,GAAA,CAAK0C,CAAU,EAAA,IAAA,CAAK,cAAcA,CAAK,CAAC,CACjE1C,CAAAA,CAAAA,CAAO,OAAS0C,CAAAA,CAAAA,EAAU,CACxB,IAAK,CAAA,GAAA,CAAI,MAAOA,CAAAA,CAAK,CAAIlC,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAASkC,CAAAA,CAAAA,CAAAA,GAAU,KAAK,SAAUA,CAAAA,CAAK,EAClE,CAAC,CAAA,CAAA,CAECvC,CAAkBM,EAAAA,kBAAAA,CAAaN,CAAc,CAAA,GAC/C,KAAK,GAAI,CAAA,cAAA,CAAiB,EAAC,CAC3B,IAAK,CAAA,GAAA,CAAI,eAAiBA,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAgB,CAAA,GAAA,CAAKuC,CAAU,EAAA,IAAA,CAAK,cAAcA,CAAK,CAAA,CAAA,CACjFvC,CAAe,CAAA,OAAA,CAASuC,CAAU,EAAA,CAChC,KAAK,GAAI,CAAA,MAAA,CAAOA,CAAK,CAAA,CAAA,CAAIlC,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,EAASkC,CAAU,CAAA,GAAA,IAAA,CAAK,SAAUA,CAAAA,CAAK,EAClE,CAAC,GAEL,CAEU,SAAA,CAAUzC,CAAiByD,CAAAA,CAAAA,CAA4B,CAnnBnE,IAAAxB,EAqnBI,OADoBA,CAAAA,CAAAA,CAAAA,CAAA,KAAK,GAAI,CAAA,MAAA,GAAT,YAAAA,CAAkBjC,CAAAA,CAAAA,CAAAA,GAGpC,CAAG+D,EAAAA,OAAAA,CAAAA,gBAAAA,EAA0B/D,CAAqByD,CAAAA,WAAAA,EAAAA,CAAAA,EAAa,KAAK,GAAI,CAAA,SAAA,CAAA,CAE5E,CAEA,MAAgB,oBAAuB,EAAA,CACrC,GAAK,IAAK,CAAA,OAAA,CACV,GAAI,CACF,MAAMzD,CAAAA,CAAU,MAAM,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,IAAA,CAAK,OAAQ,CAAA,OAAA,CAAQ,GAAG,IAAK,CAAA,WAAA,CAAA,QAAA,CAAqB,CAGrFiD,CAAAA,CAAAA,CAAY,IAAK,CAAA,OAAA,CAAQ,WAAW,CAAG,EAAA,IAAA,CAAK,SAAajD,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,CAAS,CACpE,CAAA,IAAA,CAAK,QAAQ,UAAW,CAAA,CAAA,EAAG,IAAK,CAAA,SAAA,CAAA,CAAA,EAAaA,CAAS,CAAA,CAAA,CAAA,CACtD,KAAK,OAAQ,CAAA,UAAA,CAAW,KAAK,SAAS,CAAA,CAE1C,KAAK,WAAYA,CAAAA,CAAAA,CAAU,CAAC,IAAA,CAAK,aAAcA,CAAAA,CAAO,CAAC,CAAIiD,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAW,QAAQ,CAAA,CAC9E,KAAK,WAAYA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAW,QAAQ,EACtC,OAASb,CAAP,CAAA,CACA,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,KAAA,CAAM,qDAAqD,CAC9E,CAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAMA,CAAAA,CAAK,EAC9B,MAAM,IAAA,CAAK,UAAW,EAAA,CAAE,KAAOA,CAAAA,CAAAA,EAAU,KAAK,MAAO,CAAA,MAAA,CAAO,IAAKA,CAAAA,CAAK,CAAC,EACzE,CACF,CAEU,KAAA,EAAQ,CAChB,IAAA,CAAK,OAAU,CAAA,CAAA,CACf,KAAK,QAAW,CAAA,GAClB,CAEU,OAAU,EAAA,CACb,KAAK,OACV,EAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,QAAQ,CAAG,EAAA,IAAA,CAAK,WAAuB,CAAA,QAAA,CAAA,CAAA,IAAA,CAAK,OAAO,EACrF,CAEU,aAAcZ,CAAAA,CAAAA,CAAsC,CAC5D,OAAI,OAAOA,CAAAA,EAAY,UAAYA,CAAmB,YAAA,MAAA,CAC7C,CAAC,IAAA,CAAK,YAAaA,CAAAA,CAAO,CAAC,CAE7BA,CAAAA,CAAAA,CAAQ,GAAKwB,CAAAA,CAAAA,EAAoB,IAAK,CAAA,YAAA,CAAaA,CAAO,CAAC,CACpE,CAKF;;ACjqBO,MAAM,iBAAmBgB;;;;;;;;;"} +\ No newline at end of file +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.es.js b/node_modules/@walletconnect/ethereum-provider/dist/index.es.js +index 0dbe869..44a27f2 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.es.js ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.es.js +@@ -1,2 +1,2 @@ +-import{EventEmitter as P}from"events";import{getAccountsFromNamespaces as _,getSdkError as A,isValidArray as f}from"@walletconnect/utils";import{UniversalProvider as S}from"@walletconnect/universal-provider";const R="wc",T="ethereum_provider",$=`${R}@2:${T}:`,j="https://rpc.walletconnect.org/v1/",u=["eth_sendTransaction","personal_sign"],y=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],g=["chainChanged","accountsChanged"],b=["chainChanged","accountsChanged","message","disconnect","connect"];var q=Object.defineProperty,N=Object.defineProperties,D=Object.getOwnPropertyDescriptors,M=Object.getOwnPropertySymbols,U=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,O=(r,t,s)=>t in r?q(r,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[t]=s,p=(r,t)=>{for(var s in t||(t={}))U.call(t,s)&&O(r,s,t[s]);if(M)for(var s of M(t))Q.call(t,s)&&O(r,s,t[s]);return r},E=(r,t)=>N(r,D(t));function m(r){return Number(r[0].split(":")[1])}function v(r){return`0x${r.toString(16)}`}function L(r){const{chains:t,optionalChains:s,methods:i,optionalMethods:e,events:n,optionalEvents:o,rpcMap:c}=r;if(!f(t))throw new Error("Invalid chains");const a={chains:t,methods:i||u,events:n||g,rpcMap:p({},t.length?{[m(t)]:c[m(t)]}:{})},h=n?.filter(l=>!g.includes(l)),d=i?.filter(l=>!u.includes(l));if(!s&&!o&&!e&&!(h!=null&&h.length)&&!(d!=null&&d.length))return{required:t.length?a:void 0};const w=h?.length&&d?.length||!s,I={chains:[...new Set(w?a.chains.concat(s||[]):s)],methods:[...new Set(a.methods.concat(e!=null&&e.length?e:y))],events:[...new Set(a.events.concat(o!=null&&o.length?o:b))],rpcMap:c};return{required:t.length?a:void 0,optional:s.length?I:void 0}}class C{constructor(){this.events=new P,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=$,this.on=(t,s)=>(this.events.on(t,s),this),this.once=(t,s)=>(this.events.once(t,s),this),this.removeListener=(t,s)=>(this.events.removeListener(t,s),this),this.off=(t,s)=>(this.events.off(t,s),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const s=new C;return await s.initialize(t),s}async request(t,s){return await this.signer.request(t,this.formatChainId(this.chainId),s)}sendAsync(t,s,i){this.signer.sendAsync(t,s,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=L(this.rpc);try{const e=await new Promise(async(o,c)=>{var a;this.rpc.showQrModal&&((a=this.modal)==null||a.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(E(p({namespaces:p({},s&&{[this.namespace]:s})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic})).then(h=>{o(h)}).catch(h=>{c(new Error(h.message))})});if(!e)return;const n=_(e.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:v(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{this.modal&&this.modal.closeModal()}}async authenticate(t,s){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const i=await new Promise(async(n,o)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(a=>{!a.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(E(p({},t),{chains:this.rpc.chains}),s).then(a=>{n(a)}).catch(a=>{o(new Error(a.message))})}),e=i.session;if(e){const n=_(e.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:v(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:s}=t,{event:i}=s;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const s=parseInt(t);this.chainId=s,this.events.emit("chainChanged",v(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",E(p({},A("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var s,i;this.rpc.showQrModal&&((s=this.modal)==null||s.closeModal(),(i=this.modal)==null||i.openModal({uri:t})),this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const s=t.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));s.length&&(this.chainId=s[0],this.events.emit("chainChanged",v(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const s=this.parseChainId(t);this.chainId=s,this.switchEthereumChain(s)}}parseAccountId(t){const[s,i,e]=t.split(":");return{chainId:`${s}:${i}`,address:e}}setAccounts(t){this.accounts=t.filter(s=>this.parseChainId(this.parseAccountId(s).chainId)===this.chainId).map(s=>this.parseAccountId(s).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var s,i;const e=(s=t?.chains)!=null?s:[],n=(i=t?.optionalChains)!=null?i:[],o=e.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const c=e.length?t?.methods||u:[],a=e.length?t?.events||g:[],h=t?.optionalMethods||[],d=t?.optionalEvents||[],w=t?.rpcMap||this.buildRpcMap(o,t.projectId),I=t?.qrModalOptions||void 0;return{chains:e?.map(l=>this.formatChainId(l)),optionalChains:n.map(l=>this.formatChainId(l)),methods:c,events:a,optionalMethods:h,optionalEvents:d,rpcMap:w,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:I,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,s){const i={};return t.forEach(e=>{i[e]=this.getRpcUrl(e,s)}),i}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?m(this.rpc.chains):m(this.rpc.optionalChains),this.signer=await S.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const{WalletConnectModal:i}=await import("@walletconnect/modal");s=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(s)try{this.modal=new s(p({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:s,optionalChains:i,rpcMap:e}=t;s&&f(s)&&(this.rpc.chains=s.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=e?.[n]||this.getRpcUrl(n)})),i&&f(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=e?.[n]||this.getRpcUrl(n)}))}getRpcUrl(t,s){var i;return((i=this.rpc.rpcMap)==null?void 0:i[t])||`${j}?chainId=eip155:${t}&projectId=${s||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),s=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:s?.accounts),this.setAccounts(s?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(s=>this.signer.logger.warn(s))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(s=>this.parseAccount(s))}}const x=C;export{x as EthereumProvider,b as OPTIONAL_EVENTS,y as OPTIONAL_METHODS,g as REQUIRED_EVENTS,u as REQUIRED_METHODS,C as default}; ++import{EventEmitter as P}from"events";import{getAccountsFromNamespaces as _,getSdkError as A,isValidArray as f}from"@walletconnect/utils";import{UniversalProvider as S}from"@walletconnect/universal-provider";const R="wc",T="ethereum_provider",$=`${R}@2:${T}:`,j="https://rpc.walletconnect.org/v1/",g=["eth_sendTransaction","personal_sign"],y=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],u=["chainChanged","accountsChanged"],b=["chainChanged","accountsChanged","message","disconnect","connect"];var q=Object.defineProperty,N=Object.defineProperties,D=Object.getOwnPropertyDescriptors,M=Object.getOwnPropertySymbols,U=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,O=(r,t,s)=>t in r?q(r,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[t]=s,p=(r,t)=>{for(var s in t||(t={}))U.call(t,s)&&O(r,s,t[s]);if(M)for(var s of M(t))Q.call(t,s)&&O(r,s,t[s]);return r},E=(r,t)=>N(r,D(t));function m(r){return Number(r[0].split(":")[1])}function v(r){return`0x${r.toString(16)}`}function L(r){const{chains:t,optionalChains:s,methods:i,optionalMethods:e,events:n,optionalEvents:o,rpcMap:c}=r;if(!f(t))throw new Error("Invalid chains");const a={chains:t,methods:i||g,events:n||u,rpcMap:p({},t.length?{[m(t)]:c[m(t)]}:{})},h=n?.filter(l=>!u.includes(l)),d=i?.filter(l=>!g.includes(l));if(!s&&!o&&!e&&!(h!=null&&h.length)&&!(d!=null&&d.length))return{required:t.length?a:void 0};const w=h?.length&&d?.length||!s,I={chains:[...new Set(w?a.chains.concat(s||[]):s)],methods:[...new Set(a.methods.concat(e!=null&&e.length?e:y))],events:[...new Set(a.events.concat(o!=null&&o.length?o:b))],rpcMap:c};return{required:t.length?a:void 0,optional:s.length?I:void 0}}class C{constructor(){this.events=new P,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=$,this.on=(t,s)=>(this.events.on(t,s),this),this.once=(t,s)=>(this.events.once(t,s),this),this.removeListener=(t,s)=>(this.events.removeListener(t,s),this),this.off=(t,s)=>(this.events.off(t,s),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const s=new C;return await s.initialize(t),s}async request(t,s){return await this.signer.request(t,this.formatChainId(this.chainId),s)}sendAsync(t,s,i){this.signer.sendAsync(t,s,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=L(this.rpc);try{const e=await new Promise(async(o,c)=>{var a;this.rpc.showQrModal&&((a=this.modal)==null||a.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(E(p({namespaces:p({},s&&{[this.namespace]:s})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic})).then(h=>{o(h)}).catch(h=>{c(new Error(h.message))})});if(!e)return;const n=_(e.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:v(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{this.modal&&this.modal.closeModal()}}async authenticate(t,s){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const i=await new Promise(async(n,o)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(a=>{!a.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(E(p({},t),{chains:this.rpc.chains}),s).then(a=>{n(a)}).catch(a=>{o(new Error(a.message))})}),e=i.session;if(e){const n=_(e.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:v(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:s}=t,{event:i}=s;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const s=parseInt(t);this.chainId=s,this.events.emit("chainChanged",v(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",E(p({},A("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var s,i;this.rpc.showQrModal&&((s=this.modal)==null||s.closeModal(),(i=this.modal)==null||i.openModal({uri:t})),this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const s=t.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));s.length&&(this.chainId=s[0],this.events.emit("chainChanged",v(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const s=this.parseChainId(t);this.chainId=s,this.switchEthereumChain(s)}}parseAccountId(t){const[s,i,e]=t.split(":");return{chainId:`${s}:${i}`,address:e}}setAccounts(t){this.accounts=t.filter(s=>this.parseChainId(this.parseAccountId(s).chainId)===this.chainId).map(s=>this.parseAccountId(s).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var s,i;const e=(s=t?.chains)!=null?s:[],n=(i=t?.optionalChains)!=null?i:[],o=e.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const c=e.length?t?.methods||g:[],a=e.length?t?.events||u:[],h=t?.optionalMethods||[],d=t?.optionalEvents||[],w=t?.rpcMap||this.buildRpcMap(o,t.projectId),I=t?.qrModalOptions||void 0;return{chains:e?.map(l=>this.formatChainId(l)),optionalChains:n.map(l=>this.formatChainId(l)),methods:c,events:a,optionalMethods:h,optionalEvents:d,rpcMap:w,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:I,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,s){const i={};return t.forEach(e=>{i[e]=this.getRpcUrl(e,s)}),i}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?m(this.rpc.chains):m(this.rpc.optionalChains),this.signer=await S.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const{WalletConnectModal:i}=await import("@walletconnect/modal");s=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(s)try{this.modal=new s(p({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:s,optionalChains:i,rpcMap:e}=t;s&&f(s)&&(this.rpc.chains=s.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=e?.[n]||this.getRpcUrl(n)})),i&&f(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=e?.[n]||this.getRpcUrl(n)}))}getRpcUrl(t,s){var i;return((i=this.rpc.rpcMap)==null?void 0:i[t])||`${j}?chainId=eip155:${t}&projectId=${s||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),s=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:s?.accounts),this.setAccounts(s?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(s=>this.signer.logger.warn(s))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(s=>this.parseAccount(s))}}const x=C;export{x as EthereumProvider,b as OPTIONAL_EVENTS,y as OPTIONAL_METHODS,C as Provider,u as REQUIRED_EVENTS,g as REQUIRED_METHODS}; + //# sourceMappingURL=index.es.js.map +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.es.js.map b/node_modules/@walletconnect/ethereum-provider/dist/index.es.js.map +index 0ebfa1e..ed78e84 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.es.js.map ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.es.js.map +@@ -1 +1 @@ +-{"version":3,"file":"index.es.js","sources":["../src/constants/values.ts","../src/constants/rpc.ts","../src/EthereumProvider.ts","../src/index.ts"],"sourcesContent":["export const PROTOCOL = \"wc\";\nexport const WC_VERSION = 2;\nexport const CONTEXT = \"ethereum_provider\";\nexport const STORAGE_KEY = `${PROTOCOL}@${WC_VERSION}:${CONTEXT}:`;\nexport const RPC_URL = \"https://rpc.walletconnect.org/v1/\";\n","export const REQUIRED_METHODS = [\"eth_sendTransaction\", \"personal_sign\"];\nexport const OPTIONAL_METHODS = [\n \"eth_accounts\",\n \"eth_requestAccounts\",\n \"eth_sendRawTransaction\",\n \"eth_sign\",\n \"eth_signTransaction\",\n \"eth_signTypedData\",\n \"eth_signTypedData_v3\",\n \"eth_signTypedData_v4\",\n \"eth_sendTransaction\",\n \"personal_sign\",\n \"wallet_switchEthereumChain\",\n \"wallet_addEthereumChain\",\n \"wallet_getPermissions\",\n \"wallet_requestPermissions\",\n \"wallet_registerOnboarding\",\n \"wallet_watchAsset\",\n \"wallet_scanQRCode\",\n \"wallet_sendCalls\",\n \"wallet_getCapabilities\",\n \"wallet_getCallsStatus\",\n \"wallet_showCallsStatus\",\n];\nexport const REQUIRED_EVENTS = [\"chainChanged\", \"accountsChanged\"];\nexport const OPTIONAL_EVENTS = [\n \"chainChanged\",\n \"accountsChanged\",\n \"message\",\n \"disconnect\",\n \"connect\",\n];\n","import { EventEmitter } from \"events\";\nimport { getAccountsFromNamespaces, getSdkError, isValidArray } from \"@walletconnect/utils\";\nimport { KeyValueStorageOptions } from \"@walletconnect/keyvaluestorage\";\nimport {\n IEthereumProvider as IProvider,\n IEthereumProviderEvents,\n ProviderAccounts,\n RequestArguments,\n QrModalOptions,\n} from \"./types\";\nimport {\n Metadata,\n Namespace,\n UniversalProvider,\n UniversalProviderOpts,\n} from \"@walletconnect/universal-provider\";\nimport { AuthTypes, SessionTypes, SignClientTypes } from \"@walletconnect/types\";\nimport { JsonRpcResult } from \"@walletconnect/jsonrpc-types\";\nimport {\n STORAGE_KEY,\n REQUIRED_METHODS,\n REQUIRED_EVENTS,\n RPC_URL,\n OPTIONAL_METHODS,\n OPTIONAL_EVENTS,\n} from \"./constants\";\n\nexport type RpcMethod =\n | \"personal_sign\"\n | \"eth_sendTransaction\"\n | \"eth_accounts\"\n | \"eth_requestAccounts\"\n | \"eth_call\"\n | \"eth_getBalance\"\n | \"eth_sendRawTransaction\"\n | \"eth_sign\"\n | \"eth_signTransaction\"\n | \"eth_signTypedData\"\n | \"eth_signTypedData_v3\"\n | \"eth_signTypedData_v4\"\n | \"wallet_switchEthereumChain\"\n | \"wallet_addEthereumChain\"\n | \"wallet_getPermissions\"\n | \"wallet_requestPermissions\"\n | \"wallet_registerOnboarding\"\n | \"wallet_watchAsset\"\n | \"wallet_scanQRCode\"\n | \"wallet_sendCalls\"\n | \"wallet_getCapabilities\"\n | \"wallet_getCallsStatus\"\n | \"wallet_showCallsStatus\";\n\nexport type RpcEvent = \"accountsChanged\" | \"chainChanged\" | \"message\" | \"disconnect\" | \"connect\";\n\nexport interface EthereumRpcMap {\n [chainId: string]: string;\n}\n\nexport interface SessionEvent {\n event: { name: string; data: any };\n chainId: string;\n}\n\nexport interface EthereumRpcConfig {\n chains: string[];\n optionalChains: string[];\n methods: string[];\n optionalMethods?: string[];\n /**\n * @description Events that the wallet MUST support or the connection will be rejected\n */\n events: string[];\n optionalEvents?: string[];\n rpcMap: EthereumRpcMap;\n projectId: string;\n metadata?: Metadata;\n showQrModal: boolean;\n qrModalOptions?: QrModalOptions;\n}\nexport interface ConnectOps {\n chains?: number[];\n optionalChains?: number[];\n rpcMap?: EthereumRpcMap;\n pairingTopic?: string;\n}\n\nexport type AuthenticateParams = {\n chains?: number[];\n} & Omit;\n\nexport interface IEthereumProvider extends IProvider {\n connect(opts?: ConnectOps | undefined): Promise;\n}\n\nexport function getRpcUrl(chainId: string, rpc: EthereumRpcConfig): string | undefined {\n let rpcUrl: string | undefined;\n if (rpc.rpcMap) {\n rpcUrl = rpc.rpcMap[getEthereumChainId([chainId])];\n }\n return rpcUrl;\n}\n\nexport function getEthereumChainId(chains: string[]): number {\n return Number(chains[0].split(\":\")[1]);\n}\n\nexport function toHexChainId(chainId: number): string {\n return `0x${chainId.toString(16)}`;\n}\n\nexport type NamespacesParams = {\n chains: EthereumRpcConfig[\"chains\"];\n optionalChains: EthereumRpcConfig[\"optionalChains\"];\n methods?: EthereumRpcConfig[\"methods\"];\n optionalMethods?: EthereumRpcConfig[\"methods\"];\n events?: EthereumRpcConfig[\"events\"];\n rpcMap: EthereumRpcConfig[\"rpcMap\"];\n optionalEvents?: EthereumRpcConfig[\"events\"];\n};\n\nexport function buildNamespaces(params: NamespacesParams): {\n required?: Namespace;\n optional?: Namespace;\n} {\n const { chains, optionalChains, methods, optionalMethods, events, optionalEvents, rpcMap } =\n params;\n if (!isValidArray(chains)) {\n throw new Error(\"Invalid chains\");\n }\n\n const required: Namespace = {\n chains,\n methods: methods || REQUIRED_METHODS,\n events: events || REQUIRED_EVENTS,\n rpcMap: {\n ...(chains.length\n ? { [getEthereumChainId(chains)]: rpcMap[getEthereumChainId(chains)] }\n : {}),\n },\n };\n\n // make a list of events and methods that require additional permissions\n // so we know if we should to include the required chains in the optional namespace\n const eventsRequiringPermissions = events?.filter((event) => !REQUIRED_EVENTS.includes(event));\n const methodsRequiringPermissions = methods?.filter((event) => !REQUIRED_METHODS.includes(event));\n\n if (\n !optionalChains &&\n !optionalEvents &&\n !optionalMethods &&\n !eventsRequiringPermissions?.length &&\n !methodsRequiringPermissions?.length\n ) {\n return { required: chains.length ? required : undefined };\n }\n\n /*\n * decides whether or not to include the required chains in the optional namespace\n * use case: if there is a single chain as required but additional methods/events as optional\n */\n const shouldIncludeRequiredChains =\n (eventsRequiringPermissions?.length && methodsRequiringPermissions?.length) || !optionalChains;\n\n const optional: Namespace = {\n chains: [\n ...new Set(\n shouldIncludeRequiredChains ? required.chains.concat(optionalChains || []) : optionalChains,\n ),\n ],\n methods: [\n ...new Set(\n required.methods.concat(optionalMethods?.length ? optionalMethods : OPTIONAL_METHODS),\n ),\n ],\n events: [\n ...new Set(required.events.concat(optionalEvents?.length ? optionalEvents : OPTIONAL_EVENTS)),\n ],\n rpcMap,\n };\n\n return {\n required: chains.length ? required : undefined,\n optional: optionalChains.length ? optional : undefined,\n };\n}\n\n// helper type to force setting at least one value in an array\ntype ArrayOneOrMore = {\n 0: T;\n} & Array;\n\n/**\n * @param {number[]} chains - The Chains your app intents to use and the peer MUST support. If the peer does not support these chains, the connection will be rejected.\n * @param {number[]} optionalChains - The Chains your app MAY attempt to use and the peer MAY support. If the peer does not support these chains, the connection will still be established.\n * @description either chains or optionalChains must be provided\n */\nexport type ChainsProps =\n | {\n chains: ArrayOneOrMore;\n optionalChains?: number[];\n }\n | {\n chains?: number[];\n optionalChains: ArrayOneOrMore;\n };\n\nexport type EthereumProviderOptions = {\n projectId: string;\n /**\n * @note Methods that your app intents to use and the peer MUST support. If the peer does not support these methods, the connection will be rejected.\n * @default [\"eth_sendTransaction\", \"personal_sign\"]\n */\n methods?: string[];\n /**\n * @note Methods that your app MAY attempt to use and the peer MAY support. If the peer does not support these methods, the connection will still be established.\n */\n optionalMethods?: string[];\n events?: string[];\n optionalEvents?: string[];\n rpcMap?: EthereumRpcMap;\n metadata?: Metadata;\n showQrModal: boolean;\n qrModalOptions?: QrModalOptions;\n disableProviderPing?: boolean;\n relayUrl?: string;\n storageOptions?: KeyValueStorageOptions;\n} & ChainsProps &\n UniversalProviderOpts;\n\nexport class EthereumProvider implements IEthereumProvider {\n public events = new EventEmitter();\n public namespace = \"eip155\";\n public accounts: string[] = [];\n public signer: InstanceType;\n public chainId = 1;\n public modal?: any;\n\n protected rpc: EthereumRpcConfig;\n protected readonly STORAGE_KEY = STORAGE_KEY;\n\n constructor() {\n // assigned during initialize\n this.signer = {} as InstanceType;\n this.rpc = {} as EthereumRpcConfig;\n }\n\n static async init(opts: EthereumProviderOptions): Promise {\n const provider = new EthereumProvider();\n await provider.initialize(opts);\n return provider;\n }\n\n public async request(args: RequestArguments, expiry?: number): Promise {\n return await this.signer.request(args, this.formatChainId(this.chainId), expiry);\n }\n\n public sendAsync(\n args: RequestArguments,\n callback: (error: Error | null, response: JsonRpcResult) => void,\n expiry?: number,\n ): void {\n this.signer.sendAsync(args, callback, this.formatChainId(this.chainId), expiry);\n }\n\n get connected(): boolean {\n if (!this.signer.client) return false;\n return this.signer.client.core.relayer.connected;\n }\n\n get connecting(): boolean {\n if (!this.signer.client) return false;\n return this.signer.client.core.relayer.connecting;\n }\n\n public async enable(): Promise {\n if (!this.session) await this.connect();\n const accounts = await this.request({ method: \"eth_requestAccounts\" });\n return accounts as ProviderAccounts;\n }\n\n public async connect(opts?: ConnectOps): Promise {\n if (!this.signer.client) {\n throw new Error(\"Provider not initialized. Call init() first\");\n }\n\n this.loadConnectOpts(opts);\n const { required, optional } = buildNamespaces(this.rpc);\n try {\n const session = await new Promise(\n async (resolve, reject) => {\n if (this.rpc.showQrModal) {\n this.modal?.subscribeModal((state: { open: boolean }) => {\n // the modal was closed so reject the promise\n if (!state.open && !this.signer.session) {\n this.signer.abortPairingAttempt();\n reject(new Error(\"Connection request reset. Please try again.\"));\n }\n });\n }\n await this.signer\n .connect({\n namespaces: {\n ...(required && {\n [this.namespace]: required,\n }),\n },\n ...(optional && {\n optionalNamespaces: {\n [this.namespace]: optional,\n },\n }),\n pairingTopic: opts?.pairingTopic,\n })\n .then((session?: SessionTypes.Struct) => {\n resolve(session);\n })\n .catch((error: Error) => {\n reject(new Error(error.message));\n });\n },\n );\n if (!session) return;\n\n const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);\n // if no required chains are set, use the approved accounts to fetch chainIds\n this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);\n this.setAccounts(accounts);\n this.events.emit(\"connect\", { chainId: toHexChainId(this.chainId) });\n } catch (error) {\n this.signer.logger.error(error);\n throw error;\n } finally {\n if (this.modal) this.modal.closeModal();\n }\n }\n\n public async authenticate(\n params: AuthenticateParams,\n walletUniversalLink?: string,\n ): Promise {\n if (!this.signer.client) {\n throw new Error(\"Provider not initialized. Call init() first\");\n }\n\n this.loadConnectOpts({\n chains: params?.chains,\n });\n\n try {\n const result = await new Promise(\n async (resolve, reject) => {\n if (this.rpc.showQrModal) {\n this.modal?.subscribeModal((state: { open: boolean }) => {\n // the modal was closed so reject the promise\n if (!state.open && !this.signer.session) {\n this.signer.abortPairingAttempt();\n reject(new Error(\"Connection request reset. Please try again.\"));\n }\n });\n }\n await this.signer\n .authenticate(\n {\n ...params,\n chains: this.rpc.chains,\n },\n walletUniversalLink,\n )\n .then((result: AuthTypes.AuthenticateResponseResult) => {\n resolve(result);\n })\n .catch((error: Error) => {\n reject(new Error(error.message));\n });\n },\n );\n\n const session = result.session;\n if (session) {\n const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);\n // if no required chains are set, use the approved accounts to fetch chainIds as both contain :\n this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);\n this.setAccounts(accounts);\n this.events.emit(\"connect\", { chainId: toHexChainId(this.chainId) });\n }\n return result;\n } catch (error) {\n this.signer.logger.error(error);\n throw error;\n } finally {\n if (this.modal) this.modal.closeModal();\n }\n }\n\n public async disconnect(): Promise {\n if (this.session) {\n await this.signer.disconnect();\n }\n this.reset();\n }\n\n public on: IEthereumProviderEvents[\"on\"] = (event, listener) => {\n this.events.on(event, listener);\n return this;\n };\n\n public once: IEthereumProviderEvents[\"once\"] = (event, listener) => {\n this.events.once(event, listener);\n return this;\n };\n\n public removeListener: IEthereumProviderEvents[\"removeListener\"] = (event, listener) => {\n this.events.removeListener(event, listener);\n return this;\n };\n\n public off: IEthereumProviderEvents[\"off\"] = (event, listener) => {\n this.events.off(event, listener);\n return this;\n };\n\n get isWalletConnect() {\n return true;\n }\n\n get session() {\n return this.signer.session;\n }\n\n // ---------- Protected --------------------------------------------- //\n\n protected registerEventListeners() {\n this.signer.on(\"session_event\", (payload: SignClientTypes.EventArguments[\"session_event\"]) => {\n const { params } = payload;\n const { event } = params;\n if (event.name === \"accountsChanged\") {\n this.accounts = this.parseAccounts(event.data);\n this.events.emit(\"accountsChanged\", this.accounts);\n } else if (event.name === \"chainChanged\") {\n this.setChainId(this.formatChainId(event.data));\n } else {\n this.events.emit(event.name as any, event.data);\n }\n this.events.emit(\"session_event\", payload);\n });\n\n this.signer.on(\"chainChanged\", (chainId: string) => {\n const chain = parseInt(chainId);\n this.chainId = chain;\n this.events.emit(\"chainChanged\", toHexChainId(this.chainId));\n this.persist();\n });\n\n this.signer.on(\n \"session_update\",\n (payload: SignClientTypes.EventArguments[\"session_update\"]) => {\n this.events.emit(\"session_update\", payload);\n },\n );\n\n this.signer.on(\n \"session_delete\",\n (payload: SignClientTypes.EventArguments[\"session_delete\"]) => {\n this.reset();\n this.events.emit(\"session_delete\", payload);\n this.events.emit(\"disconnect\", {\n ...getSdkError(\"USER_DISCONNECTED\"),\n data: payload.topic,\n name: \"USER_DISCONNECTED\",\n });\n },\n );\n\n this.signer.on(\"display_uri\", (uri: string) => {\n if (this.rpc.showQrModal) {\n // to refresh the QR we have to close the modal and open it again\n // until proper API is provided by walletconnect modal\n this.modal?.closeModal();\n this.modal?.openModal({ uri });\n }\n this.events.emit(\"display_uri\", uri);\n });\n }\n\n protected switchEthereumChain(chainId: number): void {\n this.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: chainId.toString(16) }],\n });\n }\n\n protected isCompatibleChainId(chainId: string): boolean {\n return typeof chainId === \"string\" ? chainId.startsWith(`${this.namespace}:`) : false;\n }\n\n protected formatChainId(chainId: number): string {\n return `${this.namespace}:${chainId}`;\n }\n\n protected parseChainId(chainId: string): number {\n return Number(chainId.split(\":\")[1]);\n }\n\n protected setChainIds(chains: string[]) {\n const compatible = chains.filter((x) => this.isCompatibleChainId(x));\n const chainIds = compatible.map((c) => this.parseChainId(c));\n if (chainIds.length) {\n this.chainId = chainIds[0];\n this.events.emit(\"chainChanged\", toHexChainId(this.chainId));\n this.persist();\n }\n }\n\n protected setChainId(chain: string) {\n if (this.isCompatibleChainId(chain)) {\n const chainId = this.parseChainId(chain);\n this.chainId = chainId;\n this.switchEthereumChain(chainId);\n }\n }\n\n protected parseAccountId(account: string): { chainId: string; address: string } {\n const [namespace, reference, address] = account.split(\":\");\n const chainId = `${namespace}:${reference}`;\n return { chainId, address };\n }\n\n protected setAccounts(accounts: string[]) {\n this.accounts = accounts\n .filter((x) => this.parseChainId(this.parseAccountId(x).chainId) === this.chainId)\n .map((x) => this.parseAccountId(x).address);\n this.events.emit(\"accountsChanged\", this.accounts);\n }\n\n protected getRpcConfig(opts: EthereumProviderOptions): EthereumRpcConfig {\n const requiredChains = opts?.chains ?? [];\n const optionalChains = opts?.optionalChains ?? [];\n const allChains = requiredChains.concat(optionalChains);\n if (!allChains.length)\n throw new Error(\"No chains specified in either `chains` or `optionalChains`\");\n const requiredMethods = requiredChains.length ? opts?.methods || REQUIRED_METHODS : [];\n const requiredEvents = requiredChains.length ? opts?.events || REQUIRED_EVENTS : [];\n const optionalMethods = opts?.optionalMethods || [];\n const optionalEvents = opts?.optionalEvents || [];\n const rpcMap = opts?.rpcMap || this.buildRpcMap(allChains, opts.projectId);\n const qrModalOptions = opts?.qrModalOptions || undefined;\n return {\n chains: requiredChains?.map((chain) => this.formatChainId(chain)),\n optionalChains: optionalChains.map((chain) => this.formatChainId(chain)),\n methods: requiredMethods,\n events: requiredEvents,\n optionalMethods,\n optionalEvents,\n rpcMap,\n showQrModal: Boolean(opts?.showQrModal),\n qrModalOptions,\n projectId: opts.projectId,\n metadata: opts.metadata,\n };\n }\n\n protected buildRpcMap(chains: number[], projectId: string): EthereumRpcMap {\n const map: EthereumRpcMap = {};\n chains.forEach((chain) => {\n map[chain] = this.getRpcUrl(chain, projectId);\n });\n return map;\n }\n\n protected async initialize(opts: EthereumProviderOptions) {\n this.rpc = this.getRpcConfig(opts);\n\n this.chainId = this.rpc.chains.length\n ? getEthereumChainId(this.rpc.chains)\n : getEthereumChainId(this.rpc.optionalChains);\n this.signer = await UniversalProvider.init({\n projectId: this.rpc.projectId,\n metadata: this.rpc.metadata,\n disableProviderPing: opts.disableProviderPing,\n relayUrl: opts.relayUrl,\n storageOptions: opts.storageOptions,\n customStoragePrefix: opts.customStoragePrefix,\n telemetryEnabled: opts.telemetryEnabled,\n });\n this.registerEventListeners();\n await this.loadPersistedSession();\n if (this.rpc.showQrModal) {\n let WalletConnectModalClass;\n try {\n const { WalletConnectModal } = await import(\"@walletconnect/modal\");\n WalletConnectModalClass = WalletConnectModal;\n } catch {\n throw new Error(\"To use QR modal, please install @walletconnect/modal package\");\n }\n if (WalletConnectModalClass) {\n try {\n this.modal = new WalletConnectModalClass({\n projectId: this.rpc.projectId,\n ...this.rpc.qrModalOptions,\n });\n } catch (e) {\n this.signer.logger.error(e);\n throw new Error(\"Could not generate WalletConnectModal Instance\");\n }\n }\n }\n }\n\n protected loadConnectOpts(opts?: ConnectOps) {\n if (!opts) return;\n const { chains, optionalChains, rpcMap } = opts;\n if (chains && isValidArray(chains)) {\n this.rpc.chains = chains.map((chain) => this.formatChainId(chain));\n chains.forEach((chain) => {\n this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);\n });\n }\n if (optionalChains && isValidArray(optionalChains)) {\n this.rpc.optionalChains = [];\n this.rpc.optionalChains = optionalChains?.map((chain) => this.formatChainId(chain));\n optionalChains.forEach((chain) => {\n this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);\n });\n }\n }\n\n protected getRpcUrl(chainId: number, projectId?: string): string {\n const providedRpc = this.rpc.rpcMap?.[chainId];\n return (\n providedRpc ||\n `${RPC_URL}?chainId=eip155:${chainId}&projectId=${projectId || this.rpc.projectId}`\n );\n }\n\n protected async loadPersistedSession() {\n if (!this.session) return;\n try {\n const chainId = await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);\n\n // cater to both inline & nested namespace formats\n const namespace = this.session.namespaces[`${this.namespace}:${chainId}`]\n ? this.session.namespaces[`${this.namespace}:${chainId}`]\n : this.session.namespaces[this.namespace];\n\n this.setChainIds(chainId ? [this.formatChainId(chainId)] : namespace?.accounts);\n this.setAccounts(namespace?.accounts);\n } catch (error) {\n this.signer.logger.error(\"Failed to load persisted session, clearing state...\");\n this.signer.logger.error(error);\n await this.disconnect().catch((error) => this.signer.logger.warn(error));\n }\n }\n\n protected reset() {\n this.chainId = 1;\n this.accounts = [];\n }\n\n protected persist() {\n if (!this.session) return;\n this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`, this.chainId);\n }\n\n protected parseAccounts(payload: string | string[]): string[] {\n if (typeof payload === \"string\" || payload instanceof String) {\n return [this.parseAccount(payload)];\n }\n return payload.map((account: string) => this.parseAccount(account));\n }\n\n protected parseAccount = (payload: any): string => {\n return this.isCompatibleChainId(payload) ? this.parseAccountId(payload).address : payload;\n };\n}\n\nexport default EthereumProvider;\n","import { EthereumProvider as Provider } from \"./EthereumProvider\";\nexport const EthereumProvider = Provider;\nexport type { EthereumProviderOptions, RpcEvent, RpcMethod } from \"./EthereumProvider\";\nexport * from \"./constants/rpc\";\nexport default Provider;\n"],"names":["chains","chainId","params","optionalChains","methods","optionalMethods","events","optionalEvents","rpcMap","isValidArray","required","REQUIRED_METHODS","REQUIRED_EVENTS","__spreadValues","eventsRequiringPermissions","event","methodsRequiringPermissions","shouldIncludeRequiredChains","optional","OPTIONAL_METHODS","OPTIONAL_EVENTS","EthereumProvider","EventEmitter","STORAGE_KEY","listener","payload","opts","provider","args","expiry","callback","session","resolve","reject","_a","state","__spreadProps","error","accounts","getAccountsFromNamespaces","walletUniversalLink","result","chain","getSdkError","uri","_b","chainIds","x","c","account","namespace","reference","address","requiredChains","allChains","requiredMethods","requiredEvents","qrModalOptions","projectId","map","UniversalProvider","WalletConnectModalClass","WalletConnectModal","e","RPC_URL","Provider"],"mappings":";;;;AAAa,MAAA,QAAA,CAAW,IACX,CACA,OAAA,CAAU,oBACV,WAAc,CAAA,CAAA,EAAG,QAA0B,CAAA,GAAA,EAAA,OAAA,CAAA,CAAA,CAAA,CAC3C,OAAU,CAAA;;ACJhB,MAAM,iBAAmB,CAAC,qBAAA,CAAuB,eAAe,CAC1D,CAAA,gBAAA,CAAmB,CAC9B,cACA,CAAA,qBAAA,CACA,wBACA,CAAA,UAAA,CACA,sBACA,mBACA,CAAA,sBAAA,CACA,uBACA,qBACA,CAAA,eAAA,CACA,6BACA,yBACA,CAAA,uBAAA,CACA,2BACA,CAAA,2BAAA,CACA,oBACA,mBACA,CAAA,kBAAA,CACA,yBACA,uBACA,CAAA,wBACF,EACa,eAAkB,CAAA,CAAC,cAAgB,CAAA,iBAAiB,EACpD,eAAkB,CAAA,CAC7B,eACA,iBACA,CAAA,SAAA,CACA,aACA,SACF;;6aCuEO,SAAS,kBAAmBA,CAAAA,CAAAA,CAA0B,CAC3D,OAAO,MAAA,CAAOA,EAAO,CAAC,CAAA,CAAE,MAAM,GAAG,CAAA,CAAE,CAAC,CAAC,CACvC,UAEgB,YAAaC,CAAAA,CAAAA,CAAyB,CACpD,OAAO,CAAKA,EAAAA,EAAAA,CAAAA,CAAQ,SAAS,EAAE,CAAA,CAAA,CACjC,CAYO,SAAS,eAAgBC,CAAAA,CAAAA,CAG9B,CACA,KAAM,CAAE,MAAAF,CAAAA,CAAAA,CAAQ,cAAAG,CAAAA,CAAAA,CAAgB,QAAAC,CAAS,CAAA,eAAA,CAAAC,CAAiB,CAAA,MAAA,CAAAC,CAAQ,CAAA,cAAA,CAAAC,EAAgB,MAAAC,CAAAA,CAAO,CACvFN,CAAAA,CAAAA,CACF,GAAI,CAACO,aAAaT,CAAM,CAAA,CACtB,MAAM,IAAI,KAAM,CAAA,gBAAgB,EAGlC,MAAMU,CAAAA,CAAsB,CAC1B,MAAAV,CAAAA,CAAAA,CACA,QAASI,CAAWO,EAAAA,gBAAAA,CACpB,MAAQL,CAAAA,CAAAA,EAAUM,eAClB,CAAA,MAAA,CAAQC,EAAA,EACFb,CAAAA,CAAAA,CAAO,MACP,CAAA,CAAE,CAAC,kBAAA,CAAmBA,CAAM,CAAC,EAAGQ,CAAO,CAAA,kBAAA,CAAmBR,CAAM,CAAC,CAAE,CACnE,CAAA,EAER,CAAA,CAAA,CAIMc,CAA6BR,CAAAA,CAAAA,EAAA,YAAAA,CAAQ,CAAA,MAAA,CAAQS,CAAU,EAAA,CAACH,eAAgB,CAAA,QAAA,CAASG,CAAK,CACtFC,CAAAA,CAAAA,CAAAA,CAA8BZ,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAS,CAAA,MAAA,CAAQW,GAAU,CAACJ,gBAAAA,CAAiB,QAASI,CAAAA,CAAK,CAE/F,CAAA,CAAA,GACE,CAACZ,CACD,EAAA,CAACI,GACD,CAACF,CAAAA,EACD,EAACS,CAAA,EAAA,IAAA,EAAAA,CAA4B,CAAA,MAAA,CAAA,EAC7B,EAACE,CAAAA,EAAA,MAAAA,CAA6B,CAAA,MAAA,CAAA,CAE9B,OAAO,CAAE,QAAUhB,CAAAA,CAAAA,CAAO,OAASU,CAAW,CAAA,KAAA,CAAU,CAO1D,CAAA,MAAMO,CACHH,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAA4B,CAAA,MAAA,IAAUE,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAA6B,CAAA,MAAA,CAAA,EAAW,CAACb,CAE5Ee,CAAAA,CAAAA,CAAsB,CAC1B,MAAA,CAAQ,CACN,GAAG,IAAI,GACLD,CAAAA,CAAAA,CAA8BP,CAAS,CAAA,MAAA,CAAO,MAAOP,CAAAA,CAAAA,EAAkB,EAAE,CAAA,CAAIA,CAC/E,CACF,CACA,CAAA,OAAA,CAAS,CACP,GAAG,IAAI,IACLO,CAAS,CAAA,OAAA,CAAQ,OAAOL,CAAA,EAAA,IAAA,EAAAA,CAAiB,CAAA,MAAA,CAASA,CAAkBc,CAAAA,gBAAgB,CACtF,CACF,CAAA,CACA,MAAQ,CAAA,CACN,GAAG,IAAI,IAAIT,CAAS,CAAA,MAAA,CAAO,MAAOH,CAAAA,CAAAA,EAAA,IAAAA,EAAAA,CAAAA,CAAgB,OAASA,CAAiBa,CAAAA,eAAe,CAAC,CAC9F,CACA,CAAA,MAAA,CAAAZ,CACF,CAEA,CAAA,OAAO,CACL,QAAA,CAAUR,CAAO,CAAA,MAAA,CAASU,EAAW,KACrC,CAAA,CAAA,QAAA,CAAUP,CAAe,CAAA,MAAA,CAASe,CAAW,CAAA,KAAA,CAC/C,CACF,CA6CO,MAAMG,kBAA8C,CAWzD,WAAc,EAAA,CAVd,KAAO,MAAS,CAAA,IAAIC,aACpB,IAAO,CAAA,SAAA,CAAY,SACnB,IAAO,CAAA,QAAA,CAAqB,EAAC,CAE7B,IAAO,CAAA,OAAA,CAAU,EAIjB,IAAmB,CAAA,WAAA,CAAcC,WAmKjC,CAAA,IAAA,CAAO,EAAoC,CAAA,CAACR,EAAOS,CACjD,IAAA,IAAA,CAAK,MAAO,CAAA,EAAA,CAAGT,CAAOS,CAAAA,CAAQ,EACvB,IAGT,CAAA,CAAA,IAAA,CAAO,IAAwC,CAAA,CAACT,CAAOS,CAAAA,CAAAA,IACrD,KAAK,MAAO,CAAA,IAAA,CAAKT,CAAOS,CAAAA,CAAQ,CACzB,CAAA,IAAA,CAAA,CAGT,KAAO,cAA4D,CAAA,CAACT,CAAOS,CAAAA,CAAAA,IACzE,IAAK,CAAA,MAAA,CAAO,eAAeT,CAAOS,CAAAA,CAAQ,CACnC,CAAA,IAAA,CAAA,CAGT,IAAO,CAAA,GAAA,CAAsC,CAACT,CAAOS,CAAAA,CAAAA,IACnD,KAAK,MAAO,CAAA,GAAA,CAAIT,EAAOS,CAAQ,CAAA,CACxB,IA4PT,CAAA,CAAA,IAAA,CAAU,YAAgBC,CAAAA,CAAAA,EACjB,KAAK,mBAAoBA,CAAAA,CAAO,CAAI,CAAA,IAAA,CAAK,cAAeA,CAAAA,CAAO,EAAE,OAAUA,CAAAA,CAAAA,CA7alF,IAAK,CAAA,MAAA,CAAS,EAAC,CACf,KAAK,GAAM,CAAA,GACb,CAEA,aAAa,IAAA,CAAKC,EAA0D,CAC1E,MAAMC,CAAW,CAAA,IAAIN,kBACrB,CAAA,OAAA,MAAMM,EAAS,UAAWD,CAAAA,CAAI,CACvBC,CAAAA,CACT,CAEA,MAAa,QAAqBC,CAAwBC,CAAAA,CAAAA,CAA6B,CACrF,OAAO,MAAM,IAAA,CAAK,OAAO,OAAQD,CAAAA,CAAAA,CAAM,KAAK,aAAc,CAAA,IAAA,CAAK,OAAO,CAAGC,CAAAA,CAAM,CACjF,CAEO,SACLD,CAAAA,CAAAA,CACAE,EACAD,CACM,CAAA,CACN,IAAK,CAAA,MAAA,CAAO,SAAUD,CAAAA,CAAAA,CAAME,EAAU,IAAK,CAAA,aAAA,CAAc,IAAK,CAAA,OAAO,CAAGD,CAAAA,CAAM,EAChF,CAEA,IAAI,SAAqB,EAAA,CACvB,OAAK,IAAA,CAAK,OAAO,MACV,CAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,UADP,CAElC,CAAA,CAEA,IAAI,UAAA,EAAsB,CACxB,OAAK,KAAK,MAAO,CAAA,MAAA,CACV,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,IAAA,CAAK,QAAQ,UADP,CAAA,CAAA,CAElC,CAEA,MAAa,MAAA,EAAoC,CAC/C,OAAK,IAAA,CAAK,OAAS,EAAA,MAAM,IAAK,CAAA,OAAA,GACb,MAAM,IAAA,CAAK,OAAQ,CAAA,CAAE,MAAQ,CAAA,qBAAsB,CAAC,CAEvE,CAEA,MAAa,OAAA,CAAQH,CAAkC,CAAA,CACrD,GAAI,CAAC,IAAA,CAAK,MAAO,CAAA,MAAA,CACf,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAG/D,IAAK,CAAA,eAAA,CAAgBA,CAAI,CAAA,CACzB,KAAM,CAAE,QAAA,CAAAhB,CAAU,CAAA,QAAA,CAAAQ,CAAS,CAAA,CAAI,gBAAgB,IAAK,CAAA,GAAG,CACvD,CAAA,GAAI,CACF,MAAMa,EAAU,MAAM,IAAI,QACxB,MAAOC,CAAAA,CAASC,IAAW,CAjSnC,IAAAC,CAkSc,CAAA,IAAA,CAAK,GAAI,CAAA,WAAA,GAAA,CACXA,EAAA,IAAK,CAAA,KAAA,GAAL,IAAAA,EAAAA,CAAAA,CAAY,cAAgBC,CAAAA,CAAAA,EAA6B,CAEnD,CAACA,CAAAA,CAAM,IAAQ,EAAA,CAAC,IAAK,CAAA,MAAA,CAAO,UAC9B,IAAK,CAAA,MAAA,CAAO,mBAAoB,EAAA,CAChCF,CAAO,CAAA,IAAI,MAAM,6CAA6C,CAAC,CAEnE,EAAA,CAAA,CAAA,CAAA,CAEF,MAAM,IAAA,CAAK,OACR,OAAQG,CAAAA,CAAAA,CAAAvB,CAAA,CAAA,CACP,UAAYA,CAAAA,CAAAA,CAAA,GACNH,CAAY,EAAA,CACd,CAAC,IAAA,CAAK,SAAS,EAAGA,CACpB,CAEEQ,CAAAA,CAAAA,CAAAA,CAAAA,EAAY,CACd,kBAAoB,CAAA,CAClB,CAAC,IAAK,CAAA,SAAS,EAAGA,CACpB,CACF,CAAA,CAAA,CAVO,CAWP,YAAcQ,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,YACtB,CAAA,CAAC,EACA,IAAMK,CAAAA,CAAAA,EAAkC,CACvCC,CAAAA,CAAQD,CAAO,EACjB,CAAC,CACA,CAAA,KAAA,CAAOM,CAAiB,EAAA,CACvBJ,CAAO,CAAA,IAAI,MAAMI,CAAM,CAAA,OAAO,CAAC,EACjC,CAAC,EACL,CACF,CACA,CAAA,GAAI,CAACN,CAAAA,CAAS,OAEd,MAAMO,EAAWC,yBAA0BR,CAAAA,CAAAA,CAAQ,UAAY,CAAA,CAAC,IAAK,CAAA,SAAS,CAAC,CAE/E,CAAA,IAAA,CAAK,YAAY,IAAK,CAAA,GAAA,CAAI,OAAO,MAAS,CAAA,IAAA,CAAK,GAAI,CAAA,MAAA,CAASO,CAAQ,CAAA,CACpE,KAAK,WAAYA,CAAAA,CAAQ,CACzB,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,UAAW,CAAE,OAAA,CAAS,YAAa,CAAA,IAAA,CAAK,OAAO,CAAE,CAAC,EACrE,CAAA,MAASD,CAAP,CAAA,CACA,MAAK,IAAA,CAAA,MAAA,CAAO,OAAO,KAAMA,CAAAA,CAAK,CACxBA,CAAAA,CACR,CAAE,OAAA,CACI,KAAK,KAAO,EAAA,IAAA,CAAK,KAAM,CAAA,UAAA,GAC7B,CACF,CAEA,MAAa,YAAA,CACXnC,CACAsC,CAAAA,CAAAA,CAC2D,CAC3D,GAAI,CAAC,IAAK,CAAA,MAAA,CAAO,OACf,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAG/D,IAAK,CAAA,eAAA,CAAgB,CACnB,MAAA,CAAQtC,GAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAQ,MAClB,CAAC,CAED,CAAA,GAAI,CACF,MAAMuC,CAAAA,CAAS,MAAM,IAAI,OACvB,CAAA,MAAOT,EAASC,CAAW,GAAA,CA9VnC,IAAAC,CAAAA,CA+Vc,IAAK,CAAA,GAAA,CAAI,eACXA,CAAA,CAAA,IAAA,CAAK,KAAL,GAAA,IAAA,EAAAA,CAAY,CAAA,cAAA,CAAgBC,GAA6B,CAEnD,CAACA,CAAM,CAAA,IAAA,EAAQ,CAAC,IAAA,CAAK,OAAO,OAC9B,GAAA,IAAA,CAAK,MAAO,CAAA,mBAAA,EACZF,CAAAA,CAAAA,CAAO,IAAI,KAAM,CAAA,6CAA6C,CAAC,CAEnE,EAAA,CAAA,CAAA,CAAA,CAEF,MAAM,IAAK,CAAA,MAAA,CACR,YACCG,CAAAA,CAAAA,CAAAvB,CAAA,CAAA,EAAA,CACKX,GADL,CAEE,MAAA,CAAQ,IAAK,CAAA,GAAA,CAAI,MACnB,CAAA,CAAA,CACAsC,CACF,CACC,CAAA,IAAA,CAAMC,CAAiD,EAAA,CACtDT,CAAQS,CAAAA,CAAM,EAChB,CAAC,CAAA,CACA,KAAOJ,CAAAA,CAAAA,EAAiB,CACvBJ,CAAAA,CAAO,IAAI,KAAMI,CAAAA,CAAAA,CAAM,OAAO,CAAC,EACjC,CAAC,EACL,CACF,CAAA,CAEMN,CAAUU,CAAAA,CAAAA,CAAO,OACvB,CAAA,GAAIV,EAAS,CACX,MAAMO,CAAWC,CAAAA,yBAAAA,CAA0BR,CAAQ,CAAA,UAAA,CAAY,CAAC,IAAK,CAAA,SAAS,CAAC,CAE/E,CAAA,IAAA,CAAK,YAAY,IAAK,CAAA,GAAA,CAAI,MAAO,CAAA,MAAA,CAAS,IAAK,CAAA,GAAA,CAAI,OAASO,CAAQ,CAAA,CACpE,IAAK,CAAA,WAAA,CAAYA,CAAQ,CAAA,CACzB,KAAK,MAAO,CAAA,IAAA,CAAK,SAAW,CAAA,CAAE,OAAS,CAAA,YAAA,CAAa,KAAK,OAAO,CAAE,CAAC,EAAA,CAErE,OAAOG,CACT,OAASJ,CAAP,CAAA,CACA,MAAK,IAAA,CAAA,MAAA,CAAO,MAAO,CAAA,KAAA,CAAMA,CAAK,CACxBA,CAAAA,CACR,CAAE,OAAA,CACI,IAAK,CAAA,KAAA,EAAO,KAAK,KAAM,CAAA,UAAA,GAC7B,CACF,CAEA,MAAa,YAA4B,CACnC,IAAA,CAAK,OACP,EAAA,MAAM,IAAK,CAAA,MAAA,CAAO,YAEpB,CAAA,IAAA,CAAK,KAAM,GACb,CAsBA,IAAI,iBAAkB,CACpB,OAAO,CACT,CAAA,CAEA,IAAI,OAAA,EAAU,CACZ,OAAO,IAAA,CAAK,MAAO,CAAA,OACrB,CAIU,sBAAA,EAAyB,CACjC,IAAK,CAAA,MAAA,CAAO,EAAG,CAAA,eAAA,CAAkBZ,CAA6D,EAAA,CAC5F,KAAM,CAAE,MAAA,CAAAvB,CAAO,CAAA,CAAIuB,CACb,CAAA,CAAE,MAAAV,CAAM,CAAA,CAAIb,CACda,CAAAA,CAAAA,CAAM,IAAS,GAAA,iBAAA,EACjB,KAAK,QAAW,CAAA,IAAA,CAAK,aAAcA,CAAAA,CAAAA,CAAM,IAAI,CAAA,CAC7C,KAAK,MAAO,CAAA,IAAA,CAAK,kBAAmB,IAAK,CAAA,QAAQ,GACxCA,CAAM,CAAA,IAAA,GAAS,cACxB,CAAA,IAAA,CAAK,UAAW,CAAA,IAAA,CAAK,cAAcA,CAAM,CAAA,IAAI,CAAC,CAAA,CAE9C,IAAK,CAAA,MAAA,CAAO,KAAKA,CAAM,CAAA,IAAA,CAAaA,CAAM,CAAA,IAAI,CAEhD,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,eAAA,CAAiBU,CAAO,EAC3C,CAAC,CAAA,CAED,KAAK,MAAO,CAAA,EAAA,CAAG,cAAiBxB,CAAAA,CAAAA,EAAoB,CAClD,MAAMyC,EAAQ,QAASzC,CAAAA,CAAO,CAC9B,CAAA,IAAA,CAAK,OAAUyC,CAAAA,CAAAA,CACf,KAAK,MAAO,CAAA,IAAA,CAAK,cAAgB,CAAA,YAAA,CAAa,IAAK,CAAA,OAAO,CAAC,CAC3D,CAAA,IAAA,CAAK,UACP,CAAC,EAED,IAAK,CAAA,MAAA,CAAO,EACV,CAAA,gBAAA,CACCjB,CAA8D,EAAA,CAC7D,KAAK,MAAO,CAAA,IAAA,CAAK,gBAAkBA,CAAAA,CAAO,EAC5C,CACF,EAEA,IAAK,CAAA,MAAA,CAAO,EACV,CAAA,gBAAA,CACCA,CAA8D,EAAA,CAC7D,KAAK,KAAM,EAAA,CACX,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,gBAAA,CAAkBA,CAAO,CAC1C,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,YAAcW,CAAAA,CAAAA,CAAAvB,EAAA,EAC1B8B,CAAAA,WAAAA,CAAY,mBAAmB,CAAA,CAAA,CADL,CAE7B,IAAA,CAAMlB,EAAQ,KACd,CAAA,IAAA,CAAM,mBACR,CAAA,CAAC,EACH,CACF,EAEA,IAAK,CAAA,MAAA,CAAO,GAAG,aAAgBmB,CAAAA,CAAAA,EAAgB,CAzdnD,IAAAV,CAAAA,CAAAW,CA0dU,CAAA,IAAA,CAAK,GAAI,CAAA,WAAA,GAAA,CAGXX,EAAA,IAAK,CAAA,KAAA,GAAL,IAAAA,EAAAA,CAAAA,CAAY,UACZW,EAAAA,CAAAA,CAAAA,CAAAA,CAAA,KAAK,KAAL,GAAA,IAAA,EAAAA,CAAY,CAAA,SAAA,CAAU,CAAE,GAAA,CAAAD,CAAI,CAE9B,CAAA,CAAA,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,aAAeA,CAAAA,CAAG,EACrC,CAAC,EACH,CAEU,mBAAA,CAAoB3C,CAAuB,CAAA,CACnD,KAAK,OAAQ,CAAA,CACX,MAAQ,CAAA,4BAAA,CACR,MAAQ,CAAA,CAAC,CAAE,OAASA,CAAAA,CAAAA,CAAQ,QAAS,CAAA,EAAE,CAAE,CAAC,CAC5C,CAAC,EACH,CAEU,mBAAoBA,CAAAA,CAAAA,CAA0B,CACtD,OAAO,OAAOA,CAAY,EAAA,QAAA,CAAWA,CAAQ,CAAA,UAAA,CAAW,GAAG,IAAK,CAAA,SAAA,CAAA,CAAA,CAAY,CAAI,CAAA,CAAA,CAClF,CAEU,aAAA,CAAcA,EAAyB,CAC/C,OAAO,CAAG,EAAA,IAAA,CAAK,SAAaA,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,CAC9B,CAEU,YAAaA,CAAAA,CAAAA,CAAyB,CAC9C,OAAO,MAAOA,CAAAA,CAAAA,CAAQ,MAAM,GAAG,CAAA,CAAE,CAAC,CAAC,CACrC,CAEU,YAAYD,CAAkB,CAAA,CAEtC,MAAM8C,CAAAA,CADa9C,CAAO,CAAA,MAAA,CAAQ+C,GAAM,IAAK,CAAA,mBAAA,CAAoBA,CAAC,CAAC,CACvC,CAAA,GAAA,CAAKC,GAAM,IAAK,CAAA,YAAA,CAAaA,CAAC,CAAC,CAAA,CACvDF,EAAS,MACX,GAAA,IAAA,CAAK,OAAUA,CAAAA,CAAAA,CAAS,CAAC,CAAA,CACzB,KAAK,MAAO,CAAA,IAAA,CAAK,cAAgB,CAAA,YAAA,CAAa,IAAK,CAAA,OAAO,CAAC,CAC3D,CAAA,IAAA,CAAK,OAAQ,EAAA,EAEjB,CAEU,UAAA,CAAWJ,EAAe,CAClC,GAAI,IAAK,CAAA,mBAAA,CAAoBA,CAAK,CAAA,CAAG,CACnC,MAAMzC,CAAAA,CAAU,IAAK,CAAA,YAAA,CAAayC,CAAK,CAAA,CACvC,KAAK,OAAUzC,CAAAA,CAAAA,CACf,IAAK,CAAA,mBAAA,CAAoBA,CAAO,EAAA,CAEpC,CAEU,cAAegD,CAAAA,CAAAA,CAAuD,CAC9E,KAAM,CAACC,CAAAA,CAAWC,EAAWC,CAAO,CAAA,CAAIH,EAAQ,KAAM,CAAA,GAAG,EAEzD,OAAO,CAAE,OADO,CAAA,CAAA,EAAGC,CAAaC,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,CAAAA,CACd,QAAAC,CAAQ,CAC5B,CAEU,WAAA,CAAYd,CAAoB,CAAA,CACxC,KAAK,QAAWA,CAAAA,CAAAA,CACb,MAAQS,CAAAA,CAAAA,EAAM,IAAK,CAAA,YAAA,CAAa,KAAK,cAAeA,CAAAA,CAAC,CAAE,CAAA,OAAO,CAAM,GAAA,IAAA,CAAK,OAAO,CAChF,CAAA,GAAA,CAAKA,CAAM,EAAA,IAAA,CAAK,cAAeA,CAAAA,CAAC,EAAE,OAAO,CAAA,CAC5C,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,iBAAA,CAAmB,KAAK,QAAQ,EACnD,CAEU,YAAA,CAAarB,CAAkD,CAAA,CAthB3E,IAAAQ,CAAAW,CAAAA,CAAAA,CAuhBI,MAAMQ,CAAiBnB,CAAAA,CAAAA,CAAAA,CAAAR,GAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,MAAN,GAAA,IAAA,CAAAQ,CAAgB,CAAA,GACjC/B,CAAiB0C,CAAAA,CAAAA,CAAAA,CAAAnB,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,cAAA,GAAN,KAAAmB,CAAwB,CAAA,EACzCS,CAAAA,CAAAA,CAAYD,CAAe,CAAA,MAAA,CAAOlD,CAAc,CACtD,CAAA,GAAI,CAACmD,CAAAA,CAAU,MACb,CAAA,MAAM,IAAI,KAAM,CAAA,4DAA4D,CAC9E,CAAA,MAAMC,CAAkBF,CAAAA,CAAAA,CAAe,QAAS3B,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,OAAA,GAAWf,gBAAmB,CAAA,GAC9E6C,CAAiBH,CAAAA,CAAAA,CAAe,MAAS3B,CAAAA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,SAAUd,eAAkB,CAAA,GAC3EP,CAAkBqB,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAAM,CAAA,eAAA,GAAmB,EAAC,CAC5CnB,CAAiBmB,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAAM,CAAA,cAAA,GAAkB,EAAC,CAC1ClB,CAASkB,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAAM,CAAA,MAAA,GAAU,IAAK,CAAA,WAAA,CAAY4B,CAAW5B,CAAAA,CAAAA,CAAK,SAAS,CACnE+B,CAAAA,CAAAA,CAAAA,CAAiB/B,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,cAAA,GAAkB,OAC/C,OAAO,CACL,MAAQ2B,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAgB,IAAKX,CAAU,EAAA,IAAA,CAAK,aAAcA,CAAAA,CAAK,CAC/D,CAAA,CAAA,cAAA,CAAgBvC,EAAe,GAAKuC,CAAAA,CAAAA,EAAU,IAAK,CAAA,aAAA,CAAcA,CAAK,CAAC,EACvE,OAASa,CAAAA,CAAAA,CACT,OAAQC,CACR,CAAA,eAAA,CAAAnD,EACA,cAAAE,CAAAA,CAAAA,CACA,MAAAC,CAAAA,CAAAA,CACA,WAAa,CAAA,CAAA,EAAQkB,GAAA,IAAAA,EAAAA,CAAAA,CAAM,WAC3B,CAAA,CAAA,cAAA,CAAA+B,CACA,CAAA,SAAA,CAAW/B,EAAK,SAChB,CAAA,QAAA,CAAUA,CAAK,CAAA,QACjB,CACF,CAEU,YAAY1B,CAAkB0D,CAAAA,CAAAA,CAAmC,CACzE,MAAMC,CAAsB,CAAA,GAC5B,OAAA3D,CAAAA,CAAO,OAAS0C,CAAAA,CAAAA,EAAU,CACxBiB,CAAAA,CAAIjB,CAAK,CAAI,CAAA,IAAA,CAAK,SAAUA,CAAAA,CAAAA,CAAOgB,CAAS,EAC9C,CAAC,CACMC,CAAAA,CACT,CAEA,MAAgB,UAAWjC,CAAAA,CAAAA,CAA+B,CAiBxD,GAhBA,IAAA,CAAK,IAAM,IAAK,CAAA,YAAA,CAAaA,CAAI,CAEjC,CAAA,IAAA,CAAK,OAAU,CAAA,IAAA,CAAK,GAAI,CAAA,MAAA,CAAO,OAC3B,kBAAmB,CAAA,IAAA,CAAK,GAAI,CAAA,MAAM,CAClC,CAAA,kBAAA,CAAmB,KAAK,GAAI,CAAA,cAAc,CAC9C,CAAA,IAAA,CAAK,MAAS,CAAA,MAAMkC,kBAAkB,IAAK,CAAA,CACzC,SAAW,CAAA,IAAA,CAAK,GAAI,CAAA,SAAA,CACpB,SAAU,IAAK,CAAA,GAAA,CAAI,QACnB,CAAA,mBAAA,CAAqBlC,CAAK,CAAA,mBAAA,CAC1B,SAAUA,CAAK,CAAA,QAAA,CACf,cAAgBA,CAAAA,CAAAA,CAAK,cACrB,CAAA,mBAAA,CAAqBA,EAAK,mBAC1B,CAAA,gBAAA,CAAkBA,CAAK,CAAA,gBACzB,CAAC,CAAA,CACD,KAAK,sBAAuB,EAAA,CAC5B,MAAM,IAAK,CAAA,oBAAA,GACP,IAAK,CAAA,GAAA,CAAI,WAAa,CAAA,CACxB,IAAImC,CAAAA,CACJ,GAAI,CACF,KAAM,CAAE,kBAAA,CAAAC,CAAmB,CAAA,CAAI,MAAa,OAAA,sBAAsB,CAClED,CAAAA,CAAAA,CAA0BC,EAC5B,CAAA,MAAQC,EAAN,CACA,MAAM,IAAI,KAAA,CAAM,8DAA8D,CAChF,CACA,GAAIF,CAAAA,CACF,GAAI,CACF,IAAK,CAAA,KAAA,CAAQ,IAAIA,CAAwBhD,CAAAA,CAAAA,CAAA,CACvC,SAAA,CAAW,IAAK,CAAA,GAAA,CAAI,WACjB,IAAK,CAAA,GAAA,CAAI,cACb,CAAA,EACH,CAASkD,MAAAA,CAAAA,CAAP,CACA,MAAK,IAAA,CAAA,MAAA,CAAO,OAAO,KAAMA,CAAAA,CAAC,EACpB,IAAI,KAAA,CAAM,gDAAgD,CAClE,CAGN,CAAA,CAEU,gBAAgBrC,CAAmB,CAAA,CAC3C,GAAI,CAACA,CAAM,CAAA,OACX,KAAM,CAAE,MAAA,CAAA1B,CAAQ,CAAA,cAAA,CAAAG,CAAgB,CAAA,MAAA,CAAAK,CAAO,CAAIkB,CAAAA,CAAAA,CACvC1B,CAAUS,EAAAA,YAAAA,CAAaT,CAAM,CAAA,GAC/B,KAAK,GAAI,CAAA,MAAA,CAASA,CAAO,CAAA,GAAA,CAAK0C,CAAU,EAAA,IAAA,CAAK,cAAcA,CAAK,CAAC,CACjE1C,CAAAA,CAAAA,CAAO,OAAS0C,CAAAA,CAAAA,EAAU,CACxB,IAAK,CAAA,GAAA,CAAI,MAAOA,CAAAA,CAAK,CAAIlC,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAASkC,CAAAA,CAAAA,CAAAA,GAAU,KAAK,SAAUA,CAAAA,CAAK,EAClE,CAAC,CAAA,CAAA,CAECvC,CAAkBM,EAAAA,YAAAA,CAAaN,CAAc,CAAA,GAC/C,KAAK,GAAI,CAAA,cAAA,CAAiB,EAAC,CAC3B,IAAK,CAAA,GAAA,CAAI,eAAiBA,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAgB,CAAA,GAAA,CAAKuC,CAAU,EAAA,IAAA,CAAK,cAAcA,CAAK,CAAA,CAAA,CACjFvC,CAAe,CAAA,OAAA,CAASuC,CAAU,EAAA,CAChC,KAAK,GAAI,CAAA,MAAA,CAAOA,CAAK,CAAA,CAAA,CAAIlC,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,EAASkC,CAAU,CAAA,GAAA,IAAA,CAAK,SAAUA,CAAAA,CAAK,EAClE,CAAC,GAEL,CAEU,SAAA,CAAUzC,CAAiByD,CAAAA,CAAAA,CAA4B,CAlnBnE,IAAAxB,EAonBI,OADoBA,CAAAA,CAAAA,CAAAA,CAAA,KAAK,GAAI,CAAA,MAAA,GAAT,YAAAA,CAAkBjC,CAAAA,CAAAA,CAAAA,GAGpC,CAAG+D,EAAAA,OAAAA,CAAAA,gBAAAA,EAA0B/D,CAAqByD,CAAAA,WAAAA,EAAAA,CAAAA,EAAa,KAAK,GAAI,CAAA,SAAA,CAAA,CAE5E,CAEA,MAAgB,oBAAuB,EAAA,CACrC,GAAK,IAAK,CAAA,OAAA,CACV,GAAI,CACF,MAAMzD,CAAAA,CAAU,MAAM,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,IAAA,CAAK,OAAQ,CAAA,OAAA,CAAQ,GAAG,IAAK,CAAA,WAAA,CAAA,QAAA,CAAqB,CAGrFiD,CAAAA,CAAAA,CAAY,IAAK,CAAA,OAAA,CAAQ,WAAW,CAAG,EAAA,IAAA,CAAK,SAAajD,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,CAAS,CACpE,CAAA,IAAA,CAAK,QAAQ,UAAW,CAAA,CAAA,EAAG,IAAK,CAAA,SAAA,CAAA,CAAA,EAAaA,CAAS,CAAA,CAAA,CAAA,CACtD,KAAK,OAAQ,CAAA,UAAA,CAAW,KAAK,SAAS,CAAA,CAE1C,KAAK,WAAYA,CAAAA,CAAAA,CAAU,CAAC,IAAA,CAAK,aAAcA,CAAAA,CAAO,CAAC,CAAIiD,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAW,QAAQ,CAAA,CAC9E,KAAK,WAAYA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAW,QAAQ,EACtC,OAASb,CAAP,CAAA,CACA,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,KAAA,CAAM,qDAAqD,CAC9E,CAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAMA,CAAAA,CAAK,EAC9B,MAAM,IAAA,CAAK,UAAW,EAAA,CAAE,KAAOA,CAAAA,CAAAA,EAAU,KAAK,MAAO,CAAA,MAAA,CAAO,IAAKA,CAAAA,CAAK,CAAC,EACzE,CACF,CAEU,KAAA,EAAQ,CAChB,IAAA,CAAK,OAAU,CAAA,CAAA,CACf,KAAK,QAAW,CAAA,GAClB,CAEU,OAAU,EAAA,CACb,KAAK,OACV,EAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,QAAQ,CAAG,EAAA,IAAA,CAAK,WAAuB,CAAA,QAAA,CAAA,CAAA,IAAA,CAAK,OAAO,EACrF,CAEU,aAAcZ,CAAAA,CAAAA,CAAsC,CAC5D,OAAI,OAAOA,CAAAA,EAAY,UAAYA,CAAmB,YAAA,MAAA,CAC7C,CAAC,IAAA,CAAK,YAAaA,CAAAA,CAAO,CAAC,CAE7BA,CAAAA,CAAAA,CAAQ,GAAKwB,CAAAA,CAAAA,EAAoB,IAAK,CAAA,YAAA,CAAaA,CAAO,CAAC,CACpE,CAKF;;AChqBO,MAAM,iBAAmBgB;;;;"} +\ No newline at end of file ++{"version":3,"file":"index.es.js","sources":["../src/constants/values.ts","../src/constants/rpc.ts","../src/EthereumProvider.ts","../src/index.ts"],"sourcesContent":["export const PROTOCOL = \"wc\";\nexport const WC_VERSION = 2;\nexport const CONTEXT = \"ethereum_provider\";\nexport const STORAGE_KEY = `${PROTOCOL}@${WC_VERSION}:${CONTEXT}:`;\nexport const RPC_URL = \"https://rpc.walletconnect.org/v1/\";\n","export const REQUIRED_METHODS = [\"eth_sendTransaction\", \"personal_sign\"];\nexport const OPTIONAL_METHODS = [\n \"eth_accounts\",\n \"eth_requestAccounts\",\n \"eth_sendRawTransaction\",\n \"eth_sign\",\n \"eth_signTransaction\",\n \"eth_signTypedData\",\n \"eth_signTypedData_v3\",\n \"eth_signTypedData_v4\",\n \"eth_sendTransaction\",\n \"personal_sign\",\n \"wallet_switchEthereumChain\",\n \"wallet_addEthereumChain\",\n \"wallet_getPermissions\",\n \"wallet_requestPermissions\",\n \"wallet_registerOnboarding\",\n \"wallet_watchAsset\",\n \"wallet_scanQRCode\",\n \"wallet_sendCalls\",\n \"wallet_getCapabilities\",\n \"wallet_getCallsStatus\",\n \"wallet_showCallsStatus\",\n];\nexport const REQUIRED_EVENTS = [\"chainChanged\", \"accountsChanged\"];\nexport const OPTIONAL_EVENTS = [\n \"chainChanged\",\n \"accountsChanged\",\n \"message\",\n \"disconnect\",\n \"connect\",\n];\n","import { EventEmitter } from \"events\";\nimport { getAccountsFromNamespaces, getSdkError, isValidArray } from \"@walletconnect/utils\";\nimport { KeyValueStorageOptions } from \"@walletconnect/keyvaluestorage\";\nimport {\n IEthereumProvider as IProvider,\n IEthereumProviderEvents,\n ProviderAccounts,\n RequestArguments,\n QrModalOptions,\n} from \"./types\";\nimport {\n Metadata,\n Namespace,\n UniversalProvider,\n UniversalProviderOpts,\n} from \"@walletconnect/universal-provider\";\nimport { AuthTypes, SessionTypes, SignClientTypes } from \"@walletconnect/types\";\nimport { JsonRpcResult } from \"@walletconnect/jsonrpc-types\";\nimport {\n STORAGE_KEY,\n REQUIRED_METHODS,\n REQUIRED_EVENTS,\n RPC_URL,\n OPTIONAL_METHODS,\n OPTIONAL_EVENTS,\n} from \"./constants\";\n\nexport type RpcMethod =\n | \"personal_sign\"\n | \"eth_sendTransaction\"\n | \"eth_accounts\"\n | \"eth_requestAccounts\"\n | \"eth_call\"\n | \"eth_getBalance\"\n | \"eth_sendRawTransaction\"\n | \"eth_sign\"\n | \"eth_signTransaction\"\n | \"eth_signTypedData\"\n | \"eth_signTypedData_v3\"\n | \"eth_signTypedData_v4\"\n | \"wallet_switchEthereumChain\"\n | \"wallet_addEthereumChain\"\n | \"wallet_getPermissions\"\n | \"wallet_requestPermissions\"\n | \"wallet_registerOnboarding\"\n | \"wallet_watchAsset\"\n | \"wallet_scanQRCode\"\n | \"wallet_sendCalls\"\n | \"wallet_getCapabilities\"\n | \"wallet_getCallsStatus\"\n | \"wallet_showCallsStatus\";\n\nexport type RpcEvent = \"accountsChanged\" | \"chainChanged\" | \"message\" | \"disconnect\" | \"connect\";\n\nexport interface EthereumRpcMap {\n [chainId: string]: string;\n}\n\nexport interface SessionEvent {\n event: { name: string; data: any };\n chainId: string;\n}\n\nexport interface EthereumRpcConfig {\n chains: string[];\n optionalChains: string[];\n methods: string[];\n optionalMethods?: string[];\n /**\n * @description Events that the wallet MUST support or the connection will be rejected\n */\n events: string[];\n optionalEvents?: string[];\n rpcMap: EthereumRpcMap;\n projectId: string;\n metadata?: Metadata;\n showQrModal: boolean;\n qrModalOptions?: QrModalOptions;\n}\nexport interface ConnectOps {\n chains?: number[];\n optionalChains?: number[];\n rpcMap?: EthereumRpcMap;\n pairingTopic?: string;\n}\n\nexport type AuthenticateParams = {\n chains?: number[];\n} & Omit;\n\nexport interface IEthereumProvider extends IProvider {\n connect(opts?: ConnectOps | undefined): Promise;\n}\n\nexport function getRpcUrl(chainId: string, rpc: EthereumRpcConfig): string | undefined {\n let rpcUrl: string | undefined;\n if (rpc.rpcMap) {\n rpcUrl = rpc.rpcMap[getEthereumChainId([chainId])];\n }\n return rpcUrl;\n}\n\nexport function getEthereumChainId(chains: string[]): number {\n return Number(chains[0].split(\":\")[1]);\n}\n\nexport function toHexChainId(chainId: number): string {\n return `0x${chainId.toString(16)}`;\n}\n\nexport type NamespacesParams = {\n chains: EthereumRpcConfig[\"chains\"];\n optionalChains: EthereumRpcConfig[\"optionalChains\"];\n methods?: EthereumRpcConfig[\"methods\"];\n optionalMethods?: EthereumRpcConfig[\"methods\"];\n events?: EthereumRpcConfig[\"events\"];\n rpcMap: EthereumRpcConfig[\"rpcMap\"];\n optionalEvents?: EthereumRpcConfig[\"events\"];\n};\n\nexport function buildNamespaces(params: NamespacesParams): {\n required?: Namespace;\n optional?: Namespace;\n} {\n const { chains, optionalChains, methods, optionalMethods, events, optionalEvents, rpcMap } =\n params;\n if (!isValidArray(chains)) {\n throw new Error(\"Invalid chains\");\n }\n\n const required: Namespace = {\n chains,\n methods: methods || REQUIRED_METHODS,\n events: events || REQUIRED_EVENTS,\n rpcMap: {\n ...(chains.length\n ? { [getEthereumChainId(chains)]: rpcMap[getEthereumChainId(chains)] }\n : {}),\n },\n };\n\n // make a list of events and methods that require additional permissions\n // so we know if we should to include the required chains in the optional namespace\n const eventsRequiringPermissions = events?.filter((event) => !REQUIRED_EVENTS.includes(event));\n const methodsRequiringPermissions = methods?.filter((event) => !REQUIRED_METHODS.includes(event));\n\n if (\n !optionalChains &&\n !optionalEvents &&\n !optionalMethods &&\n !eventsRequiringPermissions?.length &&\n !methodsRequiringPermissions?.length\n ) {\n return { required: chains.length ? required : undefined };\n }\n\n /*\n * decides whether or not to include the required chains in the optional namespace\n * use case: if there is a single chain as required but additional methods/events as optional\n */\n const shouldIncludeRequiredChains =\n (eventsRequiringPermissions?.length && methodsRequiringPermissions?.length) || !optionalChains;\n\n const optional: Namespace = {\n chains: [\n ...new Set(\n shouldIncludeRequiredChains ? required.chains.concat(optionalChains || []) : optionalChains,\n ),\n ],\n methods: [\n ...new Set(\n required.methods.concat(optionalMethods?.length ? optionalMethods : OPTIONAL_METHODS),\n ),\n ],\n events: [\n ...new Set(required.events.concat(optionalEvents?.length ? optionalEvents : OPTIONAL_EVENTS)),\n ],\n rpcMap,\n };\n\n return {\n required: chains.length ? required : undefined,\n optional: optionalChains.length ? optional : undefined,\n };\n}\n\n// helper type to force setting at least one value in an array\ntype ArrayOneOrMore = {\n 0: T;\n} & Array;\n\n/**\n * @param {number[]} chains - The Chains your app intents to use and the peer MUST support. If the peer does not support these chains, the connection will be rejected.\n * @param {number[]} optionalChains - The Chains your app MAY attempt to use and the peer MAY support. If the peer does not support these chains, the connection will still be established.\n * @description either chains or optionalChains must be provided\n */\nexport type ChainsProps =\n | {\n chains: ArrayOneOrMore;\n optionalChains?: number[];\n }\n | {\n chains?: number[];\n optionalChains: ArrayOneOrMore;\n };\n\nexport type EthereumProviderOptions = {\n projectId: string;\n /**\n * @note Methods that your app intents to use and the peer MUST support. If the peer does not support these methods, the connection will be rejected.\n * @default [\"eth_sendTransaction\", \"personal_sign\"]\n */\n methods?: string[];\n /**\n * @note Methods that your app MAY attempt to use and the peer MAY support. If the peer does not support these methods, the connection will still be established.\n */\n optionalMethods?: string[];\n events?: string[];\n optionalEvents?: string[];\n rpcMap?: EthereumRpcMap;\n metadata?: Metadata;\n showQrModal: boolean;\n qrModalOptions?: QrModalOptions;\n disableProviderPing?: boolean;\n relayUrl?: string;\n storageOptions?: KeyValueStorageOptions;\n} & ChainsProps &\n UniversalProviderOpts;\n\nexport class EthereumProvider implements IEthereumProvider {\n public events = new EventEmitter();\n public namespace = \"eip155\";\n public accounts: string[] = [];\n public signer: InstanceType;\n public chainId = 1;\n public modal?: any;\n\n protected rpc: EthereumRpcConfig;\n protected readonly STORAGE_KEY = STORAGE_KEY;\n\n constructor() {\n // assigned during initialize\n this.signer = {} as InstanceType;\n this.rpc = {} as EthereumRpcConfig;\n }\n\n static async init(opts: EthereumProviderOptions): Promise {\n const provider = new EthereumProvider();\n await provider.initialize(opts);\n return provider;\n }\n\n public async request(args: RequestArguments, expiry?: number): Promise {\n return await this.signer.request(args, this.formatChainId(this.chainId), expiry);\n }\n\n public sendAsync(\n args: RequestArguments,\n callback: (error: Error | null, response: JsonRpcResult) => void,\n expiry?: number,\n ): void {\n this.signer.sendAsync(args, callback, this.formatChainId(this.chainId), expiry);\n }\n\n get connected(): boolean {\n if (!this.signer.client) return false;\n return this.signer.client.core.relayer.connected;\n }\n\n get connecting(): boolean {\n if (!this.signer.client) return false;\n return this.signer.client.core.relayer.connecting;\n }\n\n public async enable(): Promise {\n if (!this.session) await this.connect();\n const accounts = await this.request({ method: \"eth_requestAccounts\" });\n return accounts as ProviderAccounts;\n }\n\n public async connect(opts?: ConnectOps): Promise {\n if (!this.signer.client) {\n throw new Error(\"Provider not initialized. Call init() first\");\n }\n\n this.loadConnectOpts(opts);\n const { required, optional } = buildNamespaces(this.rpc);\n try {\n const session = await new Promise(\n async (resolve, reject) => {\n if (this.rpc.showQrModal) {\n this.modal?.subscribeModal((state: { open: boolean }) => {\n // the modal was closed so reject the promise\n if (!state.open && !this.signer.session) {\n this.signer.abortPairingAttempt();\n reject(new Error(\"Connection request reset. Please try again.\"));\n }\n });\n }\n await this.signer\n .connect({\n namespaces: {\n ...(required && {\n [this.namespace]: required,\n }),\n },\n ...(optional && {\n optionalNamespaces: {\n [this.namespace]: optional,\n },\n }),\n pairingTopic: opts?.pairingTopic,\n })\n .then((session?: SessionTypes.Struct) => {\n resolve(session);\n })\n .catch((error: Error) => {\n reject(new Error(error.message));\n });\n },\n );\n if (!session) return;\n\n const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);\n // if no required chains are set, use the approved accounts to fetch chainIds\n this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);\n this.setAccounts(accounts);\n this.events.emit(\"connect\", { chainId: toHexChainId(this.chainId) });\n } catch (error) {\n this.signer.logger.error(error);\n throw error;\n } finally {\n if (this.modal) this.modal.closeModal();\n }\n }\n\n public async authenticate(\n params: AuthenticateParams,\n walletUniversalLink?: string,\n ): Promise {\n if (!this.signer.client) {\n throw new Error(\"Provider not initialized. Call init() first\");\n }\n\n this.loadConnectOpts({\n chains: params?.chains,\n });\n\n try {\n const result = await new Promise(\n async (resolve, reject) => {\n if (this.rpc.showQrModal) {\n this.modal?.subscribeModal((state: { open: boolean }) => {\n // the modal was closed so reject the promise\n if (!state.open && !this.signer.session) {\n this.signer.abortPairingAttempt();\n reject(new Error(\"Connection request reset. Please try again.\"));\n }\n });\n }\n await this.signer\n .authenticate(\n {\n ...params,\n chains: this.rpc.chains,\n },\n walletUniversalLink,\n )\n .then((result: AuthTypes.AuthenticateResponseResult) => {\n resolve(result);\n })\n .catch((error: Error) => {\n reject(new Error(error.message));\n });\n },\n );\n\n const session = result.session;\n if (session) {\n const accounts = getAccountsFromNamespaces(session.namespaces, [this.namespace]);\n // if no required chains are set, use the approved accounts to fetch chainIds as both contain :\n this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);\n this.setAccounts(accounts);\n this.events.emit(\"connect\", { chainId: toHexChainId(this.chainId) });\n }\n return result;\n } catch (error) {\n this.signer.logger.error(error);\n throw error;\n } finally {\n if (this.modal) this.modal.closeModal();\n }\n }\n\n public async disconnect(): Promise {\n if (this.session) {\n await this.signer.disconnect();\n }\n this.reset();\n }\n\n public on: IEthereumProviderEvents[\"on\"] = (event, listener) => {\n this.events.on(event, listener);\n return this;\n };\n\n public once: IEthereumProviderEvents[\"once\"] = (event, listener) => {\n this.events.once(event, listener);\n return this;\n };\n\n public removeListener: IEthereumProviderEvents[\"removeListener\"] = (event, listener) => {\n this.events.removeListener(event, listener);\n return this;\n };\n\n public off: IEthereumProviderEvents[\"off\"] = (event, listener) => {\n this.events.off(event, listener);\n return this;\n };\n\n get isWalletConnect() {\n return true;\n }\n\n get session() {\n return this.signer.session;\n }\n\n // ---------- Protected --------------------------------------------- //\n\n protected registerEventListeners() {\n this.signer.on(\"session_event\", (payload: SignClientTypes.EventArguments[\"session_event\"]) => {\n const { params } = payload;\n const { event } = params;\n if (event.name === \"accountsChanged\") {\n this.accounts = this.parseAccounts(event.data);\n this.events.emit(\"accountsChanged\", this.accounts);\n } else if (event.name === \"chainChanged\") {\n this.setChainId(this.formatChainId(event.data));\n } else {\n this.events.emit(event.name as any, event.data);\n }\n this.events.emit(\"session_event\", payload);\n });\n\n this.signer.on(\"chainChanged\", (chainId: string) => {\n const chain = parseInt(chainId);\n this.chainId = chain;\n this.events.emit(\"chainChanged\", toHexChainId(this.chainId));\n this.persist();\n });\n\n this.signer.on(\n \"session_update\",\n (payload: SignClientTypes.EventArguments[\"session_update\"]) => {\n this.events.emit(\"session_update\", payload);\n },\n );\n\n this.signer.on(\n \"session_delete\",\n (payload: SignClientTypes.EventArguments[\"session_delete\"]) => {\n this.reset();\n this.events.emit(\"session_delete\", payload);\n this.events.emit(\"disconnect\", {\n ...getSdkError(\"USER_DISCONNECTED\"),\n data: payload.topic,\n name: \"USER_DISCONNECTED\",\n });\n },\n );\n\n this.signer.on(\"display_uri\", (uri: string) => {\n if (this.rpc.showQrModal) {\n // to refresh the QR we have to close the modal and open it again\n // until proper API is provided by walletconnect modal\n this.modal?.closeModal();\n this.modal?.openModal({ uri });\n }\n this.events.emit(\"display_uri\", uri);\n });\n }\n\n protected switchEthereumChain(chainId: number): void {\n this.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: chainId.toString(16) }],\n });\n }\n\n protected isCompatibleChainId(chainId: string): boolean {\n return typeof chainId === \"string\" ? chainId.startsWith(`${this.namespace}:`) : false;\n }\n\n protected formatChainId(chainId: number): string {\n return `${this.namespace}:${chainId}`;\n }\n\n protected parseChainId(chainId: string): number {\n return Number(chainId.split(\":\")[1]);\n }\n\n protected setChainIds(chains: string[]) {\n const compatible = chains.filter((x) => this.isCompatibleChainId(x));\n const chainIds = compatible.map((c) => this.parseChainId(c));\n if (chainIds.length) {\n this.chainId = chainIds[0];\n this.events.emit(\"chainChanged\", toHexChainId(this.chainId));\n this.persist();\n }\n }\n\n protected setChainId(chain: string) {\n if (this.isCompatibleChainId(chain)) {\n const chainId = this.parseChainId(chain);\n this.chainId = chainId;\n this.switchEthereumChain(chainId);\n }\n }\n\n protected parseAccountId(account: string): { chainId: string; address: string } {\n const [namespace, reference, address] = account.split(\":\");\n const chainId = `${namespace}:${reference}`;\n return { chainId, address };\n }\n\n protected setAccounts(accounts: string[]) {\n this.accounts = accounts\n .filter((x) => this.parseChainId(this.parseAccountId(x).chainId) === this.chainId)\n .map((x) => this.parseAccountId(x).address);\n this.events.emit(\"accountsChanged\", this.accounts);\n }\n\n protected getRpcConfig(opts: EthereumProviderOptions): EthereumRpcConfig {\n const requiredChains = opts?.chains ?? [];\n const optionalChains = opts?.optionalChains ?? [];\n const allChains = requiredChains.concat(optionalChains);\n if (!allChains.length)\n throw new Error(\"No chains specified in either `chains` or `optionalChains`\");\n const requiredMethods = requiredChains.length ? opts?.methods || REQUIRED_METHODS : [];\n const requiredEvents = requiredChains.length ? opts?.events || REQUIRED_EVENTS : [];\n const optionalMethods = opts?.optionalMethods || [];\n const optionalEvents = opts?.optionalEvents || [];\n const rpcMap = opts?.rpcMap || this.buildRpcMap(allChains, opts.projectId);\n const qrModalOptions = opts?.qrModalOptions || undefined;\n return {\n chains: requiredChains?.map((chain) => this.formatChainId(chain)),\n optionalChains: optionalChains.map((chain) => this.formatChainId(chain)),\n methods: requiredMethods,\n events: requiredEvents,\n optionalMethods,\n optionalEvents,\n rpcMap,\n showQrModal: Boolean(opts?.showQrModal),\n qrModalOptions,\n projectId: opts.projectId,\n metadata: opts.metadata,\n };\n }\n\n protected buildRpcMap(chains: number[], projectId: string): EthereumRpcMap {\n const map: EthereumRpcMap = {};\n chains.forEach((chain) => {\n map[chain] = this.getRpcUrl(chain, projectId);\n });\n return map;\n }\n\n protected async initialize(opts: EthereumProviderOptions) {\n this.rpc = this.getRpcConfig(opts);\n\n this.chainId = this.rpc.chains.length\n ? getEthereumChainId(this.rpc.chains)\n : getEthereumChainId(this.rpc.optionalChains);\n this.signer = await UniversalProvider.init({\n projectId: this.rpc.projectId,\n metadata: this.rpc.metadata,\n disableProviderPing: opts.disableProviderPing,\n relayUrl: opts.relayUrl,\n storageOptions: opts.storageOptions,\n customStoragePrefix: opts.customStoragePrefix,\n telemetryEnabled: opts.telemetryEnabled,\n logger: opts.logger,\n });\n this.registerEventListeners();\n await this.loadPersistedSession();\n if (this.rpc.showQrModal) {\n let WalletConnectModalClass;\n try {\n const { WalletConnectModal } = await import(\"@walletconnect/modal\");\n WalletConnectModalClass = WalletConnectModal;\n } catch {\n throw new Error(\"To use QR modal, please install @walletconnect/modal package\");\n }\n if (WalletConnectModalClass) {\n try {\n this.modal = new WalletConnectModalClass({\n projectId: this.rpc.projectId,\n ...this.rpc.qrModalOptions,\n });\n } catch (e) {\n this.signer.logger.error(e);\n throw new Error(\"Could not generate WalletConnectModal Instance\");\n }\n }\n }\n }\n\n protected loadConnectOpts(opts?: ConnectOps) {\n if (!opts) return;\n const { chains, optionalChains, rpcMap } = opts;\n if (chains && isValidArray(chains)) {\n this.rpc.chains = chains.map((chain) => this.formatChainId(chain));\n chains.forEach((chain) => {\n this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);\n });\n }\n if (optionalChains && isValidArray(optionalChains)) {\n this.rpc.optionalChains = [];\n this.rpc.optionalChains = optionalChains?.map((chain) => this.formatChainId(chain));\n optionalChains.forEach((chain) => {\n this.rpc.rpcMap[chain] = rpcMap?.[chain] || this.getRpcUrl(chain);\n });\n }\n }\n\n protected getRpcUrl(chainId: number, projectId?: string): string {\n const providedRpc = this.rpc.rpcMap?.[chainId];\n return (\n providedRpc ||\n `${RPC_URL}?chainId=eip155:${chainId}&projectId=${projectId || this.rpc.projectId}`\n );\n }\n\n protected async loadPersistedSession() {\n if (!this.session) return;\n try {\n const chainId = await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);\n\n // cater to both inline & nested namespace formats\n const namespace = this.session.namespaces[`${this.namespace}:${chainId}`]\n ? this.session.namespaces[`${this.namespace}:${chainId}`]\n : this.session.namespaces[this.namespace];\n\n this.setChainIds(chainId ? [this.formatChainId(chainId)] : namespace?.accounts);\n this.setAccounts(namespace?.accounts);\n } catch (error) {\n this.signer.logger.error(\"Failed to load persisted session, clearing state...\");\n this.signer.logger.error(error);\n await this.disconnect().catch((error) => this.signer.logger.warn(error));\n }\n }\n\n protected reset() {\n this.chainId = 1;\n this.accounts = [];\n }\n\n protected persist() {\n if (!this.session) return;\n this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`, this.chainId);\n }\n\n protected parseAccounts(payload: string | string[]): string[] {\n if (typeof payload === \"string\" || payload instanceof String) {\n return [this.parseAccount(payload)];\n }\n return payload.map((account: string) => this.parseAccount(account));\n }\n\n protected parseAccount = (payload: any): string => {\n return this.isCompatibleChainId(payload) ? this.parseAccountId(payload).address : payload;\n };\n}\n\nexport default EthereumProvider;\n","import { EthereumProvider as Provider } from \"./EthereumProvider\";\nexport const EthereumProvider = Provider;\nexport type { EthereumProviderOptions, RpcEvent, RpcMethod } from \"./EthereumProvider\";\nexport * from \"./constants/rpc\";\nexport { Provider };\n"],"names":["chains","chainId","params","optionalChains","methods","optionalMethods","events","optionalEvents","rpcMap","isValidArray","required","REQUIRED_METHODS","REQUIRED_EVENTS","__spreadValues","eventsRequiringPermissions","event","methodsRequiringPermissions","shouldIncludeRequiredChains","optional","OPTIONAL_METHODS","OPTIONAL_EVENTS","EthereumProvider","EventEmitter","STORAGE_KEY","listener","payload","opts","provider","args","expiry","callback","session","resolve","reject","_a","state","__spreadProps","error","accounts","getAccountsFromNamespaces","walletUniversalLink","result","chain","getSdkError","uri","_b","chainIds","x","c","account","namespace","reference","address","requiredChains","allChains","requiredMethods","requiredEvents","qrModalOptions","projectId","map","UniversalProvider","WalletConnectModalClass","WalletConnectModal","e","RPC_URL","Provider"],"mappings":";;;;AAAa,MAAA,QAAA,CAAW,IACX,CACA,OAAA,CAAU,oBACV,WAAc,CAAA,CAAA,EAAG,QAA0B,CAAA,GAAA,EAAA,OAAA,CAAA,CAAA,CAAA,CAC3C,OAAU,CAAA;;ACJhB,MAAM,iBAAmB,CAAC,qBAAA,CAAuB,eAAe,CAC1D,CAAA,gBAAA,CAAmB,CAC9B,cACA,CAAA,qBAAA,CACA,wBACA,CAAA,UAAA,CACA,sBACA,mBACA,CAAA,sBAAA,CACA,uBACA,qBACA,CAAA,eAAA,CACA,6BACA,yBACA,CAAA,uBAAA,CACA,2BACA,CAAA,2BAAA,CACA,oBACA,mBACA,CAAA,kBAAA,CACA,yBACA,uBACA,CAAA,wBACF,EACa,eAAkB,CAAA,CAAC,cAAgB,CAAA,iBAAiB,EACpD,eAAkB,CAAA,CAC7B,eACA,iBACA,CAAA,SAAA,CACA,aACA,SACF;;6aCuEO,SAAS,kBAAmBA,CAAAA,CAAAA,CAA0B,CAC3D,OAAO,MAAA,CAAOA,EAAO,CAAC,CAAA,CAAE,MAAM,GAAG,CAAA,CAAE,CAAC,CAAC,CACvC,UAEgB,YAAaC,CAAAA,CAAAA,CAAyB,CACpD,OAAO,CAAKA,EAAAA,EAAAA,CAAAA,CAAQ,SAAS,EAAE,CAAA,CAAA,CACjC,CAYO,SAAS,eAAgBC,CAAAA,CAAAA,CAG9B,CACA,KAAM,CAAE,MAAAF,CAAAA,CAAAA,CAAQ,cAAAG,CAAAA,CAAAA,CAAgB,QAAAC,CAAS,CAAA,eAAA,CAAAC,CAAiB,CAAA,MAAA,CAAAC,CAAQ,CAAA,cAAA,CAAAC,EAAgB,MAAAC,CAAAA,CAAO,CACvFN,CAAAA,CAAAA,CACF,GAAI,CAACO,aAAaT,CAAM,CAAA,CACtB,MAAM,IAAI,KAAM,CAAA,gBAAgB,EAGlC,MAAMU,CAAAA,CAAsB,CAC1B,MAAAV,CAAAA,CAAAA,CACA,QAASI,CAAWO,EAAAA,gBAAAA,CACpB,MAAQL,CAAAA,CAAAA,EAAUM,eAClB,CAAA,MAAA,CAAQC,EAAA,EACFb,CAAAA,CAAAA,CAAO,MACP,CAAA,CAAE,CAAC,kBAAA,CAAmBA,CAAM,CAAC,EAAGQ,CAAO,CAAA,kBAAA,CAAmBR,CAAM,CAAC,CAAE,CACnE,CAAA,EAER,CAAA,CAAA,CAIMc,CAA6BR,CAAAA,CAAAA,EAAA,YAAAA,CAAQ,CAAA,MAAA,CAAQS,CAAU,EAAA,CAACH,eAAgB,CAAA,QAAA,CAASG,CAAK,CACtFC,CAAAA,CAAAA,CAAAA,CAA8BZ,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAS,CAAA,MAAA,CAAQW,GAAU,CAACJ,gBAAAA,CAAiB,QAASI,CAAAA,CAAK,CAE/F,CAAA,CAAA,GACE,CAACZ,CACD,EAAA,CAACI,GACD,CAACF,CAAAA,EACD,EAACS,CAAA,EAAA,IAAA,EAAAA,CAA4B,CAAA,MAAA,CAAA,EAC7B,EAACE,CAAAA,EAAA,MAAAA,CAA6B,CAAA,MAAA,CAAA,CAE9B,OAAO,CAAE,QAAUhB,CAAAA,CAAAA,CAAO,OAASU,CAAW,CAAA,KAAA,CAAU,CAO1D,CAAA,MAAMO,CACHH,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAA4B,CAAA,MAAA,IAAUE,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAA6B,CAAA,MAAA,CAAA,EAAW,CAACb,CAE5Ee,CAAAA,CAAAA,CAAsB,CAC1B,MAAA,CAAQ,CACN,GAAG,IAAI,GACLD,CAAAA,CAAAA,CAA8BP,CAAS,CAAA,MAAA,CAAO,MAAOP,CAAAA,CAAAA,EAAkB,EAAE,CAAA,CAAIA,CAC/E,CACF,CACA,CAAA,OAAA,CAAS,CACP,GAAG,IAAI,IACLO,CAAS,CAAA,OAAA,CAAQ,OAAOL,CAAA,EAAA,IAAA,EAAAA,CAAiB,CAAA,MAAA,CAASA,CAAkBc,CAAAA,gBAAgB,CACtF,CACF,CAAA,CACA,MAAQ,CAAA,CACN,GAAG,IAAI,IAAIT,CAAS,CAAA,MAAA,CAAO,MAAOH,CAAAA,CAAAA,EAAA,IAAAA,EAAAA,CAAAA,CAAgB,OAASA,CAAiBa,CAAAA,eAAe,CAAC,CAC9F,CACA,CAAA,MAAA,CAAAZ,CACF,CAEA,CAAA,OAAO,CACL,QAAA,CAAUR,CAAO,CAAA,MAAA,CAASU,EAAW,KACrC,CAAA,CAAA,QAAA,CAAUP,CAAe,CAAA,MAAA,CAASe,CAAW,CAAA,KAAA,CAC/C,CACF,CA6CO,MAAMG,kBAA8C,CAWzD,WAAc,EAAA,CAVd,KAAO,MAAS,CAAA,IAAIC,aACpB,IAAO,CAAA,SAAA,CAAY,SACnB,IAAO,CAAA,QAAA,CAAqB,EAAC,CAE7B,IAAO,CAAA,OAAA,CAAU,EAIjB,IAAmB,CAAA,WAAA,CAAcC,WAmKjC,CAAA,IAAA,CAAO,EAAoC,CAAA,CAACR,EAAOS,CACjD,IAAA,IAAA,CAAK,MAAO,CAAA,EAAA,CAAGT,CAAOS,CAAAA,CAAQ,EACvB,IAGT,CAAA,CAAA,IAAA,CAAO,IAAwC,CAAA,CAACT,CAAOS,CAAAA,CAAAA,IACrD,KAAK,MAAO,CAAA,IAAA,CAAKT,CAAOS,CAAAA,CAAQ,CACzB,CAAA,IAAA,CAAA,CAGT,KAAO,cAA4D,CAAA,CAACT,CAAOS,CAAAA,CAAAA,IACzE,IAAK,CAAA,MAAA,CAAO,eAAeT,CAAOS,CAAAA,CAAQ,CACnC,CAAA,IAAA,CAAA,CAGT,IAAO,CAAA,GAAA,CAAsC,CAACT,CAAOS,CAAAA,CAAAA,IACnD,KAAK,MAAO,CAAA,GAAA,CAAIT,EAAOS,CAAQ,CAAA,CACxB,IA6PT,CAAA,CAAA,IAAA,CAAU,YAAgBC,CAAAA,CAAAA,EACjB,KAAK,mBAAoBA,CAAAA,CAAO,CAAI,CAAA,IAAA,CAAK,cAAeA,CAAAA,CAAO,EAAE,OAAUA,CAAAA,CAAAA,CA9alF,IAAK,CAAA,MAAA,CAAS,EAAC,CACf,KAAK,GAAM,CAAA,GACb,CAEA,aAAa,IAAA,CAAKC,EAA0D,CAC1E,MAAMC,CAAW,CAAA,IAAIN,kBACrB,CAAA,OAAA,MAAMM,EAAS,UAAWD,CAAAA,CAAI,CACvBC,CAAAA,CACT,CAEA,MAAa,QAAqBC,CAAwBC,CAAAA,CAAAA,CAA6B,CACrF,OAAO,MAAM,IAAA,CAAK,OAAO,OAAQD,CAAAA,CAAAA,CAAM,IAAK,CAAA,aAAA,CAAc,IAAK,CAAA,OAAO,EAAGC,CAAM,CACjF,CAEO,SAAA,CACLD,CACAE,CAAAA,CAAAA,CACAD,EACM,CACN,IAAA,CAAK,MAAO,CAAA,SAAA,CAAUD,CAAME,CAAAA,CAAAA,CAAU,KAAK,aAAc,CAAA,IAAA,CAAK,OAAO,CAAA,CAAGD,CAAM,EAChF,CAEA,IAAI,SAAA,EAAqB,CACvB,OAAK,IAAK,CAAA,MAAA,CAAO,OACV,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,IAAA,CAAK,OAAQ,CAAA,SAAA,CADP,EAElC,CAEA,IAAI,UAAsB,EAAA,CACxB,OAAK,IAAA,CAAK,OAAO,MACV,CAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,WADP,CAElC,CAAA,CAEA,MAAa,MAAoC,EAAA,CAC/C,OAAK,IAAK,CAAA,OAAA,EAAS,MAAM,IAAA,CAAK,OAAQ,EAAA,CACrB,MAAM,IAAK,CAAA,OAAA,CAAQ,CAAE,MAAA,CAAQ,qBAAsB,CAAC,CAEvE,CAEA,MAAa,OAAQH,CAAAA,CAAAA,CAAkC,CACrD,GAAI,CAAC,IAAK,CAAA,MAAA,CAAO,MACf,CAAA,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAG/D,CAAA,IAAA,CAAK,eAAgBA,CAAAA,CAAI,CACzB,CAAA,KAAM,CAAE,QAAAhB,CAAAA,CAAAA,CAAU,QAAAQ,CAAAA,CAAS,CAAI,CAAA,eAAA,CAAgB,KAAK,GAAG,CAAA,CACvD,GAAI,CACF,MAAMa,CAAAA,CAAU,MAAM,IAAI,OAAA,CACxB,MAAOC,CAASC,CAAAA,CAAAA,GAAW,CAjSnC,IAAAC,CAAAA,CAkSc,IAAK,CAAA,GAAA,CAAI,WACXA,GAAAA,CAAAA,CAAAA,CAAA,KAAK,KAAL,GAAA,IAAA,EAAAA,CAAY,CAAA,cAAA,CAAgBC,CAA6B,EAAA,CAEnD,CAACA,CAAM,CAAA,IAAA,EAAQ,CAAC,IAAA,CAAK,MAAO,CAAA,OAAA,GAC9B,KAAK,MAAO,CAAA,mBAAA,EACZF,CAAAA,CAAAA,CAAO,IAAI,KAAA,CAAM,6CAA6C,CAAC,CAAA,EAEnE,CAEF,CAAA,CAAA,CAAA,MAAM,IAAK,CAAA,MAAA,CACR,QAAQG,CAAAvB,CAAAA,CAAAA,CAAA,CACP,UAAA,CAAYA,CAAA,CAAA,EAAA,CACNH,GAAY,CACd,CAAC,IAAK,CAAA,SAAS,EAAGA,CACpB,IAEEQ,CAAY,EAAA,CACd,mBAAoB,CAClB,CAAC,KAAK,SAAS,EAAGA,CACpB,CACF,CAVO,CAAA,CAAA,CAWP,aAAcQ,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,YACtB,CAAC,CAAA,CAAA,CACA,KAAMK,CAAkC,EAAA,CACvCC,CAAQD,CAAAA,CAAO,EACjB,CAAC,EACA,KAAOM,CAAAA,CAAAA,EAAiB,CACvBJ,CAAAA,CAAO,IAAI,KAAA,CAAMI,EAAM,OAAO,CAAC,EACjC,CAAC,EACL,CACF,EACA,GAAI,CAACN,CAAS,CAAA,OAEd,MAAMO,CAAAA,CAAWC,0BAA0BR,CAAQ,CAAA,UAAA,CAAY,CAAC,IAAA,CAAK,SAAS,CAAC,EAE/E,IAAK,CAAA,WAAA,CAAY,KAAK,GAAI,CAAA,MAAA,CAAO,OAAS,IAAK,CAAA,GAAA,CAAI,MAASO,CAAAA,CAAQ,CACpE,CAAA,IAAA,CAAK,YAAYA,CAAQ,CAAA,CACzB,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,SAAA,CAAW,CAAE,OAAS,CAAA,YAAA,CAAa,IAAK,CAAA,OAAO,CAAE,CAAC,EACrE,CAASD,MAAAA,CAAAA,CAAP,CACA,MAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,MAAMA,CAAK,CAAA,CACxBA,CACR,CAAA,OAAE,CACI,IAAA,CAAK,OAAO,IAAK,CAAA,KAAA,CAAM,UAAW,GACxC,CACF,CAEA,MAAa,YACXnC,CAAAA,CAAAA,CACAsC,CAC2D,CAAA,CAC3D,GAAI,CAAC,KAAK,MAAO,CAAA,MAAA,CACf,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAG/D,CAAA,IAAA,CAAK,eAAgB,CAAA,CACnB,MAAQtC,CAAAA,CAAAA,EAAA,YAAAA,CAAQ,CAAA,MAClB,CAAC,CAAA,CAED,GAAI,CACF,MAAMuC,CAAS,CAAA,MAAM,IAAI,OAAA,CACvB,MAAOT,CAAAA,CAASC,IAAW,CA9VnC,IAAAC,CA+Vc,CAAA,IAAA,CAAK,GAAI,CAAA,WAAA,GAAA,CACXA,EAAA,IAAK,CAAA,KAAA,GAAL,IAAAA,EAAAA,CAAAA,CAAY,cAAgBC,CAAAA,CAAAA,EAA6B,CAEnD,CAACA,CAAAA,CAAM,IAAQ,EAAA,CAAC,IAAK,CAAA,MAAA,CAAO,UAC9B,IAAK,CAAA,MAAA,CAAO,mBAAoB,EAAA,CAChCF,CAAO,CAAA,IAAI,MAAM,6CAA6C,CAAC,GAEnE,CAEF,CAAA,CAAA,CAAA,MAAM,KAAK,MACR,CAAA,YAAA,CACCG,CAAAvB,CAAAA,CAAAA,CAAA,EACKX,CAAAA,CAAAA,CAAAA,CADL,CAEE,MAAQ,CAAA,IAAA,CAAK,GAAI,CAAA,MACnB,CACAsC,CAAAA,CAAAA,CACF,EACC,IAAMC,CAAAA,CAAAA,EAAiD,CACtDT,CAAAA,CAAQS,CAAM,EAChB,CAAC,CACA,CAAA,KAAA,CAAOJ,CAAiB,EAAA,CACvBJ,CAAO,CAAA,IAAI,MAAMI,CAAM,CAAA,OAAO,CAAC,EACjC,CAAC,EACL,CACF,CAEMN,CAAAA,CAAAA,CAAUU,CAAO,CAAA,OAAA,CACvB,GAAIV,CAAAA,CAAS,CACX,MAAMO,CAAAA,CAAWC,yBAA0BR,CAAAA,CAAAA,CAAQ,UAAY,CAAA,CAAC,KAAK,SAAS,CAAC,EAE/E,IAAK,CAAA,WAAA,CAAY,KAAK,GAAI,CAAA,MAAA,CAAO,MAAS,CAAA,IAAA,CAAK,GAAI,CAAA,MAAA,CAASO,CAAQ,CACpE,CAAA,IAAA,CAAK,WAAYA,CAAAA,CAAQ,CACzB,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,SAAA,CAAW,CAAE,OAAA,CAAS,YAAa,CAAA,IAAA,CAAK,OAAO,CAAE,CAAC,EAErE,CAAA,OAAOG,CACT,CAAA,MAASJ,EAAP,CACA,MAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAMA,CAAAA,CAAK,EACxBA,CACR,CAAA,OAAE,CACI,IAAA,CAAK,KAAO,EAAA,IAAA,CAAK,MAAM,UAAW,GACxC,CACF,CAEA,MAAa,UAAA,EAA4B,CACnC,IAAK,CAAA,OAAA,EACP,MAAM,IAAA,CAAK,MAAO,CAAA,UAAA,GAEpB,IAAK,CAAA,KAAA,GACP,CAsBA,IAAI,eAAA,EAAkB,CACpB,OAAO,CAAA,CACT,CAEA,IAAI,OAAU,EAAA,CACZ,OAAO,IAAK,CAAA,MAAA,CAAO,OACrB,CAIU,sBAAyB,EAAA,CACjC,KAAK,MAAO,CAAA,EAAA,CAAG,eAAkBZ,CAAAA,CAAAA,EAA6D,CAC5F,KAAM,CAAE,MAAAvB,CAAAA,CAAO,CAAIuB,CAAAA,CAAAA,CACb,CAAE,KAAA,CAAAV,CAAM,CAAIb,CAAAA,CAAAA,CACda,CAAM,CAAA,IAAA,GAAS,iBACjB,EAAA,IAAA,CAAK,SAAW,IAAK,CAAA,aAAA,CAAcA,CAAM,CAAA,IAAI,CAC7C,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,iBAAA,CAAmB,KAAK,QAAQ,CAAA,EACxCA,EAAM,IAAS,GAAA,cAAA,CACxB,IAAK,CAAA,UAAA,CAAW,IAAK,CAAA,aAAA,CAAcA,EAAM,IAAI,CAAC,CAE9C,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAKA,EAAM,IAAaA,CAAAA,CAAAA,CAAM,IAAI,CAAA,CAEhD,IAAK,CAAA,MAAA,CAAO,KAAK,eAAiBU,CAAAA,CAAO,EAC3C,CAAC,CAED,CAAA,IAAA,CAAK,OAAO,EAAG,CAAA,cAAA,CAAiBxB,CAAoB,EAAA,CAClD,MAAMyC,CAAAA,CAAQ,SAASzC,CAAO,CAAA,CAC9B,IAAK,CAAA,OAAA,CAAUyC,CACf,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,cAAA,CAAgB,YAAa,CAAA,IAAA,CAAK,OAAO,CAAC,EAC3D,IAAK,CAAA,OAAA,GACP,CAAC,CAAA,CAED,KAAK,MAAO,CAAA,EAAA,CACV,gBACCjB,CAAAA,CAAAA,EAA8D,CAC7D,IAAA,CAAK,OAAO,IAAK,CAAA,gBAAA,CAAkBA,CAAO,EAC5C,CACF,CAAA,CAEA,KAAK,MAAO,CAAA,EAAA,CACV,gBACCA,CAAAA,CAAAA,EAA8D,CAC7D,IAAA,CAAK,OACL,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,gBAAkBA,CAAAA,CAAO,EAC1C,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,YAAA,CAAcW,CAAAvB,CAAAA,CAAAA,CAAA,GAC1B8B,WAAY,CAAA,mBAAmB,CADL,CAAA,CAAA,CAE7B,IAAMlB,CAAAA,CAAAA,CAAQ,MACd,IAAM,CAAA,mBACR,CAAC,CAAA,EACH,CACF,CAAA,CAEA,KAAK,MAAO,CAAA,EAAA,CAAG,cAAgBmB,CAAgB,EAAA,CAzdnD,IAAAV,CAAAW,CAAAA,CAAAA,CA0dU,IAAK,CAAA,GAAA,CAAI,WAGXX,GAAAA,CAAAA,CAAAA,CAAA,KAAK,KAAL,GAAA,IAAA,EAAAA,CAAY,CAAA,UAAA,EAAA,CAAA,CACZW,CAAA,CAAA,IAAA,CAAK,QAAL,IAAAA,EAAAA,CAAAA,CAAY,SAAU,CAAA,CAAE,GAAAD,CAAAA,CAAI,IAE9B,IAAK,CAAA,MAAA,CAAO,IAAK,CAAA,aAAA,CAAeA,CAAG,EACrC,CAAC,EACH,CAEU,mBAAoB3C,CAAAA,CAAAA,CAAuB,CACnD,IAAA,CAAK,QAAQ,CACX,MAAA,CAAQ,4BACR,CAAA,MAAA,CAAQ,CAAC,CAAE,QAASA,CAAQ,CAAA,QAAA,CAAS,EAAE,CAAE,CAAC,CAC5C,CAAC,EACH,CAEU,oBAAoBA,CAA0B,CAAA,CACtD,OAAO,OAAOA,CAAAA,EAAY,QAAWA,CAAAA,CAAAA,CAAQ,UAAW,CAAA,CAAA,EAAG,KAAK,SAAY,CAAA,CAAA,CAAA,CAAA,CAAI,CAClF,CAAA,CAEU,aAAcA,CAAAA,CAAAA,CAAyB,CAC/C,OAAO,CAAA,EAAG,IAAK,CAAA,SAAA,CAAA,CAAA,EAAaA,CAC9B,CAAA,CAAA,CAEU,aAAaA,CAAyB,CAAA,CAC9C,OAAO,MAAA,CAAOA,CAAQ,CAAA,KAAA,CAAM,GAAG,CAAE,CAAA,CAAC,CAAC,CACrC,CAEU,WAAA,CAAYD,EAAkB,CAEtC,MAAM8C,CADa9C,CAAAA,CAAAA,CAAO,MAAQ+C,CAAAA,CAAAA,EAAM,KAAK,mBAAoBA,CAAAA,CAAC,CAAC,CAAA,CACvC,GAAKC,CAAAA,CAAAA,EAAM,KAAK,YAAaA,CAAAA,CAAC,CAAC,CACvDF,CAAAA,CAAAA,CAAS,SACX,IAAK,CAAA,OAAA,CAAUA,CAAS,CAAA,CAAC,CACzB,CAAA,IAAA,CAAK,OAAO,IAAK,CAAA,cAAA,CAAgB,YAAa,CAAA,IAAA,CAAK,OAAO,CAAC,EAC3D,IAAK,CAAA,OAAA,EAET,EAAA,CAEU,UAAWJ,CAAAA,CAAAA,CAAe,CAClC,GAAI,IAAA,CAAK,mBAAoBA,CAAAA,CAAK,CAAG,CAAA,CACnC,MAAMzC,CAAU,CAAA,IAAA,CAAK,YAAayC,CAAAA,CAAK,CACvC,CAAA,IAAA,CAAK,QAAUzC,CACf,CAAA,IAAA,CAAK,mBAAoBA,CAAAA,CAAO,EAEpC,CAAA,CAEU,eAAegD,CAAuD,CAAA,CAC9E,KAAM,CAACC,CAAWC,CAAAA,CAAAA,CAAWC,CAAO,CAAIH,CAAAA,CAAAA,CAAQ,MAAM,GAAG,CAAA,CAEzD,OAAO,CAAE,OAAA,CADO,CAAGC,EAAAA,CAAAA,CAAAA,CAAAA,EAAaC,CACd,CAAA,CAAA,CAAA,OAAA,CAAAC,CAAQ,CAC5B,CAEU,WAAYd,CAAAA,CAAAA,CAAoB,CACxC,IAAA,CAAK,SAAWA,CACb,CAAA,MAAA,CAAQS,CAAM,EAAA,IAAA,CAAK,YAAa,CAAA,IAAA,CAAK,eAAeA,CAAC,CAAA,CAAE,OAAO,CAAA,GAAM,IAAK,CAAA,OAAO,EAChF,GAAKA,CAAAA,CAAAA,EAAM,IAAK,CAAA,cAAA,CAAeA,CAAC,CAAA,CAAE,OAAO,CAC5C,CAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,iBAAmB,CAAA,IAAA,CAAK,QAAQ,EACnD,CAEU,YAAarB,CAAAA,CAAAA,CAAkD,CAthB3E,IAAAQ,EAAAW,CAuhBI,CAAA,MAAMQ,GAAiBnB,CAAAR,CAAAA,CAAAA,EAAA,YAAAA,CAAM,CAAA,MAAA,GAAN,IAAAQ,CAAAA,CAAAA,CAAgB,EAAC,CAClC/B,GAAiB0C,CAAAnB,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,cAAN,GAAA,IAAA,CAAAmB,EAAwB,EAAC,CAC1CS,CAAYD,CAAAA,CAAAA,CAAe,MAAOlD,CAAAA,CAAc,EACtD,GAAI,CAACmD,CAAU,CAAA,MAAA,CACb,MAAM,IAAI,MAAM,4DAA4D,CAAA,CAC9E,MAAMC,CAAAA,CAAkBF,CAAe,CAAA,MAAA,CAAA,CAAS3B,GAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,OAAWf,GAAAA,gBAAAA,CAAmB,EAAC,CAC/E6C,EAAiBH,CAAe,CAAA,MAAA,CAAA,CAAS3B,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,MAAA,GAAUd,gBAAkB,EAAC,CAC5EP,CAAkBqB,CAAAA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,kBAAmB,EAAC,CAC5CnB,CAAiBmB,CAAAA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,iBAAkB,EAAC,CAC1ClB,CAASkB,CAAAA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAM,SAAU,IAAK,CAAA,WAAA,CAAY4B,CAAW5B,CAAAA,CAAAA,CAAK,SAAS,CAAA,CACnE+B,GAAiB/B,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAM,CAAA,cAAA,GAAkB,KAC/C,CAAA,CAAA,OAAO,CACL,MAAQ2B,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAgB,GAAKX,CAAAA,CAAAA,EAAU,KAAK,aAAcA,CAAAA,CAAK,CAC/D,CAAA,CAAA,cAAA,CAAgBvC,CAAe,CAAA,GAAA,CAAKuC,GAAU,IAAK,CAAA,aAAA,CAAcA,CAAK,CAAC,CACvE,CAAA,OAAA,CAASa,EACT,MAAQC,CAAAA,CAAAA,CACR,gBAAAnD,CACA,CAAA,cAAA,CAAAE,EACA,MAAAC,CAAAA,CAAAA,CACA,WAAa,CAAA,CAAA,EAAQkB,CAAA,EAAA,IAAA,EAAAA,EAAM,WAC3B,CAAA,CAAA,cAAA,CAAA+B,CACA,CAAA,SAAA,CAAW/B,CAAK,CAAA,SAAA,CAChB,SAAUA,CAAK,CAAA,QACjB,CACF,CAEU,WAAY1B,CAAAA,CAAAA,CAAkB0D,EAAmC,CACzE,MAAMC,CAAsB,CAAA,EAC5B,CAAA,OAAA3D,EAAO,OAAS0C,CAAAA,CAAAA,EAAU,CACxBiB,CAAAA,CAAIjB,CAAK,CAAA,CAAI,KAAK,SAAUA,CAAAA,CAAAA,CAAOgB,CAAS,EAC9C,CAAC,CAAA,CACMC,CACT,CAEA,MAAgB,UAAWjC,CAAAA,CAAAA,CAA+B,CAkBxD,GAjBA,KAAK,GAAM,CAAA,IAAA,CAAK,aAAaA,CAAI,CAAA,CAEjC,KAAK,OAAU,CAAA,IAAA,CAAK,GAAI,CAAA,MAAA,CAAO,MAC3B,CAAA,kBAAA,CAAmB,KAAK,GAAI,CAAA,MAAM,CAClC,CAAA,kBAAA,CAAmB,IAAK,CAAA,GAAA,CAAI,cAAc,CAC9C,CAAA,IAAA,CAAK,MAAS,CAAA,MAAMkC,iBAAkB,CAAA,IAAA,CAAK,CACzC,SAAW,CAAA,IAAA,CAAK,GAAI,CAAA,SAAA,CACpB,QAAU,CAAA,IAAA,CAAK,IAAI,QACnB,CAAA,mBAAA,CAAqBlC,CAAK,CAAA,mBAAA,CAC1B,QAAUA,CAAAA,CAAAA,CAAK,SACf,cAAgBA,CAAAA,CAAAA,CAAK,cACrB,CAAA,mBAAA,CAAqBA,CAAK,CAAA,mBAAA,CAC1B,iBAAkBA,CAAK,CAAA,gBAAA,CACvB,MAAQA,CAAAA,CAAAA,CAAK,MACf,CAAC,EACD,IAAK,CAAA,sBAAA,GACL,MAAM,IAAA,CAAK,sBACP,CAAA,IAAA,CAAK,GAAI,CAAA,WAAA,CAAa,CACxB,IAAImC,EACJ,GAAI,CACF,KAAM,CAAE,kBAAAC,CAAAA,CAAmB,EAAI,MAAM,OAAO,sBAAsB,CAAA,CAClED,CAA0BC,CAAAA,EAC5B,OAAQC,CAAN,CAAA,CACA,MAAM,IAAI,KAAM,CAAA,8DAA8D,CAChF,CACA,GAAIF,CACF,CAAA,GAAI,CACF,IAAA,CAAK,MAAQ,IAAIA,CAAAA,CAAwBhD,CAAA,CAAA,CACvC,SAAW,CAAA,IAAA,CAAK,IAAI,SACjB,CAAA,CAAA,IAAA,CAAK,GAAI,CAAA,cAAA,CACb,EACH,CAAA,MAASkD,EAAP,CACA,MAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAMA,CAAAA,CAAC,EACpB,IAAI,KAAA,CAAM,gDAAgD,CAClE,CAGN,CAAA,CAEU,gBAAgBrC,CAAmB,CAAA,CAC3C,GAAI,CAACA,CAAM,CAAA,OACX,KAAM,CAAE,MAAA,CAAA1B,CAAQ,CAAA,cAAA,CAAAG,CAAgB,CAAA,MAAA,CAAAK,CAAO,CAAIkB,CAAAA,CAAAA,CACvC1B,CAAUS,EAAAA,YAAAA,CAAaT,CAAM,CAAA,GAC/B,KAAK,GAAI,CAAA,MAAA,CAASA,CAAO,CAAA,GAAA,CAAK0C,CAAU,EAAA,IAAA,CAAK,cAAcA,CAAK,CAAC,CACjE1C,CAAAA,CAAAA,CAAO,OAAS0C,CAAAA,CAAAA,EAAU,CACxB,IAAK,CAAA,GAAA,CAAI,MAAOA,CAAAA,CAAK,CAAIlC,CAAAA,CAAAA,CAAAA,EAAA,YAAAA,CAASkC,CAAAA,CAAAA,CAAAA,GAAU,KAAK,SAAUA,CAAAA,CAAK,EAClE,CAAC,CAAA,CAAA,CAECvC,CAAkBM,EAAAA,YAAAA,CAAaN,CAAc,CAAA,GAC/C,KAAK,GAAI,CAAA,cAAA,CAAiB,EAAC,CAC3B,IAAK,CAAA,GAAA,CAAI,eAAiBA,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,CAAgB,CAAA,GAAA,CAAKuC,CAAU,EAAA,IAAA,CAAK,cAAcA,CAAK,CAAA,CAAA,CACjFvC,CAAe,CAAA,OAAA,CAASuC,CAAU,EAAA,CAChC,KAAK,GAAI,CAAA,MAAA,CAAOA,CAAK,CAAA,CAAA,CAAIlC,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAAA,EAASkC,CAAU,CAAA,GAAA,IAAA,CAAK,SAAUA,CAAAA,CAAK,EAClE,CAAC,GAEL,CAEU,SAAA,CAAUzC,CAAiByD,CAAAA,CAAAA,CAA4B,CAnnBnE,IAAAxB,EAqnBI,OADoBA,CAAAA,CAAAA,CAAAA,CAAA,KAAK,GAAI,CAAA,MAAA,GAAT,YAAAA,CAAkBjC,CAAAA,CAAAA,CAAAA,GAGpC,CAAG+D,EAAAA,OAAAA,CAAAA,gBAAAA,EAA0B/D,CAAqByD,CAAAA,WAAAA,EAAAA,CAAAA,EAAa,KAAK,GAAI,CAAA,SAAA,CAAA,CAE5E,CAEA,MAAgB,oBAAuB,EAAA,CACrC,GAAK,IAAK,CAAA,OAAA,CACV,GAAI,CACF,MAAMzD,CAAAA,CAAU,MAAM,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,IAAA,CAAK,OAAQ,CAAA,OAAA,CAAQ,GAAG,IAAK,CAAA,WAAA,CAAA,QAAA,CAAqB,CAGrFiD,CAAAA,CAAAA,CAAY,IAAK,CAAA,OAAA,CAAQ,WAAW,CAAG,EAAA,IAAA,CAAK,SAAajD,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,CAAS,CACpE,CAAA,IAAA,CAAK,QAAQ,UAAW,CAAA,CAAA,EAAG,IAAK,CAAA,SAAA,CAAA,CAAA,EAAaA,CAAS,CAAA,CAAA,CAAA,CACtD,KAAK,OAAQ,CAAA,UAAA,CAAW,KAAK,SAAS,CAAA,CAE1C,KAAK,WAAYA,CAAAA,CAAAA,CAAU,CAAC,IAAA,CAAK,aAAcA,CAAAA,CAAO,CAAC,CAAIiD,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAW,QAAQ,CAAA,CAC9E,KAAK,WAAYA,CAAAA,CAAAA,EAAA,IAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAW,QAAQ,EACtC,OAASb,CAAP,CAAA,CACA,IAAK,CAAA,MAAA,CAAO,MAAO,CAAA,KAAA,CAAM,qDAAqD,CAC9E,CAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,KAAMA,CAAAA,CAAK,EAC9B,MAAM,IAAA,CAAK,UAAW,EAAA,CAAE,KAAOA,CAAAA,CAAAA,EAAU,KAAK,MAAO,CAAA,MAAA,CAAO,IAAKA,CAAAA,CAAK,CAAC,EACzE,CACF,CAEU,KAAA,EAAQ,CAChB,IAAA,CAAK,OAAU,CAAA,CAAA,CACf,KAAK,QAAW,CAAA,GAClB,CAEU,OAAU,EAAA,CACb,KAAK,OACV,EAAA,IAAA,CAAK,MAAO,CAAA,MAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,QAAQ,CAAG,EAAA,IAAA,CAAK,WAAuB,CAAA,QAAA,CAAA,CAAA,IAAA,CAAK,OAAO,EACrF,CAEU,aAAcZ,CAAAA,CAAAA,CAAsC,CAC5D,OAAI,OAAOA,CAAAA,EAAY,UAAYA,CAAmB,YAAA,MAAA,CAC7C,CAAC,IAAA,CAAK,YAAaA,CAAAA,CAAO,CAAC,CAE7BA,CAAAA,CAAAA,CAAQ,GAAKwB,CAAAA,CAAAA,EAAoB,IAAK,CAAA,YAAA,CAAaA,CAAO,CAAC,CACpE,CAKF;;ACjqBO,MAAM,iBAAmBgB;;;;"} +\ No newline at end of file +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js b/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js +index 022569c..4f6ab31 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js +@@ -1,4 +1,4 @@ +-(function(bn,fr){typeof exports=="object"&&typeof module<"u"?fr(exports):typeof define=="function"&&define.amd?define(["exports"],fr):(bn=typeof globalThis<"u"?globalThis:bn||self,fr(bn["@walletconnect/ethereum-provider"]={}))})(this,function(bn){"use strict";var fr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function z6(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function zu(r){var e=r.default;if(typeof e=="function"){var t=function(){return e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(i){var n=Object.getOwnPropertyDescriptor(r,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return r[i]}})}),t}var qr={exports:{}},ga=typeof Reflect=="object"?Reflect:null,tg=ga&&typeof ga.apply=="function"?ga.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)},Xf;ga&&typeof ga.ownKeys=="function"?Xf=ga.ownKeys:Object.getOwnPropertySymbols?Xf=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Xf=function(e){return Object.getOwnPropertyNames(e)};function H6(r){console&&console.warn&&console.warn(r)}var rg=Number.isNaN||function(e){return e!==e};function Jt(){Jt.init.call(this)}qr.exports=Jt,qr.exports.once=K6,Jt.EventEmitter=Jt,Jt.prototype._events=void 0,Jt.prototype._eventsCount=0,Jt.prototype._maxListeners=void 0;var ig=10;function el(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(Jt,"defaultMaxListeners",{enumerable:!0,get:function(){return ig},set:function(r){if(typeof r!="number"||r<0||rg(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");ig=r}}),Jt.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Jt.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||rg(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function ng(r){return r._maxListeners===void 0?Jt.defaultMaxListeners:r._maxListeners}Jt.prototype.getMaxListeners=function(){return ng(this)},Jt.prototype.emit=function(e){for(var t=[],i=1;i0&&(a=t[0]),a instanceof Error)throw a;var f=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw f.context=a,f}var h=s[e];if(h===void 0)return!1;if(typeof h=="function")tg(h,this,t);else for(var u=h.length,g=fg(h,u),i=0;i0&&a.length>n&&!a.warned){a.warned=!0;var f=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");f.name="MaxListenersExceededWarning",f.emitter=r,f.type=e,f.count=a.length,H6(f)}return r}Jt.prototype.addListener=function(e,t){return sg(this,e,t,!1)},Jt.prototype.on=Jt.prototype.addListener,Jt.prototype.prependListener=function(e,t){return sg(this,e,t,!0)};function k6(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function og(r,e,t){var i={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},n=k6.bind(i);return n.listener=t,i.wrapFn=n,n}Jt.prototype.once=function(e,t){return el(t),this.on(e,og(this,e,t)),this},Jt.prototype.prependOnceListener=function(e,t){return el(t),this.prependListener(e,og(this,e,t)),this},Jt.prototype.removeListener=function(e,t){var i,n,s,a,f;if(el(t),n=this._events,n===void 0)return this;if(i=n[e],i===void 0)return this;if(i===t||i.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if(typeof i!="function"){for(s=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){f=i[a].listener,s=a;break}if(s<0)return this;s===0?i.shift():j6(i,s),i.length===1&&(n[e]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",e,f||t)}return this},Jt.prototype.off=Jt.prototype.removeListener,Jt.prototype.removeAllListeners=function(e){var t,i,n;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[e]),this;if(arguments.length===0){var s=Object.keys(i),a;for(n=0;n=0;n--)this.removeListener(e,t[n]);return this};function ag(r,e,t){var i=r._events;if(i===void 0)return[];var n=i[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?W6(n):fg(n,n.length)}Jt.prototype.listeners=function(e){return ag(this,e,!0)},Jt.prototype.rawListeners=function(e){return ag(this,e,!1)},Jt.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):cg.call(r,e)},Jt.prototype.listenerCount=cg;function cg(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Jt.prototype.eventNames=function(){return this._eventsCount>0?Xf(this._events):[]};function fg(r,e){for(var t=new Array(e),i=0;i"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Z6:typeof navigator<"u"?pg(navigator.userAgent):s5()}function i5(r){return r!==""&&t5.reduce(function(e,t){var i=t[0],n=t[1];if(e)return e;var s=n.exec(r);return!!s&&[i,s]},!1)}function pg(r){var e=i5(r);if(!e)return null;var t=e[0],i=e[1];if(t==="searchbot")return new Q6;var n=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);n?n.length0&&(a=t[0]),a instanceof Error)throw a;var f=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw f.context=a,f}var h=s[e];if(h===void 0)return!1;if(typeof h=="function")rg(h,this,t);else for(var u=h.length,g=lg(h,u),i=0;i0&&a.length>n&&!a.warned){a.warned=!0;var f=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");f.name="MaxListenersExceededWarning",f.emitter=r,f.type=e,f.count=a.length,V6(f)}return r}Jt.prototype.addListener=function(e,t){return og(this,e,t,!1)},Jt.prototype.on=Jt.prototype.addListener,Jt.prototype.prependListener=function(e,t){return og(this,e,t,!0)};function G6(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ag(r,e,t){var i={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},n=G6.bind(i);return n.listener=t,i.wrapFn=n,n}Jt.prototype.once=function(e,t){return tl(t),this.on(e,ag(this,e,t)),this},Jt.prototype.prependOnceListener=function(e,t){return tl(t),this.prependListener(e,ag(this,e,t)),this},Jt.prototype.removeListener=function(e,t){var i,n,s,a,f;if(tl(t),n=this._events,n===void 0)return this;if(i=n[e],i===void 0)return this;if(i===t||i.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if(typeof i!="function"){for(s=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){f=i[a].listener,s=a;break}if(s<0)return this;s===0?i.shift():Y6(i,s),i.length===1&&(n[e]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",e,f||t)}return this},Jt.prototype.off=Jt.prototype.removeListener,Jt.prototype.removeAllListeners=function(e){var t,i,n;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[e]),this;if(arguments.length===0){var s=Object.keys(i),a;for(n=0;n=0;n--)this.removeListener(e,t[n]);return this};function cg(r,e,t){var i=r._events;if(i===void 0)return[];var n=i[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?J6(n):lg(n,n.length)}Jt.prototype.listeners=function(e){return cg(this,e,!0)},Jt.prototype.rawListeners=function(e){return cg(this,e,!1)},Jt.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):fg.call(r,e)},Jt.prototype.listenerCount=fg;function fg(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Jt.prototype.eventNames=function(){return this._eventsCount>0?el(this._events):[]};function lg(r,e){for(var t=new Array(e),i=0;i"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new i5:typeof navigator<"u"?gg(navigator.userAgent):l5()}function c5(r){return r!==""&&o5.reduce(function(e,t){var i=t[0],n=t[1];if(e)return e;var s=n.exec(r);return!!s&&[i,s]},!1)}function gg(r){var e=c5(r);if(!e)return null;var t=e[0],i=e[1];if(t==="searchbot")return new r5;var n=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);n?n.length=0;f--)(a=r[f])&&(s=(n<3?a(s):n>3?a(e,t,s):a(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}function l5(r,e){return function(t,i){e(t,i,r)}}function h5(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function u5(r,e,t,i){function n(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function f(g){try{u(i.next(g))}catch(w){a(w)}}function h(g){try{u(i.throw(g))}catch(w){a(w)}}function u(g){g.done?s(g.value):n(g.value).then(f,h)}u((i=i.apply(r,e||[])).next())})}function d5(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,a;return a={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function f(u){return function(g){return h([u,g])}}function h(u){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,n=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function gg(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(f){a={error:f}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s}function v5(){for(var r=[],e=0;e1||f(P,M)})})}function f(P,M){try{h(i[P](M))}catch(O){w(s[0][3],O)}}function h(P){P.value instanceof Mc?Promise.resolve(P.value.v).then(u,g):w(s[0][2],P)}function u(P){f("next",P)}function g(P){f("throw",P)}function w(P,M){P(M),s.shift(),s.length&&f(s[0][0],s[0][1])}}function w5(r){var e,t;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=r[n]?function(a){return(t=!t)?{value:Mc(r[n](a)),done:n==="return"}:s?s(a):a}:s}}function y5(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof ju=="function"?ju(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=r[s]&&function(a){return new Promise(function(f,h){a=r[s](a),n(f,h,a.done,a.value)})}}function n(s,a,f,h){Promise.resolve(h).then(function(u){s({value:u,done:f})},a)}}function _5(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function x5(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function A5(r){return r&&r.__esModule?r:{default:r}}function E5(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function S5(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var I5=Object.freeze({__proto__:null,__extends:a5,get __assign(){return ku},__rest:c5,__decorate:f5,__param:l5,__metadata:h5,__awaiter:u5,__generator:d5,__createBinding:p5,__exportStar:g5,__values:ju,__read:gg,__spread:v5,__spreadArrays:m5,__await:Mc,__asyncGenerator:b5,__asyncDelegator:w5,__asyncValues:y5,__makeTemplateObject:_5,__importStar:x5,__importDefault:A5,__classPrivateFieldGet:E5,__classPrivateFieldSet:S5}),tl=zu(I5),Wu={},Cc={},vg;function M5(){if(vg)return Cc;vg=1,Object.defineProperty(Cc,"__esModule",{value:!0}),Cc.delay=void 0;function r(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}return Cc.delay=r,Cc}var yo={},Ku={},_o={},mg;function C5(){return mg||(mg=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.ONE_THOUSAND=_o.ONE_HUNDRED=void 0,_o.ONE_HUNDRED=100,_o.ONE_THOUSAND=1e3),_o}var Vu={},bg;function P5(){return bg||(bg=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.ONE_YEAR=r.FOUR_WEEKS=r.THREE_WEEKS=r.TWO_WEEKS=r.ONE_WEEK=r.THIRTY_DAYS=r.SEVEN_DAYS=r.FIVE_DAYS=r.THREE_DAYS=r.ONE_DAY=r.TWENTY_FOUR_HOURS=r.TWELVE_HOURS=r.SIX_HOURS=r.THREE_HOURS=r.ONE_HOUR=r.SIXTY_MINUTES=r.THIRTY_MINUTES=r.TEN_MINUTES=r.FIVE_MINUTES=r.ONE_MINUTE=r.SIXTY_SECONDS=r.THIRTY_SECONDS=r.TEN_SECONDS=r.FIVE_SECONDS=r.ONE_SECOND=void 0,r.ONE_SECOND=1,r.FIVE_SECONDS=5,r.TEN_SECONDS=10,r.THIRTY_SECONDS=30,r.SIXTY_SECONDS=60,r.ONE_MINUTE=r.SIXTY_SECONDS,r.FIVE_MINUTES=r.ONE_MINUTE*5,r.TEN_MINUTES=r.ONE_MINUTE*10,r.THIRTY_MINUTES=r.ONE_MINUTE*30,r.SIXTY_MINUTES=r.ONE_MINUTE*60,r.ONE_HOUR=r.SIXTY_MINUTES,r.THREE_HOURS=r.ONE_HOUR*3,r.SIX_HOURS=r.ONE_HOUR*6,r.TWELVE_HOURS=r.ONE_HOUR*12,r.TWENTY_FOUR_HOURS=r.ONE_HOUR*24,r.ONE_DAY=r.TWENTY_FOUR_HOURS,r.THREE_DAYS=r.ONE_DAY*3,r.FIVE_DAYS=r.ONE_DAY*5,r.SEVEN_DAYS=r.ONE_DAY*7,r.THIRTY_DAYS=r.ONE_DAY*30,r.ONE_WEEK=r.SEVEN_DAYS,r.TWO_WEEKS=r.ONE_WEEK*2,r.THREE_WEEKS=r.ONE_WEEK*3,r.FOUR_WEEKS=r.ONE_WEEK*4,r.ONE_YEAR=r.ONE_DAY*365}(Vu)),Vu}var wg;function yg(){return wg||(wg=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=tl;e.__exportStar(C5(),r),e.__exportStar(P5(),r)}(Ku)),Ku}var _g;function D5(){if(_g)return yo;_g=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.fromMiliseconds=yo.toMiliseconds=void 0;const r=yg();function e(i){return i*r.ONE_THOUSAND}yo.toMiliseconds=e;function t(i){return Math.floor(i/r.ONE_THOUSAND)}return yo.fromMiliseconds=t,yo}var xg;function O5(){return xg||(xg=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=tl;e.__exportStar(M5(),r),e.__exportStar(D5(),r)}(Wu)),Wu}var va={},Ag;function R5(){if(Ag)return va;Ag=1,Object.defineProperty(va,"__esModule",{value:!0}),va.Watch=void 0;class r{constructor(){this.timestamps=new Map}start(t){if(this.timestamps.has(t))throw new Error(`Watch already started for label: ${t}`);this.timestamps.set(t,{started:Date.now()})}stop(t){const i=this.get(t);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);const n=Date.now()-i.started;this.timestamps.set(t,{started:i.started,elapsed:n})}get(t){const i=this.timestamps.get(t);if(typeof i>"u")throw new Error(`No timestamp found for label: ${t}`);return i}elapsed(t){const i=this.get(t);return i.elapsed||Date.now()-i.started}}return va.Watch=r,va.default=r,va}var Gu={},Pc={},Eg;function T5(){if(Eg)return Pc;Eg=1,Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.IWatch=void 0;class r{}return Pc.IWatch=r,Pc}var Sg;function $5(){return Sg||(Sg=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),tl.__exportStar(T5(),r)}(Gu)),Gu}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=tl;e.__exportStar(O5(),r),e.__exportStar(R5(),r),e.__exportStar($5(),r),e.__exportStar(yg(),r)})(Ae);var rr={};Object.defineProperty(rr,"__esModule",{value:!0}),rr.getLocalStorage=rr.getLocalStorageOrThrow=rr.getCrypto=rr.getCryptoOrThrow=Ig=rr.getLocation=rr.getLocationOrThrow=Yu=rr.getNavigator=rr.getNavigatorOrThrow=Dc=rr.getDocument=rr.getDocumentOrThrow=rr.getFromWindowOrThrow=rr.getFromWindow=void 0;function xo(r){let e;return typeof window<"u"&&typeof window[r]<"u"&&(e=window[r]),e}rr.getFromWindow=xo;function ma(r){const e=xo(r);if(!e)throw new Error(`${r} is not defined in Window`);return e}rr.getFromWindowOrThrow=ma;function N5(){return ma("document")}rr.getDocumentOrThrow=N5;function L5(){return xo("document")}var Dc=rr.getDocument=L5;function B5(){return ma("navigator")}rr.getNavigatorOrThrow=B5;function F5(){return xo("navigator")}var Yu=rr.getNavigator=F5;function U5(){return ma("location")}rr.getLocationOrThrow=U5;function q5(){return xo("location")}var Ig=rr.getLocation=q5;function z5(){return ma("crypto")}rr.getCryptoOrThrow=z5;function H5(){return xo("crypto")}rr.getCrypto=H5;function k5(){return ma("localStorage")}rr.getLocalStorageOrThrow=k5;function j5(){return xo("localStorage")}rr.getLocalStorage=j5;var Ju={};Object.defineProperty(Ju,"__esModule",{value:!0});var Mg=Ju.getWindowMetadata=void 0;const Cg=rr;function W5(){let r,e;try{r=Cg.getDocumentOrThrow(),e=Cg.getLocationOrThrow()}catch{return null}function t(){const w=r.getElementsByTagName("link"),P=[];for(let M=0;M-1){const W=O.getAttribute("href");if(W)if(W.toLowerCase().indexOf("https:")===-1&&W.toLowerCase().indexOf("http:")===-1&&W.indexOf("//")!==0){let H=e.protocol+"//"+e.host;if(W.indexOf("/")===0)H+=W;else{const F=e.pathname.split("/");F.pop();const Y=F.join("/");H+=Y+"/"+W}P.push(H)}else if(W.indexOf("//")===0){const H=e.protocol+W;P.push(H)}else P.push(W)}}return P}function i(...w){const P=r.getElementsByTagName("meta");for(let M=0;MO.getAttribute(W)).filter(W=>W?w.includes(W):!1);if($.length&&$){const W=O.getAttribute("content");if(W)return W}}return""}function n(){let w=i("name","og:site_name","og:title","twitter:title");return w||(w=r.title),w}function s(){return i("description","og:description","twitter:description","keywords")}const a=n(),f=s(),h=e.origin,u=t();return{description:f,url:h,icons:u,name:a}}Mg=Ju.getWindowMetadata=W5;var Oc={},K5=r=>encodeURIComponent(r).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Pg="%[a-f0-9]{2}",Dg=new RegExp("("+Pg+")|([^%]+?)","gi"),Og=new RegExp("("+Pg+")+","gi");function Qu(r,e){try{return[decodeURIComponent(r.join(""))]}catch{}if(r.length===1)return r;e=e||1;var t=r.slice(0,e),i=r.slice(e);return Array.prototype.concat.call([],Qu(t),Qu(i))}function V5(r){try{return decodeURIComponent(r)}catch{for(var e=r.match(Dg)||[],t=1;t{if(!(typeof r=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[r];const t=r.indexOf(e);return t===-1?[r]:[r.slice(0,t),r.slice(t+e.length)]},Q5=function(r,e){for(var t={},i=Object.keys(r),n=Array.isArray(e),s=0;sF==null,a=Symbol("encodeFragmentIdentifier");function f(F){switch(F.arrayFormat){case"index":return Y=>(B,z)=>{const j=B.length;return z===void 0||F.skipNull&&z===null||F.skipEmptyString&&z===""?B:z===null?[...B,[g(Y,F),"[",j,"]"].join("")]:[...B,[g(Y,F),"[",g(j,F),"]=",g(z,F)].join("")]};case"bracket":return Y=>(B,z)=>z===void 0||F.skipNull&&z===null||F.skipEmptyString&&z===""?B:z===null?[...B,[g(Y,F),"[]"].join("")]:[...B,[g(Y,F),"[]=",g(z,F)].join("")];case"colon-list-separator":return Y=>(B,z)=>z===void 0||F.skipNull&&z===null||F.skipEmptyString&&z===""?B:z===null?[...B,[g(Y,F),":list="].join("")]:[...B,[g(Y,F),":list=",g(z,F)].join("")];case"comma":case"separator":case"bracket-separator":{const Y=F.arrayFormat==="bracket-separator"?"[]=":"=";return B=>(z,j)=>j===void 0||F.skipNull&&j===null||F.skipEmptyString&&j===""?z:(j=j===null?"":j,z.length===0?[[g(B,F),Y,g(j,F)].join("")]:[[z,g(j,F)].join(F.arrayFormatSeparator)])}default:return Y=>(B,z)=>z===void 0||F.skipNull&&z===null||F.skipEmptyString&&z===""?B:z===null?[...B,g(Y,F)]:[...B,[g(Y,F),"=",g(z,F)].join("")]}}function h(F){let Y;switch(F.arrayFormat){case"index":return(B,z,j)=>{if(Y=/\[(\d*)\]$/.exec(B),B=B.replace(/\[\d*\]$/,""),!Y){j[B]=z;return}j[B]===void 0&&(j[B]={}),j[B][Y[1]]=z};case"bracket":return(B,z,j)=>{if(Y=/(\[\])$/.exec(B),B=B.replace(/\[\]$/,""),!Y){j[B]=z;return}if(j[B]===void 0){j[B]=[z];return}j[B]=[].concat(j[B],z)};case"colon-list-separator":return(B,z,j)=>{if(Y=/(:list)$/.exec(B),B=B.replace(/:list$/,""),!Y){j[B]=z;return}if(j[B]===void 0){j[B]=[z];return}j[B]=[].concat(j[B],z)};case"comma":case"separator":return(B,z,j)=>{const _=typeof z=="string"&&z.includes(F.arrayFormatSeparator),U=typeof z=="string"&&!_&&w(z,F).includes(F.arrayFormatSeparator);z=U?w(z,F):z;const ee=_||U?z.split(F.arrayFormatSeparator).map(oe=>w(oe,F)):z===null?z:w(z,F);j[B]=ee};case"bracket-separator":return(B,z,j)=>{const _=/(\[\])$/.test(B);if(B=B.replace(/\[\]$/,""),!_){j[B]=z&&w(z,F);return}const U=z===null?[]:z.split(F.arrayFormatSeparator).map(ee=>w(ee,F));if(j[B]===void 0){j[B]=U;return}j[B]=[].concat(j[B],U)};default:return(B,z,j)=>{if(j[B]===void 0){j[B]=z;return}j[B]=[].concat(j[B],z)}}}function u(F){if(typeof F!="string"||F.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function g(F,Y){return Y.encode?Y.strict?e(F):encodeURIComponent(F):F}function w(F,Y){return Y.decode?t(F):F}function P(F){return Array.isArray(F)?F.sort():typeof F=="object"?P(Object.keys(F)).sort((Y,B)=>Number(Y)-Number(B)).map(Y=>F[Y]):F}function M(F){const Y=F.indexOf("#");return Y!==-1&&(F=F.slice(0,Y)),F}function O(F){let Y="";const B=F.indexOf("#");return B!==-1&&(Y=F.slice(B)),Y}function $(F){F=M(F);const Y=F.indexOf("?");return Y===-1?"":F.slice(Y+1)}function W(F,Y){return Y.parseNumbers&&!Number.isNaN(Number(F))&&typeof F=="string"&&F.trim()!==""?F=Number(F):Y.parseBooleans&&F!==null&&(F.toLowerCase()==="true"||F.toLowerCase()==="false")&&(F=F.toLowerCase()==="true"),F}function H(F,Y){Y=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},Y),u(Y.arrayFormatSeparator);const B=h(Y),z=Object.create(null);if(typeof F!="string"||(F=F.trim().replace(/^[?#&]/,""),!F))return z;for(const j of F.split("&")){if(j==="")continue;let[_,U]=i(Y.decode?j.replace(/\+/g," "):j,"=");U=U===void 0?null:["comma","separator","bracket-separator"].includes(Y.arrayFormat)?U:w(U,Y),B(w(_,Y),U,z)}for(const j of Object.keys(z)){const _=z[j];if(typeof _=="object"&&_!==null)for(const U of Object.keys(_))_[U]=W(_[U],Y);else z[j]=W(_,Y)}return Y.sort===!1?z:(Y.sort===!0?Object.keys(z).sort():Object.keys(z).sort(Y.sort)).reduce((j,_)=>{const U=z[_];return U&&typeof U=="object"&&!Array.isArray(U)?j[_]=P(U):j[_]=U,j},Object.create(null))}r.extract=$,r.parse=H,r.stringify=(F,Y)=>{if(!F)return"";Y=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},Y),u(Y.arrayFormatSeparator);const B=U=>Y.skipNull&&s(F[U])||Y.skipEmptyString&&F[U]==="",z=f(Y),j={};for(const U of Object.keys(F))B(U)||(j[U]=F[U]);const _=Object.keys(j);return Y.sort!==!1&&_.sort(Y.sort),_.map(U=>{const ee=F[U];return ee===void 0?"":ee===null?g(U,Y):Array.isArray(ee)?ee.length===0&&Y.arrayFormat==="bracket-separator"?g(U,Y)+"[]":ee.reduce(z(U),[]).join("&"):g(U,Y)+"="+g(ee,Y)}).filter(U=>U.length>0).join("&")},r.parseUrl=(F,Y)=>{Y=Object.assign({decode:!0},Y);const[B,z]=i(F,"#");return Object.assign({url:B.split("?")[0]||"",query:H($(F),Y)},Y&&Y.parseFragmentIdentifier&&z?{fragmentIdentifier:w(z,Y)}:{})},r.stringifyUrl=(F,Y)=>{Y=Object.assign({encode:!0,strict:!0,[a]:!0},Y);const B=M(F.url).split("?")[0]||"",z=r.extract(F.url),j=r.parse(z,{sort:!1}),_=Object.assign(j,F.query);let U=r.stringify(_,Y);U&&(U=`?${U}`);let ee=O(F.url);return F.fragmentIdentifier&&(ee=`#${Y[a]?g(F.fragmentIdentifier,Y):F.fragmentIdentifier}`),`${B}${U}${ee}`},r.pick=(F,Y,B)=>{B=Object.assign({parseFragmentIdentifier:!0,[a]:!1},B);const{url:z,query:j,fragmentIdentifier:_}=r.parseUrl(F,B);return r.stringifyUrl({url:z,query:n(j,Y),fragmentIdentifier:_},B)},r.exclude=(F,Y,B)=>{const z=Array.isArray(Y)?j=>!Y.includes(j):(j,_)=>!Y(j,_);return r.pick(F,z,B)}})(Oc);var Rg={exports:{}};/** ++ ***************************************************************************** */var Wu=function(r,e){return Wu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])},Wu(r,e)};function u5(r,e){Wu(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Ku=function(){return Ku=Object.assign||function(e){for(var t,i=1,n=arguments.length;i=0;f--)(a=r[f])&&(s=(n<3?a(s):n>3?a(e,t,s):a(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}function g5(r,e){return function(t,i){e(t,i,r)}}function v5(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function m5(r,e,t,i){function n(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function f(g){try{u(i.next(g))}catch(w){a(w)}}function h(g){try{u(i.throw(g))}catch(w){a(w)}}function u(g){g.done?s(g.value):n(g.value).then(f,h)}u((i=i.apply(r,e||[])).next())})}function b5(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,a;return a={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function f(u){return function(g){return h([u,g])}}function h(u){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,n=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function vg(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(f){a={error:f}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s}function _5(){for(var r=[],e=0;e1||f(M,C)})})}function f(M,C){try{h(i[M](C))}catch(O){w(s[0][3],O)}}function h(M){M.value instanceof Cc?Promise.resolve(M.value.v).then(u,g):w(s[0][2],M)}function u(M){f("next",M)}function g(M){f("throw",M)}function w(M,C){M(C),s.shift(),s.length&&f(s[0][0],s[0][1])}}function E5(r){var e,t;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=r[n]?function(a){return(t=!t)?{value:Cc(r[n](a)),done:n==="return"}:s?s(a):a}:s}}function S5(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Vu=="function"?Vu(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=r[s]&&function(a){return new Promise(function(f,h){a=r[s](a),n(f,h,a.done,a.value)})}}function n(s,a,f,h){Promise.resolve(h).then(function(u){s({value:u,done:f})},a)}}function I5(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function M5(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function C5(r){return r&&r.__esModule?r:{default:r}}function P5(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function D5(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var O5=Object.freeze({__proto__:null,__extends:u5,get __assign(){return Ku},__rest:d5,__decorate:p5,__param:g5,__metadata:v5,__awaiter:m5,__generator:b5,__createBinding:w5,__exportStar:y5,__values:Vu,__read:vg,__spread:_5,__spreadArrays:x5,__await:Cc,__asyncGenerator:A5,__asyncDelegator:E5,__asyncValues:S5,__makeTemplateObject:I5,__importStar:M5,__importDefault:C5,__classPrivateFieldGet:P5,__classPrivateFieldSet:D5}),rl=ju(O5),Gu={},Pc={},mg;function R5(){if(mg)return Pc;mg=1,Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.delay=void 0;function r(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}return Pc.delay=r,Pc}var _o={},Yu={},xo={},bg;function T5(){return bg||(bg=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.ONE_THOUSAND=xo.ONE_HUNDRED=void 0,xo.ONE_HUNDRED=100,xo.ONE_THOUSAND=1e3),xo}var Ju={},wg;function $5(){return wg||(wg=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.ONE_YEAR=r.FOUR_WEEKS=r.THREE_WEEKS=r.TWO_WEEKS=r.ONE_WEEK=r.THIRTY_DAYS=r.SEVEN_DAYS=r.FIVE_DAYS=r.THREE_DAYS=r.ONE_DAY=r.TWENTY_FOUR_HOURS=r.TWELVE_HOURS=r.SIX_HOURS=r.THREE_HOURS=r.ONE_HOUR=r.SIXTY_MINUTES=r.THIRTY_MINUTES=r.TEN_MINUTES=r.FIVE_MINUTES=r.ONE_MINUTE=r.SIXTY_SECONDS=r.THIRTY_SECONDS=r.TEN_SECONDS=r.FIVE_SECONDS=r.ONE_SECOND=void 0,r.ONE_SECOND=1,r.FIVE_SECONDS=5,r.TEN_SECONDS=10,r.THIRTY_SECONDS=30,r.SIXTY_SECONDS=60,r.ONE_MINUTE=r.SIXTY_SECONDS,r.FIVE_MINUTES=r.ONE_MINUTE*5,r.TEN_MINUTES=r.ONE_MINUTE*10,r.THIRTY_MINUTES=r.ONE_MINUTE*30,r.SIXTY_MINUTES=r.ONE_MINUTE*60,r.ONE_HOUR=r.SIXTY_MINUTES,r.THREE_HOURS=r.ONE_HOUR*3,r.SIX_HOURS=r.ONE_HOUR*6,r.TWELVE_HOURS=r.ONE_HOUR*12,r.TWENTY_FOUR_HOURS=r.ONE_HOUR*24,r.ONE_DAY=r.TWENTY_FOUR_HOURS,r.THREE_DAYS=r.ONE_DAY*3,r.FIVE_DAYS=r.ONE_DAY*5,r.SEVEN_DAYS=r.ONE_DAY*7,r.THIRTY_DAYS=r.ONE_DAY*30,r.ONE_WEEK=r.SEVEN_DAYS,r.TWO_WEEKS=r.ONE_WEEK*2,r.THREE_WEEKS=r.ONE_WEEK*3,r.FOUR_WEEKS=r.ONE_WEEK*4,r.ONE_YEAR=r.ONE_DAY*365}(Ju)),Ju}var yg;function _g(){return yg||(yg=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=rl;e.__exportStar(T5(),r),e.__exportStar($5(),r)}(Yu)),Yu}var xg;function N5(){if(xg)return _o;xg=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.fromMiliseconds=_o.toMiliseconds=void 0;const r=_g();function e(i){return i*r.ONE_THOUSAND}_o.toMiliseconds=e;function t(i){return Math.floor(i/r.ONE_THOUSAND)}return _o.fromMiliseconds=t,_o}var Ag;function L5(){return Ag||(Ag=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=rl;e.__exportStar(R5(),r),e.__exportStar(N5(),r)}(Gu)),Gu}var ba={},Eg;function B5(){if(Eg)return ba;Eg=1,Object.defineProperty(ba,"__esModule",{value:!0}),ba.Watch=void 0;class r{constructor(){this.timestamps=new Map}start(t){if(this.timestamps.has(t))throw new Error(`Watch already started for label: ${t}`);this.timestamps.set(t,{started:Date.now()})}stop(t){const i=this.get(t);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);const n=Date.now()-i.started;this.timestamps.set(t,{started:i.started,elapsed:n})}get(t){const i=this.timestamps.get(t);if(typeof i>"u")throw new Error(`No timestamp found for label: ${t}`);return i}elapsed(t){const i=this.get(t);return i.elapsed||Date.now()-i.started}}return ba.Watch=r,ba.default=r,ba}var Qu={},Dc={},Sg;function F5(){if(Sg)return Dc;Sg=1,Object.defineProperty(Dc,"__esModule",{value:!0}),Dc.IWatch=void 0;class r{}return Dc.IWatch=r,Dc}var Ig;function U5(){return Ig||(Ig=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),rl.__exportStar(F5(),r)}(Qu)),Qu}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=rl;e.__exportStar(L5(),r),e.__exportStar(B5(),r),e.__exportStar(U5(),r),e.__exportStar(_g(),r)})(_e);var rr={};Object.defineProperty(rr,"__esModule",{value:!0}),rr.getLocalStorage=rr.getLocalStorageOrThrow=rr.getCrypto=rr.getCryptoOrThrow=Mg=rr.getLocation=rr.getLocationOrThrow=Zu=rr.getNavigator=rr.getNavigatorOrThrow=Oc=rr.getDocument=rr.getDocumentOrThrow=rr.getFromWindowOrThrow=rr.getFromWindow=void 0;function Ao(r){let e;return typeof window<"u"&&typeof window[r]<"u"&&(e=window[r]),e}rr.getFromWindow=Ao;function wa(r){const e=Ao(r);if(!e)throw new Error(`${r} is not defined in Window`);return e}rr.getFromWindowOrThrow=wa;function q5(){return wa("document")}rr.getDocumentOrThrow=q5;function z5(){return Ao("document")}var Oc=rr.getDocument=z5;function H5(){return wa("navigator")}rr.getNavigatorOrThrow=H5;function k5(){return Ao("navigator")}var Zu=rr.getNavigator=k5;function j5(){return wa("location")}rr.getLocationOrThrow=j5;function W5(){return Ao("location")}var Mg=rr.getLocation=W5;function K5(){return wa("crypto")}rr.getCryptoOrThrow=K5;function V5(){return Ao("crypto")}rr.getCrypto=V5;function G5(){return wa("localStorage")}rr.getLocalStorageOrThrow=G5;function Y5(){return Ao("localStorage")}rr.getLocalStorage=Y5;var Xu={};Object.defineProperty(Xu,"__esModule",{value:!0});var Cg=Xu.getWindowMetadata=void 0;const Pg=rr;function J5(){let r,e;try{r=Pg.getDocumentOrThrow(),e=Pg.getLocationOrThrow()}catch{return null}function t(){const w=r.getElementsByTagName("link"),M=[];for(let C=0;C-1){const j=O.getAttribute("href");if(j)if(j.toLowerCase().indexOf("https:")===-1&&j.toLowerCase().indexOf("http:")===-1&&j.indexOf("//")!==0){let H=e.protocol+"//"+e.host;if(j.indexOf("/")===0)H+=j;else{const F=e.pathname.split("/");F.pop();const G=F.join("/");H+=G+"/"+j}M.push(H)}else if(j.indexOf("//")===0){const H=e.protocol+j;M.push(H)}else M.push(j)}}return M}function i(...w){const M=r.getElementsByTagName("meta");for(let C=0;CO.getAttribute(j)).filter(j=>j?w.includes(j):!1);if($.length&&$){const j=O.getAttribute("content");if(j)return j}}return""}function n(){let w=i("name","og:site_name","og:title","twitter:title");return w||(w=r.title),w}function s(){return i("description","og:description","twitter:description","keywords")}const a=n(),f=s(),h=e.origin,u=t();return{description:f,url:h,icons:u,name:a}}Cg=Xu.getWindowMetadata=J5;var Rc={},Q5=r=>encodeURIComponent(r).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Dg="%[a-f0-9]{2}",Og=new RegExp("("+Dg+")|([^%]+?)","gi"),Rg=new RegExp("("+Dg+")+","gi");function ed(r,e){try{return[decodeURIComponent(r.join(""))]}catch{}if(r.length===1)return r;e=e||1;var t=r.slice(0,e),i=r.slice(e);return Array.prototype.concat.call([],ed(t),ed(i))}function Z5(r){try{return decodeURIComponent(r)}catch{for(var e=r.match(Og)||[],t=1;t{if(!(typeof r=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[r];const t=r.indexOf(e);return t===-1?[r]:[r.slice(0,t),r.slice(t+e.length)]},r4=function(r,e){for(var t={},i=Object.keys(r),n=Array.isArray(e),s=0;sF==null,a=Symbol("encodeFragmentIdentifier");function f(F){switch(F.arrayFormat){case"index":return G=>(B,z)=>{const W=B.length;return z===void 0||F.skipNull&&z===null||F.skipEmptyString&&z===""?B:z===null?[...B,[g(G,F),"[",W,"]"].join("")]:[...B,[g(G,F),"[",g(W,F),"]=",g(z,F)].join("")]};case"bracket":return G=>(B,z)=>z===void 0||F.skipNull&&z===null||F.skipEmptyString&&z===""?B:z===null?[...B,[g(G,F),"[]"].join("")]:[...B,[g(G,F),"[]=",g(z,F)].join("")];case"colon-list-separator":return G=>(B,z)=>z===void 0||F.skipNull&&z===null||F.skipEmptyString&&z===""?B:z===null?[...B,[g(G,F),":list="].join("")]:[...B,[g(G,F),":list=",g(z,F)].join("")];case"comma":case"separator":case"bracket-separator":{const G=F.arrayFormat==="bracket-separator"?"[]=":"=";return B=>(z,W)=>W===void 0||F.skipNull&&W===null||F.skipEmptyString&&W===""?z:(W=W===null?"":W,z.length===0?[[g(B,F),G,g(W,F)].join("")]:[[z,g(W,F)].join(F.arrayFormatSeparator)])}default:return G=>(B,z)=>z===void 0||F.skipNull&&z===null||F.skipEmptyString&&z===""?B:z===null?[...B,g(G,F)]:[...B,[g(G,F),"=",g(z,F)].join("")]}}function h(F){let G;switch(F.arrayFormat){case"index":return(B,z,W)=>{if(G=/\[(\d*)\]$/.exec(B),B=B.replace(/\[\d*\]$/,""),!G){W[B]=z;return}W[B]===void 0&&(W[B]={}),W[B][G[1]]=z};case"bracket":return(B,z,W)=>{if(G=/(\[\])$/.exec(B),B=B.replace(/\[\]$/,""),!G){W[B]=z;return}if(W[B]===void 0){W[B]=[z];return}W[B]=[].concat(W[B],z)};case"colon-list-separator":return(B,z,W)=>{if(G=/(:list)$/.exec(B),B=B.replace(/:list$/,""),!G){W[B]=z;return}if(W[B]===void 0){W[B]=[z];return}W[B]=[].concat(W[B],z)};case"comma":case"separator":return(B,z,W)=>{const _=typeof z=="string"&&z.includes(F.arrayFormatSeparator),U=typeof z=="string"&&!_&&w(z,F).includes(F.arrayFormatSeparator);z=U?w(z,F):z;const ee=_||U?z.split(F.arrayFormatSeparator).map(oe=>w(oe,F)):z===null?z:w(z,F);W[B]=ee};case"bracket-separator":return(B,z,W)=>{const _=/(\[\])$/.test(B);if(B=B.replace(/\[\]$/,""),!_){W[B]=z&&w(z,F);return}const U=z===null?[]:z.split(F.arrayFormatSeparator).map(ee=>w(ee,F));if(W[B]===void 0){W[B]=U;return}W[B]=[].concat(W[B],U)};default:return(B,z,W)=>{if(W[B]===void 0){W[B]=z;return}W[B]=[].concat(W[B],z)}}}function u(F){if(typeof F!="string"||F.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function g(F,G){return G.encode?G.strict?e(F):encodeURIComponent(F):F}function w(F,G){return G.decode?t(F):F}function M(F){return Array.isArray(F)?F.sort():typeof F=="object"?M(Object.keys(F)).sort((G,B)=>Number(G)-Number(B)).map(G=>F[G]):F}function C(F){const G=F.indexOf("#");return G!==-1&&(F=F.slice(0,G)),F}function O(F){let G="";const B=F.indexOf("#");return B!==-1&&(G=F.slice(B)),G}function $(F){F=C(F);const G=F.indexOf("?");return G===-1?"":F.slice(G+1)}function j(F,G){return G.parseNumbers&&!Number.isNaN(Number(F))&&typeof F=="string"&&F.trim()!==""?F=Number(F):G.parseBooleans&&F!==null&&(F.toLowerCase()==="true"||F.toLowerCase()==="false")&&(F=F.toLowerCase()==="true"),F}function H(F,G){G=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},G),u(G.arrayFormatSeparator);const B=h(G),z=Object.create(null);if(typeof F!="string"||(F=F.trim().replace(/^[?#&]/,""),!F))return z;for(const W of F.split("&")){if(W==="")continue;let[_,U]=i(G.decode?W.replace(/\+/g," "):W,"=");U=U===void 0?null:["comma","separator","bracket-separator"].includes(G.arrayFormat)?U:w(U,G),B(w(_,G),U,z)}for(const W of Object.keys(z)){const _=z[W];if(typeof _=="object"&&_!==null)for(const U of Object.keys(_))_[U]=j(_[U],G);else z[W]=j(_,G)}return G.sort===!1?z:(G.sort===!0?Object.keys(z).sort():Object.keys(z).sort(G.sort)).reduce((W,_)=>{const U=z[_];return U&&typeof U=="object"&&!Array.isArray(U)?W[_]=M(U):W[_]=U,W},Object.create(null))}r.extract=$,r.parse=H,r.stringify=(F,G)=>{if(!F)return"";G=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},G),u(G.arrayFormatSeparator);const B=U=>G.skipNull&&s(F[U])||G.skipEmptyString&&F[U]==="",z=f(G),W={};for(const U of Object.keys(F))B(U)||(W[U]=F[U]);const _=Object.keys(W);return G.sort!==!1&&_.sort(G.sort),_.map(U=>{const ee=F[U];return ee===void 0?"":ee===null?g(U,G):Array.isArray(ee)?ee.length===0&&G.arrayFormat==="bracket-separator"?g(U,G)+"[]":ee.reduce(z(U),[]).join("&"):g(U,G)+"="+g(ee,G)}).filter(U=>U.length>0).join("&")},r.parseUrl=(F,G)=>{G=Object.assign({decode:!0},G);const[B,z]=i(F,"#");return Object.assign({url:B.split("?")[0]||"",query:H($(F),G)},G&&G.parseFragmentIdentifier&&z?{fragmentIdentifier:w(z,G)}:{})},r.stringifyUrl=(F,G)=>{G=Object.assign({encode:!0,strict:!0,[a]:!0},G);const B=C(F.url).split("?")[0]||"",z=r.extract(F.url),W=r.parse(z,{sort:!1}),_=Object.assign(W,F.query);let U=r.stringify(_,G);U&&(U=`?${U}`);let ee=O(F.url);return F.fragmentIdentifier&&(ee=`#${G[a]?g(F.fragmentIdentifier,G):F.fragmentIdentifier}`),`${B}${U}${ee}`},r.pick=(F,G,B)=>{B=Object.assign({parseFragmentIdentifier:!0,[a]:!1},B);const{url:z,query:W,fragmentIdentifier:_}=r.parseUrl(F,B);return r.stringifyUrl({url:z,query:n(W,G),fragmentIdentifier:_},B)},r.exclude=(F,G,B)=>{const z=Array.isArray(G)?W=>!G.includes(W):(W,_)=>!G(W,_);return r.pick(F,z,B)}})(Rc);var Tg={exports:{}};/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT +- */(function(r){(function(){var e="input is invalid type",t="finalize already called",i=typeof window=="object",n=i?window:{};n.JS_SHA3_NO_WINDOW&&(i=!1);var s=!i&&typeof self=="object",a=!n.JS_SHA3_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?n=fr:s&&(n=self);var f=!n.JS_SHA3_NO_COMMON_JS&&!0&&r.exports,h=!n.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",u="0123456789abcdef".split(""),g=[31,7936,2031616,520093696],w=[4,1024,262144,67108864],P=[1,256,65536,16777216],M=[6,1536,393216,100663296],O=[0,8,16,24],$=[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],W=[224,256,384,512],H=[128,256],F=["hex","buffer","arrayBuffer","array","digest"],Y={128:168,256:136};(n.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(R){return Object.prototype.toString.call(R)==="[object Array]"}),h&&(n.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(R){return typeof R=="object"&&R.buffer&&R.buffer.constructor===ArrayBuffer});for(var B=function(R,X,V){return function(J){return new x(R,X,R).update(J)[V]()}},z=function(R,X,V){return function(J,K){return new x(R,X,K).update(J)[V]()}},j=function(R,X,V){return function(J,K,E,G){return l["cshake"+R].update(J,K,E,G)[V]()}},_=function(R,X,V){return function(J,K,E,G){return l["kmac"+R].update(J,K,E,G)[V]()}},U=function(R,X,V,J){for(var K=0;K>5,this.byteCount=this.blockCount<<2,this.outputBlocks=V>>5,this.extraBytes=(V&31)>>3;for(var J=0;J<50;++J)this.s[J]=0}x.prototype.update=function(R){if(this.finalized)throw new Error(t);var X,V=typeof R;if(V!=="string"){if(V==="object"){if(R===null)throw new Error(e);if(h&&R.constructor===ArrayBuffer)R=new Uint8Array(R);else if(!Array.isArray(R)&&(!h||!ArrayBuffer.isView(R)))throw new Error(e)}else throw new Error(e);X=!0}for(var J=this.blocks,K=this.byteCount,E=R.length,G=this.blockCount,re=0,le=this.s,he,ge;re>2]|=R[re]<>2]|=ge<>2]|=(192|ge>>6)<>2]|=(128|ge&63)<=57344?(J[he>>2]|=(224|ge>>12)<>2]|=(128|ge>>6&63)<>2]|=(128|ge&63)<>2]|=(240|ge>>18)<>2]|=(128|ge>>12&63)<>2]|=(128|ge>>6&63)<>2]|=(128|ge&63)<=K){for(this.start=he-K,this.block=J[G],he=0;he>8,V=R&255;V>0;)K.unshift(V),R=R>>8,V=R&255,++J;return X?K.push(J):K.unshift(J),this.update(K),K.length},x.prototype.encodeString=function(R){var X,V=typeof R;if(V!=="string"){if(V==="object"){if(R===null)throw new Error(e);if(h&&R.constructor===ArrayBuffer)R=new Uint8Array(R);else if(!Array.isArray(R)&&(!h||!ArrayBuffer.isView(R)))throw new Error(e)}else throw new Error(e);X=!0}var J=0,K=R.length;if(X)J=K;else for(var E=0;E=57344?J+=3:(G=65536+((G&1023)<<10|R.charCodeAt(++E)&1023),J+=4)}return J+=this.encode(J*8),this.update(R),J},x.prototype.bytepad=function(R,X){for(var V=this.encode(X),J=0;J>2]|=this.padding[X&3],this.lastByteIndex===this.byteCount)for(R[0]=R[V],X=1;X>4&15]+u[re&15]+u[re>>12&15]+u[re>>8&15]+u[re>>20&15]+u[re>>16&15]+u[re>>28&15]+u[re>>24&15];E%R===0&&(ae(X),K=0)}return J&&(re=X[K],G+=u[re>>4&15]+u[re&15],J>1&&(G+=u[re>>12&15]+u[re>>8&15]),J>2&&(G+=u[re>>20&15]+u[re>>16&15])),G},x.prototype.arrayBuffer=function(){this.finalize();var R=this.blockCount,X=this.s,V=this.outputBlocks,J=this.extraBytes,K=0,E=0,G=this.outputBits>>3,re;J?re=new ArrayBuffer(V+1<<2):re=new ArrayBuffer(G);for(var le=new Uint32Array(re);E>8&255,G[re+2]=le>>16&255,G[re+3]=le>>24&255;E%R===0&&ae(X)}return J&&(re=E<<2,le=X[K],G[re]=le&255,J>1&&(G[re+1]=le>>8&255),J>2&&(G[re+2]=le>>16&255)),G};function N(R,X,V){x.call(this,R,X,V)}N.prototype=new x,N.prototype.finalize=function(){return this.encode(this.outputBits,!0),x.prototype.finalize.call(this)};var ae=function(R){var X,V,J,K,E,G,re,le,he,ge,He,Te,Ce,Xe,$e,be,Pe,De,ye,Ie,Oe,me,Me,Be,we,ke,We,xe,Ve,Ke,Ge,mt,It,Ye,Pt,Ot,Ze,rt,et,Ne,it,tt,Re,lt,ht,Le,ut,nt,Fe,st,Qe,qe,dt,Ht,at,kt,_t,qt,Qr,Zr,Xr,ei,vr;for(J=0;J<48;J+=2)K=R[0]^R[10]^R[20]^R[30]^R[40],E=R[1]^R[11]^R[21]^R[31]^R[41],G=R[2]^R[12]^R[22]^R[32]^R[42],re=R[3]^R[13]^R[23]^R[33]^R[43],le=R[4]^R[14]^R[24]^R[34]^R[44],he=R[5]^R[15]^R[25]^R[35]^R[45],ge=R[6]^R[16]^R[26]^R[36]^R[46],He=R[7]^R[17]^R[27]^R[37]^R[47],Te=R[8]^R[18]^R[28]^R[38]^R[48],Ce=R[9]^R[19]^R[29]^R[39]^R[49],X=Te^(G<<1|re>>>31),V=Ce^(re<<1|G>>>31),R[0]^=X,R[1]^=V,R[10]^=X,R[11]^=V,R[20]^=X,R[21]^=V,R[30]^=X,R[31]^=V,R[40]^=X,R[41]^=V,X=K^(le<<1|he>>>31),V=E^(he<<1|le>>>31),R[2]^=X,R[3]^=V,R[12]^=X,R[13]^=V,R[22]^=X,R[23]^=V,R[32]^=X,R[33]^=V,R[42]^=X,R[43]^=V,X=G^(ge<<1|He>>>31),V=re^(He<<1|ge>>>31),R[4]^=X,R[5]^=V,R[14]^=X,R[15]^=V,R[24]^=X,R[25]^=V,R[34]^=X,R[35]^=V,R[44]^=X,R[45]^=V,X=le^(Te<<1|Ce>>>31),V=he^(Ce<<1|Te>>>31),R[6]^=X,R[7]^=V,R[16]^=X,R[17]^=V,R[26]^=X,R[27]^=V,R[36]^=X,R[37]^=V,R[46]^=X,R[47]^=V,X=ge^(K<<1|E>>>31),V=He^(E<<1|K>>>31),R[8]^=X,R[9]^=V,R[18]^=X,R[19]^=V,R[28]^=X,R[29]^=V,R[38]^=X,R[39]^=V,R[48]^=X,R[49]^=V,Xe=R[0],$e=R[1],Le=R[11]<<4|R[10]>>>28,ut=R[10]<<4|R[11]>>>28,xe=R[20]<<3|R[21]>>>29,Ve=R[21]<<3|R[20]>>>29,Zr=R[31]<<9|R[30]>>>23,Xr=R[30]<<9|R[31]>>>23,tt=R[40]<<18|R[41]>>>14,Re=R[41]<<18|R[40]>>>14,Ye=R[2]<<1|R[3]>>>31,Pt=R[3]<<1|R[2]>>>31,be=R[13]<<12|R[12]>>>20,Pe=R[12]<<12|R[13]>>>20,nt=R[22]<<10|R[23]>>>22,Fe=R[23]<<10|R[22]>>>22,Ke=R[33]<<13|R[32]>>>19,Ge=R[32]<<13|R[33]>>>19,ei=R[42]<<2|R[43]>>>30,vr=R[43]<<2|R[42]>>>30,Ht=R[5]<<30|R[4]>>>2,at=R[4]<<30|R[5]>>>2,Ot=R[14]<<6|R[15]>>>26,Ze=R[15]<<6|R[14]>>>26,De=R[25]<<11|R[24]>>>21,ye=R[24]<<11|R[25]>>>21,st=R[34]<<15|R[35]>>>17,Qe=R[35]<<15|R[34]>>>17,mt=R[45]<<29|R[44]>>>3,It=R[44]<<29|R[45]>>>3,Be=R[6]<<28|R[7]>>>4,we=R[7]<<28|R[6]>>>4,kt=R[17]<<23|R[16]>>>9,_t=R[16]<<23|R[17]>>>9,rt=R[26]<<25|R[27]>>>7,et=R[27]<<25|R[26]>>>7,Ie=R[36]<<21|R[37]>>>11,Oe=R[37]<<21|R[36]>>>11,qe=R[47]<<24|R[46]>>>8,dt=R[46]<<24|R[47]>>>8,lt=R[8]<<27|R[9]>>>5,ht=R[9]<<27|R[8]>>>5,ke=R[18]<<20|R[19]>>>12,We=R[19]<<20|R[18]>>>12,qt=R[29]<<7|R[28]>>>25,Qr=R[28]<<7|R[29]>>>25,Ne=R[38]<<8|R[39]>>>24,it=R[39]<<8|R[38]>>>24,me=R[48]<<14|R[49]>>>18,Me=R[49]<<14|R[48]>>>18,R[0]=Xe^~be&De,R[1]=$e^~Pe&ye,R[10]=Be^~ke&xe,R[11]=we^~We&Ve,R[20]=Ye^~Ot&rt,R[21]=Pt^~Ze&et,R[30]=lt^~Le&nt,R[31]=ht^~ut&Fe,R[40]=Ht^~kt&qt,R[41]=at^~_t&Qr,R[2]=be^~De&Ie,R[3]=Pe^~ye&Oe,R[12]=ke^~xe&Ke,R[13]=We^~Ve&Ge,R[22]=Ot^~rt&Ne,R[23]=Ze^~et&it,R[32]=Le^~nt&st,R[33]=ut^~Fe&Qe,R[42]=kt^~qt&Zr,R[43]=_t^~Qr&Xr,R[4]=De^~Ie&me,R[5]=ye^~Oe&Me,R[14]=xe^~Ke&mt,R[15]=Ve^~Ge&It,R[24]=rt^~Ne&tt,R[25]=et^~it&Re,R[34]=nt^~st&qe,R[35]=Fe^~Qe&dt,R[44]=qt^~Zr&ei,R[45]=Qr^~Xr&vr,R[6]=Ie^~me&Xe,R[7]=Oe^~Me&$e,R[16]=Ke^~mt&Be,R[17]=Ge^~It&we,R[26]=Ne^~tt&Ye,R[27]=it^~Re&Pt,R[36]=st^~qe<,R[37]=Qe^~dt&ht,R[46]=Zr^~ei&Ht,R[47]=Xr^~vr&at,R[8]=me^~Xe&be,R[9]=Me^~$e&Pe,R[18]=mt^~Be&ke,R[19]=It^~we&We,R[28]=tt^~Ye&Ot,R[29]=Re^~Pt&Ze,R[38]=qe^~lt&Le,R[39]=dt^~ht&ut,R[48]=ei^~Ht&kt,R[49]=vr^~at&_t,R[0]^=$[J],R[1]^=$[J+1]};if(f)r.exports=l;else for(y=0;y{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{r.push(e)}}),r.length)throw new Error("missing "+r.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(r){return r.message}return null}const Lg=e4();var Xu;(function(r){r.DEBUG="DEBUG",r.INFO="INFO",r.WARNING="WARNING",r.ERROR="ERROR",r.OFF="OFF"})(Xu||(Xu={}));var wn;(function(r){r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",r.NETWORK_ERROR="NETWORK_ERROR",r.SERVER_ERROR="SERVER_ERROR",r.TIMEOUT="TIMEOUT",r.BUFFER_OVERRUN="BUFFER_OVERRUN",r.NUMERIC_FAULT="NUMERIC_FAULT",r.MISSING_NEW="MISSING_NEW",r.INVALID_ARGUMENT="INVALID_ARGUMENT",r.MISSING_ARGUMENT="MISSING_ARGUMENT",r.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",r.CALL_EXCEPTION="CALL_EXCEPTION",r.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",r.NONCE_EXPIRED="NONCE_EXPIRED",r.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",r.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",r.TRANSACTION_REPLACED="TRANSACTION_REPLACED",r.ACTION_REJECTED="ACTION_REJECTED"})(wn||(wn={}));const Bg="0123456789abcdef";class xt{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const i=e.toLowerCase();rl[i]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(Ng>rl[i])&&console.log.apply(console,t)}debug(...e){this._log(xt.levels.DEBUG,e)}info(...e){this._log(xt.levels.INFO,e)}warn(...e){this._log(xt.levels.WARNING,e)}makeError(e,t,i){if($g)return this.makeError("censored error",t,{});t||(t=xt.errors.UNKNOWN_ERROR),i||(i={});const n=[];Object.keys(i).forEach(h=>{const u=i[h];try{if(u instanceof Uint8Array){let g="";for(let w=0;w>4],g+=Bg[u[w]&15];n.push(h+"=Uint8Array(0x"+g+")")}else n.push(h+"="+JSON.stringify(u))}catch{n.push(h+"="+JSON.stringify(i[h].toString()))}}),n.push(`code=${t}`),n.push(`version=${this.version}`);const s=e;let a="";switch(t){case wn.NUMERIC_FAULT:{a="NUMERIC_FAULT";const h=e;switch(h){case"overflow":case"underflow":case"division-by-zero":a+="-"+h;break;case"negative-power":case"negative-width":a+="-unsupported";break;case"unbound-bitwise-result":a+="-unbound-result";break}break}case wn.CALL_EXCEPTION:case wn.INSUFFICIENT_FUNDS:case wn.MISSING_NEW:case wn.NONCE_EXPIRED:case wn.REPLACEMENT_UNDERPRICED:case wn.TRANSACTION_REPLACED:case wn.UNPREDICTABLE_GAS_LIMIT:a=t;break}a&&(e+=" [ See: https://links.ethers.org/v5-errors-"+a+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const f=new Error(e);return f.reason=s,f.code=t,Object.keys(i).forEach(function(h){f[h]=i[h]}),f}throwError(e,t,i){throw this.makeError(e,t,i)}throwArgumentError(e,t,i){return this.throwError(e,xt.errors.INVALID_ARGUMENT,{argument:t,value:i})}assert(e,t,i,n){e||this.throwError(t,i,n)}assertArgument(e,t,i,n){e||this.throwArgumentError(t,i,n)}checkNormalize(e){Lg&&this.throwError("platform missing String.prototype.normalize",xt.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Lg})}checkSafeUint53(e,t){typeof e=="number"&&(t==null&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,xt.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,xt.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,i){i?i=": "+i:i="",et&&this.throwError("too many arguments"+i,xt.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){(e===Object||e==null)&&this.throwError("missing new",xt.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",xt.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",xt.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return Zu||(Zu=new xt(X5)),Zu}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",xt.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),Tg){if(!e)return;this.globalLogger().throwError("error censorship permanent",xt.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}$g=!!e,Tg=!!t}static setLogLevel(e){const t=rl[e.toLowerCase()];if(t==null){xt.globalLogger().warn("invalid log level - "+e);return}Ng=t}static from(e){return new xt(e)}}xt.errors=wn,xt.levels=Xu;const t4="bytes/5.7.0",br=new xt(t4);function Fg(r){return!!r.toHexString}function ba(r){return r.slice||(r.slice=function(){const e=Array.prototype.slice.call(arguments);return ba(new Uint8Array(Array.prototype.slice.apply(r,e)))}),r}function r4(r){return Oi(r)&&!(r.length%2)||wa(r)}function Ug(r){return typeof r=="number"&&r==r&&r%1===0}function wa(r){if(r==null)return!1;if(r.constructor===Uint8Array)return!0;if(typeof r=="string"||!Ug(r.length)||r.length<0)return!1;for(let e=0;e=256)return!1}return!0}function ur(r,e){if(e||(e={}),typeof r=="number"){br.checkSafeUint53(r,"invalid arrayify value");const t=[];for(;r;)t.unshift(r&255),r=parseInt(String(r/256));return t.length===0&&t.push(0),ba(new Uint8Array(t))}if(e.allowMissingPrefix&&typeof r=="string"&&r.substring(0,2)!=="0x"&&(r="0x"+r),Fg(r)&&(r=r.toHexString()),Oi(r)){let t=r.substring(2);t.length%2&&(e.hexPad==="left"?t="0"+t:e.hexPad==="right"?t+="0":br.throwArgumentError("hex data is odd-length","value",r));const i=[];for(let n=0;nur(n)),t=e.reduce((n,s)=>n+s.length,0),i=new Uint8Array(t);return e.reduce((n,s)=>(i.set(s,n),n+s.length),0),ba(i)}function n4(r,e){r=ur(r),r.length>e&&br.throwArgumentError("value out of range","value",arguments[0]);const t=new Uint8Array(e);return t.set(r,e-r.length),ba(t)}function Oi(r,e){return!(typeof r!="string"||!r.match(/^0x[0-9A-Fa-f]*$/)||e&&r.length!==2+2*e)}const ed="0123456789abcdef";function ii(r,e){if(e||(e={}),typeof r=="number"){br.checkSafeUint53(r,"invalid hexlify value");let t="";for(;r;)t=ed[r&15]+t,r=Math.floor(r/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if(typeof r=="bigint")return r=r.toString(16),r.length%2?"0x0"+r:"0x"+r;if(e.allowMissingPrefix&&typeof r=="string"&&r.substring(0,2)!=="0x"&&(r="0x"+r),Fg(r))return r.toHexString();if(Oi(r))return r.length%2&&(e.hexPad==="left"?r="0x0"+r.substring(2):e.hexPad==="right"?r+="0":br.throwArgumentError("hex data is odd-length","value",r)),r.toLowerCase();if(wa(r)){let t="0x";for(let i=0;i>4]+ed[n&15]}return t}return br.throwArgumentError("invalid hexlify value","value",r)}function s4(r){if(typeof r!="string")r=ii(r);else if(!Oi(r)||r.length%2)return null;return(r.length-2)/2}function qg(r,e,t){return typeof r!="string"?r=ii(r):(!Oi(r)||r.length%2)&&br.throwArgumentError("invalid hexData","value",r),e=2+2*e,t!=null?"0x"+r.substring(e,2+2*t):"0x"+r.substring(e)}function Fn(r,e){for(typeof r!="string"?r=ii(r):Oi(r)||br.throwArgumentError("invalid hex string","value",r),r.length>2*e+2&&br.throwArgumentError("value out of range","value",arguments[1]);r.length<2*e+2;)r="0x0"+r.substring(2);return r}function zg(r){const e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(r4(r)){let t=ur(r);t.length===64?(e.v=27+(t[32]>>7),t[32]&=127,e.r=ii(t.slice(0,32)),e.s=ii(t.slice(32,64))):t.length===65?(e.r=ii(t.slice(0,32)),e.s=ii(t.slice(32,64)),e.v=t[64]):br.throwArgumentError("invalid signature string","signature",r),e.v<27&&(e.v===0||e.v===1?e.v+=27:br.throwArgumentError("signature invalid v byte","signature",r)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(t[32]|=128),e._vs=ii(t.slice(32,64))}else{if(e.r=r.r,e.s=r.s,e.v=r.v,e.recoveryParam=r.recoveryParam,e._vs=r._vs,e._vs!=null){const n=n4(ur(e._vs),32);e._vs=ii(n);const s=n[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&br.throwArgumentError("signature recoveryParam mismatch _vs","signature",r),n[0]&=127;const a=ii(n);e.s==null?e.s=a:e.s!==a&&br.throwArgumentError("signature v mismatch _vs","signature",r)}if(e.recoveryParam==null)e.v==null?br.throwArgumentError("signature missing v and recoveryParam","signature",r):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{const n=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==n&&br.throwArgumentError("signature recoveryParam mismatch v","signature",r)}e.r==null||!Oi(e.r)?br.throwArgumentError("signature missing or invalid r","signature",r):e.r=Fn(e.r,32),e.s==null||!Oi(e.s)?br.throwArgumentError("signature missing or invalid s","signature",r):e.s=Fn(e.s,32);const t=ur(e.s);t[0]>=128&&br.throwArgumentError("signature s out of range","signature",r),e.recoveryParam&&(t[0]|=128);const i=ii(t);e._vs&&(Oi(e._vs)||br.throwArgumentError("signature invalid _vs","signature",r),e._vs=Fn(e._vs,32)),e._vs==null?e._vs=i:e._vs!==i&&br.throwArgumentError("signature _vs mismatch v and s","signature",r)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function td(r){return"0x"+Z5.keccak_256(ur(r))}var Hg={exports:{}},o4={},a4=Object.freeze({__proto__:null,default:o4}),il=zu(a4);(function(r){(function(e,t){function i(m,l){if(!m)throw new Error(l||"Assertion failed")}function n(m,l){m.super_=l;var d=function(){};d.prototype=l.prototype,m.prototype=new d,m.prototype.constructor=m}function s(m,l,d){if(s.isBN(m))return m;this.negative=0,this.words=null,this.length=0,this.red=null,m!==null&&((l==="le"||l==="be")&&(d=l,l=10),this._init(m||0,l||10,d||"be"))}typeof e=="object"?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;var a;try{typeof window<"u"&&typeof window.Buffer<"u"?a=window.Buffer:a=il.Buffer}catch{}s.isBN=function(l){return l instanceof s?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===s.wordSize&&Array.isArray(l.words)},s.max=function(l,d){return l.cmp(d)>0?l:d},s.min=function(l,d){return l.cmp(d)<0?l:d},s.prototype._init=function(l,d,y){if(typeof l=="number")return this._initNumber(l,d,y);if(typeof l=="object")return this._initArray(l,d,y);d==="hex"&&(d=16),i(d===(d|0)&&d>=2&&d<=36),l=l.toString().replace(/\s+/g,"");var C=0;l[0]==="-"&&(C++,this.negative=1),C=0;C-=3)S=l[C]|l[C-1]<<8|l[C-2]<<16,this.words[D]|=S<>>26-v&67108863,v+=24,v>=26&&(v-=26,D++);else if(y==="le")for(C=0,D=0;C>>26-v&67108863,v+=24,v>=26&&(v-=26,D++);return this._strip()};function f(m,l){var d=m.charCodeAt(l);if(d>=48&&d<=57)return d-48;if(d>=65&&d<=70)return d-55;if(d>=97&&d<=102)return d-87;i(!1,"Invalid character in "+m)}function h(m,l,d){var y=f(m,d);return d-1>=l&&(y|=f(m,d-1)<<4),y}s.prototype._parseHex=function(l,d,y){this.length=Math.ceil((l.length-d)/6),this.words=new Array(this.length);for(var C=0;C=d;C-=2)v=h(l,d,C)<=18?(D-=18,S+=1,this.words[S]|=v>>>26):D+=8;else{var A=l.length-d;for(C=A%2===0?d+1:d;C=18?(D-=18,S+=1,this.words[S]|=v>>>26):D+=8}this._strip()};function u(m,l,d,y){for(var C=0,D=0,S=Math.min(m.length,d),v=l;v=49?D=A-49+10:A>=17?D=A-17+10:D=A,i(A>=0&&D1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=w}catch{s.prototype.inspect=w}else s.prototype.inspect=w;function w(){return(this.red?""}var P=["","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"],M=[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],O=[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];s.prototype.toString=function(l,d){l=l||10,d=d|0||1;var y;if(l===16||l==="hex"){y="";for(var C=0,D=0,S=0;S>>24-C&16777215,C+=2,C>=26&&(C-=26,S--),D!==0||S!==this.length-1?y=P[6-A.length]+A+y:y=A+y}for(D!==0&&(y=D.toString(16)+y);y.length%d!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(l===(l|0)&&l>=2&&l<=36){var x=M[l],N=O[l];y="";var ae=this.clone();for(ae.negative=0;!ae.isZero();){var R=ae.modrn(N).toString(l);ae=ae.idivn(N),ae.isZero()?y=R+y:y=P[x-R.length]+R+y}for(this.isZero()&&(y="0"+y);y.length%d!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}i(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},s.prototype.toJSON=function(){return this.toString(16,2)},a&&(s.prototype.toBuffer=function(l,d){return this.toArrayLike(a,l,d)}),s.prototype.toArray=function(l,d){return this.toArrayLike(Array,l,d)};var $=function(l,d){return l.allocUnsafe?l.allocUnsafe(d):new l(d)};s.prototype.toArrayLike=function(l,d,y){this._strip();var C=this.byteLength(),D=y||Math.max(1,C);i(C<=D,"byte array longer than desired length"),i(D>0,"Requested array length <= 0");var S=$(l,D),v=d==="le"?"LE":"BE";return this["_toArrayLike"+v](S,C),S},s.prototype._toArrayLikeLE=function(l,d){for(var y=0,C=0,D=0,S=0;D>8&255),y>16&255),S===6?(y>24&255),C=0,S=0):(C=v>>>24,S+=2)}if(y=0&&(l[y--]=v>>8&255),y>=0&&(l[y--]=v>>16&255),S===6?(y>=0&&(l[y--]=v>>24&255),C=0,S=0):(C=v>>>24,S+=2)}if(y>=0)for(l[y--]=C;y>=0;)l[y--]=0},Math.clz32?s.prototype._countBits=function(l){return 32-Math.clz32(l)}:s.prototype._countBits=function(l){var d=l,y=0;return d>=4096&&(y+=13,d>>>=13),d>=64&&(y+=7,d>>>=7),d>=8&&(y+=4,d>>>=4),d>=2&&(y+=2,d>>>=2),y+d},s.prototype._zeroBits=function(l){if(l===0)return 26;var d=l,y=0;return d&8191||(y+=13,d>>>=13),d&127||(y+=7,d>>>=7),d&15||(y+=4,d>>>=4),d&3||(y+=2,d>>>=2),d&1||y++,y},s.prototype.bitLength=function(){var l=this.words[this.length-1],d=this._countBits(l);return(this.length-1)*26+d};function W(m){for(var l=new Array(m.bitLength()),d=0;d>>C&1}return l}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,d=0;dl.length?this.clone().ior(l):l.clone().ior(this)},s.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},s.prototype.iuand=function(l){var d;this.length>l.length?d=l:d=this;for(var y=0;yl.length?this.clone().iand(l):l.clone().iand(this)},s.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},s.prototype.iuxor=function(l){var d,y;this.length>l.length?(d=this,y=l):(d=l,y=this);for(var C=0;Cl.length?this.clone().ixor(l):l.clone().ixor(this)},s.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},s.prototype.inotn=function(l){i(typeof l=="number"&&l>=0);var d=Math.ceil(l/26)|0,y=l%26;this._expand(d),y>0&&d--;for(var C=0;C0&&(this.words[C]=~this.words[C]&67108863>>26-y),this._strip()},s.prototype.notn=function(l){return this.clone().inotn(l)},s.prototype.setn=function(l,d){i(typeof l=="number"&&l>=0);var y=l/26|0,C=l%26;return this._expand(y+1),d?this.words[y]=this.words[y]|1<l.length?(y=this,C=l):(y=l,C=this);for(var D=0,S=0;S>>26;for(;D!==0&&S>>26;if(this.length=y.length,D!==0)this.words[this.length]=D,this.length++;else if(y!==this)for(;Sl.length?this.clone().iadd(l):l.clone().iadd(this)},s.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var d=this.iadd(l);return l.negative=1,d._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var y=this.cmp(l);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var C,D;y>0?(C=this,D=l):(C=l,D=this);for(var S=0,v=0;v>26,this.words[v]=d&67108863;for(;S!==0&&v>26,this.words[v]=d&67108863;if(S===0&&v>>26,ae=A&67108863,R=Math.min(x,l.length-1),X=Math.max(0,x-m.length+1);X<=R;X++){var V=x-X|0;C=m.words[V]|0,D=l.words[X]|0,S=C*D+ae,N+=S/67108864|0,ae=S&67108863}d.words[x]=ae|0,A=N|0}return A!==0?d.words[x]=A|0:d.length--,d._strip()}var F=function(l,d,y){var C=l.words,D=d.words,S=y.words,v=0,A,x,N,ae=C[0]|0,R=ae&8191,X=ae>>>13,V=C[1]|0,J=V&8191,K=V>>>13,E=C[2]|0,G=E&8191,re=E>>>13,le=C[3]|0,he=le&8191,ge=le>>>13,He=C[4]|0,Te=He&8191,Ce=He>>>13,Xe=C[5]|0,$e=Xe&8191,be=Xe>>>13,Pe=C[6]|0,De=Pe&8191,ye=Pe>>>13,Ie=C[7]|0,Oe=Ie&8191,me=Ie>>>13,Me=C[8]|0,Be=Me&8191,we=Me>>>13,ke=C[9]|0,We=ke&8191,xe=ke>>>13,Ve=D[0]|0,Ke=Ve&8191,Ge=Ve>>>13,mt=D[1]|0,It=mt&8191,Ye=mt>>>13,Pt=D[2]|0,Ot=Pt&8191,Ze=Pt>>>13,rt=D[3]|0,et=rt&8191,Ne=rt>>>13,it=D[4]|0,tt=it&8191,Re=it>>>13,lt=D[5]|0,ht=lt&8191,Le=lt>>>13,ut=D[6]|0,nt=ut&8191,Fe=ut>>>13,st=D[7]|0,Qe=st&8191,qe=st>>>13,dt=D[8]|0,Ht=dt&8191,at=dt>>>13,kt=D[9]|0,_t=kt&8191,qt=kt>>>13;y.negative=l.negative^d.negative,y.length=19,A=Math.imul(R,Ke),x=Math.imul(R,Ge),x=x+Math.imul(X,Ke)|0,N=Math.imul(X,Ge);var Qr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Qr>>>26)|0,Qr&=67108863,A=Math.imul(J,Ke),x=Math.imul(J,Ge),x=x+Math.imul(K,Ke)|0,N=Math.imul(K,Ge),A=A+Math.imul(R,It)|0,x=x+Math.imul(R,Ye)|0,x=x+Math.imul(X,It)|0,N=N+Math.imul(X,Ye)|0;var Zr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,A=Math.imul(G,Ke),x=Math.imul(G,Ge),x=x+Math.imul(re,Ke)|0,N=Math.imul(re,Ge),A=A+Math.imul(J,It)|0,x=x+Math.imul(J,Ye)|0,x=x+Math.imul(K,It)|0,N=N+Math.imul(K,Ye)|0,A=A+Math.imul(R,Ot)|0,x=x+Math.imul(R,Ze)|0,x=x+Math.imul(X,Ot)|0,N=N+Math.imul(X,Ze)|0;var Xr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,A=Math.imul(he,Ke),x=Math.imul(he,Ge),x=x+Math.imul(ge,Ke)|0,N=Math.imul(ge,Ge),A=A+Math.imul(G,It)|0,x=x+Math.imul(G,Ye)|0,x=x+Math.imul(re,It)|0,N=N+Math.imul(re,Ye)|0,A=A+Math.imul(J,Ot)|0,x=x+Math.imul(J,Ze)|0,x=x+Math.imul(K,Ot)|0,N=N+Math.imul(K,Ze)|0,A=A+Math.imul(R,et)|0,x=x+Math.imul(R,Ne)|0,x=x+Math.imul(X,et)|0,N=N+Math.imul(X,Ne)|0;var ei=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(ei>>>26)|0,ei&=67108863,A=Math.imul(Te,Ke),x=Math.imul(Te,Ge),x=x+Math.imul(Ce,Ke)|0,N=Math.imul(Ce,Ge),A=A+Math.imul(he,It)|0,x=x+Math.imul(he,Ye)|0,x=x+Math.imul(ge,It)|0,N=N+Math.imul(ge,Ye)|0,A=A+Math.imul(G,Ot)|0,x=x+Math.imul(G,Ze)|0,x=x+Math.imul(re,Ot)|0,N=N+Math.imul(re,Ze)|0,A=A+Math.imul(J,et)|0,x=x+Math.imul(J,Ne)|0,x=x+Math.imul(K,et)|0,N=N+Math.imul(K,Ne)|0,A=A+Math.imul(R,tt)|0,x=x+Math.imul(R,Re)|0,x=x+Math.imul(X,tt)|0,N=N+Math.imul(X,Re)|0;var vr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(vr>>>26)|0,vr&=67108863,A=Math.imul($e,Ke),x=Math.imul($e,Ge),x=x+Math.imul(be,Ke)|0,N=Math.imul(be,Ge),A=A+Math.imul(Te,It)|0,x=x+Math.imul(Te,Ye)|0,x=x+Math.imul(Ce,It)|0,N=N+Math.imul(Ce,Ye)|0,A=A+Math.imul(he,Ot)|0,x=x+Math.imul(he,Ze)|0,x=x+Math.imul(ge,Ot)|0,N=N+Math.imul(ge,Ze)|0,A=A+Math.imul(G,et)|0,x=x+Math.imul(G,Ne)|0,x=x+Math.imul(re,et)|0,N=N+Math.imul(re,Ne)|0,A=A+Math.imul(J,tt)|0,x=x+Math.imul(J,Re)|0,x=x+Math.imul(K,tt)|0,N=N+Math.imul(K,Re)|0,A=A+Math.imul(R,ht)|0,x=x+Math.imul(R,Le)|0,x=x+Math.imul(X,ht)|0,N=N+Math.imul(X,Le)|0;var Ai=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Ai>>>26)|0,Ai&=67108863,A=Math.imul(De,Ke),x=Math.imul(De,Ge),x=x+Math.imul(ye,Ke)|0,N=Math.imul(ye,Ge),A=A+Math.imul($e,It)|0,x=x+Math.imul($e,Ye)|0,x=x+Math.imul(be,It)|0,N=N+Math.imul(be,Ye)|0,A=A+Math.imul(Te,Ot)|0,x=x+Math.imul(Te,Ze)|0,x=x+Math.imul(Ce,Ot)|0,N=N+Math.imul(Ce,Ze)|0,A=A+Math.imul(he,et)|0,x=x+Math.imul(he,Ne)|0,x=x+Math.imul(ge,et)|0,N=N+Math.imul(ge,Ne)|0,A=A+Math.imul(G,tt)|0,x=x+Math.imul(G,Re)|0,x=x+Math.imul(re,tt)|0,N=N+Math.imul(re,Re)|0,A=A+Math.imul(J,ht)|0,x=x+Math.imul(J,Le)|0,x=x+Math.imul(K,ht)|0,N=N+Math.imul(K,Le)|0,A=A+Math.imul(R,nt)|0,x=x+Math.imul(R,Fe)|0,x=x+Math.imul(X,nt)|0,N=N+Math.imul(X,Fe)|0;var Mn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Mn>>>26)|0,Mn&=67108863,A=Math.imul(Oe,Ke),x=Math.imul(Oe,Ge),x=x+Math.imul(me,Ke)|0,N=Math.imul(me,Ge),A=A+Math.imul(De,It)|0,x=x+Math.imul(De,Ye)|0,x=x+Math.imul(ye,It)|0,N=N+Math.imul(ye,Ye)|0,A=A+Math.imul($e,Ot)|0,x=x+Math.imul($e,Ze)|0,x=x+Math.imul(be,Ot)|0,N=N+Math.imul(be,Ze)|0,A=A+Math.imul(Te,et)|0,x=x+Math.imul(Te,Ne)|0,x=x+Math.imul(Ce,et)|0,N=N+Math.imul(Ce,Ne)|0,A=A+Math.imul(he,tt)|0,x=x+Math.imul(he,Re)|0,x=x+Math.imul(ge,tt)|0,N=N+Math.imul(ge,Re)|0,A=A+Math.imul(G,ht)|0,x=x+Math.imul(G,Le)|0,x=x+Math.imul(re,ht)|0,N=N+Math.imul(re,Le)|0,A=A+Math.imul(J,nt)|0,x=x+Math.imul(J,Fe)|0,x=x+Math.imul(K,nt)|0,N=N+Math.imul(K,Fe)|0,A=A+Math.imul(R,Qe)|0,x=x+Math.imul(R,qe)|0,x=x+Math.imul(X,Qe)|0,N=N+Math.imul(X,qe)|0;var Ei=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Ei>>>26)|0,Ei&=67108863,A=Math.imul(Be,Ke),x=Math.imul(Be,Ge),x=x+Math.imul(we,Ke)|0,N=Math.imul(we,Ge),A=A+Math.imul(Oe,It)|0,x=x+Math.imul(Oe,Ye)|0,x=x+Math.imul(me,It)|0,N=N+Math.imul(me,Ye)|0,A=A+Math.imul(De,Ot)|0,x=x+Math.imul(De,Ze)|0,x=x+Math.imul(ye,Ot)|0,N=N+Math.imul(ye,Ze)|0,A=A+Math.imul($e,et)|0,x=x+Math.imul($e,Ne)|0,x=x+Math.imul(be,et)|0,N=N+Math.imul(be,Ne)|0,A=A+Math.imul(Te,tt)|0,x=x+Math.imul(Te,Re)|0,x=x+Math.imul(Ce,tt)|0,N=N+Math.imul(Ce,Re)|0,A=A+Math.imul(he,ht)|0,x=x+Math.imul(he,Le)|0,x=x+Math.imul(ge,ht)|0,N=N+Math.imul(ge,Le)|0,A=A+Math.imul(G,nt)|0,x=x+Math.imul(G,Fe)|0,x=x+Math.imul(re,nt)|0,N=N+Math.imul(re,Fe)|0,A=A+Math.imul(J,Qe)|0,x=x+Math.imul(J,qe)|0,x=x+Math.imul(K,Qe)|0,N=N+Math.imul(K,qe)|0,A=A+Math.imul(R,Ht)|0,x=x+Math.imul(R,at)|0,x=x+Math.imul(X,Ht)|0,N=N+Math.imul(X,at)|0;var Cn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Cn>>>26)|0,Cn&=67108863,A=Math.imul(We,Ke),x=Math.imul(We,Ge),x=x+Math.imul(xe,Ke)|0,N=Math.imul(xe,Ge),A=A+Math.imul(Be,It)|0,x=x+Math.imul(Be,Ye)|0,x=x+Math.imul(we,It)|0,N=N+Math.imul(we,Ye)|0,A=A+Math.imul(Oe,Ot)|0,x=x+Math.imul(Oe,Ze)|0,x=x+Math.imul(me,Ot)|0,N=N+Math.imul(me,Ze)|0,A=A+Math.imul(De,et)|0,x=x+Math.imul(De,Ne)|0,x=x+Math.imul(ye,et)|0,N=N+Math.imul(ye,Ne)|0,A=A+Math.imul($e,tt)|0,x=x+Math.imul($e,Re)|0,x=x+Math.imul(be,tt)|0,N=N+Math.imul(be,Re)|0,A=A+Math.imul(Te,ht)|0,x=x+Math.imul(Te,Le)|0,x=x+Math.imul(Ce,ht)|0,N=N+Math.imul(Ce,Le)|0,A=A+Math.imul(he,nt)|0,x=x+Math.imul(he,Fe)|0,x=x+Math.imul(ge,nt)|0,N=N+Math.imul(ge,Fe)|0,A=A+Math.imul(G,Qe)|0,x=x+Math.imul(G,qe)|0,x=x+Math.imul(re,Qe)|0,N=N+Math.imul(re,qe)|0,A=A+Math.imul(J,Ht)|0,x=x+Math.imul(J,at)|0,x=x+Math.imul(K,Ht)|0,N=N+Math.imul(K,at)|0,A=A+Math.imul(R,_t)|0,x=x+Math.imul(R,qt)|0,x=x+Math.imul(X,_t)|0,N=N+Math.imul(X,qt)|0;var Pn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Pn>>>26)|0,Pn&=67108863,A=Math.imul(We,It),x=Math.imul(We,Ye),x=x+Math.imul(xe,It)|0,N=Math.imul(xe,Ye),A=A+Math.imul(Be,Ot)|0,x=x+Math.imul(Be,Ze)|0,x=x+Math.imul(we,Ot)|0,N=N+Math.imul(we,Ze)|0,A=A+Math.imul(Oe,et)|0,x=x+Math.imul(Oe,Ne)|0,x=x+Math.imul(me,et)|0,N=N+Math.imul(me,Ne)|0,A=A+Math.imul(De,tt)|0,x=x+Math.imul(De,Re)|0,x=x+Math.imul(ye,tt)|0,N=N+Math.imul(ye,Re)|0,A=A+Math.imul($e,ht)|0,x=x+Math.imul($e,Le)|0,x=x+Math.imul(be,ht)|0,N=N+Math.imul(be,Le)|0,A=A+Math.imul(Te,nt)|0,x=x+Math.imul(Te,Fe)|0,x=x+Math.imul(Ce,nt)|0,N=N+Math.imul(Ce,Fe)|0,A=A+Math.imul(he,Qe)|0,x=x+Math.imul(he,qe)|0,x=x+Math.imul(ge,Qe)|0,N=N+Math.imul(ge,qe)|0,A=A+Math.imul(G,Ht)|0,x=x+Math.imul(G,at)|0,x=x+Math.imul(re,Ht)|0,N=N+Math.imul(re,at)|0,A=A+Math.imul(J,_t)|0,x=x+Math.imul(J,qt)|0,x=x+Math.imul(K,_t)|0,N=N+Math.imul(K,qt)|0;var Si=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Si>>>26)|0,Si&=67108863,A=Math.imul(We,Ot),x=Math.imul(We,Ze),x=x+Math.imul(xe,Ot)|0,N=Math.imul(xe,Ze),A=A+Math.imul(Be,et)|0,x=x+Math.imul(Be,Ne)|0,x=x+Math.imul(we,et)|0,N=N+Math.imul(we,Ne)|0,A=A+Math.imul(Oe,tt)|0,x=x+Math.imul(Oe,Re)|0,x=x+Math.imul(me,tt)|0,N=N+Math.imul(me,Re)|0,A=A+Math.imul(De,ht)|0,x=x+Math.imul(De,Le)|0,x=x+Math.imul(ye,ht)|0,N=N+Math.imul(ye,Le)|0,A=A+Math.imul($e,nt)|0,x=x+Math.imul($e,Fe)|0,x=x+Math.imul(be,nt)|0,N=N+Math.imul(be,Fe)|0,A=A+Math.imul(Te,Qe)|0,x=x+Math.imul(Te,qe)|0,x=x+Math.imul(Ce,Qe)|0,N=N+Math.imul(Ce,qe)|0,A=A+Math.imul(he,Ht)|0,x=x+Math.imul(he,at)|0,x=x+Math.imul(ge,Ht)|0,N=N+Math.imul(ge,at)|0,A=A+Math.imul(G,_t)|0,x=x+Math.imul(G,qt)|0,x=x+Math.imul(re,_t)|0,N=N+Math.imul(re,qt)|0;var cn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(cn>>>26)|0,cn&=67108863,A=Math.imul(We,et),x=Math.imul(We,Ne),x=x+Math.imul(xe,et)|0,N=Math.imul(xe,Ne),A=A+Math.imul(Be,tt)|0,x=x+Math.imul(Be,Re)|0,x=x+Math.imul(we,tt)|0,N=N+Math.imul(we,Re)|0,A=A+Math.imul(Oe,ht)|0,x=x+Math.imul(Oe,Le)|0,x=x+Math.imul(me,ht)|0,N=N+Math.imul(me,Le)|0,A=A+Math.imul(De,nt)|0,x=x+Math.imul(De,Fe)|0,x=x+Math.imul(ye,nt)|0,N=N+Math.imul(ye,Fe)|0,A=A+Math.imul($e,Qe)|0,x=x+Math.imul($e,qe)|0,x=x+Math.imul(be,Qe)|0,N=N+Math.imul(be,qe)|0,A=A+Math.imul(Te,Ht)|0,x=x+Math.imul(Te,at)|0,x=x+Math.imul(Ce,Ht)|0,N=N+Math.imul(Ce,at)|0,A=A+Math.imul(he,_t)|0,x=x+Math.imul(he,qt)|0,x=x+Math.imul(ge,_t)|0,N=N+Math.imul(ge,qt)|0;var fn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(fn>>>26)|0,fn&=67108863,A=Math.imul(We,tt),x=Math.imul(We,Re),x=x+Math.imul(xe,tt)|0,N=Math.imul(xe,Re),A=A+Math.imul(Be,ht)|0,x=x+Math.imul(Be,Le)|0,x=x+Math.imul(we,ht)|0,N=N+Math.imul(we,Le)|0,A=A+Math.imul(Oe,nt)|0,x=x+Math.imul(Oe,Fe)|0,x=x+Math.imul(me,nt)|0,N=N+Math.imul(me,Fe)|0,A=A+Math.imul(De,Qe)|0,x=x+Math.imul(De,qe)|0,x=x+Math.imul(ye,Qe)|0,N=N+Math.imul(ye,qe)|0,A=A+Math.imul($e,Ht)|0,x=x+Math.imul($e,at)|0,x=x+Math.imul(be,Ht)|0,N=N+Math.imul(be,at)|0,A=A+Math.imul(Te,_t)|0,x=x+Math.imul(Te,qt)|0,x=x+Math.imul(Ce,_t)|0,N=N+Math.imul(Ce,qt)|0;var Cr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,A=Math.imul(We,ht),x=Math.imul(We,Le),x=x+Math.imul(xe,ht)|0,N=Math.imul(xe,Le),A=A+Math.imul(Be,nt)|0,x=x+Math.imul(Be,Fe)|0,x=x+Math.imul(we,nt)|0,N=N+Math.imul(we,Fe)|0,A=A+Math.imul(Oe,Qe)|0,x=x+Math.imul(Oe,qe)|0,x=x+Math.imul(me,Qe)|0,N=N+Math.imul(me,qe)|0,A=A+Math.imul(De,Ht)|0,x=x+Math.imul(De,at)|0,x=x+Math.imul(ye,Ht)|0,N=N+Math.imul(ye,at)|0,A=A+Math.imul($e,_t)|0,x=x+Math.imul($e,qt)|0,x=x+Math.imul(be,_t)|0,N=N+Math.imul(be,qt)|0;var Dn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Dn>>>26)|0,Dn&=67108863,A=Math.imul(We,nt),x=Math.imul(We,Fe),x=x+Math.imul(xe,nt)|0,N=Math.imul(xe,Fe),A=A+Math.imul(Be,Qe)|0,x=x+Math.imul(Be,qe)|0,x=x+Math.imul(we,Qe)|0,N=N+Math.imul(we,qe)|0,A=A+Math.imul(Oe,Ht)|0,x=x+Math.imul(Oe,at)|0,x=x+Math.imul(me,Ht)|0,N=N+Math.imul(me,at)|0,A=A+Math.imul(De,_t)|0,x=x+Math.imul(De,qt)|0,x=x+Math.imul(ye,_t)|0,N=N+Math.imul(ye,qt)|0;var On=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(On>>>26)|0,On&=67108863,A=Math.imul(We,Qe),x=Math.imul(We,qe),x=x+Math.imul(xe,Qe)|0,N=Math.imul(xe,qe),A=A+Math.imul(Be,Ht)|0,x=x+Math.imul(Be,at)|0,x=x+Math.imul(we,Ht)|0,N=N+Math.imul(we,at)|0,A=A+Math.imul(Oe,_t)|0,x=x+Math.imul(Oe,qt)|0,x=x+Math.imul(me,_t)|0,N=N+Math.imul(me,qt)|0;var Rn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Rn>>>26)|0,Rn&=67108863,A=Math.imul(We,Ht),x=Math.imul(We,at),x=x+Math.imul(xe,Ht)|0,N=Math.imul(xe,at),A=A+Math.imul(Be,_t)|0,x=x+Math.imul(Be,qt)|0,x=x+Math.imul(we,_t)|0,N=N+Math.imul(we,qt)|0;var ta=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(ta>>>26)|0,ta&=67108863,A=Math.imul(We,_t),x=Math.imul(We,qt),x=x+Math.imul(xe,_t)|0,N=Math.imul(xe,qt);var co=(v+A|0)+((x&8191)<<13)|0;return v=(N+(x>>>13)|0)+(co>>>26)|0,co&=67108863,S[0]=Qr,S[1]=Zr,S[2]=Xr,S[3]=ei,S[4]=vr,S[5]=Ai,S[6]=Mn,S[7]=Ei,S[8]=Cn,S[9]=Pn,S[10]=Si,S[11]=cn,S[12]=fn,S[13]=Cr,S[14]=Dn,S[15]=On,S[16]=Rn,S[17]=ta,S[18]=co,v!==0&&(S[19]=v,y.length++),y};Math.imul||(F=H);function Y(m,l,d){d.negative=l.negative^m.negative,d.length=m.length+l.length;for(var y=0,C=0,D=0;D>>26)|0,C+=S>>>26,S&=67108863}d.words[D]=v,y=S,S=C}return y!==0?d.words[D]=y:d.length--,d._strip()}function B(m,l,d){return Y(m,l,d)}s.prototype.mulTo=function(l,d){var y,C=this.length+l.length;return this.length===10&&l.length===10?y=F(this,l,d):C<63?y=H(this,l,d):C<1024?y=Y(this,l,d):y=B(this,l,d),y},s.prototype.mul=function(l){var d=new s(null);return d.words=new Array(this.length+l.length),this.mulTo(l,d)},s.prototype.mulf=function(l){var d=new s(null);return d.words=new Array(this.length+l.length),B(this,l,d)},s.prototype.imul=function(l){return this.clone().mulTo(l,this)},s.prototype.imuln=function(l){var d=l<0;d&&(l=-l),i(typeof l=="number"),i(l<67108864);for(var y=0,C=0;C>=26,y+=D/67108864|0,y+=S>>>26,this.words[C]=S&67108863}return y!==0&&(this.words[C]=y,this.length++),d?this.ineg():this},s.prototype.muln=function(l){return this.clone().imuln(l)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(l){var d=W(l);if(d.length===0)return new s(1);for(var y=this,C=0;C=0);var d=l%26,y=(l-d)/26,C=67108863>>>26-d<<26-d,D;if(d!==0){var S=0;for(D=0;D>>26-d}S&&(this.words[D]=S,this.length++)}if(y!==0){for(D=this.length-1;D>=0;D--)this.words[D+y]=this.words[D];for(D=0;D=0);var C;d?C=(d-d%26)/26:C=0;var D=l%26,S=Math.min((l-D)/26,this.length),v=67108863^67108863>>>D<S)for(this.length-=S,x=0;x=0&&(N!==0||x>=C);x--){var ae=this.words[x]|0;this.words[x]=N<<26-D|ae>>>D,N=ae&v}return A&&N!==0&&(A.words[A.length++]=N),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(l,d,y){return i(this.negative===0),this.iushrn(l,d,y)},s.prototype.shln=function(l){return this.clone().ishln(l)},s.prototype.ushln=function(l){return this.clone().iushln(l)},s.prototype.shrn=function(l){return this.clone().ishrn(l)},s.prototype.ushrn=function(l){return this.clone().iushrn(l)},s.prototype.testn=function(l){i(typeof l=="number"&&l>=0);var d=l%26,y=(l-d)/26,C=1<=0);var d=l%26,y=(l-d)/26;if(i(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(d!==0&&y++,this.length=Math.min(y,this.length),d!==0){var C=67108863^67108863>>>d<=67108864;d++)this.words[d]-=67108864,d===this.length-1?this.words[d+1]=1:this.words[d+1]++;return this.length=Math.max(this.length,d+1),this},s.prototype.isubn=function(l){if(i(typeof l=="number"),i(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var d=0;d>26)-(A/67108864|0),this.words[D+y]=S&67108863}for(;D>26,this.words[D+y]=S&67108863;if(v===0)return this._strip();for(i(v===-1),v=0,D=0;D>26,this.words[D]=S&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(l,d){var y=this.length-l.length,C=this.clone(),D=l,S=D.words[D.length-1]|0,v=this._countBits(S);y=26-v,y!==0&&(D=D.ushln(y),C.iushln(y),S=D.words[D.length-1]|0);var A=C.length-D.length,x;if(d!=="mod"){x=new s(null),x.length=A+1,x.words=new Array(x.length);for(var N=0;N=0;R--){var X=(C.words[D.length+R]|0)*67108864+(C.words[D.length+R-1]|0);for(X=Math.min(X/S|0,67108863),C._ishlnsubmul(D,X,R);C.negative!==0;)X--,C.negative=0,C._ishlnsubmul(D,1,R),C.isZero()||(C.negative^=1);x&&(x.words[R]=X)}return x&&x._strip(),C._strip(),d!=="div"&&y!==0&&C.iushrn(y),{div:x||null,mod:C}},s.prototype.divmod=function(l,d,y){if(i(!l.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var C,D,S;return this.negative!==0&&l.negative===0?(S=this.neg().divmod(l,d),d!=="mod"&&(C=S.div.neg()),d!=="div"&&(D=S.mod.neg(),y&&D.negative!==0&&D.iadd(l)),{div:C,mod:D}):this.negative===0&&l.negative!==0?(S=this.divmod(l.neg(),d),d!=="mod"&&(C=S.div.neg()),{div:C,mod:S.mod}):this.negative&l.negative?(S=this.neg().divmod(l.neg(),d),d!=="div"&&(D=S.mod.neg(),y&&D.negative!==0&&D.isub(l)),{div:S.div,mod:D}):l.length>this.length||this.cmp(l)<0?{div:new s(0),mod:this}:l.length===1?d==="div"?{div:this.divn(l.words[0]),mod:null}:d==="mod"?{div:null,mod:new s(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new s(this.modrn(l.words[0]))}:this._wordDiv(l,d)},s.prototype.div=function(l){return this.divmod(l,"div",!1).div},s.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},s.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},s.prototype.divRound=function(l){var d=this.divmod(l);if(d.mod.isZero())return d.div;var y=d.div.negative!==0?d.mod.isub(l):d.mod,C=l.ushrn(1),D=l.andln(1),S=y.cmp(C);return S<0||D===1&&S===0?d.div:d.div.negative!==0?d.div.isubn(1):d.div.iaddn(1)},s.prototype.modrn=function(l){var d=l<0;d&&(l=-l),i(l<=67108863);for(var y=(1<<26)%l,C=0,D=this.length-1;D>=0;D--)C=(y*C+(this.words[D]|0))%l;return d?-C:C},s.prototype.modn=function(l){return this.modrn(l)},s.prototype.idivn=function(l){var d=l<0;d&&(l=-l),i(l<=67108863);for(var y=0,C=this.length-1;C>=0;C--){var D=(this.words[C]|0)+y*67108864;this.words[C]=D/l|0,y=D%l}return this._strip(),d?this.ineg():this},s.prototype.divn=function(l){return this.clone().idivn(l)},s.prototype.egcd=function(l){i(l.negative===0),i(!l.isZero());var d=this,y=l.clone();d.negative!==0?d=d.umod(l):d=d.clone();for(var C=new s(1),D=new s(0),S=new s(0),v=new s(1),A=0;d.isEven()&&y.isEven();)d.iushrn(1),y.iushrn(1),++A;for(var x=y.clone(),N=d.clone();!d.isZero();){for(var ae=0,R=1;!(d.words[0]&R)&&ae<26;++ae,R<<=1);if(ae>0)for(d.iushrn(ae);ae-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(x),D.isub(N)),C.iushrn(1),D.iushrn(1);for(var X=0,V=1;!(y.words[0]&V)&&X<26;++X,V<<=1);if(X>0)for(y.iushrn(X);X-- >0;)(S.isOdd()||v.isOdd())&&(S.iadd(x),v.isub(N)),S.iushrn(1),v.iushrn(1);d.cmp(y)>=0?(d.isub(y),C.isub(S),D.isub(v)):(y.isub(d),S.isub(C),v.isub(D))}return{a:S,b:v,gcd:y.iushln(A)}},s.prototype._invmp=function(l){i(l.negative===0),i(!l.isZero());var d=this,y=l.clone();d.negative!==0?d=d.umod(l):d=d.clone();for(var C=new s(1),D=new s(0),S=y.clone();d.cmpn(1)>0&&y.cmpn(1)>0;){for(var v=0,A=1;!(d.words[0]&A)&&v<26;++v,A<<=1);if(v>0)for(d.iushrn(v);v-- >0;)C.isOdd()&&C.iadd(S),C.iushrn(1);for(var x=0,N=1;!(y.words[0]&N)&&x<26;++x,N<<=1);if(x>0)for(y.iushrn(x);x-- >0;)D.isOdd()&&D.iadd(S),D.iushrn(1);d.cmp(y)>=0?(d.isub(y),C.isub(D)):(y.isub(d),D.isub(C))}var ae;return d.cmpn(1)===0?ae=C:ae=D,ae.cmpn(0)<0&&ae.iadd(l),ae},s.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var d=this.clone(),y=l.clone();d.negative=0,y.negative=0;for(var C=0;d.isEven()&&y.isEven();C++)d.iushrn(1),y.iushrn(1);do{for(;d.isEven();)d.iushrn(1);for(;y.isEven();)y.iushrn(1);var D=d.cmp(y);if(D<0){var S=d;d=y,y=S}else if(D===0||y.cmpn(1)===0)break;d.isub(y)}while(!0);return y.iushln(C)},s.prototype.invm=function(l){return this.egcd(l).a.umod(l)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(l){return this.words[0]&l},s.prototype.bincn=function(l){i(typeof l=="number");var d=l%26,y=(l-d)/26,C=1<>>26,v&=67108863,this.words[S]=v}return D!==0&&(this.words[S]=D,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(l){var d=l<0;if(this.negative!==0&&!d)return-1;if(this.negative===0&&d)return 1;this._strip();var y;if(this.length>1)y=1;else{d&&(l=-l),i(l<=67108863,"Number is too big");var C=this.words[0]|0;y=C===l?0:Cl.length)return 1;if(this.length=0;y--){var C=this.words[y]|0,D=l.words[y]|0;if(C!==D){CD&&(d=1);break}}return d},s.prototype.gtn=function(l){return this.cmpn(l)===1},s.prototype.gt=function(l){return this.cmp(l)===1},s.prototype.gten=function(l){return this.cmpn(l)>=0},s.prototype.gte=function(l){return this.cmp(l)>=0},s.prototype.ltn=function(l){return this.cmpn(l)===-1},s.prototype.lt=function(l){return this.cmp(l)===-1},s.prototype.lten=function(l){return this.cmpn(l)<=0},s.prototype.lte=function(l){return this.cmp(l)<=0},s.prototype.eqn=function(l){return this.cmpn(l)===0},s.prototype.eq=function(l){return this.cmp(l)===0},s.red=function(l){return new L(l)},s.prototype.toRed=function(l){return i(!this.red,"Already a number in reduction context"),i(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},s.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(l){return this.red=l,this},s.prototype.forceRed=function(l){return i(!this.red,"Already a number in reduction context"),this._forceRed(l)},s.prototype.redAdd=function(l){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},s.prototype.redIAdd=function(l){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},s.prototype.redSub=function(l){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},s.prototype.redISub=function(l){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},s.prototype.redShl=function(l){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},s.prototype.redMul=function(l){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},s.prototype.redIMul=function(l){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},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(l){return i(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var z={k256:null,p224:null,p192:null,p25519:null};function j(m,l){this.name=m,this.p=new s(l,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}j.prototype._tmp=function(){var l=new s(null);return l.words=new Array(Math.ceil(this.n/13)),l},j.prototype.ireduce=function(l){var d=l,y;do this.split(d,this.tmp),d=this.imulK(d),d=d.iadd(this.tmp),y=d.bitLength();while(y>this.n);var C=y0?d.isub(this.p):d.strip!==void 0?d.strip():d._strip(),d},j.prototype.split=function(l,d){l.iushrn(this.n,0,d)},j.prototype.imulK=function(l){return l.imul(this.k)};function _(){j.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(_,j),_.prototype.split=function(l,d){for(var y=4194303,C=Math.min(l.length,9),D=0;D>>22,S=v}S>>>=22,l.words[D-10]=S,S===0&&l.length>10?l.length-=10:l.length-=9},_.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var d=0,y=0;y>>=26,l.words[y]=D,d=C}return d!==0&&(l.words[l.length++]=d),l},s._prime=function(l){if(z[l])return z[l];var d;if(l==="k256")d=new _;else if(l==="p224")d=new U;else if(l==="p192")d=new ee;else if(l==="p25519")d=new oe;else throw new Error("Unknown prime "+l);return z[l]=d,d};function L(m){if(typeof m=="string"){var l=s._prime(m);this.m=l.p,this.prime=l}else i(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}L.prototype._verify1=function(l){i(l.negative===0,"red works only with positives"),i(l.red,"red works only with red numbers")},L.prototype._verify2=function(l,d){i((l.negative|d.negative)===0,"red works only with positives"),i(l.red&&l.red===d.red,"red works only with red numbers")},L.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(g(l,l.umod(this.m)._forceRed(this)),l)},L.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},L.prototype.add=function(l,d){this._verify2(l,d);var y=l.add(d);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},L.prototype.iadd=function(l,d){this._verify2(l,d);var y=l.iadd(d);return y.cmp(this.m)>=0&&y.isub(this.m),y},L.prototype.sub=function(l,d){this._verify2(l,d);var y=l.sub(d);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},L.prototype.isub=function(l,d){this._verify2(l,d);var y=l.isub(d);return y.cmpn(0)<0&&y.iadd(this.m),y},L.prototype.shl=function(l,d){return this._verify1(l),this.imod(l.ushln(d))},L.prototype.imul=function(l,d){return this._verify2(l,d),this.imod(l.imul(d))},L.prototype.mul=function(l,d){return this._verify2(l,d),this.imod(l.mul(d))},L.prototype.isqr=function(l){return this.imul(l,l.clone())},L.prototype.sqr=function(l){return this.mul(l,l)},L.prototype.sqrt=function(l){if(l.isZero())return l.clone();var d=this.m.andln(3);if(i(d%2===1),d===3){var y=this.m.add(new s(1)).iushrn(2);return this.pow(l,y)}for(var C=this.m.subn(1),D=0;!C.isZero()&&C.andln(1)===0;)D++,C.iushrn(1);i(!C.isZero());var S=new s(1).toRed(this),v=S.redNeg(),A=this.m.subn(1).iushrn(1),x=this.m.bitLength();for(x=new s(2*x*x).toRed(this);this.pow(x,A).cmp(v)!==0;)x.redIAdd(v);for(var N=this.pow(x,C),ae=this.pow(l,C.addn(1).iushrn(1)),R=this.pow(l,C),X=D;R.cmp(S)!==0;){for(var V=R,J=0;V.cmp(S)!==0;J++)V=V.redSqr();i(J=0;D--){for(var N=d.words[D],ae=x-1;ae>=0;ae--){var R=N>>ae&1;if(S!==C[0]&&(S=this.sqr(S)),R===0&&v===0){A=0;continue}v<<=1,v|=R,A++,!(A!==y&&(D!==0||ae!==0))&&(S=this.mul(S,C[v]),A=0,v=0)}x=26}return S},L.prototype.convertTo=function(l){var d=l.umod(this.m);return d===l?d.clone():d},L.prototype.convertFrom=function(l){var d=l.clone();return d.red=null,d},s.mont=function(l){return new b(l)};function b(m){L.call(this,m),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)}n(b,L),b.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},b.prototype.convertFrom=function(l){var d=this.imod(l.mul(this.rinv));return d.red=null,d},b.prototype.imul=function(l,d){if(l.isZero()||d.isZero())return l.words[0]=0,l.length=1,l;var y=l.imul(d),C=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=y.isub(C).iushrn(this.shift),S=D;return D.cmp(this.m)>=0?S=D.isub(this.m):D.cmpn(0)<0&&(S=D.iadd(this.m)),S._forceRed(this)},b.prototype.mul=function(l,d){if(l.isZero()||d.isZero())return new s(0)._forceRed(this);var y=l.mul(d),C=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=y.isub(C).iushrn(this.shift),S=D;return D.cmp(this.m)>=0?S=D.isub(this.m):D.cmpn(0)<0&&(S=D.iadd(this.m)),S._forceRed(this)},b.prototype.invm=function(l){var d=this.imod(l._invmp(this.m).mul(this.r2));return d._forceRed(this)}})(r,fr)})(Hg);var vt=Hg.exports;const kg="bignumber/5.7.0";var nl=vt.BN;const ds=new xt(kg),rd={},jg=9007199254740991;function c4(r){return r!=null&&(ir.isBigNumber(r)||typeof r=="number"&&r%1===0||typeof r=="string"&&!!r.match(/^-?[0-9]+$/)||Oi(r)||typeof r=="bigint"||wa(r))}let Wg=!1;class ir{constructor(e,t){e!==rd&&ds.throwError("cannot call constructor directly; use BigNumber.from",xt.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=t,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return gi(Tt(this).fromTwos(e))}toTwos(e){return gi(Tt(this).toTwos(e))}abs(){return this._hex[0]==="-"?ir.from(this._hex.substring(1)):this}add(e){return gi(Tt(this).add(Tt(e)))}sub(e){return gi(Tt(this).sub(Tt(e)))}div(e){return ir.from(e).isZero()&&Vi("division-by-zero","div"),gi(Tt(this).div(Tt(e)))}mul(e){return gi(Tt(this).mul(Tt(e)))}mod(e){const t=Tt(e);return t.isNeg()&&Vi("division-by-zero","mod"),gi(Tt(this).umod(t))}pow(e){const t=Tt(e);return t.isNeg()&&Vi("negative-power","pow"),gi(Tt(this).pow(t))}and(e){const t=Tt(e);return(this.isNegative()||t.isNeg())&&Vi("unbound-bitwise-result","and"),gi(Tt(this).and(t))}or(e){const t=Tt(e);return(this.isNegative()||t.isNeg())&&Vi("unbound-bitwise-result","or"),gi(Tt(this).or(t))}xor(e){const t=Tt(e);return(this.isNegative()||t.isNeg())&&Vi("unbound-bitwise-result","xor"),gi(Tt(this).xor(t))}mask(e){return(this.isNegative()||e<0)&&Vi("negative-width","mask"),gi(Tt(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Vi("negative-width","shl"),gi(Tt(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Vi("negative-width","shr"),gi(Tt(this).shrn(e))}eq(e){return Tt(this).eq(Tt(e))}lt(e){return Tt(this).lt(Tt(e))}lte(e){return Tt(this).lte(Tt(e))}gt(e){return Tt(this).gt(Tt(e))}gte(e){return Tt(this).gte(Tt(e))}isNegative(){return this._hex[0]==="-"}isZero(){return Tt(this).isZero()}toNumber(){try{return Tt(this).toNumber()}catch{Vi("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return ds.throwError("this platform does not support BigInt",xt.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?Wg||(Wg=!0,ds.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?ds.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",xt.errors.UNEXPECTED_ARGUMENT,{}):ds.throwError("BigNumber.toString does not accept parameters",xt.errors.UNEXPECTED_ARGUMENT,{})),Tt(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof ir)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new ir(rd,Rc(e)):e.match(/^-?[0-9]+$/)?new ir(rd,Rc(new nl(e))):ds.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Vi("underflow","BigNumber.from",e),(e>=jg||e<=-jg)&&Vi("overflow","BigNumber.from",e),ir.from(String(e));const t=e;if(typeof t=="bigint")return ir.from(t.toString());if(wa(t))return ir.from(ii(t));if(t)if(t.toHexString){const i=t.toHexString();if(typeof i=="string")return ir.from(i)}else{let i=t._hex;if(i==null&&t.type==="BigNumber"&&(i=t.hex),typeof i=="string"&&(Oi(i)||i[0]==="-"&&Oi(i.substring(1))))return ir.from(i)}return ds.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}}function Rc(r){if(typeof r!="string")return Rc(r.toString(16));if(r[0]==="-")return r=r.substring(1),r[0]==="-"&&ds.throwArgumentError("invalid hex","value",r),r=Rc(r),r==="0x00"?r:"-"+r;if(r.substring(0,2)!=="0x"&&(r="0x"+r),r==="0x")return"0x00";for(r.length%2&&(r="0x0"+r.substring(2));r.length>4&&r.substring(0,4)==="0x00";)r="0x"+r.substring(4);return r}function gi(r){return ir.from(Rc(r))}function Tt(r){const e=ir.from(r).toHexString();return e[0]==="-"?new nl("-"+e.substring(3),16):new nl(e.substring(2),16)}function Vi(r,e,t){const i={fault:r,operation:e};return t!=null&&(i.value=t),ds.throwError(r,xt.errors.NUMERIC_FAULT,i)}function f4(r){return new nl(r,36).toString(16)}const ni=new xt(kg),Tc={},Kg=ir.from(0),Vg=ir.from(-1);function Gg(r,e,t,i){const n={fault:e,operation:t};return i!==void 0&&(n.value=i),ni.throwError(r,xt.errors.NUMERIC_FAULT,n)}let $c="0";for(;$c.length<256;)$c+=$c;function id(r){if(typeof r!="number")try{r=ir.from(r).toNumber()}catch{}return typeof r=="number"&&r>=0&&r<=256&&!(r%1)?"1"+$c.substring(0,r):ni.throwArgumentError("invalid decimal size","decimals",r)}function nd(r,e){e==null&&(e=0);const t=id(e);r=ir.from(r);const i=r.lt(Kg);i&&(r=r.mul(Vg));let n=r.mod(t).toString();for(;n.length2&&ni.throwArgumentError("too many decimal points","value",r);let s=n[0],a=n[1];for(s||(s="0"),a||(a="0");a[a.length-1]==="0";)a=a.substring(0,a.length-1);for(a.length>t.length-1&&Gg("fractional component exceeds decimals","underflow","parseFixed"),a===""&&(a="0");a.lengthe[a]==null?h:(typeof e[a]!==f&&ni.throwArgumentError("invalid fixed format ("+a+" not "+f+")","format."+a,e[a]),e[a]);t=s("signed","boolean",t),i=s("width","number",i),n=s("decimals","number",n)}return i%8&&ni.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",i),n>80&&ni.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",n),new ya(Tc,t,i,n)}}class zr{constructor(e,t,i,n){e!==Tc&&ni.throwError("cannot use FixedNumber constructor; use FixedNumber.from",xt.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=n,this._hex=t,this._value=i,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&ni.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);const t=ps(this._value,this.format.decimals),i=ps(e._value,e.format.decimals);return zr.fromValue(t.add(i),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);const t=ps(this._value,this.format.decimals),i=ps(e._value,e.format.decimals);return zr.fromValue(t.sub(i),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);const t=ps(this._value,this.format.decimals),i=ps(e._value,e.format.decimals);return zr.fromValue(t.mul(i).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);const t=ps(this._value,this.format.decimals),i=ps(e._value,e.format.decimals);return zr.fromValue(t.mul(this.format._multiplier).div(i),this.format.decimals,this.format)}floor(){const e=this.toString().split(".");e.length===1&&e.push("0");let t=zr.from(e[0],this.format);const i=!e[1].match(/^(0*)$/);return this.isNegative()&&i&&(t=t.subUnsafe(Yg.toFormat(t.format))),t}ceiling(){const e=this.toString().split(".");e.length===1&&e.push("0");let t=zr.from(e[0],this.format);const i=!e[1].match(/^(0*)$/);return!this.isNegative()&&i&&(t=t.addUnsafe(Yg.toFormat(t.format))),t}round(e){e==null&&(e=0);const t=this.toString().split(".");if(t.length===1&&t.push("0"),(e<0||e>80||e%1)&&ni.throwArgumentError("invalid decimal count","decimals",e),t[1].length<=e)return this;const i=zr.from("1"+$c.substring(0,e),this.format),n=l4.toFormat(this.format);return this.mulUnsafe(i).addUnsafe(n).floor().divUnsafe(i)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&ni.throwArgumentError("invalid byte width","width",e);const t=ir.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return Fn(t,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return zr.fromString(this._value,e)}static fromValue(e,t,i){return i==null&&t!=null&&!c4(t)&&(i=t,t=null),t==null&&(t=0),i==null&&(i="fixed"),zr.fromString(nd(e,t),ya.from(i))}static fromString(e,t){t==null&&(t="fixed");const i=ya.from(t),n=ps(e,i.decimals);!i.signed&&n.lt(Kg)&&Gg("unsigned value cannot be negative","overflow","value",e);let s=null;i.signed?s=n.toTwos(i.width).toHexString():(s=n.toHexString(),s=Fn(s,i.width/8));const a=nd(n,i.decimals);return new zr(Tc,s,a,i)}static fromBytes(e,t){t==null&&(t="fixed");const i=ya.from(t);if(ur(e).length>i.width/8)throw new Error("overflow");let n=ir.from(e);i.signed&&(n=n.fromTwos(i.width));const s=n.toTwos((i.signed?0:1)+i.width).toHexString(),a=nd(n,i.decimals);return new zr(Tc,s,a,i)}static from(e,t){if(typeof e=="string")return zr.fromString(e,t);if(wa(e))return zr.fromBytes(e,t);try{return zr.fromValue(e,0,t)}catch(i){if(i.code!==xt.errors.INVALID_ARGUMENT)throw i}return ni.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}}const Yg=zr.from(1),l4=zr.from("0.5"),h4="strings/5.7.0",Jg=new xt(h4);var sl;(function(r){r.current="",r.NFC="NFC",r.NFD="NFD",r.NFKC="NFKC",r.NFKD="NFKD"})(sl||(sl={}));var _a;(function(r){r.UNEXPECTED_CONTINUE="unexpected continuation byte",r.BAD_PREFIX="bad codepoint prefix",r.OVERRUN="string overrun",r.MISSING_CONTINUE="missing continuation byte",r.OUT_OF_RANGE="out of UTF-8 range",r.UTF16_SURROGATE="UTF-16 surrogate",r.OVERLONG="overlong representation"})(_a||(_a={}));function u4(r,e,t,i,n){return Jg.throwArgumentError(`invalid codepoint at offset ${e}; ${r}`,"bytes",t)}function Qg(r,e,t,i,n){if(r===_a.BAD_PREFIX||r===_a.UNEXPECTED_CONTINUE){let s=0;for(let a=e+1;a>6===2;a++)s++;return s}return r===_a.OVERRUN?t.length-e-1:0}function d4(r,e,t,i,n){return r===_a.OVERLONG?(i.push(n),0):(i.push(65533),Qg(r,e,t))}Object.freeze({error:u4,ignore:Qg,replace:d4});function sd(r,e=sl.current){e!=sl.current&&(Jg.checkNormalize(),r=r.normalize(e));let t=[];for(let i=0;i>6|192),t.push(n&63|128);else if((n&64512)==55296){i++;const s=r.charCodeAt(i);if(i>=r.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");const a=65536+((n&1023)<<10)+(s&1023);t.push(a>>18|240),t.push(a>>12&63|128),t.push(a>>6&63|128),t.push(a&63|128)}else t.push(n>>12|224),t.push(n>>6&63|128),t.push(n&63|128)}return ur(t)}function p4(r){if(r.length%4!==0)throw new Error("bad data");let e=[];for(let t=0;t{let s=n.split(":");t+=parseInt(s[0],16),i[t]=e(s[1])}),i}function Zg(r){let e=0;return r.split(",").map(t=>{let i=t.split("-");i.length===1?i[1]="0":i[1]===""&&(i[1]="1");let n=e+parseInt(i[0],16);return e=parseInt(i[1],16),{l:n,h:e}})}Zg("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(r=>parseInt(r,16)),od("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),od("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),od("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",p4),Zg("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");const Xg="hash/5.7.0";function g4(r){r=atob(r);const e=[];for(let t=0;t0&&Array.isArray(f)?n(f,a-1):t.push(f)})};return n(r,e),t}function v4(r){const e={};for(let t=0;t>--h&1}const w=31,P=Math.pow(2,w),M=P>>>1,O=M>>1,$=P-1;let W=0;for(let z=0;z1;){let oe=j+_>>>1;z>>1|g(),U=U<<1^M,ee=(ee^M)<<1|M|1;F=U,Y=1+ee-U}let B=i-4;return H.map(z=>{switch(z-B){case 3:return B+65792+(r[f++]<<16|r[f++]<<8|r[f++]);case 2:return B+256+(r[f++]<<8|r[f++]);case 1:return B+r[f++];default:return z-1}})}function b4(r){let e=0;return()=>r[e++]}function w4(r){return b4(m4(r))}function y4(r){return r&1?~r>>1:r>>1}function _4(r,e){let t=Array(r);for(let i=0;ie[a]):t}function A4(r){let e=[];for(;;){let t=r();if(t==0)break;e.push(S4(t,r))}for(;;){let t=r()-1;if(t<0)break;e.push(I4(t,r))}return v4(ev(e))}function E4(r){let e=[];for(;;){let t=r();if(t==0)break;e.push(t)}return e}function rv(r,e,t){let i=Array(r).fill(void 0).map(()=>[]);for(let n=0;ni[a].push(s));return i}function S4(r,e){let t=1+e(),i=e(),n=E4(e),s=rv(n.length,1+r,e);return ev(s.map((a,f)=>{const h=a[0],u=a.slice(1);return Array(n[f]).fill(void 0).map((g,w)=>{let P=w*i;return[h+w*t,u.map(M=>M+P)]})}))}function I4(r,e){let t=1+e();return rv(t,1+r,e).map(n=>[n[0],n.slice(1)])}function M4(r){let e=ol(r).sort((i,n)=>i-n);return t();function t(){let i=[];for(;;){let u=ol(r,e);if(u.length==0)break;i.push({set:new Set(u),node:t()})}i.sort((u,g)=>g.set.size-u.set.size);let n=r(),s=n%3;n=n/3|0;let a=!!(n&1);n>>=1;let f=n==1,h=n==2;return{branches:i,valid:s,fe0f:a,save:f,check:h}}}function C4(){return w4(g4("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}const al=C4();new Set(ol(al)),new Set(ol(al)),A4(al),M4(al),new xt(Xg),new Uint8Array(32).fill(0);const P4=`Ethereum Signed Message: +-`;function iv(r){return typeof r=="string"&&(r=sd(r)),td(i4([sd(P4),sd(String(r.length)),r]))}const D4="rlp/5.7.0";new xt(D4);const O4="address/5.7.0",Nc=new xt(O4);function nv(r){Oi(r,20)||Nc.throwArgumentError("invalid address","address",r),r=r.toLowerCase();const e=r.substring(2).split(""),t=new Uint8Array(40);for(let n=0;n<40;n++)t[n]=e[n].charCodeAt(0);const i=ur(td(t));for(let n=0;n<40;n+=2)i[n>>1]>>4>=8&&(e[n]=e[n].toUpperCase()),(i[n>>1]&15)>=8&&(e[n+1]=e[n+1].toUpperCase());return"0x"+e.join("")}const R4=9007199254740991;function T4(r){return Math.log10?Math.log10(r):Math.log(r)/Math.LN10}const ad={};for(let r=0;r<10;r++)ad[String(r)]=String(r);for(let r=0;r<26;r++)ad[String.fromCharCode(65+r)]=String(10+r);const sv=Math.floor(T4(R4));function $4(r){r=r.toUpperCase(),r=r.substring(4)+r.substring(0,2)+"00";let e=r.split("").map(i=>ad[i]).join("");for(;e.length>=sv;){let i=e.substring(0,sv);e=parseInt(i,10)%97+e.substring(i.length)}let t=String(98-parseInt(e,10)%97);for(;t.length<2;)t="0"+t;return t}function N4(r){let e=null;if(typeof r!="string"&&Nc.throwArgumentError("invalid address","address",r),r.match(/^(0x)?[0-9a-fA-F]{40}$/))r.substring(0,2)!=="0x"&&(r="0x"+r),e=nv(r),r.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==r&&Nc.throwArgumentError("bad address checksum","address",r);else if(r.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(r.substring(2,4)!==$4(r)&&Nc.throwArgumentError("bad icap checksum","address",r),e=f4(r.substring(4));e.length<40;)e="0"+e;e=nv("0x"+e)}else Nc.throwArgumentError("invalid address","address",r);return e}const L4="properties/5.7.0";new xt(L4);function Lc(r,e,t){Object.defineProperty(r,e,{enumerable:!0,value:t,writable:!1})}new xt(Xg),new Uint8Array(32).fill(0),ir.from(-1);const B4=ir.from(0),F4=ir.from(1);ir.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Fn(F4.toHexString(),32),Fn(B4.toHexString(),32);var Ri={},$t={},Ao=ov;function ov(r,e){if(!r)throw new Error(e||"Assertion failed")}ov.equal=function(e,t,i){if(e!=t)throw new Error(i||"Assertion failed: "+e+" != "+t)};var xa={exports:{}};typeof Object.create=="function"?xa.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:xa.exports=function(e,t){if(t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}};var U4=Ao,q4=xa.exports;$t.inherits=q4;function z4(r,e){return(r.charCodeAt(e)&64512)!==55296||e<0||e+1>=r.length?!1:(r.charCodeAt(e+1)&64512)===56320}function H4(r,e){if(Array.isArray(r))return r.slice();if(!r)return[];var t=[];if(typeof r=="string")if(e){if(e==="hex")for(r=r.replace(/[^a-z0-9]+/ig,""),r.length%2!==0&&(r="0"+r),n=0;n>6|192,t[i++]=s&63|128):z4(r,n)?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),t[i++]=s>>18|240,t[i++]=s>>12&63|128,t[i++]=s>>6&63|128,t[i++]=s&63|128):(t[i++]=s>>12|224,t[i++]=s>>6&63|128,t[i++]=s&63|128)}else for(n=0;n>>24|r>>>8&65280|r<<8&16711680|(r&255)<<24;return e>>>0}$t.htonl=av;function j4(r,e){for(var t="",i=0;i>>0}return s}$t.join32=W4;function K4(r,e){for(var t=new Array(r.length*4),i=0,n=0;i>>24,t[n+1]=s>>>16&255,t[n+2]=s>>>8&255,t[n+3]=s&255):(t[n+3]=s>>>24,t[n+2]=s>>>16&255,t[n+1]=s>>>8&255,t[n]=s&255)}return t}$t.split32=K4;function V4(r,e){return r>>>e|r<<32-e}$t.rotr32=V4;function G4(r,e){return r<>>32-e}$t.rotl32=G4;function Y4(r,e){return r+e>>>0}$t.sum32=Y4;function J4(r,e,t){return r+e+t>>>0}$t.sum32_3=J4;function Q4(r,e,t,i){return r+e+t+i>>>0}$t.sum32_4=Q4;function Z4(r,e,t,i,n){return r+e+t+i+n>>>0}$t.sum32_5=Z4;function X4(r,e,t,i){var n=r[e],s=r[e+1],a=i+s>>>0,f=(a>>0,r[e+1]=a}$t.sum64=X4;function e8(r,e,t,i){var n=e+i>>>0,s=(n>>0}$t.sum64_hi=e8;function t8(r,e,t,i){var n=e+i;return n>>>0}$t.sum64_lo=t8;function r8(r,e,t,i,n,s,a,f){var h=0,u=e;u=u+i>>>0,h+=u>>0,h+=u>>0,h+=u>>0}$t.sum64_4_hi=r8;function i8(r,e,t,i,n,s,a,f){var h=e+i+s+f;return h>>>0}$t.sum64_4_lo=i8;function n8(r,e,t,i,n,s,a,f,h,u){var g=0,w=e;w=w+i>>>0,g+=w>>0,g+=w>>0,g+=w>>0,g+=w>>0}$t.sum64_5_hi=n8;function s8(r,e,t,i,n,s,a,f,h,u){var g=e+i+s+f+u;return g>>>0}$t.sum64_5_lo=s8;function o8(r,e,t){var i=e<<32-t|r>>>t;return i>>>0}$t.rotr64_hi=o8;function a8(r,e,t){var i=r<<32-t|e>>>t;return i>>>0}$t.rotr64_lo=a8;function c8(r,e,t){return r>>>t}$t.shr64_hi=c8;function f8(r,e,t){var i=r<<32-t|e>>>t;return i>>>0}$t.shr64_lo=f8;var Aa={},lv=$t,l8=Ao;function cl(){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}Aa.BlockHash=cl,cl.prototype.update=function(e,t){if(e=lv.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){e=this.pending;var i=e.length%this._delta8;this.pending=e.slice(e.length-i,e.length),this.pending.length===0&&(this.pending=null),e=lv.join32(e,0,e.length-i,this.endian);for(var n=0;n>>24&255,n[s++]=e>>>16&255,n[s++]=e>>>8&255,n[s++]=e&255}else for(n[s++]=e&255,n[s++]=e>>>8&255,n[s++]=e>>>16&255,n[s++]=e>>>24&255,n[s++]=0,n[s++]=0,n[s++]=0,n[s++]=0,a=8;a>>3}Un.g0_256=g8;function v8(r){return qn(r,17)^qn(r,19)^r>>>10}Un.g1_256=v8;var Sa=$t,m8=Aa,b8=Un,cd=Sa.rotl32,Bc=Sa.sum32,w8=Sa.sum32_5,y8=b8.ft_1,pv=m8.BlockHash,_8=[1518500249,1859775393,2400959708,3395469782];function zn(){if(!(this instanceof zn))return new zn;pv.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Sa.inherits(zn,pv);var x8=zn;zn.blockSize=512,zn.outSize=160,zn.hmacStrength=80,zn.padLength=64,zn.prototype._update=function(e,t){for(var i=this.W,n=0;n<16;n++)i[n]=e[t+n];for(;nthis.blockSize&&(e=new this.Hash().update(e).digest()),f_(e.length<=this.blockSize);for(var t=e.length;t>8,P=g&255;w?h.push(w,P):h.push(P)}return h}t.toArray=i;function n(a){return a.length===1?"0"+a:a}t.zero2=n;function s(a){for(var f="",h=0;h(P>>1)-1?$=(P>>1)-W:$=W,M.isubn($)):$=0,w[O]=$,M.iushrn(1)}return w}t.getNAF=i;function n(h,u){var g=[[],[]];h=h.clone(),u=u.clone();for(var w=0,P=0,M;h.cmpn(-w)>0||u.cmpn(-P)>0;){var O=h.andln(3)+w&3,$=u.andln(3)+P&3;O===3&&(O=-1),$===3&&($=-1);var W;O&1?(M=h.andln(7)+w&7,(M===3||M===5)&&$===2?W=-O:W=O):W=0,g[0].push(W);var H;$&1?(M=u.andln(7)+P&7,(M===3||M===5)&&O===2?H=-$:H=$):H=0,g[1].push(H),2*w===W+1&&(w=1-w),2*P===H+1&&(P=1-P),h.iushrn(1),u.iushrn(1)}return g}t.getJSF=n;function s(h,u,g){var w="_"+u;h.prototype[u]=function(){return this[w]!==void 0?this[w]:this[w]=g.call(this)}}t.cachedProperty=s;function a(h){return typeof h=="string"?t.toArray(h,"hex"):h}t.parseBytes=a;function f(h){return new vt(h,"hex","le")}t.intFromLE=f}),ll=Ti.getNAF,u_=Ti.getJSF,hl=Ti.assert;function Us(r,e){this.type=r,this.p=new vt(e.p,16),this.red=e.prime?vt.red(e.prime):vt.mont(this.p),this.zero=new vt(0).toRed(this.red),this.one=new vt(1).toRed(this.red),this.two=new vt(2).toRed(this.red),this.n=e.n&&new vt(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.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 t=this.n&&this.p.div(this.n);!t||t.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var So=Us;Us.prototype.point=function(){throw new Error("Not implemented")},Us.prototype.validate=function(){throw new Error("Not implemented")},Us.prototype._fixedNafMul=function(e,t){hl(e.precomputed);var i=e._getDoubles(),n=ll(t,1,this._bitLength),s=(1<=f;u--)h=(h<<1)+n[u];a.push(h)}for(var g=this.jpoint(null,null,null),w=this.jpoint(null,null,null),P=s;P>0;P--){for(f=0;f=0;h--){for(var u=0;h>=0&&a[h]===0;h--)u++;if(h>=0&&u++,f=f.dblp(u),h<0)break;var g=a[h];hl(g!==0),e.type==="affine"?g>0?f=f.mixedAdd(s[g-1>>1]):f=f.mixedAdd(s[-g-1>>1].neg()):g>0?f=f.add(s[g-1>>1]):f=f.add(s[-g-1>>1].neg())}return e.type==="affine"?f.toP():f},Us.prototype._wnafMulAdd=function(e,t,i,n,s){var a=this._wnafT1,f=this._wnafT2,h=this._wnafT3,u=0,g,w,P;for(g=0;g=1;g-=2){var O=g-1,$=g;if(a[O]!==1||a[$]!==1){h[O]=ll(i[O],a[O],this._bitLength),h[$]=ll(i[$],a[$],this._bitLength),u=Math.max(h[O].length,u),u=Math.max(h[$].length,u);continue}var W=[t[O],null,null,t[$]];t[O].y.cmp(t[$].y)===0?(W[1]=t[O].add(t[$]),W[2]=t[O].toJ().mixedAdd(t[$].neg())):t[O].y.cmp(t[$].y.redNeg())===0?(W[1]=t[O].toJ().mixedAdd(t[$]),W[2]=t[O].add(t[$].neg())):(W[1]=t[O].toJ().mixedAdd(t[$]),W[2]=t[O].toJ().mixedAdd(t[$].neg()));var H=[-3,-1,-5,-7,0,7,5,1,3],F=u_(i[O],i[$]);for(u=Math.max(F[0].length,u),h[O]=new Array(u),h[$]=new Array(u),w=0;w=0;g--){for(var _=0;g>=0;){var U=!0;for(w=0;w=0&&_++,z=z.dblp(_),g<0)break;for(w=0;w0?P=f[w][ee-1>>1]:ee<0&&(P=f[w][-ee-1>>1].neg()),P.type==="affine"?z=z.mixedAdd(P):z=z.add(P))}}for(g=0;g=Math.ceil((e.bitLength()+1)/t.step):!1},Gi.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var i=[this],n=this,s=0;s=0&&(M=u,O=g),w.negative&&(w=w.neg(),P=P.neg()),M.negative&&(M=M.neg(),O=O.neg()),[{a:w,b:P},{a:M,b:O}]},Yi.prototype._endoSplit=function(e){var t=this.endo.basis,i=t[0],n=t[1],s=n.b.mul(e).divRound(this.n),a=i.b.neg().mul(e).divRound(this.n),f=s.mul(i.a),h=a.mul(n.a),u=s.mul(i.b),g=a.mul(n.b),w=e.sub(f).sub(h),P=u.add(g).neg();return{k1:w,k2:P}},Yi.prototype.pointFromX=function(e,t){e=new vt(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=i.redSqrt();if(n.redSqr().redSub(i).cmp(this.zero)!==0)throw new Error("invalid point");var s=n.fromRed().isOdd();return(t&&!s||!t&&s)&&(n=n.redNeg()),this.point(e,n)},Yi.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,i=e.y,n=this.a.redMul(t),s=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return i.redSqr().redISub(s).cmpn(0)===0},Yi.prototype._endoWnafMulAdd=function(e,t,i){for(var n=this._endoWnafT1,s=this._endoWnafT2,a=0;a":""},Or.prototype.isInfinity=function(){return this.inf},Or.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(this.x.cmp(e.x)===0)return this.curve.point(null,null);var t=this.y.redSub(e.y);t.cmpn(0)!==0&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var i=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(i)).redISub(this.y);return this.curve.point(i,n)},Or.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(e.cmpn(0)===0)return this.curve.point(null,null);var t=this.curve.a,i=this.x.redSqr(),n=e.redInvm(),s=i.redAdd(i).redIAdd(i).redIAdd(t).redMul(n),a=s.redSqr().redISub(this.x.redAdd(this.x)),f=s.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,f)},Or.prototype.getX=function(){return this.x.fromRed()},Or.prototype.getY=function(){return this.y.fromRed()},Or.prototype.mul=function(e){return e=new vt(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)},Or.prototype.mulAdd=function(e,t,i){var n=[this,t],s=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,s):this.curve._wnafMulAdd(1,n,s,2)},Or.prototype.jmulAdd=function(e,t,i){var n=[this,t],s=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,s,!0):this.curve._wnafMulAdd(1,n,s,2,!0)},Or.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||this.x.cmp(e.x)===0&&this.y.cmp(e.y)===0)},Or.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var i=this.precomputed,n=function(s){return s.neg()};t.precomputed={naf:i.naf&&{wnd:i.naf.wnd,points:i.naf.points.map(n)},doubles:i.doubles&&{step:i.doubles.step,points:i.doubles.points.map(n)}}}return t},Or.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var e=this.curve.jpoint(this.x,this.y,this.curve.one);return e};function Hr(r,e,t,i){So.BasePoint.call(this,r,"jacobian"),e===null&&t===null&&i===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new vt(0)):(this.x=new vt(e,16),this.y=new vt(t,16),this.z=new vt(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}pd(Hr,So.BasePoint),Yi.prototype.jpoint=function(e,t,i){return new Hr(this,e,t,i)},Hr.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),i=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(i,n)},Hr.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Hr.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),i=this.z.redSqr(),n=this.x.redMul(t),s=e.x.redMul(i),a=this.y.redMul(t.redMul(e.z)),f=e.y.redMul(i.redMul(this.z)),h=n.redSub(s),u=a.redSub(f);if(h.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var g=h.redSqr(),w=g.redMul(h),P=n.redMul(g),M=u.redSqr().redIAdd(w).redISub(P).redISub(P),O=u.redMul(P.redISub(M)).redISub(a.redMul(w)),$=this.z.redMul(e.z).redMul(h);return this.curve.jpoint(M,O,$)},Hr.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),i=this.x,n=e.x.redMul(t),s=this.y,a=e.y.redMul(t).redMul(this.z),f=i.redSub(n),h=s.redSub(a);if(f.cmpn(0)===0)return h.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var u=f.redSqr(),g=u.redMul(f),w=i.redMul(u),P=h.redSqr().redIAdd(g).redISub(w).redISub(w),M=h.redMul(w.redISub(P)).redISub(s.redMul(g)),O=this.z.redMul(f);return this.curve.jpoint(P,M,O)},Hr.prototype.dblp=function(e){if(e===0)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var i=this;for(t=0;t=0)return!1;if(i.redIAdd(s),this.x.cmp(i)===0)return!0}},Hr.prototype.inspect=function(){return this.isInfinity()?"":""},Hr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var ul=Pa(function(r,e){var t=e;t.base=So,t.short=p_,t.mont=null,t.edwards=null}),dl=Pa(function(r,e){var t=e,i=Ti.assert;function n(f){f.type==="short"?this.curve=new ul.short(f):f.type==="edwards"?this.curve=new ul.edwards(f):this.curve=new ul.mont(f),this.g=this.curve.g,this.n=this.curve.n,this.hash=f.hash,i(this.g.validate(),"Invalid curve"),i(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}t.PresetCurve=n;function s(f,h){Object.defineProperty(t,f,{configurable:!0,enumerable:!0,get:function(){var u=new n(h);return Object.defineProperty(t,f,{configurable:!0,enumerable:!0,value:u}),u}})}s("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:Ri.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("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:Ri.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("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:Ri.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("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:Ri.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"]}),s("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:Ri.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"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Ri.sha256,gRed:!1,g:["9"]}),s("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:Ri.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var a;try{a=null.crash()}catch{a=void 0}s("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:Ri.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",a]})});function qs(r){if(!(this instanceof qs))return new qs(r);this.hash=r.hash,this.predResist=!!r.predResist,this.outLen=this.hash.outSize,this.minEntropy=r.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=xn.toArray(r.entropy,r.entropyEnc||"hex"),t=xn.toArray(r.nonce,r.nonceEnc||"hex"),i=xn.toArray(r.pers,r.persEnc||"hex");dd(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,t,i)}var Pv=qs;qs.prototype._init=function(e,t,i){var n=e.concat(t).concat(i);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var s=0;s=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(i||[])),this._reseed=1},qs.prototype.generate=function(e,t,i,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof t!="string"&&(n=i,i=t,t=null),i&&(i=xn.toArray(i,n||"hex"),this._update(i));for(var s=[];s.length"};var g_=Ti.assert;function pl(r,e){if(r instanceof pl)return r;this._importDER(r,e)||(g_(r.r&&r.s,"Signature without r or s"),this.r=new vt(r.r,16),this.s=new vt(r.s,16),r.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=r.recoveryParam)}var gl=pl;function v_(){this.place=0}function md(r,e){var t=r[e.place++];if(!(t&128))return t;var i=t&15;if(i===0||i>4)return!1;for(var n=0,s=0,a=e.place;s>>=0;return n<=127?!1:(e.place=a,n)}function Dv(r){for(var e=0,t=r.length-1;!r[e]&&!(r[e+1]&128)&&e>>3);for(r.push(t|128);--t;)r.push(e>>>(t<<3)&255);r.push(e)}pl.prototype.toDER=function(e){var t=this.r.toArray(),i=this.s.toArray();for(t[0]&128&&(t=[0].concat(t)),i[0]&128&&(i=[0].concat(i)),t=Dv(t),i=Dv(i);!i[0]&&!(i[1]&128);)i=i.slice(1);var n=[2];bd(n,t.length),n=n.concat(t),n.push(2),bd(n,i.length);var s=n.concat(i),a=[48];return bd(a,s.length),a=a.concat(s),Ti.encode(a,e)};var m_=function(){throw new Error("unsupported")},Ov=Ti.assert;function Ji(r){if(!(this instanceof Ji))return new Ji(r);typeof r=="string"&&(Ov(Object.prototype.hasOwnProperty.call(dl,r),"Unknown curve "+r),r=dl[r]),r instanceof dl.PresetCurve&&(r={curve:r}),this.curve=r.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=r.curve.g,this.g.precompute(r.curve.n.bitLength()+1),this.hash=r.hash||r.curve.hash}var b_=Ji;Ji.prototype.keyPair=function(e){return new vd(this,e)},Ji.prototype.keyFromPrivate=function(e,t){return vd.fromPrivate(this,e,t)},Ji.prototype.keyFromPublic=function(e,t){return vd.fromPublic(this,e,t)},Ji.prototype.genKeyPair=function(e){e||(e={});for(var t=new Pv({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||m_(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),i=this.n.byteLength(),n=this.n.sub(new vt(2));;){var s=new vt(t.generate(i));if(!(s.cmp(n)>0))return s.iaddn(1),this.keyFromPrivate(s)}},Ji.prototype._truncateToN=function(e,t){var i=e.byteLength()*8-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},Ji.prototype.sign=function(e,t,i,n){typeof i=="object"&&(n=i,i=null),n||(n={}),t=this.keyFromPrivate(t,i),e=this._truncateToN(new vt(e,16));for(var s=this.n.byteLength(),a=t.getPrivate().toArray("be",s),f=e.toArray("be",s),h=new Pv({hash:this.hash,entropy:a,nonce:f,pers:n.pers,persEnc:n.persEnc||"utf8"}),u=this.n.sub(new vt(1)),g=0;;g++){var w=n.k?n.k(g):new vt(h.generate(this.n.byteLength()));if(w=this._truncateToN(w,!0),!(w.cmpn(1)<=0||w.cmp(u)>=0)){var P=this.g.mul(w);if(!P.isInfinity()){var M=P.getX(),O=M.umod(this.n);if(O.cmpn(0)!==0){var $=w.invm(this.n).mul(O.mul(t.getPrivate()).iadd(e));if($=$.umod(this.n),$.cmpn(0)!==0){var W=(P.getY().isOdd()?1:0)|(M.cmp(O)!==0?2:0);return n.canonical&&$.cmp(this.nh)>0&&($=this.n.sub($),W^=1),new gl({r:O,s:$,recoveryParam:W})}}}}}},Ji.prototype.verify=function(e,t,i,n){e=this._truncateToN(new vt(e,16)),i=this.keyFromPublic(i,n),t=new gl(t,"hex");var s=t.r,a=t.s;if(s.cmpn(1)<0||s.cmp(this.n)>=0||a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var f=a.invm(this.n),h=f.mul(e).umod(this.n),u=f.mul(s).umod(this.n),g;return this.curve._maxwellTrick?(g=this.g.jmulAdd(h,i.getPublic(),u),g.isInfinity()?!1:g.eqXToP(s)):(g=this.g.mulAdd(h,i.getPublic(),u),g.isInfinity()?!1:g.getX().umod(this.n).cmp(s)===0)},Ji.prototype.recoverPubKey=function(r,e,t,i){Ov((3&t)===t,"The recovery param is more than two bits"),e=new gl(e,i);var n=this.n,s=new vt(r),a=e.r,f=e.s,h=t&1,u=t>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw new Error("Unable to find sencond key candinate");u?a=this.curve.pointFromX(a.add(this.curve.n),h):a=this.curve.pointFromX(a,h);var g=e.r.invm(n),w=n.sub(s).mul(g).umod(n),P=f.mul(g).umod(n);return this.g.mulAdd(w,a,P)},Ji.prototype.getKeyRecoveryParam=function(r,e,t,i){if(e=new gl(e,i),e.recoveryParam!==null)return e.recoveryParam;for(var n=0;n<4;n++){var s;try{s=this.recoverPubKey(r,e,n)}catch{continue}if(s.eq(t))return n}throw new Error("Unable to find valid recovery factor")};var w_=Pa(function(r,e){var t=e;t.version="6.5.4",t.utils=Ti,t.rand=function(){throw new Error("unsupported")},t.curve=ul,t.curves=dl,t.ec=b_,t.eddsa=null}),y_=w_.ec;const __="signing-key/5.7.0",wd=new xt(__);let yd=null;function Kn(){return yd||(yd=new y_("secp256k1")),yd}class x_{constructor(e){Lc(this,"curve","secp256k1"),Lc(this,"privateKey",ii(e)),s4(this.privateKey)!==32&&wd.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const t=Kn().keyFromPrivate(ur(this.privateKey));Lc(this,"publicKey","0x"+t.getPublic(!1,"hex")),Lc(this,"compressedPublicKey","0x"+t.getPublic(!0,"hex")),Lc(this,"_isSigningKey",!0)}_addPoint(e){const t=Kn().keyFromPublic(ur(this.publicKey)),i=Kn().keyFromPublic(ur(e));return"0x"+t.pub.add(i.pub).encodeCompressed("hex")}signDigest(e){const t=Kn().keyFromPrivate(ur(this.privateKey)),i=ur(e);i.length!==32&&wd.throwArgumentError("bad digest length","digest",e);const n=t.sign(i,{canonical:!0});return zg({recoveryParam:n.recoveryParam,r:Fn("0x"+n.r.toString(16),32),s:Fn("0x"+n.s.toString(16),32)})}computeSharedSecret(e){const t=Kn().keyFromPrivate(ur(this.privateKey)),i=Kn().keyFromPublic(ur(Rv(e)));return Fn("0x"+t.derive(i.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}}function A_(r,e){const t=zg(e),i={r:ur(t.r),s:ur(t.s)};return"0x"+Kn().recoverPubKey(ur(r),i,t.recoveryParam).encode("hex",!1)}function Rv(r,e){const t=ur(r);if(t.length===32){const i=new x_(t);return e?"0x"+Kn().keyFromPrivate(t).getPublic(!0,"hex"):i.publicKey}else{if(t.length===33)return e?ii(t):"0x"+Kn().keyFromPublic(t).getPublic(!1,"hex");if(t.length===65)return e?"0x"+Kn().keyFromPublic(t).getPublic(!0,"hex"):ii(t)}return wd.throwArgumentError("invalid public or private key","key","[REDACTED]")}const E_="transactions/5.7.0";new xt(E_);var Tv;(function(r){r[r.legacy=0]="legacy",r[r.eip2930=1]="eip2930",r[r.eip1559=2]="eip1559"})(Tv||(Tv={}));function S_(r){const e=Rv(r);return N4(qg(td(qg(e,1)),12))}function I_(r,e){return S_(A_(ur(r),e))}var _d={},vl={},yt={},$v={};(function(r){Object.defineProperty(r,"__esModule",{value:!0});function e(f,h){var u=f>>>16&65535,g=f&65535,w=h>>>16&65535,P=h&65535;return g*P+(u*P+g*w<<16>>>0)|0}r.mul=Math.imul||e;function t(f,h){return f+h|0}r.add=t;function i(f,h){return f-h|0}r.sub=i;function n(f,h){return f<>>32-h}r.rotl=n;function s(f,h){return f<<32-h|f>>>h}r.rotr=s;function a(f){return typeof f=="number"&&isFinite(f)&&Math.floor(f)===f}r.isInteger=Number.isInteger||a,r.MAX_SAFE_INTEGER=9007199254740991,r.isSafeInteger=function(f){return r.isInteger(f)&&f>=-r.MAX_SAFE_INTEGER&&f<=r.MAX_SAFE_INTEGER}})($v),Object.defineProperty(yt,"__esModule",{value:!0});var Nv=$v;function M_(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])<<16>>16}yt.readInt16BE=M_;function C_(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])>>>0}yt.readUint16BE=C_;function P_(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])<<16>>16}yt.readInt16LE=P_;function D_(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])>>>0}yt.readUint16LE=D_;function Lv(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>8,e[t+1]=r>>>0,e}yt.writeUint16BE=Lv,yt.writeInt16BE=Lv;function Bv(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e}yt.writeUint16LE=Bv,yt.writeInt16LE=Bv;function xd(r,e){return e===void 0&&(e=0),r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}yt.readInt32BE=xd;function Ad(r,e){return e===void 0&&(e=0),(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}yt.readUint32BE=Ad;function Ed(r,e){return e===void 0&&(e=0),r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e]}yt.readInt32LE=Ed;function Sd(r,e){return e===void 0&&(e=0),(r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e])>>>0}yt.readUint32LE=Sd;function ml(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>24,e[t+1]=r>>>16,e[t+2]=r>>>8,e[t+3]=r>>>0,e}yt.writeUint32BE=ml,yt.writeInt32BE=ml;function bl(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e[t+2]=r>>>16,e[t+3]=r>>>24,e}yt.writeUint32LE=bl,yt.writeInt32LE=bl;function O_(r,e){e===void 0&&(e=0);var t=xd(r,e),i=xd(r,e+4);return t*4294967296+i-(i>>31)*4294967296}yt.readInt64BE=O_;function R_(r,e){e===void 0&&(e=0);var t=Ad(r,e),i=Ad(r,e+4);return t*4294967296+i}yt.readUint64BE=R_;function T_(r,e){e===void 0&&(e=0);var t=Ed(r,e),i=Ed(r,e+4);return i*4294967296+t-(t>>31)*4294967296}yt.readInt64LE=T_;function $_(r,e){e===void 0&&(e=0);var t=Sd(r,e),i=Sd(r,e+4);return i*4294967296+t}yt.readUint64LE=$_;function Fv(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),ml(r/4294967296>>>0,e,t),ml(r>>>0,e,t+4),e}yt.writeUint64BE=Fv,yt.writeInt64BE=Fv;function Uv(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),bl(r>>>0,e,t),bl(r/4294967296>>>0,e,t+4),e}yt.writeUint64LE=Uv,yt.writeInt64LE=Uv;function N_(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintBE: array is too short for the given bitLength");for(var i=0,n=1,s=r/8+t-1;s>=t;s--)i+=e[s]*n,n*=256;return i}yt.readUintBE=N_;function L_(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintLE: array is too short for the given bitLength");for(var i=0,n=1,s=t;s=i;s--)t[s]=e/n&255,n*=256;return t}yt.writeUintBE=B_;function F_(r,e,t,i){if(t===void 0&&(t=new Uint8Array(r/8)),i===void 0&&(i=0),r%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!Nv.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var n=1,s=i;s>>32-16|d<<16,L=L+d|0,_^=L,_=_>>>32-12|_<<12,B=B+U|0,y^=B,y=y>>>32-16|y<<16,b=b+y|0,U^=b,U=U>>>32-12|U<<12,z=z+ee|0,C^=z,C=C>>>32-16|C<<16,m=m+C|0,ee^=m,ee=ee>>>32-12|ee<<12,j=j+oe|0,D^=j,D=D>>>32-16|D<<16,l=l+D|0,oe^=l,oe=oe>>>32-12|oe<<12,z=z+ee|0,C^=z,C=C>>>32-8|C<<8,m=m+C|0,ee^=m,ee=ee>>>32-7|ee<<7,j=j+oe|0,D^=j,D=D>>>32-8|D<<8,l=l+D|0,oe^=l,oe=oe>>>32-7|oe<<7,B=B+U|0,y^=B,y=y>>>32-8|y<<8,b=b+y|0,U^=b,U=U>>>32-7|U<<7,Y=Y+_|0,d^=Y,d=d>>>32-8|d<<8,L=L+d|0,_^=L,_=_>>>32-7|_<<7,Y=Y+U|0,D^=Y,D=D>>>32-16|D<<16,m=m+D|0,U^=m,U=U>>>32-12|U<<12,B=B+ee|0,d^=B,d=d>>>32-16|d<<16,l=l+d|0,ee^=l,ee=ee>>>32-12|ee<<12,z=z+oe|0,y^=z,y=y>>>32-16|y<<16,L=L+y|0,oe^=L,oe=oe>>>32-12|oe<<12,j=j+_|0,C^=j,C=C>>>32-16|C<<16,b=b+C|0,_^=b,_=_>>>32-12|_<<12,z=z+oe|0,y^=z,y=y>>>32-8|y<<8,L=L+y|0,oe^=L,oe=oe>>>32-7|oe<<7,j=j+_|0,C^=j,C=C>>>32-8|C<<8,b=b+C|0,_^=b,_=_>>>32-7|_<<7,B=B+ee|0,d^=B,d=d>>>32-8|d<<8,l=l+d|0,ee^=l,ee=ee>>>32-7|ee<<7,Y=Y+U|0,D^=Y,D=D>>>32-8|D<<8,m=m+D|0,U^=m,U=U>>>32-7|U<<7;Gr.writeUint32LE(Y+i|0,r,0),Gr.writeUint32LE(B+n|0,r,4),Gr.writeUint32LE(z+s|0,r,8),Gr.writeUint32LE(j+a|0,r,12),Gr.writeUint32LE(_+f|0,r,16),Gr.writeUint32LE(U+h|0,r,20),Gr.writeUint32LE(ee+u|0,r,24),Gr.writeUint32LE(oe+g|0,r,28),Gr.writeUint32LE(L+w|0,r,32),Gr.writeUint32LE(b+P|0,r,36),Gr.writeUint32LE(m+M|0,r,40),Gr.writeUint32LE(l+O|0,r,44),Gr.writeUint32LE(d+$|0,r,48),Gr.writeUint32LE(y+W|0,r,52),Gr.writeUint32LE(C+H|0,r,56),Gr.writeUint32LE(D+F|0,r,60)}function qv(r,e,t,i,n){if(n===void 0&&(n=0),r.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(i.length>>=8,e++;if(i>0)throw new Error("ChaCha: counter overflow")}var zv={},zs={};Object.defineProperty(zs,"__esModule",{value:!0});function Z_(r,e,t){return~(r-1)&e|r-1&t}zs.select=Z_;function X_(r,e){return(r|0)-(e|0)-1>>>31&1}zs.lessOrEqual=X_;function Hv(r,e){if(r.length!==e.length)return 0;for(var t=0,i=0;i>>8}zs.compare=Hv;function e7(r,e){return r.length===0||e.length===0?!1:Hv(r,e)!==0}zs.equal=e7,function(r){Object.defineProperty(r,"__esModule",{value:!0});var e=zs,t=$i;r.DIGEST_LENGTH=16;var i=function(){function a(f){this.digestLength=r.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 h=f[0]|f[1]<<8;this._r[0]=h&8191;var u=f[2]|f[3]<<8;this._r[1]=(h>>>13|u<<3)&8191;var g=f[4]|f[5]<<8;this._r[2]=(u>>>10|g<<6)&7939;var w=f[6]|f[7]<<8;this._r[3]=(g>>>7|w<<9)&8191;var P=f[8]|f[9]<<8;this._r[4]=(w>>>4|P<<12)&255,this._r[5]=P>>>1&8190;var M=f[10]|f[11]<<8;this._r[6]=(P>>>14|M<<2)&8191;var O=f[12]|f[13]<<8;this._r[7]=(M>>>11|O<<5)&8065;var $=f[14]|f[15]<<8;this._r[8]=(O>>>8|$<<8)&8191,this._r[9]=$>>>5&127,this._pad[0]=f[16]|f[17]<<8,this._pad[1]=f[18]|f[19]<<8,this._pad[2]=f[20]|f[21]<<8,this._pad[3]=f[22]|f[23]<<8,this._pad[4]=f[24]|f[25]<<8,this._pad[5]=f[26]|f[27]<<8,this._pad[6]=f[28]|f[29]<<8,this._pad[7]=f[30]|f[31]<<8}return a.prototype._blocks=function(f,h,u){for(var g=this._fin?0:2048,w=this._h[0],P=this._h[1],M=this._h[2],O=this._h[3],$=this._h[4],W=this._h[5],H=this._h[6],F=this._h[7],Y=this._h[8],B=this._h[9],z=this._r[0],j=this._r[1],_=this._r[2],U=this._r[3],ee=this._r[4],oe=this._r[5],L=this._r[6],b=this._r[7],m=this._r[8],l=this._r[9];u>=16;){var d=f[h+0]|f[h+1]<<8;w+=d&8191;var y=f[h+2]|f[h+3]<<8;P+=(d>>>13|y<<3)&8191;var C=f[h+4]|f[h+5]<<8;M+=(y>>>10|C<<6)&8191;var D=f[h+6]|f[h+7]<<8;O+=(C>>>7|D<<9)&8191;var S=f[h+8]|f[h+9]<<8;$+=(D>>>4|S<<12)&8191,W+=S>>>1&8191;var v=f[h+10]|f[h+11]<<8;H+=(S>>>14|v<<2)&8191;var A=f[h+12]|f[h+13]<<8;F+=(v>>>11|A<<5)&8191;var x=f[h+14]|f[h+15]<<8;Y+=(A>>>8|x<<8)&8191,B+=x>>>5|g;var N=0,ae=N;ae+=w*z,ae+=P*(5*l),ae+=M*(5*m),ae+=O*(5*b),ae+=$*(5*L),N=ae>>>13,ae&=8191,ae+=W*(5*oe),ae+=H*(5*ee),ae+=F*(5*U),ae+=Y*(5*_),ae+=B*(5*j),N+=ae>>>13,ae&=8191;var R=N;R+=w*j,R+=P*z,R+=M*(5*l),R+=O*(5*m),R+=$*(5*b),N=R>>>13,R&=8191,R+=W*(5*L),R+=H*(5*oe),R+=F*(5*ee),R+=Y*(5*U),R+=B*(5*_),N+=R>>>13,R&=8191;var X=N;X+=w*_,X+=P*j,X+=M*z,X+=O*(5*l),X+=$*(5*m),N=X>>>13,X&=8191,X+=W*(5*b),X+=H*(5*L),X+=F*(5*oe),X+=Y*(5*ee),X+=B*(5*U),N+=X>>>13,X&=8191;var V=N;V+=w*U,V+=P*_,V+=M*j,V+=O*z,V+=$*(5*l),N=V>>>13,V&=8191,V+=W*(5*m),V+=H*(5*b),V+=F*(5*L),V+=Y*(5*oe),V+=B*(5*ee),N+=V>>>13,V&=8191;var J=N;J+=w*ee,J+=P*U,J+=M*_,J+=O*j,J+=$*z,N=J>>>13,J&=8191,J+=W*(5*l),J+=H*(5*m),J+=F*(5*b),J+=Y*(5*L),J+=B*(5*oe),N+=J>>>13,J&=8191;var K=N;K+=w*oe,K+=P*ee,K+=M*U,K+=O*_,K+=$*j,N=K>>>13,K&=8191,K+=W*z,K+=H*(5*l),K+=F*(5*m),K+=Y*(5*b),K+=B*(5*L),N+=K>>>13,K&=8191;var E=N;E+=w*L,E+=P*oe,E+=M*ee,E+=O*U,E+=$*_,N=E>>>13,E&=8191,E+=W*j,E+=H*z,E+=F*(5*l),E+=Y*(5*m),E+=B*(5*b),N+=E>>>13,E&=8191;var G=N;G+=w*b,G+=P*L,G+=M*oe,G+=O*ee,G+=$*U,N=G>>>13,G&=8191,G+=W*_,G+=H*j,G+=F*z,G+=Y*(5*l),G+=B*(5*m),N+=G>>>13,G&=8191;var re=N;re+=w*m,re+=P*b,re+=M*L,re+=O*oe,re+=$*ee,N=re>>>13,re&=8191,re+=W*U,re+=H*_,re+=F*j,re+=Y*z,re+=B*(5*l),N+=re>>>13,re&=8191;var le=N;le+=w*l,le+=P*m,le+=M*b,le+=O*L,le+=$*oe,N=le>>>13,le&=8191,le+=W*ee,le+=H*U,le+=F*_,le+=Y*j,le+=B*z,N+=le>>>13,le&=8191,N=(N<<2)+N|0,N=N+ae|0,ae=N&8191,N=N>>>13,R+=N,w=ae,P=R,M=X,O=V,$=J,W=K,H=E,F=G,Y=re,B=le,h+=16,u-=16}this._h[0]=w,this._h[1]=P,this._h[2]=M,this._h[3]=O,this._h[4]=$,this._h[5]=W,this._h[6]=H,this._h[7]=F,this._h[8]=Y,this._h[9]=B},a.prototype.finish=function(f,h){h===void 0&&(h=0);var u=new Uint16Array(10),g,w,P,M;if(this._leftover){for(M=this._leftover,this._buffer[M++]=1;M<16;M++)this._buffer[M]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(g=this._h[1]>>>13,this._h[1]&=8191,M=2;M<10;M++)this._h[M]+=g,g=this._h[M]>>>13,this._h[M]&=8191;for(this._h[0]+=g*5,g=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=g,g=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=g,u[0]=this._h[0]+5,g=u[0]>>>13,u[0]&=8191,M=1;M<10;M++)u[M]=this._h[M]+g,g=u[M]>>>13,u[M]&=8191;for(u[9]-=8192,w=(g^1)-1,M=0;M<10;M++)u[M]&=w;for(w=~w,M=0;M<10;M++)this._h[M]=this._h[M]&w|u[M];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,P=this._h[0]+this._pad[0],this._h[0]=P&65535,M=1;M<8;M++)P=(this._h[M]+this._pad[M]|0)+(P>>>16)|0,this._h[M]=P&65535;return f[h+0]=this._h[0]>>>0,f[h+1]=this._h[0]>>>8,f[h+2]=this._h[1]>>>0,f[h+3]=this._h[1]>>>8,f[h+4]=this._h[2]>>>0,f[h+5]=this._h[2]>>>8,f[h+6]=this._h[3]>>>0,f[h+7]=this._h[3]>>>8,f[h+8]=this._h[4]>>>0,f[h+9]=this._h[4]>>>8,f[h+10]=this._h[5]>>>0,f[h+11]=this._h[5]>>>8,f[h+12]=this._h[6]>>>0,f[h+13]=this._h[6]>>>8,f[h+14]=this._h[7]>>>0,f[h+15]=this._h[7]>>>8,this._finished=!0,this},a.prototype.update=function(f){var h=0,u=f.length,g;if(this._leftover){g=16-this._leftover,g>u&&(g=u);for(var w=0;w=16&&(g=u-u%16,this._blocks(f,h,g),h+=g,u-=g),u){for(var w=0;w16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var M=new Uint8Array(16);M.set(u,M.length-u.length);var O=new Uint8Array(32);e.stream(this._key,M,O,4);var $=g.length+this.tagLength,W;if(P){if(P.length!==$)throw new Error("ChaCha20Poly1305: incorrect destination length");W=P}else W=new Uint8Array($);return e.streamXOR(this._key,M,g,W,4),this._authenticate(W.subarray(W.length-this.tagLength,W.length),O,W.subarray(0,W.length-this.tagLength),w),i.wipe(M),W},h.prototype.open=function(u,g,w,P){if(u.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(g.length0&&M.update(a.subarray(P.length%16))),M.update(w),w.length%16>0&&M.update(a.subarray(w.length%16));var O=new Uint8Array(8);P&&n.writeUint64LE(P.length,O),M.update(O),n.writeUint64LE(w.length,O),M.update(O);for(var $=M.digest(),W=0;W<$.length;W++)u[W]=$[W];M.clean(),i.wipe($),i.wipe(O)},h}();r.ChaCha20Poly1305=f}(_d);var kv={},Uc={},Md={};Object.defineProperty(Md,"__esModule",{value:!0});function t7(r){return typeof r.saveState<"u"&&typeof r.restoreState<"u"&&typeof r.cleanSavedState<"u"}Md.isSerializableHash=t7,Object.defineProperty(Uc,"__esModule",{value:!0});var Vn=Md,r7=zs,i7=$i,jv=function(){function r(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var i=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(i).clean():i.set(t);for(var n=0;n1&&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},r.prototype.expand=function(e){for(var t=new Uint8Array(e),i=0;i256)throw new Error("randomString charset is too long");let P="";const M=g.length,O=256-256%M;for(;u>0;){const $=n(Math.ceil(u*256/O),w);for(let W=0;W<$.length&&u>0;W++){const H=$[W];H0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=h[g++],u--;this._bufferLength===this.blockSize&&(s(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(u>=this.blockSize&&(g=s(this._temp,this._state,h,g,u),u%=this.blockSize);u>0;)this._buffer[this._bufferLength++]=h[g++],u--;return this},f.prototype.finish=function(h){if(!this._finished){var u=this._bytesHashed,g=this._bufferLength,w=u/536870912|0,P=u<<3,M=u%64<56?64:128;this._buffer[g]=128;for(var O=g+1;O0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},f.prototype.restoreState=function(h){return this._state.set(h.state),this._bufferLength=h.bufferLength,h.buffer&&this._buffer.set(h.buffer),this._bytesHashed=h.bytesHashed,this._finished=!1,this},f.prototype.cleanSavedState=function(h){t.wipe(h.state),h.buffer&&t.wipe(h.buffer),h.bufferLength=0,h.bytesHashed=0},f}();r.SHA256=i;var n=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 s(f,h,u,g,w){for(;w>=64;){for(var P=h[0],M=h[1],O=h[2],$=h[3],W=h[4],H=h[5],F=h[6],Y=h[7],B=0;B<16;B++){var z=g+B*4;f[B]=e.readUint32BE(u,z)}for(var B=16;B<64;B++){var j=f[B-2],_=(j>>>17|j<<32-17)^(j>>>19|j<<32-19)^j>>>10;j=f[B-15];var U=(j>>>7|j<<32-7)^(j>>>18|j<<32-18)^j>>>3;f[B]=(_+f[B-7]|0)+(U+f[B-16]|0)}for(var B=0;B<64;B++){var _=(((W>>>6|W<<26)^(W>>>11|W<<21)^(W>>>25|W<<7))+(W&H^~W&F)|0)+(Y+(n[B]+f[B]|0)|0)|0,U=((P>>>2|P<<32-2)^(P>>>13|P<<32-13)^(P>>>22|P<<32-22))+(P&M^P&O^M&O)|0;Y=F,F=H,H=W,W=$+_|0,$=O,O=M,M=P,P=_+U|0}h[0]+=P,h[1]+=M,h[2]+=O,h[3]+=$,h[4]+=W,h[5]+=H,h[6]+=F,h[7]+=Y,g+=64,w-=64}return g}function a(f){var h=new i;h.update(f);var u=h.digest();return h.clean(),u}r.hash=a})(qc);var Cd={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.sharedKey=r.generateKeyPair=r.generateKeyPairFromSeed=r.scalarMultBase=r.scalarMult=r.SHARED_KEY_LENGTH=r.SECRET_KEY_LENGTH=r.PUBLIC_KEY_LENGTH=void 0;const e=Hs,t=$i;r.PUBLIC_KEY_LENGTH=32,r.SECRET_KEY_LENGTH=32,r.SHARED_KEY_LENGTH=32;function i(B){const z=new Float64Array(16);if(B)for(let j=0;j>16&1),j[oe-1]&=65535;j[15]=_[15]-32767-(j[14]>>16&1);const ee=j[15]>>16&1;j[14]&=65535,f(_,j,1-ee)}for(let U=0;U<16;U++)B[2*U]=_[U]&255,B[2*U+1]=_[U]>>8}function u(B,z){for(let j=0;j<16;j++)B[j]=z[2*j]+(z[2*j+1]<<8);B[15]&=32767}function g(B,z,j){for(let _=0;_<16;_++)B[_]=z[_]+j[_]}function w(B,z,j){for(let _=0;_<16;_++)B[_]=z[_]-j[_]}function P(B,z,j){let _,U,ee=0,oe=0,L=0,b=0,m=0,l=0,d=0,y=0,C=0,D=0,S=0,v=0,A=0,x=0,N=0,ae=0,R=0,X=0,V=0,J=0,K=0,E=0,G=0,re=0,le=0,he=0,ge=0,He=0,Te=0,Ce=0,Xe=0,$e=j[0],be=j[1],Pe=j[2],De=j[3],ye=j[4],Ie=j[5],Oe=j[6],me=j[7],Me=j[8],Be=j[9],we=j[10],ke=j[11],We=j[12],xe=j[13],Ve=j[14],Ke=j[15];_=z[0],ee+=_*$e,oe+=_*be,L+=_*Pe,b+=_*De,m+=_*ye,l+=_*Ie,d+=_*Oe,y+=_*me,C+=_*Me,D+=_*Be,S+=_*we,v+=_*ke,A+=_*We,x+=_*xe,N+=_*Ve,ae+=_*Ke,_=z[1],oe+=_*$e,L+=_*be,b+=_*Pe,m+=_*De,l+=_*ye,d+=_*Ie,y+=_*Oe,C+=_*me,D+=_*Me,S+=_*Be,v+=_*we,A+=_*ke,x+=_*We,N+=_*xe,ae+=_*Ve,R+=_*Ke,_=z[2],L+=_*$e,b+=_*be,m+=_*Pe,l+=_*De,d+=_*ye,y+=_*Ie,C+=_*Oe,D+=_*me,S+=_*Me,v+=_*Be,A+=_*we,x+=_*ke,N+=_*We,ae+=_*xe,R+=_*Ve,X+=_*Ke,_=z[3],b+=_*$e,m+=_*be,l+=_*Pe,d+=_*De,y+=_*ye,C+=_*Ie,D+=_*Oe,S+=_*me,v+=_*Me,A+=_*Be,x+=_*we,N+=_*ke,ae+=_*We,R+=_*xe,X+=_*Ve,V+=_*Ke,_=z[4],m+=_*$e,l+=_*be,d+=_*Pe,y+=_*De,C+=_*ye,D+=_*Ie,S+=_*Oe,v+=_*me,A+=_*Me,x+=_*Be,N+=_*we,ae+=_*ke,R+=_*We,X+=_*xe,V+=_*Ve,J+=_*Ke,_=z[5],l+=_*$e,d+=_*be,y+=_*Pe,C+=_*De,D+=_*ye,S+=_*Ie,v+=_*Oe,A+=_*me,x+=_*Me,N+=_*Be,ae+=_*we,R+=_*ke,X+=_*We,V+=_*xe,J+=_*Ve,K+=_*Ke,_=z[6],d+=_*$e,y+=_*be,C+=_*Pe,D+=_*De,S+=_*ye,v+=_*Ie,A+=_*Oe,x+=_*me,N+=_*Me,ae+=_*Be,R+=_*we,X+=_*ke,V+=_*We,J+=_*xe,K+=_*Ve,E+=_*Ke,_=z[7],y+=_*$e,C+=_*be,D+=_*Pe,S+=_*De,v+=_*ye,A+=_*Ie,x+=_*Oe,N+=_*me,ae+=_*Me,R+=_*Be,X+=_*we,V+=_*ke,J+=_*We,K+=_*xe,E+=_*Ve,G+=_*Ke,_=z[8],C+=_*$e,D+=_*be,S+=_*Pe,v+=_*De,A+=_*ye,x+=_*Ie,N+=_*Oe,ae+=_*me,R+=_*Me,X+=_*Be,V+=_*we,J+=_*ke,K+=_*We,E+=_*xe,G+=_*Ve,re+=_*Ke,_=z[9],D+=_*$e,S+=_*be,v+=_*Pe,A+=_*De,x+=_*ye,N+=_*Ie,ae+=_*Oe,R+=_*me,X+=_*Me,V+=_*Be,J+=_*we,K+=_*ke,E+=_*We,G+=_*xe,re+=_*Ve,le+=_*Ke,_=z[10],S+=_*$e,v+=_*be,A+=_*Pe,x+=_*De,N+=_*ye,ae+=_*Ie,R+=_*Oe,X+=_*me,V+=_*Me,J+=_*Be,K+=_*we,E+=_*ke,G+=_*We,re+=_*xe,le+=_*Ve,he+=_*Ke,_=z[11],v+=_*$e,A+=_*be,x+=_*Pe,N+=_*De,ae+=_*ye,R+=_*Ie,X+=_*Oe,V+=_*me,J+=_*Me,K+=_*Be,E+=_*we,G+=_*ke,re+=_*We,le+=_*xe,he+=_*Ve,ge+=_*Ke,_=z[12],A+=_*$e,x+=_*be,N+=_*Pe,ae+=_*De,R+=_*ye,X+=_*Ie,V+=_*Oe,J+=_*me,K+=_*Me,E+=_*Be,G+=_*we,re+=_*ke,le+=_*We,he+=_*xe,ge+=_*Ve,He+=_*Ke,_=z[13],x+=_*$e,N+=_*be,ae+=_*Pe,R+=_*De,X+=_*ye,V+=_*Ie,J+=_*Oe,K+=_*me,E+=_*Me,G+=_*Be,re+=_*we,le+=_*ke,he+=_*We,ge+=_*xe,He+=_*Ve,Te+=_*Ke,_=z[14],N+=_*$e,ae+=_*be,R+=_*Pe,X+=_*De,V+=_*ye,J+=_*Ie,K+=_*Oe,E+=_*me,G+=_*Me,re+=_*Be,le+=_*we,he+=_*ke,ge+=_*We,He+=_*xe,Te+=_*Ve,Ce+=_*Ke,_=z[15],ae+=_*$e,R+=_*be,X+=_*Pe,V+=_*De,J+=_*ye,K+=_*Ie,E+=_*Oe,G+=_*me,re+=_*Me,le+=_*Be,he+=_*we,ge+=_*ke,He+=_*We,Te+=_*xe,Ce+=_*Ve,Xe+=_*Ke,ee+=38*R,oe+=38*X,L+=38*V,b+=38*J,m+=38*K,l+=38*E,d+=38*G,y+=38*re,C+=38*le,D+=38*he,S+=38*ge,v+=38*He,A+=38*Te,x+=38*Ce,N+=38*Xe,U=1,_=ee+U+65535,U=Math.floor(_/65536),ee=_-U*65536,_=oe+U+65535,U=Math.floor(_/65536),oe=_-U*65536,_=L+U+65535,U=Math.floor(_/65536),L=_-U*65536,_=b+U+65535,U=Math.floor(_/65536),b=_-U*65536,_=m+U+65535,U=Math.floor(_/65536),m=_-U*65536,_=l+U+65535,U=Math.floor(_/65536),l=_-U*65536,_=d+U+65535,U=Math.floor(_/65536),d=_-U*65536,_=y+U+65535,U=Math.floor(_/65536),y=_-U*65536,_=C+U+65535,U=Math.floor(_/65536),C=_-U*65536,_=D+U+65535,U=Math.floor(_/65536),D=_-U*65536,_=S+U+65535,U=Math.floor(_/65536),S=_-U*65536,_=v+U+65535,U=Math.floor(_/65536),v=_-U*65536,_=A+U+65535,U=Math.floor(_/65536),A=_-U*65536,_=x+U+65535,U=Math.floor(_/65536),x=_-U*65536,_=N+U+65535,U=Math.floor(_/65536),N=_-U*65536,_=ae+U+65535,U=Math.floor(_/65536),ae=_-U*65536,ee+=U-1+37*(U-1),U=1,_=ee+U+65535,U=Math.floor(_/65536),ee=_-U*65536,_=oe+U+65535,U=Math.floor(_/65536),oe=_-U*65536,_=L+U+65535,U=Math.floor(_/65536),L=_-U*65536,_=b+U+65535,U=Math.floor(_/65536),b=_-U*65536,_=m+U+65535,U=Math.floor(_/65536),m=_-U*65536,_=l+U+65535,U=Math.floor(_/65536),l=_-U*65536,_=d+U+65535,U=Math.floor(_/65536),d=_-U*65536,_=y+U+65535,U=Math.floor(_/65536),y=_-U*65536,_=C+U+65535,U=Math.floor(_/65536),C=_-U*65536,_=D+U+65535,U=Math.floor(_/65536),D=_-U*65536,_=S+U+65535,U=Math.floor(_/65536),S=_-U*65536,_=v+U+65535,U=Math.floor(_/65536),v=_-U*65536,_=A+U+65535,U=Math.floor(_/65536),A=_-U*65536,_=x+U+65535,U=Math.floor(_/65536),x=_-U*65536,_=N+U+65535,U=Math.floor(_/65536),N=_-U*65536,_=ae+U+65535,U=Math.floor(_/65536),ae=_-U*65536,ee+=U-1+37*(U-1),B[0]=ee,B[1]=oe,B[2]=L,B[3]=b,B[4]=m,B[5]=l,B[6]=d,B[7]=y,B[8]=C,B[9]=D,B[10]=S,B[11]=v,B[12]=A,B[13]=x,B[14]=N,B[15]=ae}function M(B,z){P(B,z,z)}function O(B,z){const j=i();for(let _=0;_<16;_++)j[_]=z[_];for(let _=253;_>=0;_--)M(j,j),_!==2&&_!==4&&P(j,j,z);for(let _=0;_<16;_++)B[_]=j[_]}function $(B,z){const j=new Uint8Array(32),_=new Float64Array(80),U=i(),ee=i(),oe=i(),L=i(),b=i(),m=i();for(let C=0;C<31;C++)j[C]=B[C];j[31]=B[31]&127|64,j[0]&=248,u(_,z);for(let C=0;C<16;C++)ee[C]=_[C];U[0]=L[0]=1;for(let C=254;C>=0;--C){const D=j[C>>>3]>>>(C&7)&1;f(U,ee,D),f(oe,L,D),g(b,U,oe),w(U,U,oe),g(oe,ee,L),w(ee,ee,L),M(L,b),M(m,U),P(U,oe,U),P(oe,ee,b),g(b,U,oe),w(U,U,oe),M(ee,U),w(oe,L,m),P(U,oe,s),g(U,U,L),P(oe,oe,U),P(U,L,m),P(L,ee,_),M(ee,b),f(U,ee,D),f(oe,L,D)}for(let C=0;C<16;C++)_[C+16]=U[C],_[C+32]=oe[C],_[C+48]=ee[C],_[C+64]=L[C];const l=_.subarray(32),d=_.subarray(16);O(l,l),P(d,d,l);const y=new Uint8Array(32);return h(y,d),y}r.scalarMult=$;function W(B){return $(B,n)}r.scalarMultBase=W;function H(B){if(B.length!==r.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${r.SECRET_KEY_LENGTH} bytes`);const z=new Uint8Array(B);return{publicKey:W(z),secretKey:z}}r.generateKeyPairFromSeed=H;function F(B){const z=(0,e.randomBytes)(32,B),j=H(z);return(0,t.wipe)(z),j}r.generateKeyPair=F;function Y(B,z,j=!1){if(B.length!==r.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(z.length!==r.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");const _=$(B,z);if(j){let U=0;for(let ee=0;ee<_.length;ee++)U|=_[ee];if(U===0)throw new Error("X25519: invalid shared key")}return _}r.sharedKey=Y})(Cd);function Gv(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function Pd(r,e){e||(e=r.reduce((n,s)=>n+s.length,0));const t=Gv(e);let i=0;for(const n of r)t.set(n,i),i+=n.length;return t}function p7(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i>>0,B=new Uint8Array(Y);H!==F;){for(var z=O[H],j=0,_=Y-1;(z!==0||j>>0,B[_]=z%f>>>0,z=z/f>>>0;if(z!==0)throw new Error("Non-zero carry");W=j,H++}for(var U=Y-W;U!==Y&&B[U]===0;)U++;for(var ee=h.repeat($);U>>0,Y=new Uint8Array(F);O[$];){var B=t[O.charCodeAt($)];if(B===255)return;for(var z=0,j=F-1;(B!==0||z>>0,Y[j]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");H=z,$++}if(O[$]!==" "){for(var _=F-H;_!==F&&Y[_]===0;)_++;for(var U=new Uint8Array(W+(F-_)),ee=W;_!==F;)U[ee++]=Y[_++];return U}}}function M(O){var $=P(O);if($)return $;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:P,decode:M}}var g7=p7,v7=g7;const Yv=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},m7=r=>new TextEncoder().encode(r),b7=r=>new TextDecoder().decode(r);class w7{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class y7{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return Jv(this,e)}}class _7{constructor(e){this.decoders=e}or(e){return Jv(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Jv=(r,e)=>new _7({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class x7{constructor(e,t,i,n){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=n,this.encoder=new w7(e,t,i),this.decoder=new y7(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const xl=({name:r,prefix:e,encode:t,decode:i})=>new x7(r,e,t,i),zc=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:n}=v7(t,e);return xl({prefix:r,name:e,encode:i,decode:s=>Yv(n(s))})},A7=(r,e,t,i)=>{const n={};for(let g=0;g=8&&(f-=8,a[u++]=255&h>>f)}if(f>=t||255&h<<8-f)throw new SyntaxError("Unexpected end of data");return a},E7=(r,e,t)=>{const i=e[e.length-1]==="=",n=(1<t;)a-=t,s+=e[n&f>>a];if(a&&(s+=e[n&f<xl({prefix:e,name:r,encode(n){return E7(n,i,t)},decode(n){return A7(n,i,t,r)}}),S7=xl({prefix:"\0",name:"identity",encode:r=>b7(r),decode:r=>m7(r)});var I7=Object.freeze({__proto__:null,identity:S7});const M7=kr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var C7=Object.freeze({__proto__:null,base2:M7});const P7=kr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var D7=Object.freeze({__proto__:null,base8:P7});const O7=zc({prefix:"9",name:"base10",alphabet:"0123456789"});var R7=Object.freeze({__proto__:null,base10:O7});const T7=kr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$7=kr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var N7=Object.freeze({__proto__:null,base16:T7,base16upper:$7});const L7=kr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),B7=kr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F7=kr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),U7=kr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),q7=kr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z7=kr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),H7=kr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),k7=kr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),j7=kr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var W7=Object.freeze({__proto__:null,base32:L7,base32upper:B7,base32pad:F7,base32padupper:U7,base32hex:q7,base32hexupper:z7,base32hexpad:H7,base32hexpadupper:k7,base32z:j7});const K7=zc({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),V7=zc({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var G7=Object.freeze({__proto__:null,base36:K7,base36upper:V7});const Y7=zc({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),J7=zc({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Q7=Object.freeze({__proto__:null,base58btc:Y7,base58flickr:J7});const Z7=kr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),X7=kr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),e9=kr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),t9=kr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var r9=Object.freeze({__proto__:null,base64:Z7,base64pad:X7,base64url:e9,base64urlpad:t9});const Qv=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),i9=Qv.reduce((r,e,t)=>(r[t]=e,r),[]),n9=Qv.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function s9(r){return r.reduce((e,t)=>(e+=i9[t],e),"")}function o9(r){const e=[];for(const t of r){const i=n9[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const a9=xl({prefix:"\u{1F680}",name:"base256emoji",encode:s9,decode:o9});var c9=Object.freeze({__proto__:null,base256emoji:a9}),f9=Xv,Zv=128,l9=127,h9=~l9,u9=Math.pow(2,31);function Xv(r,e,t){e=e||[],t=t||0;for(var i=t;r>=u9;)e[t++]=r&255|Zv,r/=128;for(;r&h9;)e[t++]=r&255|Zv,r>>>=7;return e[t]=r|0,Xv.bytes=t-i+1,e}var d9=Dd,p9=128,em=127;function Dd(r,i){var t=0,i=i||0,n=0,s=i,a,f=r.length;do{if(s>=f)throw Dd.bytes=0,new RangeError("Could not decode varint");a=r[s++],t+=n<28?(a&em)<=p9);return Dd.bytes=s-i,t}var g9=Math.pow(2,7),v9=Math.pow(2,14),m9=Math.pow(2,21),b9=Math.pow(2,28),w9=Math.pow(2,35),y9=Math.pow(2,42),_9=Math.pow(2,49),x9=Math.pow(2,56),A9=Math.pow(2,63),E9=function(r){return r(tm.encode(r,e,t),e),im=r=>tm.encodingLength(r),Od=(r,e)=>{const t=e.byteLength,i=im(r),n=i+im(t),s=new Uint8Array(n+t);return rm(r,s,0),rm(t,s,i),s.set(e,n),new I9(r,t,e,s)};class I9{constructor(e,t,i,n){this.code=e,this.size=t,this.digest=i,this.bytes=n}}const nm=({name:r,code:e,encode:t})=>new M9(r,e,t);class M9{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Od(this.code,t):t.then(i=>Od(this.code,i))}else throw Error("Unknown type, must be binary type")}}const sm=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),C9=nm({name:"sha2-256",code:18,encode:sm("SHA-256")}),P9=nm({name:"sha2-512",code:19,encode:sm("SHA-512")});var D9=Object.freeze({__proto__:null,sha256:C9,sha512:P9});const om=0,O9="identity",am=Yv;var R9=Object.freeze({__proto__:null,identity:{code:om,name:O9,encode:am,digest:r=>Od(om,am(r))}});new TextEncoder,new TextDecoder;const Da={...I7,...C7,...D7,...R7,...N7,...W7,...G7,...Q7,...r9,...c9};({...D9,...R9});function cm(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const fm=cm("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Rd=cm("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=Gv(r.length);for(let t=0;t",H9="MIT",k9={url:"https://github.com/indutny/elliptic/issues"},j9="https://github.com/indutny/elliptic",W9={brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},K9={"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"},V9={name:T9,version:$9,description:N9,main:L9,files:B9,scripts:F9,repository:U9,keywords:q9,author:z9,license:H9,bugs:k9,homepage:j9,devDependencies:W9,dependencies:K9},Li={},Gn={exports:{}};(function(r){(function(e,t){function i(L,b){if(!L)throw new Error(b||"Assertion failed")}function n(L,b){L.super_=b;var m=function(){};m.prototype=b.prototype,L.prototype=new m,L.prototype.constructor=L}function s(L,b,m){if(s.isBN(L))return L;this.negative=0,this.words=null,this.length=0,this.red=null,L!==null&&((b==="le"||b==="be")&&(m=b,b=10),this._init(L||0,b||10,m||"be"))}typeof e=="object"?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;var a;try{typeof window<"u"&&typeof window.Buffer<"u"?a=window.Buffer:a=il.Buffer}catch{}s.isBN=function(b){return b instanceof s?!0:b!==null&&typeof b=="object"&&b.constructor.wordSize===s.wordSize&&Array.isArray(b.words)},s.max=function(b,m){return b.cmp(m)>0?b:m},s.min=function(b,m){return b.cmp(m)<0?b:m},s.prototype._init=function(b,m,l){if(typeof b=="number")return this._initNumber(b,m,l);if(typeof b=="object")return this._initArray(b,m,l);m==="hex"&&(m=16),i(m===(m|0)&&m>=2&&m<=36),b=b.toString().replace(/\s+/g,"");var d=0;b[0]==="-"&&(d++,this.negative=1),d=0;d-=3)C=b[d]|b[d-1]<<8|b[d-2]<<16,this.words[y]|=C<>>26-D&67108863,D+=24,D>=26&&(D-=26,y++);else if(l==="le")for(d=0,y=0;d>>26-D&67108863,D+=24,D>=26&&(D-=26,y++);return this.strip()};function f(L,b){var m=L.charCodeAt(b);return m>=65&&m<=70?m-55:m>=97&&m<=102?m-87:m-48&15}function h(L,b,m){var l=f(L,m);return m-1>=b&&(l|=f(L,m-1)<<4),l}s.prototype._parseHex=function(b,m,l){this.length=Math.ceil((b.length-m)/6),this.words=new Array(this.length);for(var d=0;d=m;d-=2)D=h(b,m,d)<=18?(y-=18,C+=1,this.words[C]|=D>>>26):y+=8;else{var S=b.length-m;for(d=S%2===0?m+1:m;d=18?(y-=18,C+=1,this.words[C]|=D>>>26):y+=8}this.strip()};function u(L,b,m,l){for(var d=0,y=Math.min(L.length,m),C=b;C=49?d+=D-49+10:D>=17?d+=D-17+10:d+=D}return d}s.prototype._parseBase=function(b,m,l){this.words=[0],this.length=1;for(var d=0,y=1;y<=67108863;y*=m)d++;d--,y=y/m|0;for(var C=b.length-l,D=C%d,S=Math.min(C,C-D)+l,v=0,A=l;A1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},s.prototype.inspect=function(){return(this.red?""};var g=["","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"],w=[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];s.prototype.toString=function(b,m){b=b||10,m=m|0||1;var l;if(b===16||b==="hex"){l="";for(var d=0,y=0,C=0;C>>24-d&16777215,y!==0||C!==this.length-1?l=g[6-S.length]+S+l:l=S+l,d+=2,d>=26&&(d-=26,C--)}for(y!==0&&(l=y.toString(16)+l);l.length%m!==0;)l="0"+l;return this.negative!==0&&(l="-"+l),l}if(b===(b|0)&&b>=2&&b<=36){var v=w[b],A=P[b];l="";var x=this.clone();for(x.negative=0;!x.isZero();){var N=x.modn(A).toString(b);x=x.idivn(A),x.isZero()?l=N+l:l=g[v-N.length]+N+l}for(this.isZero()&&(l="0"+l);l.length%m!==0;)l="0"+l;return this.negative!==0&&(l="-"+l),l}i(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var b=this.words[0];return this.length===2?b+=this.words[1]*67108864:this.length===3&&this.words[2]===1?b+=4503599627370496+this.words[1]*67108864:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-b:b},s.prototype.toJSON=function(){return this.toString(16)},s.prototype.toBuffer=function(b,m){return i(typeof a<"u"),this.toArrayLike(a,b,m)},s.prototype.toArray=function(b,m){return this.toArrayLike(Array,b,m)},s.prototype.toArrayLike=function(b,m,l){var d=this.byteLength(),y=l||Math.max(1,d);i(d<=y,"byte array longer than desired length"),i(y>0,"Requested array length <= 0"),this.strip();var C=m==="le",D=new b(y),S,v,A=this.clone();if(C){for(v=0;!A.isZero();v++)S=A.andln(255),A.iushrn(8),D[v]=S;for(;v=4096&&(l+=13,m>>>=13),m>=64&&(l+=7,m>>>=7),m>=8&&(l+=4,m>>>=4),m>=2&&(l+=2,m>>>=2),l+m},s.prototype._zeroBits=function(b){if(b===0)return 26;var m=b,l=0;return m&8191||(l+=13,m>>>=13),m&127||(l+=7,m>>>=7),m&15||(l+=4,m>>>=4),m&3||(l+=2,m>>>=2),m&1||l++,l},s.prototype.bitLength=function(){var b=this.words[this.length-1],m=this._countBits(b);return(this.length-1)*26+m};function M(L){for(var b=new Array(L.bitLength()),m=0;m>>d}return b}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var b=0,m=0;mb.length?this.clone().ior(b):b.clone().ior(this)},s.prototype.uor=function(b){return this.length>b.length?this.clone().iuor(b):b.clone().iuor(this)},s.prototype.iuand=function(b){var m;this.length>b.length?m=b:m=this;for(var l=0;lb.length?this.clone().iand(b):b.clone().iand(this)},s.prototype.uand=function(b){return this.length>b.length?this.clone().iuand(b):b.clone().iuand(this)},s.prototype.iuxor=function(b){var m,l;this.length>b.length?(m=this,l=b):(m=b,l=this);for(var d=0;db.length?this.clone().ixor(b):b.clone().ixor(this)},s.prototype.uxor=function(b){return this.length>b.length?this.clone().iuxor(b):b.clone().iuxor(this)},s.prototype.inotn=function(b){i(typeof b=="number"&&b>=0);var m=Math.ceil(b/26)|0,l=b%26;this._expand(m),l>0&&m--;for(var d=0;d0&&(this.words[d]=~this.words[d]&67108863>>26-l),this.strip()},s.prototype.notn=function(b){return this.clone().inotn(b)},s.prototype.setn=function(b,m){i(typeof b=="number"&&b>=0);var l=b/26|0,d=b%26;return this._expand(l+1),m?this.words[l]=this.words[l]|1<b.length?(l=this,d=b):(l=b,d=this);for(var y=0,C=0;C>>26;for(;y!==0&&C>>26;if(this.length=l.length,y!==0)this.words[this.length]=y,this.length++;else if(l!==this)for(;Cb.length?this.clone().iadd(b):b.clone().iadd(this)},s.prototype.isub=function(b){if(b.negative!==0){b.negative=0;var m=this.iadd(b);return b.negative=1,m._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(b),this.negative=1,this._normSign();var l=this.cmp(b);if(l===0)return this.negative=0,this.length=1,this.words[0]=0,this;var d,y;l>0?(d=this,y=b):(d=b,y=this);for(var C=0,D=0;D>26,this.words[D]=m&67108863;for(;C!==0&&D>26,this.words[D]=m&67108863;if(C===0&&D>>26,x=S&67108863,N=Math.min(v,b.length-1),ae=Math.max(0,v-L.length+1);ae<=N;ae++){var R=v-ae|0;d=L.words[R]|0,y=b.words[ae]|0,C=d*y+x,A+=C/67108864|0,x=C&67108863}m.words[v]=x|0,S=A|0}return S!==0?m.words[v]=S|0:m.length--,m.strip()}var $=function(b,m,l){var d=b.words,y=m.words,C=l.words,D=0,S,v,A,x=d[0]|0,N=x&8191,ae=x>>>13,R=d[1]|0,X=R&8191,V=R>>>13,J=d[2]|0,K=J&8191,E=J>>>13,G=d[3]|0,re=G&8191,le=G>>>13,he=d[4]|0,ge=he&8191,He=he>>>13,Te=d[5]|0,Ce=Te&8191,Xe=Te>>>13,$e=d[6]|0,be=$e&8191,Pe=$e>>>13,De=d[7]|0,ye=De&8191,Ie=De>>>13,Oe=d[8]|0,me=Oe&8191,Me=Oe>>>13,Be=d[9]|0,we=Be&8191,ke=Be>>>13,We=y[0]|0,xe=We&8191,Ve=We>>>13,Ke=y[1]|0,Ge=Ke&8191,mt=Ke>>>13,It=y[2]|0,Ye=It&8191,Pt=It>>>13,Ot=y[3]|0,Ze=Ot&8191,rt=Ot>>>13,et=y[4]|0,Ne=et&8191,it=et>>>13,tt=y[5]|0,Re=tt&8191,lt=tt>>>13,ht=y[6]|0,Le=ht&8191,ut=ht>>>13,nt=y[7]|0,Fe=nt&8191,st=nt>>>13,Qe=y[8]|0,qe=Qe&8191,dt=Qe>>>13,Ht=y[9]|0,at=Ht&8191,kt=Ht>>>13;l.negative=b.negative^m.negative,l.length=19,S=Math.imul(N,xe),v=Math.imul(N,Ve),v=v+Math.imul(ae,xe)|0,A=Math.imul(ae,Ve);var _t=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(_t>>>26)|0,_t&=67108863,S=Math.imul(X,xe),v=Math.imul(X,Ve),v=v+Math.imul(V,xe)|0,A=Math.imul(V,Ve),S=S+Math.imul(N,Ge)|0,v=v+Math.imul(N,mt)|0,v=v+Math.imul(ae,Ge)|0,A=A+Math.imul(ae,mt)|0;var qt=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(qt>>>26)|0,qt&=67108863,S=Math.imul(K,xe),v=Math.imul(K,Ve),v=v+Math.imul(E,xe)|0,A=Math.imul(E,Ve),S=S+Math.imul(X,Ge)|0,v=v+Math.imul(X,mt)|0,v=v+Math.imul(V,Ge)|0,A=A+Math.imul(V,mt)|0,S=S+Math.imul(N,Ye)|0,v=v+Math.imul(N,Pt)|0,v=v+Math.imul(ae,Ye)|0,A=A+Math.imul(ae,Pt)|0;var Qr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Qr>>>26)|0,Qr&=67108863,S=Math.imul(re,xe),v=Math.imul(re,Ve),v=v+Math.imul(le,xe)|0,A=Math.imul(le,Ve),S=S+Math.imul(K,Ge)|0,v=v+Math.imul(K,mt)|0,v=v+Math.imul(E,Ge)|0,A=A+Math.imul(E,mt)|0,S=S+Math.imul(X,Ye)|0,v=v+Math.imul(X,Pt)|0,v=v+Math.imul(V,Ye)|0,A=A+Math.imul(V,Pt)|0,S=S+Math.imul(N,Ze)|0,v=v+Math.imul(N,rt)|0,v=v+Math.imul(ae,Ze)|0,A=A+Math.imul(ae,rt)|0;var Zr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,S=Math.imul(ge,xe),v=Math.imul(ge,Ve),v=v+Math.imul(He,xe)|0,A=Math.imul(He,Ve),S=S+Math.imul(re,Ge)|0,v=v+Math.imul(re,mt)|0,v=v+Math.imul(le,Ge)|0,A=A+Math.imul(le,mt)|0,S=S+Math.imul(K,Ye)|0,v=v+Math.imul(K,Pt)|0,v=v+Math.imul(E,Ye)|0,A=A+Math.imul(E,Pt)|0,S=S+Math.imul(X,Ze)|0,v=v+Math.imul(X,rt)|0,v=v+Math.imul(V,Ze)|0,A=A+Math.imul(V,rt)|0,S=S+Math.imul(N,Ne)|0,v=v+Math.imul(N,it)|0,v=v+Math.imul(ae,Ne)|0,A=A+Math.imul(ae,it)|0;var Xr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,S=Math.imul(Ce,xe),v=Math.imul(Ce,Ve),v=v+Math.imul(Xe,xe)|0,A=Math.imul(Xe,Ve),S=S+Math.imul(ge,Ge)|0,v=v+Math.imul(ge,mt)|0,v=v+Math.imul(He,Ge)|0,A=A+Math.imul(He,mt)|0,S=S+Math.imul(re,Ye)|0,v=v+Math.imul(re,Pt)|0,v=v+Math.imul(le,Ye)|0,A=A+Math.imul(le,Pt)|0,S=S+Math.imul(K,Ze)|0,v=v+Math.imul(K,rt)|0,v=v+Math.imul(E,Ze)|0,A=A+Math.imul(E,rt)|0,S=S+Math.imul(X,Ne)|0,v=v+Math.imul(X,it)|0,v=v+Math.imul(V,Ne)|0,A=A+Math.imul(V,it)|0,S=S+Math.imul(N,Re)|0,v=v+Math.imul(N,lt)|0,v=v+Math.imul(ae,Re)|0,A=A+Math.imul(ae,lt)|0;var ei=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(ei>>>26)|0,ei&=67108863,S=Math.imul(be,xe),v=Math.imul(be,Ve),v=v+Math.imul(Pe,xe)|0,A=Math.imul(Pe,Ve),S=S+Math.imul(Ce,Ge)|0,v=v+Math.imul(Ce,mt)|0,v=v+Math.imul(Xe,Ge)|0,A=A+Math.imul(Xe,mt)|0,S=S+Math.imul(ge,Ye)|0,v=v+Math.imul(ge,Pt)|0,v=v+Math.imul(He,Ye)|0,A=A+Math.imul(He,Pt)|0,S=S+Math.imul(re,Ze)|0,v=v+Math.imul(re,rt)|0,v=v+Math.imul(le,Ze)|0,A=A+Math.imul(le,rt)|0,S=S+Math.imul(K,Ne)|0,v=v+Math.imul(K,it)|0,v=v+Math.imul(E,Ne)|0,A=A+Math.imul(E,it)|0,S=S+Math.imul(X,Re)|0,v=v+Math.imul(X,lt)|0,v=v+Math.imul(V,Re)|0,A=A+Math.imul(V,lt)|0,S=S+Math.imul(N,Le)|0,v=v+Math.imul(N,ut)|0,v=v+Math.imul(ae,Le)|0,A=A+Math.imul(ae,ut)|0;var vr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(vr>>>26)|0,vr&=67108863,S=Math.imul(ye,xe),v=Math.imul(ye,Ve),v=v+Math.imul(Ie,xe)|0,A=Math.imul(Ie,Ve),S=S+Math.imul(be,Ge)|0,v=v+Math.imul(be,mt)|0,v=v+Math.imul(Pe,Ge)|0,A=A+Math.imul(Pe,mt)|0,S=S+Math.imul(Ce,Ye)|0,v=v+Math.imul(Ce,Pt)|0,v=v+Math.imul(Xe,Ye)|0,A=A+Math.imul(Xe,Pt)|0,S=S+Math.imul(ge,Ze)|0,v=v+Math.imul(ge,rt)|0,v=v+Math.imul(He,Ze)|0,A=A+Math.imul(He,rt)|0,S=S+Math.imul(re,Ne)|0,v=v+Math.imul(re,it)|0,v=v+Math.imul(le,Ne)|0,A=A+Math.imul(le,it)|0,S=S+Math.imul(K,Re)|0,v=v+Math.imul(K,lt)|0,v=v+Math.imul(E,Re)|0,A=A+Math.imul(E,lt)|0,S=S+Math.imul(X,Le)|0,v=v+Math.imul(X,ut)|0,v=v+Math.imul(V,Le)|0,A=A+Math.imul(V,ut)|0,S=S+Math.imul(N,Fe)|0,v=v+Math.imul(N,st)|0,v=v+Math.imul(ae,Fe)|0,A=A+Math.imul(ae,st)|0;var Ai=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Ai>>>26)|0,Ai&=67108863,S=Math.imul(me,xe),v=Math.imul(me,Ve),v=v+Math.imul(Me,xe)|0,A=Math.imul(Me,Ve),S=S+Math.imul(ye,Ge)|0,v=v+Math.imul(ye,mt)|0,v=v+Math.imul(Ie,Ge)|0,A=A+Math.imul(Ie,mt)|0,S=S+Math.imul(be,Ye)|0,v=v+Math.imul(be,Pt)|0,v=v+Math.imul(Pe,Ye)|0,A=A+Math.imul(Pe,Pt)|0,S=S+Math.imul(Ce,Ze)|0,v=v+Math.imul(Ce,rt)|0,v=v+Math.imul(Xe,Ze)|0,A=A+Math.imul(Xe,rt)|0,S=S+Math.imul(ge,Ne)|0,v=v+Math.imul(ge,it)|0,v=v+Math.imul(He,Ne)|0,A=A+Math.imul(He,it)|0,S=S+Math.imul(re,Re)|0,v=v+Math.imul(re,lt)|0,v=v+Math.imul(le,Re)|0,A=A+Math.imul(le,lt)|0,S=S+Math.imul(K,Le)|0,v=v+Math.imul(K,ut)|0,v=v+Math.imul(E,Le)|0,A=A+Math.imul(E,ut)|0,S=S+Math.imul(X,Fe)|0,v=v+Math.imul(X,st)|0,v=v+Math.imul(V,Fe)|0,A=A+Math.imul(V,st)|0,S=S+Math.imul(N,qe)|0,v=v+Math.imul(N,dt)|0,v=v+Math.imul(ae,qe)|0,A=A+Math.imul(ae,dt)|0;var Mn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Mn>>>26)|0,Mn&=67108863,S=Math.imul(we,xe),v=Math.imul(we,Ve),v=v+Math.imul(ke,xe)|0,A=Math.imul(ke,Ve),S=S+Math.imul(me,Ge)|0,v=v+Math.imul(me,mt)|0,v=v+Math.imul(Me,Ge)|0,A=A+Math.imul(Me,mt)|0,S=S+Math.imul(ye,Ye)|0,v=v+Math.imul(ye,Pt)|0,v=v+Math.imul(Ie,Ye)|0,A=A+Math.imul(Ie,Pt)|0,S=S+Math.imul(be,Ze)|0,v=v+Math.imul(be,rt)|0,v=v+Math.imul(Pe,Ze)|0,A=A+Math.imul(Pe,rt)|0,S=S+Math.imul(Ce,Ne)|0,v=v+Math.imul(Ce,it)|0,v=v+Math.imul(Xe,Ne)|0,A=A+Math.imul(Xe,it)|0,S=S+Math.imul(ge,Re)|0,v=v+Math.imul(ge,lt)|0,v=v+Math.imul(He,Re)|0,A=A+Math.imul(He,lt)|0,S=S+Math.imul(re,Le)|0,v=v+Math.imul(re,ut)|0,v=v+Math.imul(le,Le)|0,A=A+Math.imul(le,ut)|0,S=S+Math.imul(K,Fe)|0,v=v+Math.imul(K,st)|0,v=v+Math.imul(E,Fe)|0,A=A+Math.imul(E,st)|0,S=S+Math.imul(X,qe)|0,v=v+Math.imul(X,dt)|0,v=v+Math.imul(V,qe)|0,A=A+Math.imul(V,dt)|0,S=S+Math.imul(N,at)|0,v=v+Math.imul(N,kt)|0,v=v+Math.imul(ae,at)|0,A=A+Math.imul(ae,kt)|0;var Ei=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Ei>>>26)|0,Ei&=67108863,S=Math.imul(we,Ge),v=Math.imul(we,mt),v=v+Math.imul(ke,Ge)|0,A=Math.imul(ke,mt),S=S+Math.imul(me,Ye)|0,v=v+Math.imul(me,Pt)|0,v=v+Math.imul(Me,Ye)|0,A=A+Math.imul(Me,Pt)|0,S=S+Math.imul(ye,Ze)|0,v=v+Math.imul(ye,rt)|0,v=v+Math.imul(Ie,Ze)|0,A=A+Math.imul(Ie,rt)|0,S=S+Math.imul(be,Ne)|0,v=v+Math.imul(be,it)|0,v=v+Math.imul(Pe,Ne)|0,A=A+Math.imul(Pe,it)|0,S=S+Math.imul(Ce,Re)|0,v=v+Math.imul(Ce,lt)|0,v=v+Math.imul(Xe,Re)|0,A=A+Math.imul(Xe,lt)|0,S=S+Math.imul(ge,Le)|0,v=v+Math.imul(ge,ut)|0,v=v+Math.imul(He,Le)|0,A=A+Math.imul(He,ut)|0,S=S+Math.imul(re,Fe)|0,v=v+Math.imul(re,st)|0,v=v+Math.imul(le,Fe)|0,A=A+Math.imul(le,st)|0,S=S+Math.imul(K,qe)|0,v=v+Math.imul(K,dt)|0,v=v+Math.imul(E,qe)|0,A=A+Math.imul(E,dt)|0,S=S+Math.imul(X,at)|0,v=v+Math.imul(X,kt)|0,v=v+Math.imul(V,at)|0,A=A+Math.imul(V,kt)|0;var Cn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Cn>>>26)|0,Cn&=67108863,S=Math.imul(we,Ye),v=Math.imul(we,Pt),v=v+Math.imul(ke,Ye)|0,A=Math.imul(ke,Pt),S=S+Math.imul(me,Ze)|0,v=v+Math.imul(me,rt)|0,v=v+Math.imul(Me,Ze)|0,A=A+Math.imul(Me,rt)|0,S=S+Math.imul(ye,Ne)|0,v=v+Math.imul(ye,it)|0,v=v+Math.imul(Ie,Ne)|0,A=A+Math.imul(Ie,it)|0,S=S+Math.imul(be,Re)|0,v=v+Math.imul(be,lt)|0,v=v+Math.imul(Pe,Re)|0,A=A+Math.imul(Pe,lt)|0,S=S+Math.imul(Ce,Le)|0,v=v+Math.imul(Ce,ut)|0,v=v+Math.imul(Xe,Le)|0,A=A+Math.imul(Xe,ut)|0,S=S+Math.imul(ge,Fe)|0,v=v+Math.imul(ge,st)|0,v=v+Math.imul(He,Fe)|0,A=A+Math.imul(He,st)|0,S=S+Math.imul(re,qe)|0,v=v+Math.imul(re,dt)|0,v=v+Math.imul(le,qe)|0,A=A+Math.imul(le,dt)|0,S=S+Math.imul(K,at)|0,v=v+Math.imul(K,kt)|0,v=v+Math.imul(E,at)|0,A=A+Math.imul(E,kt)|0;var Pn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Pn>>>26)|0,Pn&=67108863,S=Math.imul(we,Ze),v=Math.imul(we,rt),v=v+Math.imul(ke,Ze)|0,A=Math.imul(ke,rt),S=S+Math.imul(me,Ne)|0,v=v+Math.imul(me,it)|0,v=v+Math.imul(Me,Ne)|0,A=A+Math.imul(Me,it)|0,S=S+Math.imul(ye,Re)|0,v=v+Math.imul(ye,lt)|0,v=v+Math.imul(Ie,Re)|0,A=A+Math.imul(Ie,lt)|0,S=S+Math.imul(be,Le)|0,v=v+Math.imul(be,ut)|0,v=v+Math.imul(Pe,Le)|0,A=A+Math.imul(Pe,ut)|0,S=S+Math.imul(Ce,Fe)|0,v=v+Math.imul(Ce,st)|0,v=v+Math.imul(Xe,Fe)|0,A=A+Math.imul(Xe,st)|0,S=S+Math.imul(ge,qe)|0,v=v+Math.imul(ge,dt)|0,v=v+Math.imul(He,qe)|0,A=A+Math.imul(He,dt)|0,S=S+Math.imul(re,at)|0,v=v+Math.imul(re,kt)|0,v=v+Math.imul(le,at)|0,A=A+Math.imul(le,kt)|0;var Si=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Si>>>26)|0,Si&=67108863,S=Math.imul(we,Ne),v=Math.imul(we,it),v=v+Math.imul(ke,Ne)|0,A=Math.imul(ke,it),S=S+Math.imul(me,Re)|0,v=v+Math.imul(me,lt)|0,v=v+Math.imul(Me,Re)|0,A=A+Math.imul(Me,lt)|0,S=S+Math.imul(ye,Le)|0,v=v+Math.imul(ye,ut)|0,v=v+Math.imul(Ie,Le)|0,A=A+Math.imul(Ie,ut)|0,S=S+Math.imul(be,Fe)|0,v=v+Math.imul(be,st)|0,v=v+Math.imul(Pe,Fe)|0,A=A+Math.imul(Pe,st)|0,S=S+Math.imul(Ce,qe)|0,v=v+Math.imul(Ce,dt)|0,v=v+Math.imul(Xe,qe)|0,A=A+Math.imul(Xe,dt)|0,S=S+Math.imul(ge,at)|0,v=v+Math.imul(ge,kt)|0,v=v+Math.imul(He,at)|0,A=A+Math.imul(He,kt)|0;var cn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(cn>>>26)|0,cn&=67108863,S=Math.imul(we,Re),v=Math.imul(we,lt),v=v+Math.imul(ke,Re)|0,A=Math.imul(ke,lt),S=S+Math.imul(me,Le)|0,v=v+Math.imul(me,ut)|0,v=v+Math.imul(Me,Le)|0,A=A+Math.imul(Me,ut)|0,S=S+Math.imul(ye,Fe)|0,v=v+Math.imul(ye,st)|0,v=v+Math.imul(Ie,Fe)|0,A=A+Math.imul(Ie,st)|0,S=S+Math.imul(be,qe)|0,v=v+Math.imul(be,dt)|0,v=v+Math.imul(Pe,qe)|0,A=A+Math.imul(Pe,dt)|0,S=S+Math.imul(Ce,at)|0,v=v+Math.imul(Ce,kt)|0,v=v+Math.imul(Xe,at)|0,A=A+Math.imul(Xe,kt)|0;var fn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(fn>>>26)|0,fn&=67108863,S=Math.imul(we,Le),v=Math.imul(we,ut),v=v+Math.imul(ke,Le)|0,A=Math.imul(ke,ut),S=S+Math.imul(me,Fe)|0,v=v+Math.imul(me,st)|0,v=v+Math.imul(Me,Fe)|0,A=A+Math.imul(Me,st)|0,S=S+Math.imul(ye,qe)|0,v=v+Math.imul(ye,dt)|0,v=v+Math.imul(Ie,qe)|0,A=A+Math.imul(Ie,dt)|0,S=S+Math.imul(be,at)|0,v=v+Math.imul(be,kt)|0,v=v+Math.imul(Pe,at)|0,A=A+Math.imul(Pe,kt)|0;var Cr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,S=Math.imul(we,Fe),v=Math.imul(we,st),v=v+Math.imul(ke,Fe)|0,A=Math.imul(ke,st),S=S+Math.imul(me,qe)|0,v=v+Math.imul(me,dt)|0,v=v+Math.imul(Me,qe)|0,A=A+Math.imul(Me,dt)|0,S=S+Math.imul(ye,at)|0,v=v+Math.imul(ye,kt)|0,v=v+Math.imul(Ie,at)|0,A=A+Math.imul(Ie,kt)|0;var Dn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Dn>>>26)|0,Dn&=67108863,S=Math.imul(we,qe),v=Math.imul(we,dt),v=v+Math.imul(ke,qe)|0,A=Math.imul(ke,dt),S=S+Math.imul(me,at)|0,v=v+Math.imul(me,kt)|0,v=v+Math.imul(Me,at)|0,A=A+Math.imul(Me,kt)|0;var On=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(On>>>26)|0,On&=67108863,S=Math.imul(we,at),v=Math.imul(we,kt),v=v+Math.imul(ke,at)|0,A=Math.imul(ke,kt);var Rn=(D+S|0)+((v&8191)<<13)|0;return D=(A+(v>>>13)|0)+(Rn>>>26)|0,Rn&=67108863,C[0]=_t,C[1]=qt,C[2]=Qr,C[3]=Zr,C[4]=Xr,C[5]=ei,C[6]=vr,C[7]=Ai,C[8]=Mn,C[9]=Ei,C[10]=Cn,C[11]=Pn,C[12]=Si,C[13]=cn,C[14]=fn,C[15]=Cr,C[16]=Dn,C[17]=On,C[18]=Rn,D!==0&&(C[19]=D,l.length++),l};Math.imul||($=O);function W(L,b,m){m.negative=b.negative^L.negative,m.length=L.length+b.length;for(var l=0,d=0,y=0;y>>26)|0,d+=C>>>26,C&=67108863}m.words[y]=D,l=C,C=d}return l!==0?m.words[y]=l:m.length--,m.strip()}function H(L,b,m){var l=new F;return l.mulp(L,b,m)}s.prototype.mulTo=function(b,m){var l,d=this.length+b.length;return this.length===10&&b.length===10?l=$(this,b,m):d<63?l=O(this,b,m):d<1024?l=W(this,b,m):l=H(this,b,m),l};function F(L,b){this.x=L,this.y=b}F.prototype.makeRBT=function(b){for(var m=new Array(b),l=s.prototype._countBits(b)-1,d=0;d>=1;return d},F.prototype.permute=function(b,m,l,d,y,C){for(var D=0;D>>1)y++;return 1<>>13,l[2*C+1]=y&8191,y=y>>>13;for(C=2*m;C>=26,m+=d/67108864|0,m+=y>>>26,this.words[l]=y&67108863}return m!==0&&(this.words[l]=m,this.length++),this},s.prototype.muln=function(b){return this.clone().imuln(b)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(b){var m=M(b);if(m.length===0)return new s(1);for(var l=this,d=0;d=0);var m=b%26,l=(b-m)/26,d=67108863>>>26-m<<26-m,y;if(m!==0){var C=0;for(y=0;y>>26-m}C&&(this.words[y]=C,this.length++)}if(l!==0){for(y=this.length-1;y>=0;y--)this.words[y+l]=this.words[y];for(y=0;y=0);var d;m?d=(m-m%26)/26:d=0;var y=b%26,C=Math.min((b-y)/26,this.length),D=67108863^67108863>>>y<C)for(this.length-=C,v=0;v=0&&(A!==0||v>=d);v--){var x=this.words[v]|0;this.words[v]=A<<26-y|x>>>y,A=x&D}return S&&A!==0&&(S.words[S.length++]=A),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},s.prototype.ishrn=function(b,m,l){return i(this.negative===0),this.iushrn(b,m,l)},s.prototype.shln=function(b){return this.clone().ishln(b)},s.prototype.ushln=function(b){return this.clone().iushln(b)},s.prototype.shrn=function(b){return this.clone().ishrn(b)},s.prototype.ushrn=function(b){return this.clone().iushrn(b)},s.prototype.testn=function(b){i(typeof b=="number"&&b>=0);var m=b%26,l=(b-m)/26,d=1<=0);var m=b%26,l=(b-m)/26;if(i(this.negative===0,"imaskn works only with positive numbers"),this.length<=l)return this;if(m!==0&&l++,this.length=Math.min(l,this.length),m!==0){var d=67108863^67108863>>>m<=67108864;m++)this.words[m]-=67108864,m===this.length-1?this.words[m+1]=1:this.words[m+1]++;return this.length=Math.max(this.length,m+1),this},s.prototype.isubn=function(b){if(i(typeof b=="number"),i(b<67108864),b<0)return this.iaddn(-b);if(this.negative!==0)return this.negative=0,this.iaddn(b),this.negative=1,this;if(this.words[0]-=b,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var m=0;m>26)-(S/67108864|0),this.words[y+l]=C&67108863}for(;y>26,this.words[y+l]=C&67108863;if(D===0)return this.strip();for(i(D===-1),D=0,y=0;y>26,this.words[y]=C&67108863;return this.negative=1,this.strip()},s.prototype._wordDiv=function(b,m){var l=this.length-b.length,d=this.clone(),y=b,C=y.words[y.length-1]|0,D=this._countBits(C);l=26-D,l!==0&&(y=y.ushln(l),d.iushln(l),C=y.words[y.length-1]|0);var S=d.length-y.length,v;if(m!=="mod"){v=new s(null),v.length=S+1,v.words=new Array(v.length);for(var A=0;A=0;N--){var ae=(d.words[y.length+N]|0)*67108864+(d.words[y.length+N-1]|0);for(ae=Math.min(ae/C|0,67108863),d._ishlnsubmul(y,ae,N);d.negative!==0;)ae--,d.negative=0,d._ishlnsubmul(y,1,N),d.isZero()||(d.negative^=1);v&&(v.words[N]=ae)}return v&&v.strip(),d.strip(),m!=="div"&&l!==0&&d.iushrn(l),{div:v||null,mod:d}},s.prototype.divmod=function(b,m,l){if(i(!b.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var d,y,C;return this.negative!==0&&b.negative===0?(C=this.neg().divmod(b,m),m!=="mod"&&(d=C.div.neg()),m!=="div"&&(y=C.mod.neg(),l&&y.negative!==0&&y.iadd(b)),{div:d,mod:y}):this.negative===0&&b.negative!==0?(C=this.divmod(b.neg(),m),m!=="mod"&&(d=C.div.neg()),{div:d,mod:C.mod}):this.negative&b.negative?(C=this.neg().divmod(b.neg(),m),m!=="div"&&(y=C.mod.neg(),l&&y.negative!==0&&y.isub(b)),{div:C.div,mod:y}):b.length>this.length||this.cmp(b)<0?{div:new s(0),mod:this}:b.length===1?m==="div"?{div:this.divn(b.words[0]),mod:null}:m==="mod"?{div:null,mod:new s(this.modn(b.words[0]))}:{div:this.divn(b.words[0]),mod:new s(this.modn(b.words[0]))}:this._wordDiv(b,m)},s.prototype.div=function(b){return this.divmod(b,"div",!1).div},s.prototype.mod=function(b){return this.divmod(b,"mod",!1).mod},s.prototype.umod=function(b){return this.divmod(b,"mod",!0).mod},s.prototype.divRound=function(b){var m=this.divmod(b);if(m.mod.isZero())return m.div;var l=m.div.negative!==0?m.mod.isub(b):m.mod,d=b.ushrn(1),y=b.andln(1),C=l.cmp(d);return C<0||y===1&&C===0?m.div:m.div.negative!==0?m.div.isubn(1):m.div.iaddn(1)},s.prototype.modn=function(b){i(b<=67108863);for(var m=(1<<26)%b,l=0,d=this.length-1;d>=0;d--)l=(m*l+(this.words[d]|0))%b;return l},s.prototype.idivn=function(b){i(b<=67108863);for(var m=0,l=this.length-1;l>=0;l--){var d=(this.words[l]|0)+m*67108864;this.words[l]=d/b|0,m=d%b}return this.strip()},s.prototype.divn=function(b){return this.clone().idivn(b)},s.prototype.egcd=function(b){i(b.negative===0),i(!b.isZero());var m=this,l=b.clone();m.negative!==0?m=m.umod(b):m=m.clone();for(var d=new s(1),y=new s(0),C=new s(0),D=new s(1),S=0;m.isEven()&&l.isEven();)m.iushrn(1),l.iushrn(1),++S;for(var v=l.clone(),A=m.clone();!m.isZero();){for(var x=0,N=1;!(m.words[0]&N)&&x<26;++x,N<<=1);if(x>0)for(m.iushrn(x);x-- >0;)(d.isOdd()||y.isOdd())&&(d.iadd(v),y.isub(A)),d.iushrn(1),y.iushrn(1);for(var ae=0,R=1;!(l.words[0]&R)&&ae<26;++ae,R<<=1);if(ae>0)for(l.iushrn(ae);ae-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(v),D.isub(A)),C.iushrn(1),D.iushrn(1);m.cmp(l)>=0?(m.isub(l),d.isub(C),y.isub(D)):(l.isub(m),C.isub(d),D.isub(y))}return{a:C,b:D,gcd:l.iushln(S)}},s.prototype._invmp=function(b){i(b.negative===0),i(!b.isZero());var m=this,l=b.clone();m.negative!==0?m=m.umod(b):m=m.clone();for(var d=new s(1),y=new s(0),C=l.clone();m.cmpn(1)>0&&l.cmpn(1)>0;){for(var D=0,S=1;!(m.words[0]&S)&&D<26;++D,S<<=1);if(D>0)for(m.iushrn(D);D-- >0;)d.isOdd()&&d.iadd(C),d.iushrn(1);for(var v=0,A=1;!(l.words[0]&A)&&v<26;++v,A<<=1);if(v>0)for(l.iushrn(v);v-- >0;)y.isOdd()&&y.iadd(C),y.iushrn(1);m.cmp(l)>=0?(m.isub(l),d.isub(y)):(l.isub(m),y.isub(d))}var x;return m.cmpn(1)===0?x=d:x=y,x.cmpn(0)<0&&x.iadd(b),x},s.prototype.gcd=function(b){if(this.isZero())return b.abs();if(b.isZero())return this.abs();var m=this.clone(),l=b.clone();m.negative=0,l.negative=0;for(var d=0;m.isEven()&&l.isEven();d++)m.iushrn(1),l.iushrn(1);do{for(;m.isEven();)m.iushrn(1);for(;l.isEven();)l.iushrn(1);var y=m.cmp(l);if(y<0){var C=m;m=l,l=C}else if(y===0||l.cmpn(1)===0)break;m.isub(l)}while(!0);return l.iushln(d)},s.prototype.invm=function(b){return this.egcd(b).a.umod(b)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(b){return this.words[0]&b},s.prototype.bincn=function(b){i(typeof b=="number");var m=b%26,l=(b-m)/26,d=1<>>26,D&=67108863,this.words[C]=D}return y!==0&&(this.words[C]=y,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(b){var m=b<0;if(this.negative!==0&&!m)return-1;if(this.negative===0&&m)return 1;this.strip();var l;if(this.length>1)l=1;else{m&&(b=-b),i(b<=67108863,"Number is too big");var d=this.words[0]|0;l=d===b?0:db.length)return 1;if(this.length=0;l--){var d=this.words[l]|0,y=b.words[l]|0;if(d!==y){dy&&(m=1);break}}return m},s.prototype.gtn=function(b){return this.cmpn(b)===1},s.prototype.gt=function(b){return this.cmp(b)===1},s.prototype.gten=function(b){return this.cmpn(b)>=0},s.prototype.gte=function(b){return this.cmp(b)>=0},s.prototype.ltn=function(b){return this.cmpn(b)===-1},s.prototype.lt=function(b){return this.cmp(b)===-1},s.prototype.lten=function(b){return this.cmpn(b)<=0},s.prototype.lte=function(b){return this.cmp(b)<=0},s.prototype.eqn=function(b){return this.cmpn(b)===0},s.prototype.eq=function(b){return this.cmp(b)===0},s.red=function(b){return new ee(b)},s.prototype.toRed=function(b){return i(!this.red,"Already a number in reduction context"),i(this.negative===0,"red works only with positives"),b.convertTo(this)._forceRed(b)},s.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(b){return this.red=b,this},s.prototype.forceRed=function(b){return i(!this.red,"Already a number in reduction context"),this._forceRed(b)},s.prototype.redAdd=function(b){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,b)},s.prototype.redIAdd=function(b){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,b)},s.prototype.redSub=function(b){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,b)},s.prototype.redISub=function(b){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,b)},s.prototype.redShl=function(b){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,b)},s.prototype.redMul=function(b){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,b),this.red.mul(this,b)},s.prototype.redIMul=function(b){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,b),this.red.imul(this,b)},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(b){return i(this.red&&!b.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,b)};var Y={k256:null,p224:null,p192:null,p25519:null};function B(L,b){this.name=L,this.p=new s(b,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}B.prototype._tmp=function(){var b=new s(null);return b.words=new Array(Math.ceil(this.n/13)),b},B.prototype.ireduce=function(b){var m=b,l;do this.split(m,this.tmp),m=this.imulK(m),m=m.iadd(this.tmp),l=m.bitLength();while(l>this.n);var d=l0?m.isub(this.p):m.strip!==void 0?m.strip():m._strip(),m},B.prototype.split=function(b,m){b.iushrn(this.n,0,m)},B.prototype.imulK=function(b){return b.imul(this.k)};function z(){B.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(z,B),z.prototype.split=function(b,m){for(var l=4194303,d=Math.min(b.length,9),y=0;y>>22,C=D}C>>>=22,b.words[y-10]=C,C===0&&b.length>10?b.length-=10:b.length-=9},z.prototype.imulK=function(b){b.words[b.length]=0,b.words[b.length+1]=0,b.length+=2;for(var m=0,l=0;l>>=26,b.words[l]=y,m=d}return m!==0&&(b.words[b.length++]=m),b},s._prime=function(b){if(Y[b])return Y[b];var m;if(b==="k256")m=new z;else if(b==="p224")m=new j;else if(b==="p192")m=new _;else if(b==="p25519")m=new U;else throw new Error("Unknown prime "+b);return Y[b]=m,m};function ee(L){if(typeof L=="string"){var b=s._prime(L);this.m=b.p,this.prime=b}else i(L.gtn(1),"modulus must be greater than 1"),this.m=L,this.prime=null}ee.prototype._verify1=function(b){i(b.negative===0,"red works only with positives"),i(b.red,"red works only with red numbers")},ee.prototype._verify2=function(b,m){i((b.negative|m.negative)===0,"red works only with positives"),i(b.red&&b.red===m.red,"red works only with red numbers")},ee.prototype.imod=function(b){return this.prime?this.prime.ireduce(b)._forceRed(this):b.umod(this.m)._forceRed(this)},ee.prototype.neg=function(b){return b.isZero()?b.clone():this.m.sub(b)._forceRed(this)},ee.prototype.add=function(b,m){this._verify2(b,m);var l=b.add(m);return l.cmp(this.m)>=0&&l.isub(this.m),l._forceRed(this)},ee.prototype.iadd=function(b,m){this._verify2(b,m);var l=b.iadd(m);return l.cmp(this.m)>=0&&l.isub(this.m),l},ee.prototype.sub=function(b,m){this._verify2(b,m);var l=b.sub(m);return l.cmpn(0)<0&&l.iadd(this.m),l._forceRed(this)},ee.prototype.isub=function(b,m){this._verify2(b,m);var l=b.isub(m);return l.cmpn(0)<0&&l.iadd(this.m),l},ee.prototype.shl=function(b,m){return this._verify1(b),this.imod(b.ushln(m))},ee.prototype.imul=function(b,m){return this._verify2(b,m),this.imod(b.imul(m))},ee.prototype.mul=function(b,m){return this._verify2(b,m),this.imod(b.mul(m))},ee.prototype.isqr=function(b){return this.imul(b,b.clone())},ee.prototype.sqr=function(b){return this.mul(b,b)},ee.prototype.sqrt=function(b){if(b.isZero())return b.clone();var m=this.m.andln(3);if(i(m%2===1),m===3){var l=this.m.add(new s(1)).iushrn(2);return this.pow(b,l)}for(var d=this.m.subn(1),y=0;!d.isZero()&&d.andln(1)===0;)y++,d.iushrn(1);i(!d.isZero());var C=new s(1).toRed(this),D=C.redNeg(),S=this.m.subn(1).iushrn(1),v=this.m.bitLength();for(v=new s(2*v*v).toRed(this);this.pow(v,S).cmp(D)!==0;)v.redIAdd(D);for(var A=this.pow(v,d),x=this.pow(b,d.addn(1).iushrn(1)),N=this.pow(b,d),ae=y;N.cmp(C)!==0;){for(var R=N,X=0;R.cmp(C)!==0;X++)R=R.redSqr();i(X=0;y--){for(var A=m.words[y],x=v-1;x>=0;x--){var N=A>>x&1;if(C!==d[0]&&(C=this.sqr(C)),N===0&&D===0){S=0;continue}D<<=1,D|=N,S++,!(S!==l&&(y!==0||x!==0))&&(C=this.mul(C,d[D]),S=0,D=0)}v=26}return C},ee.prototype.convertTo=function(b){var m=b.umod(this.m);return m===b?m.clone():m},ee.prototype.convertFrom=function(b){var m=b.clone();return m.red=null,m},s.mont=function(b){return new oe(b)};function oe(L){ee.call(this,L),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)}n(oe,ee),oe.prototype.convertTo=function(b){return this.imod(b.ushln(this.shift))},oe.prototype.convertFrom=function(b){var m=this.imod(b.mul(this.rinv));return m.red=null,m},oe.prototype.imul=function(b,m){if(b.isZero()||m.isZero())return b.words[0]=0,b.length=1,b;var l=b.imul(m),d=l.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),y=l.isub(d).iushrn(this.shift),C=y;return y.cmp(this.m)>=0?C=y.isub(this.m):y.cmpn(0)<0&&(C=y.iadd(this.m)),C._forceRed(this)},oe.prototype.mul=function(b,m){if(b.isZero()||m.isZero())return new s(0)._forceRed(this);var l=b.mul(m),d=l.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),y=l.isub(d).iushrn(this.shift),C=y;return y.cmp(this.m)>=0?C=y.isub(this.m):y.cmpn(0)<0&&(C=y.iadd(this.m)),C._forceRed(this)},oe.prototype.invm=function(b){var m=this.imod(b._invmp(this.m).mul(this.r2));return m._forceRed(this)}})(r,fr)})(Gn);var Td={};(function(r){var e=r;function t(s,a){if(Array.isArray(s))return s.slice();if(!s)return[];var f=[];if(typeof s!="string"){for(var h=0;h>8,w=u&255;g?f.push(g,w):f.push(w)}return f}e.toArray=t;function i(s){return s.length===1?"0"+s:s}e.zero2=i;function n(s){for(var a="",f=0;f($>>1)-1?H=($>>1)-F:H=F,W.isubn(H)):H=0,M[O]=H,W.iushrn(1)}return M}e.getNAF=s;function a(g,w){var P=[[],[]];g=g.clone(),w=w.clone();for(var M=0,O=0,$;g.cmpn(-M)>0||w.cmpn(-O)>0;){var W=g.andln(3)+M&3,H=w.andln(3)+O&3;W===3&&(W=-1),H===3&&(H=-1);var F;W&1?($=g.andln(7)+M&7,($===3||$===5)&&H===2?F=-W:F=W):F=0,P[0].push(F);var Y;H&1?($=w.andln(7)+O&7,($===3||$===5)&&W===2?Y=-H:Y=H):Y=0,P[1].push(Y),2*M===F+1&&(M=1-M),2*O===Y+1&&(O=1-O),g.iushrn(1),w.iushrn(1)}return P}e.getJSF=a;function f(g,w,P){var M="_"+w;g.prototype[w]=function(){return this[M]!==void 0?this[M]:this[M]=P.call(this)}}e.cachedProperty=f;function h(g){return typeof g=="string"?e.toArray(g,"hex"):g}e.parseBytes=h;function u(g){return new t(g,"hex","le")}e.intFromLE=u}(Li);var Al={exports:{}},$d;Al.exports=function(e){return $d||($d=new ks(null)),$d.generate(e)};function ks(r){this.rand=r}if(Al.exports.Rand=ks,ks.prototype.generate=function(e){return this._rand(e)},ks.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),i=0;i0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Il=js;js.prototype.point=function(){throw new Error("Not implemented")},js.prototype.validate=function(){throw new Error("Not implemented")},js.prototype._fixedNafMul=function(e,t){Sl(e.precomputed);var i=e._getDoubles(),n=El(t,1,this._bitLength),s=(1<=f;u--)h=(h<<1)+n[u];a.push(h)}for(var g=this.jpoint(null,null,null),w=this.jpoint(null,null,null),P=s;P>0;P--){for(f=0;f=0;h--){for(var u=0;h>=0&&a[h]===0;h--)u++;if(h>=0&&u++,f=f.dblp(u),h<0)break;var g=a[h];Sl(g!==0),e.type==="affine"?g>0?f=f.mixedAdd(s[g-1>>1]):f=f.mixedAdd(s[-g-1>>1].neg()):g>0?f=f.add(s[g-1>>1]):f=f.add(s[-g-1>>1].neg())}return e.type==="affine"?f.toP():f},js.prototype._wnafMulAdd=function(e,t,i,n,s){var a=this._wnafT1,f=this._wnafT2,h=this._wnafT3,u=0,g,w,P;for(g=0;g=1;g-=2){var O=g-1,$=g;if(a[O]!==1||a[$]!==1){h[O]=El(i[O],a[O],this._bitLength),h[$]=El(i[$],a[$],this._bitLength),u=Math.max(h[O].length,u),u=Math.max(h[$].length,u);continue}var W=[t[O],null,null,t[$]];t[O].y.cmp(t[$].y)===0?(W[1]=t[O].add(t[$]),W[2]=t[O].toJ().mixedAdd(t[$].neg())):t[O].y.cmp(t[$].y.redNeg())===0?(W[1]=t[O].toJ().mixedAdd(t[$]),W[2]=t[O].add(t[$].neg())):(W[1]=t[O].toJ().mixedAdd(t[$]),W[2]=t[O].toJ().mixedAdd(t[$].neg()));var H=[-3,-1,-5,-7,0,7,5,1,3],F=G9(i[O],i[$]);for(u=Math.max(F[0].length,u),h[O]=new Array(u),h[$]=new Array(u),w=0;w=0;g--){for(var _=0;g>=0;){var U=!0;for(w=0;w=0&&_++,z=z.dblp(_),g<0)break;for(w=0;w0?P=f[w][ee-1>>1]:ee<0&&(P=f[w][-ee-1>>1].neg()),P.type==="affine"?z=z.mixedAdd(P):z=z.add(P))}}for(g=0;g=Math.ceil((e.bitLength()+1)/t.step):!1},Zi.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var i=[this],n=this,s=0;s=0&&(M=u,O=g),w.negative&&(w=w.neg(),P=P.neg()),M.negative&&(M=M.neg(),O=O.neg()),[{a:w,b:P},{a:M,b:O}]},Xi.prototype._endoSplit=function(e){var t=this.endo.basis,i=t[0],n=t[1],s=n.b.mul(e).divRound(this.n),a=i.b.neg().mul(e).divRound(this.n),f=s.mul(i.a),h=a.mul(n.a),u=s.mul(i.b),g=a.mul(n.b),w=e.sub(f).sub(h),P=u.add(g).neg();return{k1:w,k2:P}},Xi.prototype.pointFromX=function(e,t){e=new dr(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=i.redSqrt();if(n.redSqr().redSub(i).cmp(this.zero)!==0)throw new Error("invalid point");var s=n.fromRed().isOdd();return(t&&!s||!t&&s)&&(n=n.redNeg()),this.point(e,n)},Xi.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,i=e.y,n=this.a.redMul(t),s=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return i.redSqr().redISub(s).cmpn(0)===0},Xi.prototype._endoWnafMulAdd=function(e,t,i){for(var n=this._endoWnafT1,s=this._endoWnafT2,a=0;a":""},Rr.prototype.isInfinity=function(){return this.inf},Rr.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(this.x.cmp(e.x)===0)return this.curve.point(null,null);var t=this.y.redSub(e.y);t.cmpn(0)!==0&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var i=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(i)).redISub(this.y);return this.curve.point(i,n)},Rr.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(e.cmpn(0)===0)return this.curve.point(null,null);var t=this.curve.a,i=this.x.redSqr(),n=e.redInvm(),s=i.redAdd(i).redIAdd(i).redIAdd(t).redMul(n),a=s.redSqr().redISub(this.x.redAdd(this.x)),f=s.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,f)},Rr.prototype.getX=function(){return this.x.fromRed()},Rr.prototype.getY=function(){return this.y.fromRed()},Rr.prototype.mul=function(e){return e=new dr(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)},Rr.prototype.mulAdd=function(e,t,i){var n=[this,t],s=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,s):this.curve._wnafMulAdd(1,n,s,2)},Rr.prototype.jmulAdd=function(e,t,i){var n=[this,t],s=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,s,!0):this.curve._wnafMulAdd(1,n,s,2,!0)},Rr.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||this.x.cmp(e.x)===0&&this.y.cmp(e.y)===0)},Rr.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var i=this.precomputed,n=function(s){return s.neg()};t.precomputed={naf:i.naf&&{wnd:i.naf.wnd,points:i.naf.points.map(n)},doubles:i.doubles&&{step:i.doubles.step,points:i.doubles.points.map(n)}}}return t},Rr.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var e=this.curve.jpoint(this.x,this.y,this.curve.one);return e};function jr(r,e,t,i){Oa.BasePoint.call(this,r,"jacobian"),e===null&&t===null&&i===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new dr(0)):(this.x=new dr(e,16),this.y=new dr(t,16),this.z=new dr(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}Ld(jr,Oa.BasePoint),Xi.prototype.jpoint=function(e,t,i){return new jr(this,e,t,i)},jr.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),i=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(i,n)},jr.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},jr.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),i=this.z.redSqr(),n=this.x.redMul(t),s=e.x.redMul(i),a=this.y.redMul(t.redMul(e.z)),f=e.y.redMul(i.redMul(this.z)),h=n.redSub(s),u=a.redSub(f);if(h.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var g=h.redSqr(),w=g.redMul(h),P=n.redMul(g),M=u.redSqr().redIAdd(w).redISub(P).redISub(P),O=u.redMul(P.redISub(M)).redISub(a.redMul(w)),$=this.z.redMul(e.z).redMul(h);return this.curve.jpoint(M,O,$)},jr.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),i=this.x,n=e.x.redMul(t),s=this.y,a=e.y.redMul(t).redMul(this.z),f=i.redSub(n),h=s.redSub(a);if(f.cmpn(0)===0)return h.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var u=f.redSqr(),g=u.redMul(f),w=i.redMul(u),P=h.redSqr().redIAdd(g).redISub(w).redISub(w),M=h.redMul(w.redISub(P)).redISub(s.redMul(g)),O=this.z.redMul(f);return this.curve.jpoint(P,M,O)},jr.prototype.dblp=function(e){if(e===0)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var i=this;for(t=0;t=0)return!1;if(i.redIAdd(s),this.x.cmp(i)===0)return!0}},jr.prototype.inspect=function(){return this.isInfinity()?"":""},jr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var Ra=Gn.exports,dm=xa.exports,Ml=Il,Z9=Li;function Ta(r){Ml.call(this,"mont",r),this.a=new Ra(r.a,16).toRed(this.red),this.b=new Ra(r.b,16).toRed(this.red),this.i4=new Ra(4).toRed(this.red).redInvm(),this.two=new Ra(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}dm(Ta,Ml);var X9=Ta;Ta.prototype.validate=function(e){var t=e.normalize().x,i=t.redSqr(),n=i.redMul(t).redAdd(i.redMul(this.a)).redAdd(t),s=n.redSqrt();return s.redSqr().cmp(n)===0};function Tr(r,e,t){Ml.BasePoint.call(this,r,"projective"),e===null&&t===null?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new Ra(e,16),this.z=new Ra(t,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}dm(Tr,Ml.BasePoint),Ta.prototype.decodePoint=function(e,t){return this.point(Z9.toArray(e,t),1)},Ta.prototype.point=function(e,t){return new Tr(this,e,t)},Ta.prototype.pointFromJSON=function(e){return Tr.fromJSON(this,e)},Tr.prototype.precompute=function(){},Tr.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Tr.fromJSON=function(e,t){return new Tr(e,t[0],t[1]||e.one)},Tr.prototype.inspect=function(){return this.isInfinity()?"":""},Tr.prototype.isInfinity=function(){return this.z.cmpn(0)===0},Tr.prototype.dbl=function(){var e=this.x.redAdd(this.z),t=e.redSqr(),i=this.x.redSub(this.z),n=i.redSqr(),s=t.redSub(n),a=t.redMul(n),f=s.redMul(n.redAdd(this.curve.a24.redMul(s)));return this.curve.point(a,f)},Tr.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Tr.prototype.diffAdd=function(e,t){var i=this.x.redAdd(this.z),n=this.x.redSub(this.z),s=e.x.redAdd(e.z),a=e.x.redSub(e.z),f=a.redMul(i),h=s.redMul(n),u=t.z.redMul(f.redAdd(h).redSqr()),g=t.x.redMul(f.redISub(h).redSqr());return this.curve.point(u,g)},Tr.prototype.mul=function(e){for(var t=e.clone(),i=this,n=this.curve.point(null,null),s=this,a=[];t.cmpn(0)!==0;t.iushrn(1))a.push(t.andln(1));for(var f=a.length-1;f>=0;f--)a[f]===0?(i=i.diffAdd(n,s),n=n.dbl()):(n=i.diffAdd(n,s),i=i.dbl());return n},Tr.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Tr.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Tr.prototype.eq=function(e){return this.getX().cmp(e.getX())===0},Tr.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Tr.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var ex=Li,ms=Gn.exports,pm=xa.exports,Cl=Il,tx=ex.assert;function Yn(r){this.twisted=(r.a|0)!==1,this.mOneA=this.twisted&&(r.a|0)===-1,this.extended=this.mOneA,Cl.call(this,"edwards",r),this.a=new ms(r.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new ms(r.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new ms(r.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),tx(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(r.c|0)===1}pm(Yn,Cl);var rx=Yn;Yn.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},Yn.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},Yn.prototype.jpoint=function(e,t,i,n){return this.point(e,t,i,n)},Yn.prototype.pointFromX=function(e,t){e=new ms(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr(),n=this.c2.redSub(this.a.redMul(i)),s=this.one.redSub(this.c2.redMul(this.d).redMul(i)),a=n.redMul(s.redInvm()),f=a.redSqrt();if(f.redSqr().redSub(a).cmp(this.zero)!==0)throw new Error("invalid point");var h=f.fromRed().isOdd();return(t&&!h||!t&&h)&&(f=f.redNeg()),this.point(e,f)},Yn.prototype.pointFromY=function(e,t){e=new ms(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr(),n=i.redSub(this.c2),s=i.redMul(this.d).redMul(this.c2).redSub(this.a),a=n.redMul(s.redInvm());if(a.cmp(this.zero)===0){if(t)throw new Error("invalid point");return this.point(this.zero,e)}var f=a.redSqrt();if(f.redSqr().redSub(a).cmp(this.zero)!==0)throw new Error("invalid point");return f.fromRed().isOdd()!==t&&(f=f.redNeg()),this.point(f,e)},Yn.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),i=e.y.redSqr(),n=t.redMul(this.a).redAdd(i),s=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(i)));return n.cmp(s)===0};function nr(r,e,t,i,n){Cl.BasePoint.call(this,r,"projective"),e===null&&t===null&&i===null?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new ms(e,16),this.y=new ms(t,16),this.z=i?new ms(i,16):this.curve.one,this.t=n&&new ms(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}pm(nr,Cl.BasePoint),Yn.prototype.pointFromJSON=function(e){return nr.fromJSON(this,e)},Yn.prototype.point=function(e,t,i,n){return new nr(this,e,t,i,n)},nr.fromJSON=function(e,t){return new nr(e,t[0],t[1],t[2])},nr.prototype.inspect=function(){return this.isInfinity()?"":""},nr.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)},nr.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),i=this.z.redSqr();i=i.redIAdd(i);var n=this.curve._mulA(e),s=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),a=n.redAdd(t),f=a.redSub(i),h=n.redSub(t),u=s.redMul(f),g=a.redMul(h),w=s.redMul(h),P=f.redMul(a);return this.curve.point(u,g,P,w)},nr.prototype._projDbl=function(){var e=this.x.redAdd(this.y).redSqr(),t=this.x.redSqr(),i=this.y.redSqr(),n,s,a,f,h,u;if(this.curve.twisted){f=this.curve._mulA(t);var g=f.redAdd(i);this.zOne?(n=e.redSub(t).redSub(i).redMul(g.redSub(this.curve.two)),s=g.redMul(f.redSub(i)),a=g.redSqr().redSub(g).redSub(g)):(h=this.z.redSqr(),u=g.redSub(h).redISub(h),n=e.redSub(t).redISub(i).redMul(u),s=g.redMul(f.redSub(i)),a=g.redMul(u))}else f=t.redAdd(i),h=this.curve._mulC(this.z).redSqr(),u=f.redSub(h).redSub(h),n=this.curve._mulC(e.redISub(f)).redMul(u),s=this.curve._mulC(f).redMul(t.redISub(i)),a=f.redMul(u);return this.curve.point(n,s,a)},nr.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},nr.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),i=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),s=this.z.redMul(e.z.redAdd(e.z)),a=i.redSub(t),f=s.redSub(n),h=s.redAdd(n),u=i.redAdd(t),g=a.redMul(f),w=h.redMul(u),P=a.redMul(u),M=f.redMul(h);return this.curve.point(g,w,M,P)},nr.prototype._projAdd=function(e){var t=this.z.redMul(e.z),i=t.redSqr(),n=this.x.redMul(e.x),s=this.y.redMul(e.y),a=this.curve.d.redMul(n).redMul(s),f=i.redSub(a),h=i.redAdd(a),u=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(n).redISub(s),g=t.redMul(f).redMul(u),w,P;return this.curve.twisted?(w=t.redMul(h).redMul(s.redSub(this.curve._mulA(n))),P=f.redMul(h)):(w=t.redMul(h).redMul(s.redSub(n)),P=this.curve._mulC(f).redMul(h)),this.curve.point(g,w,P)},nr.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},nr.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},nr.prototype.mulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!1)},nr.prototype.jmulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!0)},nr.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},nr.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},nr.prototype.getX=function(){return this.normalize(),this.x.fromRed()},nr.prototype.getY=function(){return this.normalize(),this.y.fromRed()},nr.prototype.eq=function(e){return this===e||this.getX().cmp(e.getX())===0&&this.getY().cmp(e.getY())===0},nr.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(t)===0)return!0;for(var i=e.clone(),n=this.curve.redN.redMul(this.z);;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),this.x.cmp(t)===0)return!0}},nr.prototype.toP=nr.prototype.normalize,nr.prototype.mixedAdd=nr.prototype.add,function(r){var e=r;e.base=Il,e.short=Q9,e.mont=X9,e.edwards=rx}(Nd);var Pl={},Bd,gm;function ix(){return gm||(gm=1,Bd={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}),Bd}(function(r){var e=r,t=Ri,i=Nd,n=Li,s=n.assert;function a(u){u.type==="short"?this.curve=new i.short(u):u.type==="edwards"?this.curve=new i.edwards(u):this.curve=new i.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,s(this.g.validate(),"Invalid curve"),s(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}e.PresetCurve=a;function f(u,g){Object.defineProperty(e,u,{configurable:!0,enumerable:!0,get:function(){var w=new a(g);return Object.defineProperty(e,u,{configurable:!0,enumerable:!0,value:w}),w}})}f("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:t.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),f("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:t.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),f("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:t.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),f("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:t.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"]}),f("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:t.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"]}),f("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:t.sha256,gRed:!1,g:["9"]}),f("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:t.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var h;try{h=ix()}catch{h=void 0}f("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:t.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",h]})})(Pl);var nx=Ri,Mo=Td,vm=Ao;function Ws(r){if(!(this instanceof Ws))return new Ws(r);this.hash=r.hash,this.predResist=!!r.predResist,this.outLen=this.hash.outSize,this.minEntropy=r.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=Mo.toArray(r.entropy,r.entropyEnc||"hex"),t=Mo.toArray(r.nonce,r.nonceEnc||"hex"),i=Mo.toArray(r.pers,r.persEnc||"hex");vm(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,t,i)}var sx=Ws;Ws.prototype._init=function(e,t,i){var n=e.concat(t).concat(i);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var s=0;s=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(i||[])),this._reseed=1},Ws.prototype.generate=function(e,t,i,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof t!="string"&&(n=i,i=t,t=null),i&&(i=Mo.toArray(i,n||"hex"),this._update(i));for(var s=[];s.length"};var Dl=Gn.exports,Ud=Li,fx=Ud.assert;function Ol(r,e){if(r instanceof Ol)return r;this._importDER(r,e)||(fx(r.r&&r.s,"Signature without r or s"),this.r=new Dl(r.r,16),this.s=new Dl(r.s,16),r.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=r.recoveryParam)}var lx=Ol;function hx(){this.place=0}function qd(r,e){var t=r[e.place++];if(!(t&128))return t;var i=t&15;if(i===0||i>4||r[e.place]===0)return!1;for(var n=0,s=0,a=e.place;s>>=0;return n<=127?!1:(e.place=a,n)}function mm(r){for(var e=0,t=r.length-1;!r[e]&&!(r[e+1]&128)&&e>>3);for(r.push(t|128);--t;)r.push(e>>>(t<<3)&255);r.push(e)}Ol.prototype.toDER=function(e){var t=this.r.toArray(),i=this.s.toArray();for(t[0]&128&&(t=[0].concat(t)),i[0]&128&&(i=[0].concat(i)),t=mm(t),i=mm(i);!i[0]&&!(i[1]&128);)i=i.slice(1);var n=[2];zd(n,t.length),n=n.concat(t),n.push(2),zd(n,i.length);var s=n.concat(i),a=[48];return zd(a,s.length),a=a.concat(s),Ud.encode(a,e)};var bs=Gn.exports,bm=sx,ux=Li,Hd=Pl,dx=Al.exports,wm=ux.assert,kd=cx,Rl=lx;function en(r){if(!(this instanceof en))return new en(r);typeof r=="string"&&(wm(Object.prototype.hasOwnProperty.call(Hd,r),"Unknown curve "+r),r=Hd[r]),r instanceof Hd.PresetCurve&&(r={curve:r}),this.curve=r.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=r.curve.g,this.g.precompute(r.curve.n.bitLength()+1),this.hash=r.hash||r.curve.hash}var px=en;en.prototype.keyPair=function(e){return new kd(this,e)},en.prototype.keyFromPrivate=function(e,t){return kd.fromPrivate(this,e,t)},en.prototype.keyFromPublic=function(e,t){return kd.fromPublic(this,e,t)},en.prototype.genKeyPair=function(e){e||(e={});for(var t=new bm({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||dx(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),i=this.n.byteLength(),n=this.n.sub(new bs(2));;){var s=new bs(t.generate(i));if(!(s.cmp(n)>0))return s.iaddn(1),this.keyFromPrivate(s)}},en.prototype._truncateToN=function(e,t,i){var n;if(bs.isBN(e)||typeof e=="number")e=new bs(e,16),n=e.byteLength();else if(typeof e=="object")n=e.length,e=new bs(e,16);else{var s=e.toString();n=s.length+1>>>1,e=new bs(s,16)}typeof i!="number"&&(i=n*8);var a=i-this.n.bitLength();return a>0&&(e=e.ushrn(a)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},en.prototype.sign=function(e,t,i,n){typeof i=="object"&&(n=i,i=null),n||(n={}),t=this.keyFromPrivate(t,i),e=this._truncateToN(e,!1,n.msgBitLength);for(var s=this.n.byteLength(),a=t.getPrivate().toArray("be",s),f=e.toArray("be",s),h=new bm({hash:this.hash,entropy:a,nonce:f,pers:n.pers,persEnc:n.persEnc||"utf8"}),u=this.n.sub(new bs(1)),g=0;;g++){var w=n.k?n.k(g):new bs(h.generate(this.n.byteLength()));if(w=this._truncateToN(w,!0),!(w.cmpn(1)<=0||w.cmp(u)>=0)){var P=this.g.mul(w);if(!P.isInfinity()){var M=P.getX(),O=M.umod(this.n);if(O.cmpn(0)!==0){var $=w.invm(this.n).mul(O.mul(t.getPrivate()).iadd(e));if($=$.umod(this.n),$.cmpn(0)!==0){var W=(P.getY().isOdd()?1:0)|(M.cmp(O)!==0?2:0);return n.canonical&&$.cmp(this.nh)>0&&($=this.n.sub($),W^=1),new Rl({r:O,s:$,recoveryParam:W})}}}}}},en.prototype.verify=function(e,t,i,n,s){s||(s={}),e=this._truncateToN(e,!1,s.msgBitLength),i=this.keyFromPublic(i,n),t=new Rl(t,"hex");var a=t.r,f=t.s;if(a.cmpn(1)<0||a.cmp(this.n)>=0||f.cmpn(1)<0||f.cmp(this.n)>=0)return!1;var h=f.invm(this.n),u=h.mul(e).umod(this.n),g=h.mul(a).umod(this.n),w;return this.curve._maxwellTrick?(w=this.g.jmulAdd(u,i.getPublic(),g),w.isInfinity()?!1:w.eqXToP(a)):(w=this.g.mulAdd(u,i.getPublic(),g),w.isInfinity()?!1:w.getX().umod(this.n).cmp(a)===0)},en.prototype.recoverPubKey=function(r,e,t,i){wm((3&t)===t,"The recovery param is more than two bits"),e=new Rl(e,i);var n=this.n,s=new bs(r),a=e.r,f=e.s,h=t&1,u=t>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw new Error("Unable to find sencond key candinate");u?a=this.curve.pointFromX(a.add(this.curve.n),h):a=this.curve.pointFromX(a,h);var g=e.r.invm(n),w=n.sub(s).mul(g).umod(n),P=f.mul(g).umod(n);return this.g.mulAdd(w,a,P)},en.prototype.getKeyRecoveryParam=function(r,e,t,i){if(e=new Rl(e,i),e.recoveryParam!==null)return e.recoveryParam;for(var n=0;n<4;n++){var s;try{s=this.recoverPubKey(r,e,n)}catch{continue}if(s.eq(t))return n}throw new Error("Unable to find valid recovery factor")};var kc=Li,ym=kc.assert,_m=kc.parseBytes,$a=kc.cachedProperty;function $r(r,e){this.eddsa=r,this._secret=_m(e.secret),r.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=_m(e.pub)}$r.fromPublic=function(e,t){return t instanceof $r?t:new $r(e,{pub:t})},$r.fromSecret=function(e,t){return t instanceof $r?t:new $r(e,{secret:t})},$r.prototype.secret=function(){return this._secret},$a($r,"pubBytes",function(){return this.eddsa.encodePoint(this.pub())}),$a($r,"pub",function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())}),$a($r,"privBytes",function(){var e=this.eddsa,t=this.hash(),i=e.encodingLength-1,n=t.slice(0,e.encodingLength);return n[0]&=248,n[i]&=127,n[i]|=64,n}),$a($r,"priv",function(){return this.eddsa.decodeInt(this.privBytes())}),$a($r,"hash",function(){return this.eddsa.hash().update(this.secret()).digest()}),$a($r,"messagePrefix",function(){return this.hash().slice(this.eddsa.encodingLength)}),$r.prototype.sign=function(e){return ym(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},$r.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)},$r.prototype.getSecret=function(e){return ym(this._secret,"KeyPair is public only"),kc.encode(this.secret(),e)},$r.prototype.getPublic=function(e){return kc.encode(this.pubBytes(),e)};var gx=$r,vx=Gn.exports,Tl=Li,xm=Tl.assert,$l=Tl.cachedProperty,mx=Tl.parseBytes;function Co(r,e){this.eddsa=r,typeof e!="object"&&(e=mx(e)),Array.isArray(e)&&(xm(e.length===r.encodingLength*2,"Signature has invalid size"),e={R:e.slice(0,r.encodingLength),S:e.slice(r.encodingLength)}),xm(e.R&&e.S,"Signature without R or S"),r.isPoint(e.R)&&(this._R=e.R),e.S instanceof vx&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}$l(Co,"S",function(){return this.eddsa.decodeInt(this.Sencoded())}),$l(Co,"R",function(){return this.eddsa.decodePoint(this.Rencoded())}),$l(Co,"Rencoded",function(){return this.eddsa.encodePoint(this.R())}),$l(Co,"Sencoded",function(){return this.eddsa.encodeInt(this.S())}),Co.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Co.prototype.toHex=function(){return Tl.encode(this.toBytes(),"hex").toUpperCase()};var bx=Co,wx=Ri,yx=Pl,Na=Li,_x=Na.assert,Am=Na.parseBytes,Em=gx,Sm=bx;function mi(r){if(_x(r==="ed25519","only tested with ed25519 so far"),!(this instanceof mi))return new mi(r);r=yx[r].curve,this.curve=r,this.g=r.g,this.g.precompute(r.n.bitLength()+1),this.pointClass=r.point().constructor,this.encodingLength=Math.ceil(r.n.bitLength()/8),this.hash=wx.sha512}var xx=mi;mi.prototype.sign=function(e,t){e=Am(e);var i=this.keyFromSecret(t),n=this.hashInt(i.messagePrefix(),e),s=this.g.mul(n),a=this.encodePoint(s),f=this.hashInt(a,i.pubBytes(),e).mul(i.priv()),h=n.add(f).umod(this.curve.n);return this.makeSignature({R:s,S:h,Rencoded:a})},mi.prototype.verify=function(e,t,i){if(e=Am(e),t=this.makeSignature(t),t.S().gte(t.eddsa.curve.n)||t.S().isNeg())return!1;var n=this.keyFromPublic(i),s=this.hashInt(t.Rencoded(),n.pubBytes(),e),a=this.g.mul(t.S()),f=t.R().add(n.pub().mul(s));return f.eq(a)},mi.prototype.hashInt=function(){for(var e=this.hash(),t=0;t0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=h[g++],u--;this._bufferLength===this.blockSize&&(s(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(u>=this.blockSize&&(g=s(this._tempHi,this._tempLo,this._stateHi,this._stateLo,h,g,u),u%=this.blockSize);u>0;)this._buffer[this._bufferLength++]=h[g++],u--;return this},f.prototype.finish=function(h){if(!this._finished){var u=this._bytesHashed,g=this._bufferLength,w=u/536870912|0,P=u<<3,M=u%128<112?128:256;this._buffer[g]=128;for(var O=g+1;O0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},f.prototype.restoreState=function(h){return this._stateHi.set(h.stateHi),this._stateLo.set(h.stateLo),this._bufferLength=h.bufferLength,h.buffer&&this._buffer.set(h.buffer),this._bytesHashed=h.bytesHashed,this._finished=!1,this},f.prototype.cleanSavedState=function(h){t.wipe(h.stateHi),t.wipe(h.stateLo),h.buffer&&t.wipe(h.buffer),h.bufferLength=0,h.bytesHashed=0},f}();r.SHA512=i;var n=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 s(f,h,u,g,w,P,M){for(var O=u[0],$=u[1],W=u[2],H=u[3],F=u[4],Y=u[5],B=u[6],z=u[7],j=g[0],_=g[1],U=g[2],ee=g[3],oe=g[4],L=g[5],b=g[6],m=g[7],l,d,y,C,D,S,v,A;M>=128;){for(var x=0;x<16;x++){var N=8*x+P;f[x]=e.readUint32BE(w,N),h[x]=e.readUint32BE(w,N+4)}for(var x=0;x<80;x++){var ae=O,R=$,X=W,V=H,J=F,K=Y,E=B,G=z,re=j,le=_,he=U,ge=ee,He=oe,Te=L,Ce=b,Xe=m;if(l=z,d=m,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=(F>>>14|oe<<32-14)^(F>>>18|oe<<32-18)^(oe>>>41-32|F<<32-(41-32)),d=(oe>>>14|F<<32-14)^(oe>>>18|F<<32-18)^(F>>>41-32|oe<<32-(41-32)),D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,l=F&Y^~F&B,d=oe&L^~oe&b,D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,l=n[x*2],d=n[x*2+1],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,l=f[x%16],d=h[x%16],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,y=v&65535|A<<16,C=D&65535|S<<16,l=y,d=C,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=(O>>>28|j<<32-28)^(j>>>34-32|O<<32-(34-32))^(j>>>39-32|O<<32-(39-32)),d=(j>>>28|O<<32-28)^(O>>>34-32|j<<32-(34-32))^(O>>>39-32|j<<32-(39-32)),D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,l=O&$^O&W^$&W,d=j&_^j&U^_&U,D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,G=v&65535|A<<16,Xe=D&65535|S<<16,l=V,d=ge,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=y,d=C,D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,V=v&65535|A<<16,ge=D&65535|S<<16,$=ae,W=R,H=X,F=V,Y=J,B=K,z=E,O=G,_=re,U=le,ee=he,oe=ge,L=He,b=Te,m=Ce,j=Xe,x%16===15)for(var N=0;N<16;N++)l=f[N],d=h[N],D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=f[(N+9)%16],d=h[(N+9)%16],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,y=f[(N+1)%16],C=h[(N+1)%16],l=(y>>>1|C<<32-1)^(y>>>8|C<<32-8)^y>>>7,d=(C>>>1|y<<32-1)^(C>>>8|y<<32-8)^(C>>>7|y<<32-7),D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,y=f[(N+14)%16],C=h[(N+14)%16],l=(y>>>19|C<<32-19)^(C>>>61-32|y<<32-(61-32))^y>>>6,d=(C>>>19|y<<32-19)^(y>>>61-32|C<<32-(61-32))^(C>>>6|y<<32-6),D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,f[N]=v&65535|A<<16,h[N]=D&65535|S<<16}l=O,d=j,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[0],d=g[0],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[0]=O=v&65535|A<<16,g[0]=j=D&65535|S<<16,l=$,d=_,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[1],d=g[1],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[1]=$=v&65535|A<<16,g[1]=_=D&65535|S<<16,l=W,d=U,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[2],d=g[2],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[2]=W=v&65535|A<<16,g[2]=U=D&65535|S<<16,l=H,d=ee,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[3],d=g[3],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[3]=H=v&65535|A<<16,g[3]=ee=D&65535|S<<16,l=F,d=oe,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[4],d=g[4],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[4]=F=v&65535|A<<16,g[4]=oe=D&65535|S<<16,l=Y,d=L,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[5],d=g[5],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[5]=Y=v&65535|A<<16,g[5]=L=D&65535|S<<16,l=B,d=b,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[6],d=g[6],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[6]=B=v&65535|A<<16,g[6]=b=D&65535|S<<16,l=z,d=m,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[7],d=g[7],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[7]=z=v&65535|A<<16,g[7]=m=D&65535|S<<16,P+=128,M-=128}return P}function a(f){var h=new i;h.update(f);var u=h.digest();return h.clean(),u}r.hash=a})(Im),function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.convertSecretKeyToX25519=r.convertPublicKeyToX25519=r.verify=r.sign=r.extractPublicKeyFromSecretKey=r.generateKeyPair=r.generateKeyPairFromSeed=r.SEED_LENGTH=r.SECRET_KEY_LENGTH=r.PUBLIC_KEY_LENGTH=r.SIGNATURE_LENGTH=void 0;const e=Hs,t=Im,i=$i;r.SIGNATURE_LENGTH=64,r.PUBLIC_KEY_LENGTH=32,r.SECRET_KEY_LENGTH=64,r.SEED_LENGTH=32;function n(V){const J=new Float64Array(16);if(V)for(let K=0;K>16&1),K[le-1]&=65535;K[15]=E[15]-32767-(K[14]>>16&1);const re=K[15]>>16&1;K[14]&=65535,$(E,K,1-re)}for(let G=0;G<16;G++)V[2*G]=E[G]&255,V[2*G+1]=E[G]>>8}function H(V,J){let K=0;for(let E=0;E<32;E++)K|=V[E]^J[E];return(1&K-1>>>8)-1}function F(V,J){const K=new Uint8Array(32),E=new Uint8Array(32);return W(K,V),W(E,J),H(K,E)}function Y(V){const J=new Uint8Array(32);return W(J,V),J[0]&1}function B(V,J){for(let K=0;K<16;K++)V[K]=J[2*K]+(J[2*K+1]<<8);V[15]&=32767}function z(V,J,K){for(let E=0;E<16;E++)V[E]=J[E]+K[E]}function j(V,J,K){for(let E=0;E<16;E++)V[E]=J[E]-K[E]}function _(V,J,K){let E,G,re=0,le=0,he=0,ge=0,He=0,Te=0,Ce=0,Xe=0,$e=0,be=0,Pe=0,De=0,ye=0,Ie=0,Oe=0,me=0,Me=0,Be=0,we=0,ke=0,We=0,xe=0,Ve=0,Ke=0,Ge=0,mt=0,It=0,Ye=0,Pt=0,Ot=0,Ze=0,rt=K[0],et=K[1],Ne=K[2],it=K[3],tt=K[4],Re=K[5],lt=K[6],ht=K[7],Le=K[8],ut=K[9],nt=K[10],Fe=K[11],st=K[12],Qe=K[13],qe=K[14],dt=K[15];E=J[0],re+=E*rt,le+=E*et,he+=E*Ne,ge+=E*it,He+=E*tt,Te+=E*Re,Ce+=E*lt,Xe+=E*ht,$e+=E*Le,be+=E*ut,Pe+=E*nt,De+=E*Fe,ye+=E*st,Ie+=E*Qe,Oe+=E*qe,me+=E*dt,E=J[1],le+=E*rt,he+=E*et,ge+=E*Ne,He+=E*it,Te+=E*tt,Ce+=E*Re,Xe+=E*lt,$e+=E*ht,be+=E*Le,Pe+=E*ut,De+=E*nt,ye+=E*Fe,Ie+=E*st,Oe+=E*Qe,me+=E*qe,Me+=E*dt,E=J[2],he+=E*rt,ge+=E*et,He+=E*Ne,Te+=E*it,Ce+=E*tt,Xe+=E*Re,$e+=E*lt,be+=E*ht,Pe+=E*Le,De+=E*ut,ye+=E*nt,Ie+=E*Fe,Oe+=E*st,me+=E*Qe,Me+=E*qe,Be+=E*dt,E=J[3],ge+=E*rt,He+=E*et,Te+=E*Ne,Ce+=E*it,Xe+=E*tt,$e+=E*Re,be+=E*lt,Pe+=E*ht,De+=E*Le,ye+=E*ut,Ie+=E*nt,Oe+=E*Fe,me+=E*st,Me+=E*Qe,Be+=E*qe,we+=E*dt,E=J[4],He+=E*rt,Te+=E*et,Ce+=E*Ne,Xe+=E*it,$e+=E*tt,be+=E*Re,Pe+=E*lt,De+=E*ht,ye+=E*Le,Ie+=E*ut,Oe+=E*nt,me+=E*Fe,Me+=E*st,Be+=E*Qe,we+=E*qe,ke+=E*dt,E=J[5],Te+=E*rt,Ce+=E*et,Xe+=E*Ne,$e+=E*it,be+=E*tt,Pe+=E*Re,De+=E*lt,ye+=E*ht,Ie+=E*Le,Oe+=E*ut,me+=E*nt,Me+=E*Fe,Be+=E*st,we+=E*Qe,ke+=E*qe,We+=E*dt,E=J[6],Ce+=E*rt,Xe+=E*et,$e+=E*Ne,be+=E*it,Pe+=E*tt,De+=E*Re,ye+=E*lt,Ie+=E*ht,Oe+=E*Le,me+=E*ut,Me+=E*nt,Be+=E*Fe,we+=E*st,ke+=E*Qe,We+=E*qe,xe+=E*dt,E=J[7],Xe+=E*rt,$e+=E*et,be+=E*Ne,Pe+=E*it,De+=E*tt,ye+=E*Re,Ie+=E*lt,Oe+=E*ht,me+=E*Le,Me+=E*ut,Be+=E*nt,we+=E*Fe,ke+=E*st,We+=E*Qe,xe+=E*qe,Ve+=E*dt,E=J[8],$e+=E*rt,be+=E*et,Pe+=E*Ne,De+=E*it,ye+=E*tt,Ie+=E*Re,Oe+=E*lt,me+=E*ht,Me+=E*Le,Be+=E*ut,we+=E*nt,ke+=E*Fe,We+=E*st,xe+=E*Qe,Ve+=E*qe,Ke+=E*dt,E=J[9],be+=E*rt,Pe+=E*et,De+=E*Ne,ye+=E*it,Ie+=E*tt,Oe+=E*Re,me+=E*lt,Me+=E*ht,Be+=E*Le,we+=E*ut,ke+=E*nt,We+=E*Fe,xe+=E*st,Ve+=E*Qe,Ke+=E*qe,Ge+=E*dt,E=J[10],Pe+=E*rt,De+=E*et,ye+=E*Ne,Ie+=E*it,Oe+=E*tt,me+=E*Re,Me+=E*lt,Be+=E*ht,we+=E*Le,ke+=E*ut,We+=E*nt,xe+=E*Fe,Ve+=E*st,Ke+=E*Qe,Ge+=E*qe,mt+=E*dt,E=J[11],De+=E*rt,ye+=E*et,Ie+=E*Ne,Oe+=E*it,me+=E*tt,Me+=E*Re,Be+=E*lt,we+=E*ht,ke+=E*Le,We+=E*ut,xe+=E*nt,Ve+=E*Fe,Ke+=E*st,Ge+=E*Qe,mt+=E*qe,It+=E*dt,E=J[12],ye+=E*rt,Ie+=E*et,Oe+=E*Ne,me+=E*it,Me+=E*tt,Be+=E*Re,we+=E*lt,ke+=E*ht,We+=E*Le,xe+=E*ut,Ve+=E*nt,Ke+=E*Fe,Ge+=E*st,mt+=E*Qe,It+=E*qe,Ye+=E*dt,E=J[13],Ie+=E*rt,Oe+=E*et,me+=E*Ne,Me+=E*it,Be+=E*tt,we+=E*Re,ke+=E*lt,We+=E*ht,xe+=E*Le,Ve+=E*ut,Ke+=E*nt,Ge+=E*Fe,mt+=E*st,It+=E*Qe,Ye+=E*qe,Pt+=E*dt,E=J[14],Oe+=E*rt,me+=E*et,Me+=E*Ne,Be+=E*it,we+=E*tt,ke+=E*Re,We+=E*lt,xe+=E*ht,Ve+=E*Le,Ke+=E*ut,Ge+=E*nt,mt+=E*Fe,It+=E*st,Ye+=E*Qe,Pt+=E*qe,Ot+=E*dt,E=J[15],me+=E*rt,Me+=E*et,Be+=E*Ne,we+=E*it,ke+=E*tt,We+=E*Re,xe+=E*lt,Ve+=E*ht,Ke+=E*Le,Ge+=E*ut,mt+=E*nt,It+=E*Fe,Ye+=E*st,Pt+=E*Qe,Ot+=E*qe,Ze+=E*dt,re+=38*Me,le+=38*Be,he+=38*we,ge+=38*ke,He+=38*We,Te+=38*xe,Ce+=38*Ve,Xe+=38*Ke,$e+=38*Ge,be+=38*mt,Pe+=38*It,De+=38*Ye,ye+=38*Pt,Ie+=38*Ot,Oe+=38*Ze,G=1,E=re+G+65535,G=Math.floor(E/65536),re=E-G*65536,E=le+G+65535,G=Math.floor(E/65536),le=E-G*65536,E=he+G+65535,G=Math.floor(E/65536),he=E-G*65536,E=ge+G+65535,G=Math.floor(E/65536),ge=E-G*65536,E=He+G+65535,G=Math.floor(E/65536),He=E-G*65536,E=Te+G+65535,G=Math.floor(E/65536),Te=E-G*65536,E=Ce+G+65535,G=Math.floor(E/65536),Ce=E-G*65536,E=Xe+G+65535,G=Math.floor(E/65536),Xe=E-G*65536,E=$e+G+65535,G=Math.floor(E/65536),$e=E-G*65536,E=be+G+65535,G=Math.floor(E/65536),be=E-G*65536,E=Pe+G+65535,G=Math.floor(E/65536),Pe=E-G*65536,E=De+G+65535,G=Math.floor(E/65536),De=E-G*65536,E=ye+G+65535,G=Math.floor(E/65536),ye=E-G*65536,E=Ie+G+65535,G=Math.floor(E/65536),Ie=E-G*65536,E=Oe+G+65535,G=Math.floor(E/65536),Oe=E-G*65536,E=me+G+65535,G=Math.floor(E/65536),me=E-G*65536,re+=G-1+37*(G-1),G=1,E=re+G+65535,G=Math.floor(E/65536),re=E-G*65536,E=le+G+65535,G=Math.floor(E/65536),le=E-G*65536,E=he+G+65535,G=Math.floor(E/65536),he=E-G*65536,E=ge+G+65535,G=Math.floor(E/65536),ge=E-G*65536,E=He+G+65535,G=Math.floor(E/65536),He=E-G*65536,E=Te+G+65535,G=Math.floor(E/65536),Te=E-G*65536,E=Ce+G+65535,G=Math.floor(E/65536),Ce=E-G*65536,E=Xe+G+65535,G=Math.floor(E/65536),Xe=E-G*65536,E=$e+G+65535,G=Math.floor(E/65536),$e=E-G*65536,E=be+G+65535,G=Math.floor(E/65536),be=E-G*65536,E=Pe+G+65535,G=Math.floor(E/65536),Pe=E-G*65536,E=De+G+65535,G=Math.floor(E/65536),De=E-G*65536,E=ye+G+65535,G=Math.floor(E/65536),ye=E-G*65536,E=Ie+G+65535,G=Math.floor(E/65536),Ie=E-G*65536,E=Oe+G+65535,G=Math.floor(E/65536),Oe=E-G*65536,E=me+G+65535,G=Math.floor(E/65536),me=E-G*65536,re+=G-1+37*(G-1),V[0]=re,V[1]=le,V[2]=he,V[3]=ge,V[4]=He,V[5]=Te,V[6]=Ce,V[7]=Xe,V[8]=$e,V[9]=be,V[10]=Pe,V[11]=De,V[12]=ye,V[13]=Ie,V[14]=Oe,V[15]=me}function U(V,J){_(V,J,J)}function ee(V,J){const K=n();let E;for(E=0;E<16;E++)K[E]=J[E];for(E=253;E>=0;E--)U(K,K),E!==2&&E!==4&&_(K,K,J);for(E=0;E<16;E++)V[E]=K[E]}function oe(V,J){const K=n();let E;for(E=0;E<16;E++)K[E]=J[E];for(E=250;E>=0;E--)U(K,K),E!==1&&_(K,K,J);for(E=0;E<16;E++)V[E]=K[E]}function L(V,J){const K=n(),E=n(),G=n(),re=n(),le=n(),he=n(),ge=n(),He=n(),Te=n();j(K,V[1],V[0]),j(Te,J[1],J[0]),_(K,K,Te),z(E,V[0],V[1]),z(Te,J[0],J[1]),_(E,E,Te),_(G,V[3],J[3]),_(G,G,u),_(re,V[2],J[2]),z(re,re,re),j(le,E,K),j(he,re,G),z(ge,re,G),z(He,E,K),_(V[0],le,he),_(V[1],He,ge),_(V[2],ge,he),_(V[3],le,He)}function b(V,J,K){for(let E=0;E<4;E++)$(V[E],J[E],K)}function m(V,J){const K=n(),E=n(),G=n();ee(G,J[2]),_(K,J[0],G),_(E,J[1],G),W(V,E),V[31]^=Y(K)<<7}function l(V,J,K){M(V[0],a),M(V[1],f),M(V[2],f),M(V[3],a);for(let E=255;E>=0;--E){const G=K[E/8|0]>>(E&7)&1;b(V,J,G),L(J,V),L(V,V),b(V,J,G)}}function d(V,J){const K=[n(),n(),n(),n()];M(K[0],g),M(K[1],w),M(K[2],f),_(K[3],g,w),l(V,K,J)}function y(V){if(V.length!==r.SEED_LENGTH)throw new Error(`ed25519: seed must be ${r.SEED_LENGTH} bytes`);const J=(0,t.hash)(V);J[0]&=248,J[31]&=127,J[31]|=64;const K=new Uint8Array(32),E=[n(),n(),n(),n()];d(E,J),m(K,E);const G=new Uint8Array(64);return G.set(V),G.set(K,32),{publicKey:K,secretKey:G}}r.generateKeyPairFromSeed=y;function C(V){const J=(0,e.randomBytes)(32,V),K=y(J);return(0,i.wipe)(J),K}r.generateKeyPair=C;function D(V){if(V.length!==r.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${r.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(V.subarray(32))}r.extractPublicKeyFromSecretKey=D;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 v(V,J){let K,E,G,re;for(E=63;E>=32;--E){for(K=0,G=E-32,re=E-12;G>4)*S[G],K=J[G]>>8,J[G]&=255;for(G=0;G<32;G++)J[G]-=K*S[G];for(E=0;E<32;E++)J[E+1]+=J[E]>>8,V[E]=J[E]&255}function A(V){const J=new Float64Array(64);for(let K=0;K<64;K++)J[K]=V[K];for(let K=0;K<64;K++)V[K]=0;v(V,J)}function x(V,J){const K=new Float64Array(64),E=[n(),n(),n(),n()],G=(0,t.hash)(V.subarray(0,32));G[0]&=248,G[31]&=127,G[31]|=64;const re=new Uint8Array(64);re.set(G.subarray(32),32);const le=new t.SHA512;le.update(re.subarray(32)),le.update(J);const he=le.digest();le.clean(),A(he),d(E,he),m(re,E),le.reset(),le.update(re.subarray(0,32)),le.update(V.subarray(32)),le.update(J);const ge=le.digest();A(ge);for(let He=0;He<32;He++)K[He]=he[He];for(let He=0;He<32;He++)for(let Te=0;Te<32;Te++)K[He+Te]+=ge[He]*G[Te];return v(re.subarray(32),K),re}r.sign=x;function N(V,J){const K=n(),E=n(),G=n(),re=n(),le=n(),he=n(),ge=n();return M(V[2],f),B(V[1],J),U(G,V[1]),_(re,G,h),j(G,G,V[2]),z(re,V[2],re),U(le,re),U(he,le),_(ge,he,le),_(K,ge,G),_(K,K,re),oe(K,K),_(K,K,G),_(K,K,re),_(K,K,re),_(V[0],K,re),U(E,V[0]),_(E,E,re),F(E,G)&&_(V[0],V[0],P),U(E,V[0]),_(E,E,re),F(E,G)?-1:(Y(V[0])===J[31]>>7&&j(V[0],a,V[0]),_(V[3],V[0],V[1]),0)}function ae(V,J,K){const E=new Uint8Array(32),G=[n(),n(),n(),n()],re=[n(),n(),n(),n()];if(K.length!==r.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${r.SIGNATURE_LENGTH} bytes`);if(N(re,V))return!1;const le=new t.SHA512;le.update(K.subarray(0,32)),le.update(V),le.update(J);const he=le.digest();return A(he),l(G,re,he),d(re,K.subarray(32)),L(G,re),m(E,G),!H(K,E)}r.verify=ae;function R(V){let J=[n(),n(),n(),n()];if(N(J,V))throw new Error("Ed25519: invalid public key");let K=n(),E=n(),G=J[1];z(K,f,G),j(E,f,G),ee(E,E),_(K,K,E);let re=new Uint8Array(32);return W(re,K),re}r.convertPublicKeyToX25519=R;function X(V){const J=(0,t.hash)(V.subarray(0,32));J[0]&=248,J[31]&=127,J[31]|=64;const K=new Uint8Array(J.subarray(0,32));return(0,i.wipe)(J),K}r.convertSecretKeyToX25519=X}(jd);const Ax="EdDSA",Ex="JWT",Nl=".",Ll="base64url",Mm="utf8",Cm="utf8",Sx=":",Ix="did",Mx="key",Pm="base58btc",Cx="z",Px="K36",Dx=32;function Wd(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Dm(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Wd(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Ox(r,e){e||(e=r.reduce((n,s)=>n+s.length,0));const t=Dm(e);let i=0;for(const n of r)t.set(n,i),i+=n.length;return Wd(t)}function Om(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const Rm=Om("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Kd=Om("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=Dm(r.length);for(let t=0;tJSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString()+"n":t),Tx=r=>{const e=/([\[:])?(\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,t=r.replace(e,'$1"$2n"$3');return JSON.parse(t,(i,n)=>typeof n=="string"&&n.match(/^\d+n$/)?BigInt(n.substring(0,n.length-1)):n)};function Po(r){if(typeof r!="string")throw new Error(`Cannot safe json parse value of type ${typeof r}`);try{return Tx(r)}catch{return r}}function ws(r){return typeof r=="string"?r:Rx(r)||""}function $m(r){return Po(Bl(La(r,Ll),Mm))}function Fl(r){return Bl(La(ws(r),Mm),Ll)}function Nm(r){const e=La(Px,Pm),t=Cx+Bl(Ox([e,r]),Pm);return[Ix,Mx,t].join(Sx)}function $x(r){return Bl(r,Ll)}function Nx(r){return La(r,Ll)}function Lx(r){return La([Fl(r.header),Fl(r.payload)].join(Nl),Cm)}function Bx(r){return[Fl(r.header),Fl(r.payload),$x(r.signature)].join(Nl)}function Vd(r){const e=r.split(Nl),t=$m(e[0]),i=$m(e[1]),n=Nx(e[2]),s=La(e.slice(0,2).join(Nl),Cm);return{header:t,payload:i,signature:n,data:s}}function Lm(r=Hs.randomBytes(Dx)){return jd.generateKeyPairFromSeed(r)}async function Fx(r,e,t,i,n=Ae.fromMiliseconds(Date.now())){const s={alg:Ax,typ:Ex},a=Nm(i.publicKey),f=n+t,h={iss:a,sub:r,aud:e,iat:n,exp:f},u=Lx({header:s,payload:h}),g=jd.sign(i.secretKey,u);return Bx({header:s,payload:h,signature:g})}const Ux={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}},qx=":";function Ba(r){const[e,t]=r.split(qx);return{namespace:e,reference:t}}function Bm(r,e=[]){const t=[];return Object.keys(r).forEach(i=>{if(e.length&&!e.includes(i))return;const n=r[i];t.push(...n.accounts)}),t}function Fm(r,e){return r.includes(":")?[r]:e.chains||[]}var zx=Object.defineProperty,Um=Object.getOwnPropertySymbols,Hx=Object.prototype.hasOwnProperty,kx=Object.prototype.propertyIsEnumerable,qm=(r,e,t)=>e in r?zx(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zm=(r,e)=>{for(var t in e||(e={}))Hx.call(e,t)&&qm(r,t,e[t]);if(Um)for(var t of Um(e))kx.call(e,t)&&qm(r,t,e[t]);return r};const jx="ReactNative",Bi={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Wx="js";function Ul(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Fa(){return!Dc()&&!!Yu()&&navigator.product===jx}function jc(){return!Ul()&&!!Yu()&&!!Dc()}function Wc(){return Fa()?Bi.reactNative:Ul()?Bi.node:jc()?Bi.browser:Bi.unknown}function Kx(){var r;try{return Fa()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(r=global.Application)==null?void 0:r.applicationId:void 0}catch{return}}function Vx(r,e){let t=Oc.parse(r);return t=zm(zm({},t),e),r=Oc.stringify(t),r}function Hm(){return Mg()||{name:"",description:"",url:"",icons:[""]}}function Gx(){if(Wc()===Bi.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:t,Version:i}=global.Platform;return[t,i].join("-")}const r=r5();if(r===null)return"unknown";const e=r.os?r.os.replace(" ","").toLowerCase():"unknown";return r.type==="browser"?[e,r.name,r.version].join("-"):[e,r.version].join("-")}function Yx(){var r;const e=Wc();return e===Bi.browser?[e,((r=Ig())==null?void 0:r.host)||"unknown"].join(":"):e}function km(r,e,t){const i=Gx(),n=Yx();return[[r,e].join("-"),[Wx,t].join("-"),i,n].join("/")}function Jx({protocol:r,version:e,relayUrl:t,sdkVersion:i,auth:n,projectId:s,useOnCloseEvent:a,bundleId:f}){const h=t.split("?"),u=km(r,e,i),g={auth:n,ua:u,projectId:s,useOnCloseEvent:a||void 0,origin:f||void 0},w=Vx(h[1]||"",g);return h[0]+"?"+w}function Do(r,e){return r.filter(t=>e.includes(t)).length===r.length}function jm(r){return Object.fromEntries(r.entries())}function Wm(r){return new Map(Object.entries(r))}function Oo(r=Ae.FIVE_MINUTES,e){const t=Ae.toMiliseconds(r||Ae.FIVE_MINUTES);let i,n,s;return{resolve:a=>{s&&i&&(clearTimeout(s),i(a))},reject:a=>{s&&n&&(clearTimeout(s),n(a))},done:()=>new Promise((a,f)=>{s=setTimeout(()=>{f(new Error(e))},t),i=a,n=f})}}function Ua(r,e,t){return new Promise(async(i,n)=>{const s=setTimeout(()=>n(new Error(t)),e);try{const a=await r;i(a)}catch(a){n(a)}clearTimeout(s)})}function Km(r,e){if(typeof e=="string"&&e.startsWith(`${r}:`))return e;if(r.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(r.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${r}`)}function Qx(r){return Km("topic",r)}function Zx(r){return Km("id",r)}function Vm(r){const[e,t]=r.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function Ir(r,e){return Ae.fromMiliseconds((e||Date.now())+Ae.toMiliseconds(r))}function Ks(r){return Date.now()>=Ae.toMiliseconds(r)}function Dt(r,e){return`${r}${e?`:${e}`:""}`}function ql(r=[],e=[]){return[...new Set([...r,...e])]}async function Xx({id:r,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const n=typeof t=="string"?JSON.parse(t):t,s=n?.href;if(typeof s!="string")return;const a=eA(s,r,e),f=Wc();if(f===Bi.browser){if(!((i=Dc())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}a.startsWith("https://")||a.startsWith("http://")?window.open(a,"_blank","noreferrer noopener"):window.open(a,rA()?"_blank":"_self","noreferrer noopener")}else f===Bi.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(a)}catch(n){console.error(n)}}function eA(r,e,t){const i=`requestId=${e}&sessionTopic=${t}`;r.endsWith("/")&&(r=r.slice(0,-1));let n=`${r}`;if(r.startsWith("https://t.me")){const s=r.includes("?")?"&startapp=":"?startapp=";n=`${n}${s}${iA(i,!0)}`}else n=`${n}/wc?${i}`;return n}async function tA(r,e){let t="";try{if(jc()&&(t=localStorage.getItem(e),t))return t;t=await r.getItem(e)}catch(i){console.error(i)}return t}function Gm(r,e){if(!r.includes(e))return null;const t=r.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Ym(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Gd(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function rA(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function iA(r,e=!1){const t=Buffer.from(r).toString("base64");return e?t.replace(/[=]/g,""):t}function Jm(r){return Buffer.from(r,"base64").toString("utf-8")}const nA="https://rpc.walletconnect.org/v1";async function sA(r,e,t,i,n,s){switch(t.t){case"eip191":return oA(r,e,t.s);case"eip1271":return await aA(r,e,t.s,i,n,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}function oA(r,e,t){return I_(iv(e),t).toLowerCase()===r.toLowerCase()}async function aA(r,e,t,i,n,s){const a=Ba(i);if(!a.namespace||!a.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const f="0x1626ba7e",h="0000000000000000000000000000000000000000000000000000000000000040",u="0000000000000000000000000000000000000000000000000000000000000041",g=t.substring(2),w=iv(e).substring(2),P=f+w+h+u+g,M=await fetch(`${s||nA}/?chainId=${i}&projectId=${n}`,{method:"POST",body:JSON.stringify({id:cA(),jsonrpc:"2.0",method:"eth_call",params:[{to:r,data:P},"latest"]})}),{result:O}=await M.json();return O?O.slice(0,f.length).toLowerCase()===f.toLowerCase():!1}catch(f){return console.error("isValidEip1271Signature: ",f),!1}}function cA(){return Date.now()+Math.floor(Math.random()*1e3)}var fA=Object.defineProperty,lA=Object.defineProperties,hA=Object.getOwnPropertyDescriptors,Qm=Object.getOwnPropertySymbols,uA=Object.prototype.hasOwnProperty,dA=Object.prototype.propertyIsEnumerable,Zm=(r,e,t)=>e in r?fA(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pA=(r,e)=>{for(var t in e||(e={}))uA.call(e,t)&&Zm(r,t,e[t]);if(Qm)for(var t of Qm(e))dA.call(e,t)&&Zm(r,t,e[t]);return r},gA=(r,e)=>lA(r,hA(e));const vA="did:pkh:",Yd=r=>r?.split(":"),mA=r=>{const e=r&&Yd(r);if(e)return r.includes(vA)?e[3]:e[1]},Jd=r=>{const e=r&&Yd(r);if(e)return e[2]+":"+e[3]},zl=r=>{const e=r&&Yd(r);if(e)return e.pop()};async function Xm(r){const{cacao:e,projectId:t}=r,{s:i,p:n}=e,s=eb(n,n.iss),a=zl(n.iss);return await sA(a,s,i,Jd(n.iss),t)}const eb=(r,e)=>{const t=`${r.domain} wants you to sign in with your Ethereum account:`,i=zl(e);if(!r.aud&&!r.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=r.statement||void 0;const s=`URI: ${r.aud||r.uri}`,a=`Version: ${r.version}`,f=`Chain ID: ${mA(e)}`,h=`Nonce: ${r.nonce}`,u=`Issued At: ${r.iat}`,g=r.exp?`Expiration Time: ${r.exp}`:void 0,w=r.nbf?`Not Before: ${r.nbf}`:void 0,P=r.requestId?`Request ID: ${r.requestId}`:void 0,M=r.resources?`Resources:${r.resources.map($=>` +-- ${$}`).join("")}`:void 0,O=Hl(r.resources);if(O){const $=Kc(O);n=IA(n,$)}return[t,i,"",n,"",s,a,f,h,u,g,w,P,M].filter($=>$!=null).join(` +-`)};function bA(r){return Buffer.from(JSON.stringify(r)).toString("base64")}function wA(r){return JSON.parse(Buffer.from(r,"base64").toString("utf-8"))}function Ro(r){if(!r)throw new Error("No recap provided, value is undefined");if(!r.att)throw new Error("No `att` property found");const e=Object.keys(r.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=r.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(n=>{const s=i[n];if(!Array.isArray(s))throw new Error(`Ability limits ${n} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${n} is empty array, must be an array with objects`);s.forEach(a=>{if(typeof a!="object")throw new Error(`Ability limits (${n}) must be an array of objects, found: ${a}`)})})})}function yA(r,e,t,i={}){return t?.sort((n,s)=>n.localeCompare(s)),{att:{[r]:_A(e,t,i)}}}function _A(r,e,t={}){e=e?.sort((n,s)=>n.localeCompare(s));const i=e.map(n=>({[`${r}/${n}`]:[t]}));return Object.assign({},...i)}function tb(r){return Ro(r),`urn:recap:${bA(r).replace(/=/g,"")}`}function Kc(r){const e=wA(r.replace("urn:recap:",""));return Ro(e),e}function xA(r,e,t){const i=yA(r,e,t);return tb(i)}function AA(r){return r&&r.includes("urn:recap:")}function EA(r,e){const t=Kc(r),i=Kc(e),n=SA(t,i);return tb(n)}function SA(r,e){Ro(r),Ro(e);const t=Object.keys(r.att).concat(Object.keys(e.att)).sort((n,s)=>n.localeCompare(s)),i={att:{}};return t.forEach(n=>{var s,a;Object.keys(((s=r.att)==null?void 0:s[n])||{}).concat(Object.keys(((a=e.att)==null?void 0:a[n])||{})).sort((f,h)=>f.localeCompare(h)).forEach(f=>{var h,u;i.att[n]=gA(pA({},i.att[n]),{[f]:((h=r.att[n])==null?void 0:h[f])||((u=e.att[n])==null?void 0:u[f])})})}),i}function IA(r="",e){Ro(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(r.includes(t))return r;const i=[];let n=0;Object.keys(e.att).forEach(f=>{const h=Object.keys(e.att[f]).map(w=>({ability:w.split("/")[0],action:w.split("/")[1]}));h.sort((w,P)=>w.action.localeCompare(P.action));const u={};h.forEach(w=>{u[w.ability]||(u[w.ability]=[]),u[w.ability].push(w.action)});const g=Object.keys(u).map(w=>(n++,`(${n}) '${w}': '${u[w].join("', '")}' for '${f}'.`));i.push(g.join(", ").replace(".,","."))});const s=i.join(" "),a=`${t}${s}`;return`${r?r+" ":""}${a}`}function rb(r){var e;const t=Kc(r);Ro(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(n=>n.split("/")[1]):[]}function ib(r){const e=Kc(r);Ro(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(n=>{var s;(s=n?.[0])!=null&&s.chains&&t.push(n[0].chains)})}),[...new Set(t.flat())]}function Hl(r){if(!r)return;const e=r?.[r.length-1];return AA(e)?e:void 0}const nb="base10",si="base16",Vs="base64pad",Vc="base64url",Gc="utf8",sb=0,ys=1,Yc=2,MA=0,ob=1,Jc=12,Qd=32;function CA(){const r=Cd.generateKeyPair();return{privateKey:Ni(r.secretKey,si),publicKey:Ni(r.publicKey,si)}}function Zd(){const r=Hs.randomBytes(Qd);return Ni(r,si)}function PA(r,e){const t=Cd.sharedKey(Qi(r,si),Qi(e,si),!0),i=new o7(qc.SHA256,t).expand(Qd);return Ni(i,si)}function kl(r){const e=qc.hash(Qi(r,si));return Ni(e,si)}function _s(r){const e=qc.hash(Qi(r,Gc));return Ni(e,si)}function ab(r){return Qi(`${r}`,nb)}function To(r){return Number(Ni(r,nb))}function DA(r){const e=ab(typeof r.type<"u"?r.type:sb);if(To(e)===ys&&typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof r.senderPublicKey<"u"?Qi(r.senderPublicKey,si):void 0,i=typeof r.iv<"u"?Qi(r.iv,si):Hs.randomBytes(Jc),n=new _d.ChaCha20Poly1305(Qi(r.symKey,si)).seal(i,Qi(r.message,Gc));return cb({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:r.encoding})}function OA(r,e){const t=ab(Yc),i=Hs.randomBytes(Jc),n=Qi(r,Gc);return cb({type:t,sealed:n,iv:i,encoding:e})}function RA(r){const e=new _d.ChaCha20Poly1305(Qi(r.symKey,si)),{sealed:t,iv:i}=Qc({encoded:r.encoded,encoding:r?.encoding}),n=e.open(i,t);if(n===null)throw new Error("Failed to decrypt");return Ni(n,Gc)}function TA(r,e){const{sealed:t}=Qc({encoded:r,encoding:e});return Ni(t,Gc)}function cb(r){const{encoding:e=Vs}=r;if(To(r.type)===Yc)return Ni(Pd([r.type,r.sealed]),e);if(To(r.type)===ys){if(typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ni(Pd([r.type,r.senderPublicKey,r.iv,r.sealed]),e)}return Ni(Pd([r.type,r.iv,r.sealed]),e)}function Qc(r){const{encoded:e,encoding:t=Vs}=r,i=Qi(e,t),n=i.slice(MA,ob),s=ob;if(To(n)===ys){const u=s+Qd,g=u+Jc,w=i.slice(s,u),P=i.slice(u,g),M=i.slice(g);return{type:n,sealed:M,iv:P,senderPublicKey:w}}if(To(n)===Yc){const u=i.slice(s),g=Hs.randomBytes(Jc);return{type:n,sealed:u,iv:g}}const a=s+Jc,f=i.slice(s,a),h=i.slice(a);return{type:n,sealed:h,iv:f}}function $A(r,e){const t=Qc({encoded:r,encoding:e?.encoding});return fb({type:To(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Ni(t.senderPublicKey,si):void 0,receiverPublicKey:e?.receiverPublicKey})}function fb(r){const e=r?.type||sb;if(e===ys){if(typeof r?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof r?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:r?.senderPublicKey,receiverPublicKey:r?.receiverPublicKey}}function lb(r){return r.type===ys&&typeof r.senderPublicKey=="string"&&typeof r.receiverPublicKey=="string"}function hb(r){return r.type===Yc}function NA(r){return new hm.ec("p256").keyFromPublic({x:Buffer.from(r.x,"base64").toString("hex"),y:Buffer.from(r.y,"base64").toString("hex")},"hex")}function LA(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function BA(r){return Buffer.from(LA(r),"base64")}function FA(r,e){const[t,i,n]=r.split("."),s=BA(n);if(s.length!==64)throw new Error("Invalid signature length");const a=s.slice(0,32).toString("hex"),f=s.slice(32,64).toString("hex"),h=`${t}.${i}`,u=new qc.SHA256().update(Buffer.from(h)).digest(),g=NA(e),w=Buffer.from(u).toString("hex");if(!g.verify(w,{r:a,s:f}))throw new Error("Invalid signature");return Vd(r).payload}const UA="irn";function Xd(r){return r?.relay||{protocol:UA}}function Zc(r){const e=Ux[r];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${r}`);return e}var qA=Object.defineProperty,zA=Object.defineProperties,HA=Object.getOwnPropertyDescriptors,ub=Object.getOwnPropertySymbols,kA=Object.prototype.hasOwnProperty,jA=Object.prototype.propertyIsEnumerable,db=(r,e,t)=>e in r?qA(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pb=(r,e)=>{for(var t in e||(e={}))kA.call(e,t)&&db(r,t,e[t]);if(ub)for(var t of ub(e))jA.call(e,t)&&db(r,t,e[t]);return r},WA=(r,e)=>zA(r,HA(e));function KA(r,e="-"){const t={},i="relay"+e;return Object.keys(r).forEach(n=>{if(n.startsWith(i)){const s=n.replace(i,""),a=r[n];t[s]=a}}),t}function gb(r){if(!r.includes("wc:")){const h=Jm(r);h!=null&&h.includes("wc:")&&(r=h)}r=r.includes("wc://")?r.replace("wc://",""):r,r=r.includes("wc:")?r.replace("wc:",""):r;const e=r.indexOf(":"),t=r.indexOf("?")!==-1?r.indexOf("?"):void 0,i=r.substring(0,e),n=r.substring(e+1,t).split("@"),s=typeof t<"u"?r.substring(t):"",a=Oc.parse(s),f=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:VA(n[0]),version:parseInt(n[1],10),symKey:a.symKey,relay:KA(a),methods:f,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function VA(r){return r.startsWith("//")?r.substring(2):r}function GA(r,e="-"){const t="relay",i={};return Object.keys(r).forEach(n=>{const s=t+e+n;r[n]&&(i[s]=r[n])}),i}function vb(r){return`${r.protocol}:${r.topic}@${r.version}?`+Oc.stringify(pb(WA(pb({symKey:r.symKey},GA(r.relay)),{expiryTimestamp:r.expiryTimestamp}),r.methods?{methods:r.methods.join(",")}:{}))}function jl(r,e,t){return`${r}?wc_ev=${t}&topic=${e}`}function qa(r){const e=[];return r.forEach(t=>{const[i,n]=t.split(":");e.push(`${i}:${n}`)}),e}function YA(r){const e=[];return Object.values(r).forEach(t=>{e.push(...qa(t.accounts))}),e}function JA(r,e){const t=[];return Object.values(r).forEach(i=>{qa(i.accounts).includes(e)&&t.push(...i.methods)}),t}function QA(r,e){const t=[];return Object.values(r).forEach(i=>{qa(i.accounts).includes(e)&&t.push(...i.events)}),t}function e0(r){return r.includes(":")}function Xc(r){return e0(r)?r.split(":")[0]:r}function ZA(r){const e={};return r?.forEach(t=>{const[i,n]=t.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[]}),e[i].accounts.push(t),e[i].chains.push(`${i}:${n}`)}),e}function mb(r,e){e=e.map(i=>i.replace("did:pkh:",""));const t=ZA(e);for(const[i,n]of Object.entries(t))n.methods?n.methods=ql(n.methods,r):n.methods=r,n.events=["chainChanged","accountsChanged"];return t}const XA={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}},eE={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 _e(r,e){const{message:t,code:i}=eE[r];return{message:e?`${t} ${e}`:t,code:i}}function Gt(r,e){const{message:t,code:i}=XA[r];return{message:e?`${t} ${e}`:t,code:i}}function Jn(r,e){return Array.isArray(r)?typeof e<"u"&&r.length?r.every(e):!0:!1}function ef(r){return Object.getPrototypeOf(r)===Object.prototype&&Object.keys(r).length}function oi(r){return typeof r>"u"}function wr(r,e){return e&&oi(r)?!0:typeof r=="string"&&!!r.trim().length}function t0(r,e){return e&&oi(r)?!0:typeof r=="number"&&!isNaN(r)}function tE(r,e){const{requiredNamespaces:t}=e,i=Object.keys(r.namespaces),n=Object.keys(t);let s=!0;return Do(n,i)?(i.forEach(a=>{const{accounts:f,methods:h,events:u}=r.namespaces[a],g=qa(f),w=t[a];(!Do(Fm(a,w),g)||!Do(w.methods,h)||!Do(w.events,u))&&(s=!1)}),s):!1}function Wl(r){return wr(r,!1)&&r.includes(":")?r.split(":").length===2:!1}function rE(r){if(wr(r,!1)&&r.includes(":")){const e=r.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Wl(t)}}return!1}function iE(r){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(wr(r,!1)){if(e(r))return!0;const t=Jm(r);return e(t)}}catch{}return!1}function nE(r){var e;return(e=r?.proposer)==null?void 0:e.publicKey}function sE(r){return r?.topic}function oE(r,e){let t=null;return wr(r?.publicKey,!1)||(t=_e("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function bb(r){let e=!0;return Jn(r)?r.length&&(e=r.every(t=>wr(t,!1))):e=!1,e}function aE(r,e,t){let i=null;return Jn(e)&&e.length?e.forEach(n=>{i||Wl(n)||(i=Gt("UNSUPPORTED_CHAINS",`${t}, chain ${n} should be a string and conform to "namespace:chainId" format`))}):Wl(r)||(i=Gt("UNSUPPORTED_CHAINS",`${t}, 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}function cE(r,e,t){let i=null;return Object.entries(r).forEach(([n,s])=>{if(i)return;const a=aE(n,Fm(n,s),`${e} ${t}`);a&&(i=a)}),i}function fE(r,e){let t=null;return Jn(r)?r.forEach(i=>{t||rE(i)||(t=Gt("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Gt("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function lE(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const n=fE(i?.accounts,`${e} namespace`);n&&(t=n)}),t}function hE(r,e){let t=null;return bb(r?.methods)?bb(r?.events)||(t=Gt("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Gt("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function wb(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const n=hE(i,`${e}, namespace`);n&&(t=n)}),t}function uE(r,e,t){let i=null;if(r&&ef(r)){const n=wb(r,e);n&&(i=n);const s=cE(r,e,t);s&&(i=s)}else i=_e("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function r0(r,e){let t=null;if(r&&ef(r)){const i=wb(r,e);i&&(t=i);const n=lE(r,e);n&&(t=n)}else t=_e("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function yb(r){return wr(r.protocol,!0)}function dE(r,e){let t=!1;return e&&!r?t=!0:r&&Jn(r)&&r.length&&r.forEach(i=>{t=yb(i)}),t}function pE(r){return typeof r=="number"}function bi(r){return typeof r<"u"&&typeof r!==null}function gE(r){return!(!r||typeof r!="object"||!r.code||!t0(r.code,!1)||!r.message||!wr(r.message,!1))}function vE(r){return!(oi(r)||!wr(r.method,!1))}function mE(r){return!(oi(r)||oi(r.result)&&oi(r.error)||!t0(r.id,!1)||!wr(r.jsonrpc,!1))}function bE(r){return!(oi(r)||!wr(r.name,!1))}function _b(r,e){return!(!Wl(e)||!YA(r).includes(e))}function wE(r,e,t){return wr(t,!1)?JA(r,e).includes(t):!1}function yE(r,e,t){return wr(t,!1)?QA(r,e).includes(t):!1}function xb(r,e,t){let i=null;const n=_E(r),s=xE(e),a=Object.keys(n),f=Object.keys(s),h=Ab(Object.keys(r)),u=Ab(Object.keys(e)),g=h.filter(w=>!u.includes(w));return g.length&&(i=_e("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces. ++ */(function(r){(function(){var e="input is invalid type",t="finalize already called",i=typeof window=="object",n=i?window:{};n.JS_SHA3_NO_WINDOW&&(i=!1);var s=!i&&typeof self=="object",a=!n.JS_SHA3_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?n=fr:s&&(n=self);var f=!n.JS_SHA3_NO_COMMON_JS&&!0&&r.exports,h=!n.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",u="0123456789abcdef".split(""),g=[31,7936,2031616,520093696],w=[4,1024,262144,67108864],M=[1,256,65536,16777216],C=[6,1536,393216,100663296],O=[0,8,16,24],$=[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],j=[224,256,384,512],H=[128,256],F=["hex","buffer","arrayBuffer","array","digest"],G={128:168,256:136};(n.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(R){return Object.prototype.toString.call(R)==="[object Array]"}),h&&(n.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(R){return typeof R=="object"&&R.buffer&&R.buffer.constructor===ArrayBuffer});for(var B=function(R,X,V){return function(J){return new x(R,X,R).update(J)[V]()}},z=function(R,X,V){return function(J,K){return new x(R,X,K).update(J)[V]()}},W=function(R,X,V){return function(J,K,E,Y){return l["cshake"+R].update(J,K,E,Y)[V]()}},_=function(R,X,V){return function(J,K,E,Y){return l["kmac"+R].update(J,K,E,Y)[V]()}},U=function(R,X,V,J){for(var K=0;K>5,this.byteCount=this.blockCount<<2,this.outputBlocks=V>>5,this.extraBytes=(V&31)>>3;for(var J=0;J<50;++J)this.s[J]=0}x.prototype.update=function(R){if(this.finalized)throw new Error(t);var X,V=typeof R;if(V!=="string"){if(V==="object"){if(R===null)throw new Error(e);if(h&&R.constructor===ArrayBuffer)R=new Uint8Array(R);else if(!Array.isArray(R)&&(!h||!ArrayBuffer.isView(R)))throw new Error(e)}else throw new Error(e);X=!0}for(var J=this.blocks,K=this.byteCount,E=R.length,Y=this.blockCount,re=0,le=this.s,he,ge;re>2]|=R[re]<>2]|=ge<>2]|=(192|ge>>6)<>2]|=(128|ge&63)<=57344?(J[he>>2]|=(224|ge>>12)<>2]|=(128|ge>>6&63)<>2]|=(128|ge&63)<>2]|=(240|ge>>18)<>2]|=(128|ge>>12&63)<>2]|=(128|ge>>6&63)<>2]|=(128|ge&63)<=K){for(this.start=he-K,this.block=J[Y],he=0;he>8,V=R&255;V>0;)K.unshift(V),R=R>>8,V=R&255,++J;return X?K.push(J):K.unshift(J),this.update(K),K.length},x.prototype.encodeString=function(R){var X,V=typeof R;if(V!=="string"){if(V==="object"){if(R===null)throw new Error(e);if(h&&R.constructor===ArrayBuffer)R=new Uint8Array(R);else if(!Array.isArray(R)&&(!h||!ArrayBuffer.isView(R)))throw new Error(e)}else throw new Error(e);X=!0}var J=0,K=R.length;if(X)J=K;else for(var E=0;E=57344?J+=3:(Y=65536+((Y&1023)<<10|R.charCodeAt(++E)&1023),J+=4)}return J+=this.encode(J*8),this.update(R),J},x.prototype.bytepad=function(R,X){for(var V=this.encode(X),J=0;J>2]|=this.padding[X&3],this.lastByteIndex===this.byteCount)for(R[0]=R[V],X=1;X>4&15]+u[re&15]+u[re>>12&15]+u[re>>8&15]+u[re>>20&15]+u[re>>16&15]+u[re>>28&15]+u[re>>24&15];E%R===0&&(ae(X),K=0)}return J&&(re=X[K],Y+=u[re>>4&15]+u[re&15],J>1&&(Y+=u[re>>12&15]+u[re>>8&15]),J>2&&(Y+=u[re>>20&15]+u[re>>16&15])),Y},x.prototype.arrayBuffer=function(){this.finalize();var R=this.blockCount,X=this.s,V=this.outputBlocks,J=this.extraBytes,K=0,E=0,Y=this.outputBits>>3,re;J?re=new ArrayBuffer(V+1<<2):re=new ArrayBuffer(Y);for(var le=new Uint32Array(re);E>8&255,Y[re+2]=le>>16&255,Y[re+3]=le>>24&255;E%R===0&&ae(X)}return J&&(re=E<<2,le=X[K],Y[re]=le&255,J>1&&(Y[re+1]=le>>8&255),J>2&&(Y[re+2]=le>>16&255)),Y};function N(R,X,V){x.call(this,R,X,V)}N.prototype=new x,N.prototype.finalize=function(){return this.encode(this.outputBits,!0),x.prototype.finalize.call(this)};var ae=function(R){var X,V,J,K,E,Y,re,le,he,ge,He,Te,Ce,Xe,$e,be,Pe,De,ye,Ie,Oe,me,Me,Be,we,ke,We,Ae,Ve,Ke,Ge,mt,It,Ye,Pt,Ot,Ze,rt,et,Ne,it,tt,Re,lt,ht,Le,ut,nt,Fe,st,Qe,qe,dt,Ht,at,kt,_t,qt,Zr,Xr,ei,ti,vr;for(J=0;J<48;J+=2)K=R[0]^R[10]^R[20]^R[30]^R[40],E=R[1]^R[11]^R[21]^R[31]^R[41],Y=R[2]^R[12]^R[22]^R[32]^R[42],re=R[3]^R[13]^R[23]^R[33]^R[43],le=R[4]^R[14]^R[24]^R[34]^R[44],he=R[5]^R[15]^R[25]^R[35]^R[45],ge=R[6]^R[16]^R[26]^R[36]^R[46],He=R[7]^R[17]^R[27]^R[37]^R[47],Te=R[8]^R[18]^R[28]^R[38]^R[48],Ce=R[9]^R[19]^R[29]^R[39]^R[49],X=Te^(Y<<1|re>>>31),V=Ce^(re<<1|Y>>>31),R[0]^=X,R[1]^=V,R[10]^=X,R[11]^=V,R[20]^=X,R[21]^=V,R[30]^=X,R[31]^=V,R[40]^=X,R[41]^=V,X=K^(le<<1|he>>>31),V=E^(he<<1|le>>>31),R[2]^=X,R[3]^=V,R[12]^=X,R[13]^=V,R[22]^=X,R[23]^=V,R[32]^=X,R[33]^=V,R[42]^=X,R[43]^=V,X=Y^(ge<<1|He>>>31),V=re^(He<<1|ge>>>31),R[4]^=X,R[5]^=V,R[14]^=X,R[15]^=V,R[24]^=X,R[25]^=V,R[34]^=X,R[35]^=V,R[44]^=X,R[45]^=V,X=le^(Te<<1|Ce>>>31),V=he^(Ce<<1|Te>>>31),R[6]^=X,R[7]^=V,R[16]^=X,R[17]^=V,R[26]^=X,R[27]^=V,R[36]^=X,R[37]^=V,R[46]^=X,R[47]^=V,X=ge^(K<<1|E>>>31),V=He^(E<<1|K>>>31),R[8]^=X,R[9]^=V,R[18]^=X,R[19]^=V,R[28]^=X,R[29]^=V,R[38]^=X,R[39]^=V,R[48]^=X,R[49]^=V,Xe=R[0],$e=R[1],Le=R[11]<<4|R[10]>>>28,ut=R[10]<<4|R[11]>>>28,Ae=R[20]<<3|R[21]>>>29,Ve=R[21]<<3|R[20]>>>29,Xr=R[31]<<9|R[30]>>>23,ei=R[30]<<9|R[31]>>>23,tt=R[40]<<18|R[41]>>>14,Re=R[41]<<18|R[40]>>>14,Ye=R[2]<<1|R[3]>>>31,Pt=R[3]<<1|R[2]>>>31,be=R[13]<<12|R[12]>>>20,Pe=R[12]<<12|R[13]>>>20,nt=R[22]<<10|R[23]>>>22,Fe=R[23]<<10|R[22]>>>22,Ke=R[33]<<13|R[32]>>>19,Ge=R[32]<<13|R[33]>>>19,ti=R[42]<<2|R[43]>>>30,vr=R[43]<<2|R[42]>>>30,Ht=R[5]<<30|R[4]>>>2,at=R[4]<<30|R[5]>>>2,Ot=R[14]<<6|R[15]>>>26,Ze=R[15]<<6|R[14]>>>26,De=R[25]<<11|R[24]>>>21,ye=R[24]<<11|R[25]>>>21,st=R[34]<<15|R[35]>>>17,Qe=R[35]<<15|R[34]>>>17,mt=R[45]<<29|R[44]>>>3,It=R[44]<<29|R[45]>>>3,Be=R[6]<<28|R[7]>>>4,we=R[7]<<28|R[6]>>>4,kt=R[17]<<23|R[16]>>>9,_t=R[16]<<23|R[17]>>>9,rt=R[26]<<25|R[27]>>>7,et=R[27]<<25|R[26]>>>7,Ie=R[36]<<21|R[37]>>>11,Oe=R[37]<<21|R[36]>>>11,qe=R[47]<<24|R[46]>>>8,dt=R[46]<<24|R[47]>>>8,lt=R[8]<<27|R[9]>>>5,ht=R[9]<<27|R[8]>>>5,ke=R[18]<<20|R[19]>>>12,We=R[19]<<20|R[18]>>>12,qt=R[29]<<7|R[28]>>>25,Zr=R[28]<<7|R[29]>>>25,Ne=R[38]<<8|R[39]>>>24,it=R[39]<<8|R[38]>>>24,me=R[48]<<14|R[49]>>>18,Me=R[49]<<14|R[48]>>>18,R[0]=Xe^~be&De,R[1]=$e^~Pe&ye,R[10]=Be^~ke&Ae,R[11]=we^~We&Ve,R[20]=Ye^~Ot&rt,R[21]=Pt^~Ze&et,R[30]=lt^~Le&nt,R[31]=ht^~ut&Fe,R[40]=Ht^~kt&qt,R[41]=at^~_t&Zr,R[2]=be^~De&Ie,R[3]=Pe^~ye&Oe,R[12]=ke^~Ae&Ke,R[13]=We^~Ve&Ge,R[22]=Ot^~rt&Ne,R[23]=Ze^~et&it,R[32]=Le^~nt&st,R[33]=ut^~Fe&Qe,R[42]=kt^~qt&Xr,R[43]=_t^~Zr&ei,R[4]=De^~Ie&me,R[5]=ye^~Oe&Me,R[14]=Ae^~Ke&mt,R[15]=Ve^~Ge&It,R[24]=rt^~Ne&tt,R[25]=et^~it&Re,R[34]=nt^~st&qe,R[35]=Fe^~Qe&dt,R[44]=qt^~Xr&ti,R[45]=Zr^~ei&vr,R[6]=Ie^~me&Xe,R[7]=Oe^~Me&$e,R[16]=Ke^~mt&Be,R[17]=Ge^~It&we,R[26]=Ne^~tt&Ye,R[27]=it^~Re&Pt,R[36]=st^~qe<,R[37]=Qe^~dt&ht,R[46]=Xr^~ti&Ht,R[47]=ei^~vr&at,R[8]=me^~Xe&be,R[9]=Me^~$e&Pe,R[18]=mt^~Be&ke,R[19]=It^~we&We,R[28]=tt^~Ye&Ot,R[29]=Re^~Pt&Ze,R[38]=qe^~lt&Le,R[39]=dt^~ht&ut,R[48]=ti^~Ht&kt,R[49]=vr^~at&_t,R[0]^=$[J],R[1]^=$[J+1]};if(f)r.exports=l;else for(y=0;y{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{r.push(e)}}),r.length)throw new Error("missing "+r.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(r){return r.message}return null}const Bg=s4();var rd;(function(r){r.DEBUG="DEBUG",r.INFO="INFO",r.WARNING="WARNING",r.ERROR="ERROR",r.OFF="OFF"})(rd||(rd={}));var yn;(function(r){r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",r.NETWORK_ERROR="NETWORK_ERROR",r.SERVER_ERROR="SERVER_ERROR",r.TIMEOUT="TIMEOUT",r.BUFFER_OVERRUN="BUFFER_OVERRUN",r.NUMERIC_FAULT="NUMERIC_FAULT",r.MISSING_NEW="MISSING_NEW",r.INVALID_ARGUMENT="INVALID_ARGUMENT",r.MISSING_ARGUMENT="MISSING_ARGUMENT",r.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",r.CALL_EXCEPTION="CALL_EXCEPTION",r.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",r.NONCE_EXPIRED="NONCE_EXPIRED",r.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",r.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",r.TRANSACTION_REPLACED="TRANSACTION_REPLACED",r.ACTION_REJECTED="ACTION_REJECTED"})(yn||(yn={}));const Fg="0123456789abcdef";class xt{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const i=e.toLowerCase();il[i]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(Lg>il[i])&&console.log.apply(console,t)}debug(...e){this._log(xt.levels.DEBUG,e)}info(...e){this._log(xt.levels.INFO,e)}warn(...e){this._log(xt.levels.WARNING,e)}makeError(e,t,i){if(Ng)return this.makeError("censored error",t,{});t||(t=xt.errors.UNKNOWN_ERROR),i||(i={});const n=[];Object.keys(i).forEach(h=>{const u=i[h];try{if(u instanceof Uint8Array){let g="";for(let w=0;w>4],g+=Fg[u[w]&15];n.push(h+"=Uint8Array(0x"+g+")")}else n.push(h+"="+JSON.stringify(u))}catch{n.push(h+"="+JSON.stringify(i[h].toString()))}}),n.push(`code=${t}`),n.push(`version=${this.version}`);const s=e;let a="";switch(t){case yn.NUMERIC_FAULT:{a="NUMERIC_FAULT";const h=e;switch(h){case"overflow":case"underflow":case"division-by-zero":a+="-"+h;break;case"negative-power":case"negative-width":a+="-unsupported";break;case"unbound-bitwise-result":a+="-unbound-result";break}break}case yn.CALL_EXCEPTION:case yn.INSUFFICIENT_FUNDS:case yn.MISSING_NEW:case yn.NONCE_EXPIRED:case yn.REPLACEMENT_UNDERPRICED:case yn.TRANSACTION_REPLACED:case yn.UNPREDICTABLE_GAS_LIMIT:a=t;break}a&&(e+=" [ See: https://links.ethers.org/v5-errors-"+a+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const f=new Error(e);return f.reason=s,f.code=t,Object.keys(i).forEach(function(h){f[h]=i[h]}),f}throwError(e,t,i){throw this.makeError(e,t,i)}throwArgumentError(e,t,i){return this.throwError(e,xt.errors.INVALID_ARGUMENT,{argument:t,value:i})}assert(e,t,i,n){e||this.throwError(t,i,n)}assertArgument(e,t,i,n){e||this.throwArgumentError(t,i,n)}checkNormalize(e){Bg&&this.throwError("platform missing String.prototype.normalize",xt.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Bg})}checkSafeUint53(e,t){typeof e=="number"&&(t==null&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,xt.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,xt.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,i){i?i=": "+i:i="",et&&this.throwError("too many arguments"+i,xt.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){(e===Object||e==null)&&this.throwError("missing new",xt.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",xt.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",xt.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return td||(td=new xt(n4)),td}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",xt.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),$g){if(!e)return;this.globalLogger().throwError("error censorship permanent",xt.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}Ng=!!e,$g=!!t}static setLogLevel(e){const t=il[e.toLowerCase()];if(t==null){xt.globalLogger().warn("invalid log level - "+e);return}Lg=t}static from(e){return new xt(e)}}xt.errors=yn,xt.levels=rd;const o4="bytes/5.7.0",br=new xt(o4);function Ug(r){return!!r.toHexString}function ya(r){return r.slice||(r.slice=function(){const e=Array.prototype.slice.call(arguments);return ya(new Uint8Array(Array.prototype.slice.apply(r,e)))}),r}function a4(r){return Oi(r)&&!(r.length%2)||_a(r)}function qg(r){return typeof r=="number"&&r==r&&r%1===0}function _a(r){if(r==null)return!1;if(r.constructor===Uint8Array)return!0;if(typeof r=="string"||!qg(r.length)||r.length<0)return!1;for(let e=0;e=256)return!1}return!0}function ur(r,e){if(e||(e={}),typeof r=="number"){br.checkSafeUint53(r,"invalid arrayify value");const t=[];for(;r;)t.unshift(r&255),r=parseInt(String(r/256));return t.length===0&&t.push(0),ya(new Uint8Array(t))}if(e.allowMissingPrefix&&typeof r=="string"&&r.substring(0,2)!=="0x"&&(r="0x"+r),Ug(r)&&(r=r.toHexString()),Oi(r)){let t=r.substring(2);t.length%2&&(e.hexPad==="left"?t="0"+t:e.hexPad==="right"?t+="0":br.throwArgumentError("hex data is odd-length","value",r));const i=[];for(let n=0;nur(n)),t=e.reduce((n,s)=>n+s.length,0),i=new Uint8Array(t);return e.reduce((n,s)=>(i.set(s,n),n+s.length),0),ya(i)}function f4(r,e){r=ur(r),r.length>e&&br.throwArgumentError("value out of range","value",arguments[0]);const t=new Uint8Array(e);return t.set(r,e-r.length),ya(t)}function Oi(r,e){return!(typeof r!="string"||!r.match(/^0x[0-9A-Fa-f]*$/)||e&&r.length!==2+2*e)}const id="0123456789abcdef";function ni(r,e){if(e||(e={}),typeof r=="number"){br.checkSafeUint53(r,"invalid hexlify value");let t="";for(;r;)t=id[r&15]+t,r=Math.floor(r/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if(typeof r=="bigint")return r=r.toString(16),r.length%2?"0x0"+r:"0x"+r;if(e.allowMissingPrefix&&typeof r=="string"&&r.substring(0,2)!=="0x"&&(r="0x"+r),Ug(r))return r.toHexString();if(Oi(r))return r.length%2&&(e.hexPad==="left"?r="0x0"+r.substring(2):e.hexPad==="right"?r+="0":br.throwArgumentError("hex data is odd-length","value",r)),r.toLowerCase();if(_a(r)){let t="0x";for(let i=0;i>4]+id[n&15]}return t}return br.throwArgumentError("invalid hexlify value","value",r)}function l4(r){if(typeof r!="string")r=ni(r);else if(!Oi(r)||r.length%2)return null;return(r.length-2)/2}function zg(r,e,t){return typeof r!="string"?r=ni(r):(!Oi(r)||r.length%2)&&br.throwArgumentError("invalid hexData","value",r),e=2+2*e,t!=null?"0x"+r.substring(e,2+2*t):"0x"+r.substring(e)}function qn(r,e){for(typeof r!="string"?r=ni(r):Oi(r)||br.throwArgumentError("invalid hex string","value",r),r.length>2*e+2&&br.throwArgumentError("value out of range","value",arguments[1]);r.length<2*e+2;)r="0x0"+r.substring(2);return r}function Hg(r){const e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(a4(r)){let t=ur(r);t.length===64?(e.v=27+(t[32]>>7),t[32]&=127,e.r=ni(t.slice(0,32)),e.s=ni(t.slice(32,64))):t.length===65?(e.r=ni(t.slice(0,32)),e.s=ni(t.slice(32,64)),e.v=t[64]):br.throwArgumentError("invalid signature string","signature",r),e.v<27&&(e.v===0||e.v===1?e.v+=27:br.throwArgumentError("signature invalid v byte","signature",r)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(t[32]|=128),e._vs=ni(t.slice(32,64))}else{if(e.r=r.r,e.s=r.s,e.v=r.v,e.recoveryParam=r.recoveryParam,e._vs=r._vs,e._vs!=null){const n=f4(ur(e._vs),32);e._vs=ni(n);const s=n[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&br.throwArgumentError("signature recoveryParam mismatch _vs","signature",r),n[0]&=127;const a=ni(n);e.s==null?e.s=a:e.s!==a&&br.throwArgumentError("signature v mismatch _vs","signature",r)}if(e.recoveryParam==null)e.v==null?br.throwArgumentError("signature missing v and recoveryParam","signature",r):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{const n=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==n&&br.throwArgumentError("signature recoveryParam mismatch v","signature",r)}e.r==null||!Oi(e.r)?br.throwArgumentError("signature missing or invalid r","signature",r):e.r=qn(e.r,32),e.s==null||!Oi(e.s)?br.throwArgumentError("signature missing or invalid s","signature",r):e.s=qn(e.s,32);const t=ur(e.s);t[0]>=128&&br.throwArgumentError("signature s out of range","signature",r),e.recoveryParam&&(t[0]|=128);const i=ni(t);e._vs&&(Oi(e._vs)||br.throwArgumentError("signature invalid _vs","signature",r),e._vs=qn(e._vs,32)),e._vs==null?e._vs=i:e._vs!==i&&br.throwArgumentError("signature _vs mismatch v and s","signature",r)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function nd(r){return"0x"+i4.keccak_256(ur(r))}var kg={exports:{}},h4={},u4=Object.freeze({__proto__:null,default:h4}),nl=ju(u4);(function(r){(function(e,t){function i(m,l){if(!m)throw new Error(l||"Assertion failed")}function n(m,l){m.super_=l;var d=function(){};d.prototype=l.prototype,m.prototype=new d,m.prototype.constructor=m}function s(m,l,d){if(s.isBN(m))return m;this.negative=0,this.words=null,this.length=0,this.red=null,m!==null&&((l==="le"||l==="be")&&(d=l,l=10),this._init(m||0,l||10,d||"be"))}typeof e=="object"?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;var a;try{typeof window<"u"&&typeof window.Buffer<"u"?a=window.Buffer:a=nl.Buffer}catch{}s.isBN=function(l){return l instanceof s?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===s.wordSize&&Array.isArray(l.words)},s.max=function(l,d){return l.cmp(d)>0?l:d},s.min=function(l,d){return l.cmp(d)<0?l:d},s.prototype._init=function(l,d,y){if(typeof l=="number")return this._initNumber(l,d,y);if(typeof l=="object")return this._initArray(l,d,y);d==="hex"&&(d=16),i(d===(d|0)&&d>=2&&d<=36),l=l.toString().replace(/\s+/g,"");var P=0;l[0]==="-"&&(P++,this.negative=1),P=0;P-=3)S=l[P]|l[P-1]<<8|l[P-2]<<16,this.words[D]|=S<>>26-v&67108863,v+=24,v>=26&&(v-=26,D++);else if(y==="le")for(P=0,D=0;P>>26-v&67108863,v+=24,v>=26&&(v-=26,D++);return this._strip()};function f(m,l){var d=m.charCodeAt(l);if(d>=48&&d<=57)return d-48;if(d>=65&&d<=70)return d-55;if(d>=97&&d<=102)return d-87;i(!1,"Invalid character in "+m)}function h(m,l,d){var y=f(m,d);return d-1>=l&&(y|=f(m,d-1)<<4),y}s.prototype._parseHex=function(l,d,y){this.length=Math.ceil((l.length-d)/6),this.words=new Array(this.length);for(var P=0;P=d;P-=2)v=h(l,d,P)<=18?(D-=18,S+=1,this.words[S]|=v>>>26):D+=8;else{var A=l.length-d;for(P=A%2===0?d+1:d;P=18?(D-=18,S+=1,this.words[S]|=v>>>26):D+=8}this._strip()};function u(m,l,d,y){for(var P=0,D=0,S=Math.min(m.length,d),v=l;v=49?D=A-49+10:A>=17?D=A-17+10:D=A,i(A>=0&&D1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=w}catch{s.prototype.inspect=w}else s.prototype.inspect=w;function w(){return(this.red?""}var M=["","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"],C=[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],O=[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];s.prototype.toString=function(l,d){l=l||10,d=d|0||1;var y;if(l===16||l==="hex"){y="";for(var P=0,D=0,S=0;S>>24-P&16777215,P+=2,P>=26&&(P-=26,S--),D!==0||S!==this.length-1?y=M[6-A.length]+A+y:y=A+y}for(D!==0&&(y=D.toString(16)+y);y.length%d!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(l===(l|0)&&l>=2&&l<=36){var x=C[l],N=O[l];y="";var ae=this.clone();for(ae.negative=0;!ae.isZero();){var R=ae.modrn(N).toString(l);ae=ae.idivn(N),ae.isZero()?y=R+y:y=M[x-R.length]+R+y}for(this.isZero()&&(y="0"+y);y.length%d!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}i(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},s.prototype.toJSON=function(){return this.toString(16,2)},a&&(s.prototype.toBuffer=function(l,d){return this.toArrayLike(a,l,d)}),s.prototype.toArray=function(l,d){return this.toArrayLike(Array,l,d)};var $=function(l,d){return l.allocUnsafe?l.allocUnsafe(d):new l(d)};s.prototype.toArrayLike=function(l,d,y){this._strip();var P=this.byteLength(),D=y||Math.max(1,P);i(P<=D,"byte array longer than desired length"),i(D>0,"Requested array length <= 0");var S=$(l,D),v=d==="le"?"LE":"BE";return this["_toArrayLike"+v](S,P),S},s.prototype._toArrayLikeLE=function(l,d){for(var y=0,P=0,D=0,S=0;D>8&255),y>16&255),S===6?(y>24&255),P=0,S=0):(P=v>>>24,S+=2)}if(y=0&&(l[y--]=v>>8&255),y>=0&&(l[y--]=v>>16&255),S===6?(y>=0&&(l[y--]=v>>24&255),P=0,S=0):(P=v>>>24,S+=2)}if(y>=0)for(l[y--]=P;y>=0;)l[y--]=0},Math.clz32?s.prototype._countBits=function(l){return 32-Math.clz32(l)}:s.prototype._countBits=function(l){var d=l,y=0;return d>=4096&&(y+=13,d>>>=13),d>=64&&(y+=7,d>>>=7),d>=8&&(y+=4,d>>>=4),d>=2&&(y+=2,d>>>=2),y+d},s.prototype._zeroBits=function(l){if(l===0)return 26;var d=l,y=0;return d&8191||(y+=13,d>>>=13),d&127||(y+=7,d>>>=7),d&15||(y+=4,d>>>=4),d&3||(y+=2,d>>>=2),d&1||y++,y},s.prototype.bitLength=function(){var l=this.words[this.length-1],d=this._countBits(l);return(this.length-1)*26+d};function j(m){for(var l=new Array(m.bitLength()),d=0;d>>P&1}return l}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,d=0;dl.length?this.clone().ior(l):l.clone().ior(this)},s.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},s.prototype.iuand=function(l){var d;this.length>l.length?d=l:d=this;for(var y=0;yl.length?this.clone().iand(l):l.clone().iand(this)},s.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},s.prototype.iuxor=function(l){var d,y;this.length>l.length?(d=this,y=l):(d=l,y=this);for(var P=0;Pl.length?this.clone().ixor(l):l.clone().ixor(this)},s.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},s.prototype.inotn=function(l){i(typeof l=="number"&&l>=0);var d=Math.ceil(l/26)|0,y=l%26;this._expand(d),y>0&&d--;for(var P=0;P0&&(this.words[P]=~this.words[P]&67108863>>26-y),this._strip()},s.prototype.notn=function(l){return this.clone().inotn(l)},s.prototype.setn=function(l,d){i(typeof l=="number"&&l>=0);var y=l/26|0,P=l%26;return this._expand(y+1),d?this.words[y]=this.words[y]|1<l.length?(y=this,P=l):(y=l,P=this);for(var D=0,S=0;S>>26;for(;D!==0&&S>>26;if(this.length=y.length,D!==0)this.words[this.length]=D,this.length++;else if(y!==this)for(;Sl.length?this.clone().iadd(l):l.clone().iadd(this)},s.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var d=this.iadd(l);return l.negative=1,d._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var y=this.cmp(l);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var P,D;y>0?(P=this,D=l):(P=l,D=this);for(var S=0,v=0;v>26,this.words[v]=d&67108863;for(;S!==0&&v>26,this.words[v]=d&67108863;if(S===0&&v>>26,ae=A&67108863,R=Math.min(x,l.length-1),X=Math.max(0,x-m.length+1);X<=R;X++){var V=x-X|0;P=m.words[V]|0,D=l.words[X]|0,S=P*D+ae,N+=S/67108864|0,ae=S&67108863}d.words[x]=ae|0,A=N|0}return A!==0?d.words[x]=A|0:d.length--,d._strip()}var F=function(l,d,y){var P=l.words,D=d.words,S=y.words,v=0,A,x,N,ae=P[0]|0,R=ae&8191,X=ae>>>13,V=P[1]|0,J=V&8191,K=V>>>13,E=P[2]|0,Y=E&8191,re=E>>>13,le=P[3]|0,he=le&8191,ge=le>>>13,He=P[4]|0,Te=He&8191,Ce=He>>>13,Xe=P[5]|0,$e=Xe&8191,be=Xe>>>13,Pe=P[6]|0,De=Pe&8191,ye=Pe>>>13,Ie=P[7]|0,Oe=Ie&8191,me=Ie>>>13,Me=P[8]|0,Be=Me&8191,we=Me>>>13,ke=P[9]|0,We=ke&8191,Ae=ke>>>13,Ve=D[0]|0,Ke=Ve&8191,Ge=Ve>>>13,mt=D[1]|0,It=mt&8191,Ye=mt>>>13,Pt=D[2]|0,Ot=Pt&8191,Ze=Pt>>>13,rt=D[3]|0,et=rt&8191,Ne=rt>>>13,it=D[4]|0,tt=it&8191,Re=it>>>13,lt=D[5]|0,ht=lt&8191,Le=lt>>>13,ut=D[6]|0,nt=ut&8191,Fe=ut>>>13,st=D[7]|0,Qe=st&8191,qe=st>>>13,dt=D[8]|0,Ht=dt&8191,at=dt>>>13,kt=D[9]|0,_t=kt&8191,qt=kt>>>13;y.negative=l.negative^d.negative,y.length=19,A=Math.imul(R,Ke),x=Math.imul(R,Ge),x=x+Math.imul(X,Ke)|0,N=Math.imul(X,Ge);var Zr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,A=Math.imul(J,Ke),x=Math.imul(J,Ge),x=x+Math.imul(K,Ke)|0,N=Math.imul(K,Ge),A=A+Math.imul(R,It)|0,x=x+Math.imul(R,Ye)|0,x=x+Math.imul(X,It)|0,N=N+Math.imul(X,Ye)|0;var Xr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,A=Math.imul(Y,Ke),x=Math.imul(Y,Ge),x=x+Math.imul(re,Ke)|0,N=Math.imul(re,Ge),A=A+Math.imul(J,It)|0,x=x+Math.imul(J,Ye)|0,x=x+Math.imul(K,It)|0,N=N+Math.imul(K,Ye)|0,A=A+Math.imul(R,Ot)|0,x=x+Math.imul(R,Ze)|0,x=x+Math.imul(X,Ot)|0,N=N+Math.imul(X,Ze)|0;var ei=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(ei>>>26)|0,ei&=67108863,A=Math.imul(he,Ke),x=Math.imul(he,Ge),x=x+Math.imul(ge,Ke)|0,N=Math.imul(ge,Ge),A=A+Math.imul(Y,It)|0,x=x+Math.imul(Y,Ye)|0,x=x+Math.imul(re,It)|0,N=N+Math.imul(re,Ye)|0,A=A+Math.imul(J,Ot)|0,x=x+Math.imul(J,Ze)|0,x=x+Math.imul(K,Ot)|0,N=N+Math.imul(K,Ze)|0,A=A+Math.imul(R,et)|0,x=x+Math.imul(R,Ne)|0,x=x+Math.imul(X,et)|0,N=N+Math.imul(X,Ne)|0;var ti=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(ti>>>26)|0,ti&=67108863,A=Math.imul(Te,Ke),x=Math.imul(Te,Ge),x=x+Math.imul(Ce,Ke)|0,N=Math.imul(Ce,Ge),A=A+Math.imul(he,It)|0,x=x+Math.imul(he,Ye)|0,x=x+Math.imul(ge,It)|0,N=N+Math.imul(ge,Ye)|0,A=A+Math.imul(Y,Ot)|0,x=x+Math.imul(Y,Ze)|0,x=x+Math.imul(re,Ot)|0,N=N+Math.imul(re,Ze)|0,A=A+Math.imul(J,et)|0,x=x+Math.imul(J,Ne)|0,x=x+Math.imul(K,et)|0,N=N+Math.imul(K,Ne)|0,A=A+Math.imul(R,tt)|0,x=x+Math.imul(R,Re)|0,x=x+Math.imul(X,tt)|0,N=N+Math.imul(X,Re)|0;var vr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(vr>>>26)|0,vr&=67108863,A=Math.imul($e,Ke),x=Math.imul($e,Ge),x=x+Math.imul(be,Ke)|0,N=Math.imul(be,Ge),A=A+Math.imul(Te,It)|0,x=x+Math.imul(Te,Ye)|0,x=x+Math.imul(Ce,It)|0,N=N+Math.imul(Ce,Ye)|0,A=A+Math.imul(he,Ot)|0,x=x+Math.imul(he,Ze)|0,x=x+Math.imul(ge,Ot)|0,N=N+Math.imul(ge,Ze)|0,A=A+Math.imul(Y,et)|0,x=x+Math.imul(Y,Ne)|0,x=x+Math.imul(re,et)|0,N=N+Math.imul(re,Ne)|0,A=A+Math.imul(J,tt)|0,x=x+Math.imul(J,Re)|0,x=x+Math.imul(K,tt)|0,N=N+Math.imul(K,Re)|0,A=A+Math.imul(R,ht)|0,x=x+Math.imul(R,Le)|0,x=x+Math.imul(X,ht)|0,N=N+Math.imul(X,Le)|0;var Ai=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Ai>>>26)|0,Ai&=67108863,A=Math.imul(De,Ke),x=Math.imul(De,Ge),x=x+Math.imul(ye,Ke)|0,N=Math.imul(ye,Ge),A=A+Math.imul($e,It)|0,x=x+Math.imul($e,Ye)|0,x=x+Math.imul(be,It)|0,N=N+Math.imul(be,Ye)|0,A=A+Math.imul(Te,Ot)|0,x=x+Math.imul(Te,Ze)|0,x=x+Math.imul(Ce,Ot)|0,N=N+Math.imul(Ce,Ze)|0,A=A+Math.imul(he,et)|0,x=x+Math.imul(he,Ne)|0,x=x+Math.imul(ge,et)|0,N=N+Math.imul(ge,Ne)|0,A=A+Math.imul(Y,tt)|0,x=x+Math.imul(Y,Re)|0,x=x+Math.imul(re,tt)|0,N=N+Math.imul(re,Re)|0,A=A+Math.imul(J,ht)|0,x=x+Math.imul(J,Le)|0,x=x+Math.imul(K,ht)|0,N=N+Math.imul(K,Le)|0,A=A+Math.imul(R,nt)|0,x=x+Math.imul(R,Fe)|0,x=x+Math.imul(X,nt)|0,N=N+Math.imul(X,Fe)|0;var Pn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Pn>>>26)|0,Pn&=67108863,A=Math.imul(Oe,Ke),x=Math.imul(Oe,Ge),x=x+Math.imul(me,Ke)|0,N=Math.imul(me,Ge),A=A+Math.imul(De,It)|0,x=x+Math.imul(De,Ye)|0,x=x+Math.imul(ye,It)|0,N=N+Math.imul(ye,Ye)|0,A=A+Math.imul($e,Ot)|0,x=x+Math.imul($e,Ze)|0,x=x+Math.imul(be,Ot)|0,N=N+Math.imul(be,Ze)|0,A=A+Math.imul(Te,et)|0,x=x+Math.imul(Te,Ne)|0,x=x+Math.imul(Ce,et)|0,N=N+Math.imul(Ce,Ne)|0,A=A+Math.imul(he,tt)|0,x=x+Math.imul(he,Re)|0,x=x+Math.imul(ge,tt)|0,N=N+Math.imul(ge,Re)|0,A=A+Math.imul(Y,ht)|0,x=x+Math.imul(Y,Le)|0,x=x+Math.imul(re,ht)|0,N=N+Math.imul(re,Le)|0,A=A+Math.imul(J,nt)|0,x=x+Math.imul(J,Fe)|0,x=x+Math.imul(K,nt)|0,N=N+Math.imul(K,Fe)|0,A=A+Math.imul(R,Qe)|0,x=x+Math.imul(R,qe)|0,x=x+Math.imul(X,Qe)|0,N=N+Math.imul(X,qe)|0;var Ei=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Ei>>>26)|0,Ei&=67108863,A=Math.imul(Be,Ke),x=Math.imul(Be,Ge),x=x+Math.imul(we,Ke)|0,N=Math.imul(we,Ge),A=A+Math.imul(Oe,It)|0,x=x+Math.imul(Oe,Ye)|0,x=x+Math.imul(me,It)|0,N=N+Math.imul(me,Ye)|0,A=A+Math.imul(De,Ot)|0,x=x+Math.imul(De,Ze)|0,x=x+Math.imul(ye,Ot)|0,N=N+Math.imul(ye,Ze)|0,A=A+Math.imul($e,et)|0,x=x+Math.imul($e,Ne)|0,x=x+Math.imul(be,et)|0,N=N+Math.imul(be,Ne)|0,A=A+Math.imul(Te,tt)|0,x=x+Math.imul(Te,Re)|0,x=x+Math.imul(Ce,tt)|0,N=N+Math.imul(Ce,Re)|0,A=A+Math.imul(he,ht)|0,x=x+Math.imul(he,Le)|0,x=x+Math.imul(ge,ht)|0,N=N+Math.imul(ge,Le)|0,A=A+Math.imul(Y,nt)|0,x=x+Math.imul(Y,Fe)|0,x=x+Math.imul(re,nt)|0,N=N+Math.imul(re,Fe)|0,A=A+Math.imul(J,Qe)|0,x=x+Math.imul(J,qe)|0,x=x+Math.imul(K,Qe)|0,N=N+Math.imul(K,qe)|0,A=A+Math.imul(R,Ht)|0,x=x+Math.imul(R,at)|0,x=x+Math.imul(X,Ht)|0,N=N+Math.imul(X,at)|0;var Dn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Dn>>>26)|0,Dn&=67108863,A=Math.imul(We,Ke),x=Math.imul(We,Ge),x=x+Math.imul(Ae,Ke)|0,N=Math.imul(Ae,Ge),A=A+Math.imul(Be,It)|0,x=x+Math.imul(Be,Ye)|0,x=x+Math.imul(we,It)|0,N=N+Math.imul(we,Ye)|0,A=A+Math.imul(Oe,Ot)|0,x=x+Math.imul(Oe,Ze)|0,x=x+Math.imul(me,Ot)|0,N=N+Math.imul(me,Ze)|0,A=A+Math.imul(De,et)|0,x=x+Math.imul(De,Ne)|0,x=x+Math.imul(ye,et)|0,N=N+Math.imul(ye,Ne)|0,A=A+Math.imul($e,tt)|0,x=x+Math.imul($e,Re)|0,x=x+Math.imul(be,tt)|0,N=N+Math.imul(be,Re)|0,A=A+Math.imul(Te,ht)|0,x=x+Math.imul(Te,Le)|0,x=x+Math.imul(Ce,ht)|0,N=N+Math.imul(Ce,Le)|0,A=A+Math.imul(he,nt)|0,x=x+Math.imul(he,Fe)|0,x=x+Math.imul(ge,nt)|0,N=N+Math.imul(ge,Fe)|0,A=A+Math.imul(Y,Qe)|0,x=x+Math.imul(Y,qe)|0,x=x+Math.imul(re,Qe)|0,N=N+Math.imul(re,qe)|0,A=A+Math.imul(J,Ht)|0,x=x+Math.imul(J,at)|0,x=x+Math.imul(K,Ht)|0,N=N+Math.imul(K,at)|0,A=A+Math.imul(R,_t)|0,x=x+Math.imul(R,qt)|0,x=x+Math.imul(X,_t)|0,N=N+Math.imul(X,qt)|0;var On=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(On>>>26)|0,On&=67108863,A=Math.imul(We,It),x=Math.imul(We,Ye),x=x+Math.imul(Ae,It)|0,N=Math.imul(Ae,Ye),A=A+Math.imul(Be,Ot)|0,x=x+Math.imul(Be,Ze)|0,x=x+Math.imul(we,Ot)|0,N=N+Math.imul(we,Ze)|0,A=A+Math.imul(Oe,et)|0,x=x+Math.imul(Oe,Ne)|0,x=x+Math.imul(me,et)|0,N=N+Math.imul(me,Ne)|0,A=A+Math.imul(De,tt)|0,x=x+Math.imul(De,Re)|0,x=x+Math.imul(ye,tt)|0,N=N+Math.imul(ye,Re)|0,A=A+Math.imul($e,ht)|0,x=x+Math.imul($e,Le)|0,x=x+Math.imul(be,ht)|0,N=N+Math.imul(be,Le)|0,A=A+Math.imul(Te,nt)|0,x=x+Math.imul(Te,Fe)|0,x=x+Math.imul(Ce,nt)|0,N=N+Math.imul(Ce,Fe)|0,A=A+Math.imul(he,Qe)|0,x=x+Math.imul(he,qe)|0,x=x+Math.imul(ge,Qe)|0,N=N+Math.imul(ge,qe)|0,A=A+Math.imul(Y,Ht)|0,x=x+Math.imul(Y,at)|0,x=x+Math.imul(re,Ht)|0,N=N+Math.imul(re,at)|0,A=A+Math.imul(J,_t)|0,x=x+Math.imul(J,qt)|0,x=x+Math.imul(K,_t)|0,N=N+Math.imul(K,qt)|0;var Si=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Si>>>26)|0,Si&=67108863,A=Math.imul(We,Ot),x=Math.imul(We,Ze),x=x+Math.imul(Ae,Ot)|0,N=Math.imul(Ae,Ze),A=A+Math.imul(Be,et)|0,x=x+Math.imul(Be,Ne)|0,x=x+Math.imul(we,et)|0,N=N+Math.imul(we,Ne)|0,A=A+Math.imul(Oe,tt)|0,x=x+Math.imul(Oe,Re)|0,x=x+Math.imul(me,tt)|0,N=N+Math.imul(me,Re)|0,A=A+Math.imul(De,ht)|0,x=x+Math.imul(De,Le)|0,x=x+Math.imul(ye,ht)|0,N=N+Math.imul(ye,Le)|0,A=A+Math.imul($e,nt)|0,x=x+Math.imul($e,Fe)|0,x=x+Math.imul(be,nt)|0,N=N+Math.imul(be,Fe)|0,A=A+Math.imul(Te,Qe)|0,x=x+Math.imul(Te,qe)|0,x=x+Math.imul(Ce,Qe)|0,N=N+Math.imul(Ce,qe)|0,A=A+Math.imul(he,Ht)|0,x=x+Math.imul(he,at)|0,x=x+Math.imul(ge,Ht)|0,N=N+Math.imul(ge,at)|0,A=A+Math.imul(Y,_t)|0,x=x+Math.imul(Y,qt)|0,x=x+Math.imul(re,_t)|0,N=N+Math.imul(re,qt)|0;var fn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(fn>>>26)|0,fn&=67108863,A=Math.imul(We,et),x=Math.imul(We,Ne),x=x+Math.imul(Ae,et)|0,N=Math.imul(Ae,Ne),A=A+Math.imul(Be,tt)|0,x=x+Math.imul(Be,Re)|0,x=x+Math.imul(we,tt)|0,N=N+Math.imul(we,Re)|0,A=A+Math.imul(Oe,ht)|0,x=x+Math.imul(Oe,Le)|0,x=x+Math.imul(me,ht)|0,N=N+Math.imul(me,Le)|0,A=A+Math.imul(De,nt)|0,x=x+Math.imul(De,Fe)|0,x=x+Math.imul(ye,nt)|0,N=N+Math.imul(ye,Fe)|0,A=A+Math.imul($e,Qe)|0,x=x+Math.imul($e,qe)|0,x=x+Math.imul(be,Qe)|0,N=N+Math.imul(be,qe)|0,A=A+Math.imul(Te,Ht)|0,x=x+Math.imul(Te,at)|0,x=x+Math.imul(Ce,Ht)|0,N=N+Math.imul(Ce,at)|0,A=A+Math.imul(he,_t)|0,x=x+Math.imul(he,qt)|0,x=x+Math.imul(ge,_t)|0,N=N+Math.imul(ge,qt)|0;var ln=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(ln>>>26)|0,ln&=67108863,A=Math.imul(We,tt),x=Math.imul(We,Re),x=x+Math.imul(Ae,tt)|0,N=Math.imul(Ae,Re),A=A+Math.imul(Be,ht)|0,x=x+Math.imul(Be,Le)|0,x=x+Math.imul(we,ht)|0,N=N+Math.imul(we,Le)|0,A=A+Math.imul(Oe,nt)|0,x=x+Math.imul(Oe,Fe)|0,x=x+Math.imul(me,nt)|0,N=N+Math.imul(me,Fe)|0,A=A+Math.imul(De,Qe)|0,x=x+Math.imul(De,qe)|0,x=x+Math.imul(ye,Qe)|0,N=N+Math.imul(ye,qe)|0,A=A+Math.imul($e,Ht)|0,x=x+Math.imul($e,at)|0,x=x+Math.imul(be,Ht)|0,N=N+Math.imul(be,at)|0,A=A+Math.imul(Te,_t)|0,x=x+Math.imul(Te,qt)|0,x=x+Math.imul(Ce,_t)|0,N=N+Math.imul(Ce,qt)|0;var Cr=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,A=Math.imul(We,ht),x=Math.imul(We,Le),x=x+Math.imul(Ae,ht)|0,N=Math.imul(Ae,Le),A=A+Math.imul(Be,nt)|0,x=x+Math.imul(Be,Fe)|0,x=x+Math.imul(we,nt)|0,N=N+Math.imul(we,Fe)|0,A=A+Math.imul(Oe,Qe)|0,x=x+Math.imul(Oe,qe)|0,x=x+Math.imul(me,Qe)|0,N=N+Math.imul(me,qe)|0,A=A+Math.imul(De,Ht)|0,x=x+Math.imul(De,at)|0,x=x+Math.imul(ye,Ht)|0,N=N+Math.imul(ye,at)|0,A=A+Math.imul($e,_t)|0,x=x+Math.imul($e,qt)|0,x=x+Math.imul(be,_t)|0,N=N+Math.imul(be,qt)|0;var Rn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Rn>>>26)|0,Rn&=67108863,A=Math.imul(We,nt),x=Math.imul(We,Fe),x=x+Math.imul(Ae,nt)|0,N=Math.imul(Ae,Fe),A=A+Math.imul(Be,Qe)|0,x=x+Math.imul(Be,qe)|0,x=x+Math.imul(we,Qe)|0,N=N+Math.imul(we,qe)|0,A=A+Math.imul(Oe,Ht)|0,x=x+Math.imul(Oe,at)|0,x=x+Math.imul(me,Ht)|0,N=N+Math.imul(me,at)|0,A=A+Math.imul(De,_t)|0,x=x+Math.imul(De,qt)|0,x=x+Math.imul(ye,_t)|0,N=N+Math.imul(ye,qt)|0;var Tn=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(Tn>>>26)|0,Tn&=67108863,A=Math.imul(We,Qe),x=Math.imul(We,qe),x=x+Math.imul(Ae,Qe)|0,N=Math.imul(Ae,qe),A=A+Math.imul(Be,Ht)|0,x=x+Math.imul(Be,at)|0,x=x+Math.imul(we,Ht)|0,N=N+Math.imul(we,at)|0,A=A+Math.imul(Oe,_t)|0,x=x+Math.imul(Oe,qt)|0,x=x+Math.imul(me,_t)|0,N=N+Math.imul(me,qt)|0;var $n=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+($n>>>26)|0,$n&=67108863,A=Math.imul(We,Ht),x=Math.imul(We,at),x=x+Math.imul(Ae,Ht)|0,N=Math.imul(Ae,at),A=A+Math.imul(Be,_t)|0,x=x+Math.imul(Be,qt)|0,x=x+Math.imul(we,_t)|0,N=N+Math.imul(we,qt)|0;var ia=(v+A|0)+((x&8191)<<13)|0;v=(N+(x>>>13)|0)+(ia>>>26)|0,ia&=67108863,A=Math.imul(We,_t),x=Math.imul(We,qt),x=x+Math.imul(Ae,_t)|0,N=Math.imul(Ae,qt);var fo=(v+A|0)+((x&8191)<<13)|0;return v=(N+(x>>>13)|0)+(fo>>>26)|0,fo&=67108863,S[0]=Zr,S[1]=Xr,S[2]=ei,S[3]=ti,S[4]=vr,S[5]=Ai,S[6]=Pn,S[7]=Ei,S[8]=Dn,S[9]=On,S[10]=Si,S[11]=fn,S[12]=ln,S[13]=Cr,S[14]=Rn,S[15]=Tn,S[16]=$n,S[17]=ia,S[18]=fo,v!==0&&(S[19]=v,y.length++),y};Math.imul||(F=H);function G(m,l,d){d.negative=l.negative^m.negative,d.length=m.length+l.length;for(var y=0,P=0,D=0;D>>26)|0,P+=S>>>26,S&=67108863}d.words[D]=v,y=S,S=P}return y!==0?d.words[D]=y:d.length--,d._strip()}function B(m,l,d){return G(m,l,d)}s.prototype.mulTo=function(l,d){var y,P=this.length+l.length;return this.length===10&&l.length===10?y=F(this,l,d):P<63?y=H(this,l,d):P<1024?y=G(this,l,d):y=B(this,l,d),y},s.prototype.mul=function(l){var d=new s(null);return d.words=new Array(this.length+l.length),this.mulTo(l,d)},s.prototype.mulf=function(l){var d=new s(null);return d.words=new Array(this.length+l.length),B(this,l,d)},s.prototype.imul=function(l){return this.clone().mulTo(l,this)},s.prototype.imuln=function(l){var d=l<0;d&&(l=-l),i(typeof l=="number"),i(l<67108864);for(var y=0,P=0;P>=26,y+=D/67108864|0,y+=S>>>26,this.words[P]=S&67108863}return y!==0&&(this.words[P]=y,this.length++),d?this.ineg():this},s.prototype.muln=function(l){return this.clone().imuln(l)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(l){var d=j(l);if(d.length===0)return new s(1);for(var y=this,P=0;P=0);var d=l%26,y=(l-d)/26,P=67108863>>>26-d<<26-d,D;if(d!==0){var S=0;for(D=0;D>>26-d}S&&(this.words[D]=S,this.length++)}if(y!==0){for(D=this.length-1;D>=0;D--)this.words[D+y]=this.words[D];for(D=0;D=0);var P;d?P=(d-d%26)/26:P=0;var D=l%26,S=Math.min((l-D)/26,this.length),v=67108863^67108863>>>D<S)for(this.length-=S,x=0;x=0&&(N!==0||x>=P);x--){var ae=this.words[x]|0;this.words[x]=N<<26-D|ae>>>D,N=ae&v}return A&&N!==0&&(A.words[A.length++]=N),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(l,d,y){return i(this.negative===0),this.iushrn(l,d,y)},s.prototype.shln=function(l){return this.clone().ishln(l)},s.prototype.ushln=function(l){return this.clone().iushln(l)},s.prototype.shrn=function(l){return this.clone().ishrn(l)},s.prototype.ushrn=function(l){return this.clone().iushrn(l)},s.prototype.testn=function(l){i(typeof l=="number"&&l>=0);var d=l%26,y=(l-d)/26,P=1<=0);var d=l%26,y=(l-d)/26;if(i(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(d!==0&&y++,this.length=Math.min(y,this.length),d!==0){var P=67108863^67108863>>>d<=67108864;d++)this.words[d]-=67108864,d===this.length-1?this.words[d+1]=1:this.words[d+1]++;return this.length=Math.max(this.length,d+1),this},s.prototype.isubn=function(l){if(i(typeof l=="number"),i(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var d=0;d>26)-(A/67108864|0),this.words[D+y]=S&67108863}for(;D>26,this.words[D+y]=S&67108863;if(v===0)return this._strip();for(i(v===-1),v=0,D=0;D>26,this.words[D]=S&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(l,d){var y=this.length-l.length,P=this.clone(),D=l,S=D.words[D.length-1]|0,v=this._countBits(S);y=26-v,y!==0&&(D=D.ushln(y),P.iushln(y),S=D.words[D.length-1]|0);var A=P.length-D.length,x;if(d!=="mod"){x=new s(null),x.length=A+1,x.words=new Array(x.length);for(var N=0;N=0;R--){var X=(P.words[D.length+R]|0)*67108864+(P.words[D.length+R-1]|0);for(X=Math.min(X/S|0,67108863),P._ishlnsubmul(D,X,R);P.negative!==0;)X--,P.negative=0,P._ishlnsubmul(D,1,R),P.isZero()||(P.negative^=1);x&&(x.words[R]=X)}return x&&x._strip(),P._strip(),d!=="div"&&y!==0&&P.iushrn(y),{div:x||null,mod:P}},s.prototype.divmod=function(l,d,y){if(i(!l.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var P,D,S;return this.negative!==0&&l.negative===0?(S=this.neg().divmod(l,d),d!=="mod"&&(P=S.div.neg()),d!=="div"&&(D=S.mod.neg(),y&&D.negative!==0&&D.iadd(l)),{div:P,mod:D}):this.negative===0&&l.negative!==0?(S=this.divmod(l.neg(),d),d!=="mod"&&(P=S.div.neg()),{div:P,mod:S.mod}):this.negative&l.negative?(S=this.neg().divmod(l.neg(),d),d!=="div"&&(D=S.mod.neg(),y&&D.negative!==0&&D.isub(l)),{div:S.div,mod:D}):l.length>this.length||this.cmp(l)<0?{div:new s(0),mod:this}:l.length===1?d==="div"?{div:this.divn(l.words[0]),mod:null}:d==="mod"?{div:null,mod:new s(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new s(this.modrn(l.words[0]))}:this._wordDiv(l,d)},s.prototype.div=function(l){return this.divmod(l,"div",!1).div},s.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},s.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},s.prototype.divRound=function(l){var d=this.divmod(l);if(d.mod.isZero())return d.div;var y=d.div.negative!==0?d.mod.isub(l):d.mod,P=l.ushrn(1),D=l.andln(1),S=y.cmp(P);return S<0||D===1&&S===0?d.div:d.div.negative!==0?d.div.isubn(1):d.div.iaddn(1)},s.prototype.modrn=function(l){var d=l<0;d&&(l=-l),i(l<=67108863);for(var y=(1<<26)%l,P=0,D=this.length-1;D>=0;D--)P=(y*P+(this.words[D]|0))%l;return d?-P:P},s.prototype.modn=function(l){return this.modrn(l)},s.prototype.idivn=function(l){var d=l<0;d&&(l=-l),i(l<=67108863);for(var y=0,P=this.length-1;P>=0;P--){var D=(this.words[P]|0)+y*67108864;this.words[P]=D/l|0,y=D%l}return this._strip(),d?this.ineg():this},s.prototype.divn=function(l){return this.clone().idivn(l)},s.prototype.egcd=function(l){i(l.negative===0),i(!l.isZero());var d=this,y=l.clone();d.negative!==0?d=d.umod(l):d=d.clone();for(var P=new s(1),D=new s(0),S=new s(0),v=new s(1),A=0;d.isEven()&&y.isEven();)d.iushrn(1),y.iushrn(1),++A;for(var x=y.clone(),N=d.clone();!d.isZero();){for(var ae=0,R=1;!(d.words[0]&R)&&ae<26;++ae,R<<=1);if(ae>0)for(d.iushrn(ae);ae-- >0;)(P.isOdd()||D.isOdd())&&(P.iadd(x),D.isub(N)),P.iushrn(1),D.iushrn(1);for(var X=0,V=1;!(y.words[0]&V)&&X<26;++X,V<<=1);if(X>0)for(y.iushrn(X);X-- >0;)(S.isOdd()||v.isOdd())&&(S.iadd(x),v.isub(N)),S.iushrn(1),v.iushrn(1);d.cmp(y)>=0?(d.isub(y),P.isub(S),D.isub(v)):(y.isub(d),S.isub(P),v.isub(D))}return{a:S,b:v,gcd:y.iushln(A)}},s.prototype._invmp=function(l){i(l.negative===0),i(!l.isZero());var d=this,y=l.clone();d.negative!==0?d=d.umod(l):d=d.clone();for(var P=new s(1),D=new s(0),S=y.clone();d.cmpn(1)>0&&y.cmpn(1)>0;){for(var v=0,A=1;!(d.words[0]&A)&&v<26;++v,A<<=1);if(v>0)for(d.iushrn(v);v-- >0;)P.isOdd()&&P.iadd(S),P.iushrn(1);for(var x=0,N=1;!(y.words[0]&N)&&x<26;++x,N<<=1);if(x>0)for(y.iushrn(x);x-- >0;)D.isOdd()&&D.iadd(S),D.iushrn(1);d.cmp(y)>=0?(d.isub(y),P.isub(D)):(y.isub(d),D.isub(P))}var ae;return d.cmpn(1)===0?ae=P:ae=D,ae.cmpn(0)<0&&ae.iadd(l),ae},s.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var d=this.clone(),y=l.clone();d.negative=0,y.negative=0;for(var P=0;d.isEven()&&y.isEven();P++)d.iushrn(1),y.iushrn(1);do{for(;d.isEven();)d.iushrn(1);for(;y.isEven();)y.iushrn(1);var D=d.cmp(y);if(D<0){var S=d;d=y,y=S}else if(D===0||y.cmpn(1)===0)break;d.isub(y)}while(!0);return y.iushln(P)},s.prototype.invm=function(l){return this.egcd(l).a.umod(l)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(l){return this.words[0]&l},s.prototype.bincn=function(l){i(typeof l=="number");var d=l%26,y=(l-d)/26,P=1<>>26,v&=67108863,this.words[S]=v}return D!==0&&(this.words[S]=D,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(l){var d=l<0;if(this.negative!==0&&!d)return-1;if(this.negative===0&&d)return 1;this._strip();var y;if(this.length>1)y=1;else{d&&(l=-l),i(l<=67108863,"Number is too big");var P=this.words[0]|0;y=P===l?0:Pl.length)return 1;if(this.length=0;y--){var P=this.words[y]|0,D=l.words[y]|0;if(P!==D){PD&&(d=1);break}}return d},s.prototype.gtn=function(l){return this.cmpn(l)===1},s.prototype.gt=function(l){return this.cmp(l)===1},s.prototype.gten=function(l){return this.cmpn(l)>=0},s.prototype.gte=function(l){return this.cmp(l)>=0},s.prototype.ltn=function(l){return this.cmpn(l)===-1},s.prototype.lt=function(l){return this.cmp(l)===-1},s.prototype.lten=function(l){return this.cmpn(l)<=0},s.prototype.lte=function(l){return this.cmp(l)<=0},s.prototype.eqn=function(l){return this.cmpn(l)===0},s.prototype.eq=function(l){return this.cmp(l)===0},s.red=function(l){return new L(l)},s.prototype.toRed=function(l){return i(!this.red,"Already a number in reduction context"),i(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},s.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(l){return this.red=l,this},s.prototype.forceRed=function(l){return i(!this.red,"Already a number in reduction context"),this._forceRed(l)},s.prototype.redAdd=function(l){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},s.prototype.redIAdd=function(l){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},s.prototype.redSub=function(l){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},s.prototype.redISub=function(l){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},s.prototype.redShl=function(l){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},s.prototype.redMul=function(l){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},s.prototype.redIMul=function(l){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},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(l){return i(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var z={k256:null,p224:null,p192:null,p25519:null};function W(m,l){this.name=m,this.p=new s(l,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}W.prototype._tmp=function(){var l=new s(null);return l.words=new Array(Math.ceil(this.n/13)),l},W.prototype.ireduce=function(l){var d=l,y;do this.split(d,this.tmp),d=this.imulK(d),d=d.iadd(this.tmp),y=d.bitLength();while(y>this.n);var P=y0?d.isub(this.p):d.strip!==void 0?d.strip():d._strip(),d},W.prototype.split=function(l,d){l.iushrn(this.n,0,d)},W.prototype.imulK=function(l){return l.imul(this.k)};function _(){W.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(_,W),_.prototype.split=function(l,d){for(var y=4194303,P=Math.min(l.length,9),D=0;D>>22,S=v}S>>>=22,l.words[D-10]=S,S===0&&l.length>10?l.length-=10:l.length-=9},_.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var d=0,y=0;y>>=26,l.words[y]=D,d=P}return d!==0&&(l.words[l.length++]=d),l},s._prime=function(l){if(z[l])return z[l];var d;if(l==="k256")d=new _;else if(l==="p224")d=new U;else if(l==="p192")d=new ee;else if(l==="p25519")d=new oe;else throw new Error("Unknown prime "+l);return z[l]=d,d};function L(m){if(typeof m=="string"){var l=s._prime(m);this.m=l.p,this.prime=l}else i(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}L.prototype._verify1=function(l){i(l.negative===0,"red works only with positives"),i(l.red,"red works only with red numbers")},L.prototype._verify2=function(l,d){i((l.negative|d.negative)===0,"red works only with positives"),i(l.red&&l.red===d.red,"red works only with red numbers")},L.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(g(l,l.umod(this.m)._forceRed(this)),l)},L.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},L.prototype.add=function(l,d){this._verify2(l,d);var y=l.add(d);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},L.prototype.iadd=function(l,d){this._verify2(l,d);var y=l.iadd(d);return y.cmp(this.m)>=0&&y.isub(this.m),y},L.prototype.sub=function(l,d){this._verify2(l,d);var y=l.sub(d);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},L.prototype.isub=function(l,d){this._verify2(l,d);var y=l.isub(d);return y.cmpn(0)<0&&y.iadd(this.m),y},L.prototype.shl=function(l,d){return this._verify1(l),this.imod(l.ushln(d))},L.prototype.imul=function(l,d){return this._verify2(l,d),this.imod(l.imul(d))},L.prototype.mul=function(l,d){return this._verify2(l,d),this.imod(l.mul(d))},L.prototype.isqr=function(l){return this.imul(l,l.clone())},L.prototype.sqr=function(l){return this.mul(l,l)},L.prototype.sqrt=function(l){if(l.isZero())return l.clone();var d=this.m.andln(3);if(i(d%2===1),d===3){var y=this.m.add(new s(1)).iushrn(2);return this.pow(l,y)}for(var P=this.m.subn(1),D=0;!P.isZero()&&P.andln(1)===0;)D++,P.iushrn(1);i(!P.isZero());var S=new s(1).toRed(this),v=S.redNeg(),A=this.m.subn(1).iushrn(1),x=this.m.bitLength();for(x=new s(2*x*x).toRed(this);this.pow(x,A).cmp(v)!==0;)x.redIAdd(v);for(var N=this.pow(x,P),ae=this.pow(l,P.addn(1).iushrn(1)),R=this.pow(l,P),X=D;R.cmp(S)!==0;){for(var V=R,J=0;V.cmp(S)!==0;J++)V=V.redSqr();i(J=0;D--){for(var N=d.words[D],ae=x-1;ae>=0;ae--){var R=N>>ae&1;if(S!==P[0]&&(S=this.sqr(S)),R===0&&v===0){A=0;continue}v<<=1,v|=R,A++,!(A!==y&&(D!==0||ae!==0))&&(S=this.mul(S,P[v]),A=0,v=0)}x=26}return S},L.prototype.convertTo=function(l){var d=l.umod(this.m);return d===l?d.clone():d},L.prototype.convertFrom=function(l){var d=l.clone();return d.red=null,d},s.mont=function(l){return new b(l)};function b(m){L.call(this,m),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)}n(b,L),b.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},b.prototype.convertFrom=function(l){var d=this.imod(l.mul(this.rinv));return d.red=null,d},b.prototype.imul=function(l,d){if(l.isZero()||d.isZero())return l.words[0]=0,l.length=1,l;var y=l.imul(d),P=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=y.isub(P).iushrn(this.shift),S=D;return D.cmp(this.m)>=0?S=D.isub(this.m):D.cmpn(0)<0&&(S=D.iadd(this.m)),S._forceRed(this)},b.prototype.mul=function(l,d){if(l.isZero()||d.isZero())return new s(0)._forceRed(this);var y=l.mul(d),P=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=y.isub(P).iushrn(this.shift),S=D;return D.cmp(this.m)>=0?S=D.isub(this.m):D.cmpn(0)<0&&(S=D.iadd(this.m)),S._forceRed(this)},b.prototype.invm=function(l){var d=this.imod(l._invmp(this.m).mul(this.r2));return d._forceRed(this)}})(r,fr)})(kg);var vt=kg.exports;const jg="bignumber/5.7.0";var sl=vt.BN;const ds=new xt(jg),sd={},Wg=9007199254740991;function d4(r){return r!=null&&(ir.isBigNumber(r)||typeof r=="number"&&r%1===0||typeof r=="string"&&!!r.match(/^-?[0-9]+$/)||Oi(r)||typeof r=="bigint"||_a(r))}let Kg=!1;class ir{constructor(e,t){e!==sd&&ds.throwError("cannot call constructor directly; use BigNumber.from",xt.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=t,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return gi(Tt(this).fromTwos(e))}toTwos(e){return gi(Tt(this).toTwos(e))}abs(){return this._hex[0]==="-"?ir.from(this._hex.substring(1)):this}add(e){return gi(Tt(this).add(Tt(e)))}sub(e){return gi(Tt(this).sub(Tt(e)))}div(e){return ir.from(e).isZero()&&Gi("division-by-zero","div"),gi(Tt(this).div(Tt(e)))}mul(e){return gi(Tt(this).mul(Tt(e)))}mod(e){const t=Tt(e);return t.isNeg()&&Gi("division-by-zero","mod"),gi(Tt(this).umod(t))}pow(e){const t=Tt(e);return t.isNeg()&&Gi("negative-power","pow"),gi(Tt(this).pow(t))}and(e){const t=Tt(e);return(this.isNegative()||t.isNeg())&&Gi("unbound-bitwise-result","and"),gi(Tt(this).and(t))}or(e){const t=Tt(e);return(this.isNegative()||t.isNeg())&&Gi("unbound-bitwise-result","or"),gi(Tt(this).or(t))}xor(e){const t=Tt(e);return(this.isNegative()||t.isNeg())&&Gi("unbound-bitwise-result","xor"),gi(Tt(this).xor(t))}mask(e){return(this.isNegative()||e<0)&&Gi("negative-width","mask"),gi(Tt(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Gi("negative-width","shl"),gi(Tt(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Gi("negative-width","shr"),gi(Tt(this).shrn(e))}eq(e){return Tt(this).eq(Tt(e))}lt(e){return Tt(this).lt(Tt(e))}lte(e){return Tt(this).lte(Tt(e))}gt(e){return Tt(this).gt(Tt(e))}gte(e){return Tt(this).gte(Tt(e))}isNegative(){return this._hex[0]==="-"}isZero(){return Tt(this).isZero()}toNumber(){try{return Tt(this).toNumber()}catch{Gi("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return ds.throwError("this platform does not support BigInt",xt.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?Kg||(Kg=!0,ds.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?ds.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",xt.errors.UNEXPECTED_ARGUMENT,{}):ds.throwError("BigNumber.toString does not accept parameters",xt.errors.UNEXPECTED_ARGUMENT,{})),Tt(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof ir)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new ir(sd,Tc(e)):e.match(/^-?[0-9]+$/)?new ir(sd,Tc(new sl(e))):ds.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Gi("underflow","BigNumber.from",e),(e>=Wg||e<=-Wg)&&Gi("overflow","BigNumber.from",e),ir.from(String(e));const t=e;if(typeof t=="bigint")return ir.from(t.toString());if(_a(t))return ir.from(ni(t));if(t)if(t.toHexString){const i=t.toHexString();if(typeof i=="string")return ir.from(i)}else{let i=t._hex;if(i==null&&t.type==="BigNumber"&&(i=t.hex),typeof i=="string"&&(Oi(i)||i[0]==="-"&&Oi(i.substring(1))))return ir.from(i)}return ds.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}}function Tc(r){if(typeof r!="string")return Tc(r.toString(16));if(r[0]==="-")return r=r.substring(1),r[0]==="-"&&ds.throwArgumentError("invalid hex","value",r),r=Tc(r),r==="0x00"?r:"-"+r;if(r.substring(0,2)!=="0x"&&(r="0x"+r),r==="0x")return"0x00";for(r.length%2&&(r="0x0"+r.substring(2));r.length>4&&r.substring(0,4)==="0x00";)r="0x"+r.substring(4);return r}function gi(r){return ir.from(Tc(r))}function Tt(r){const e=ir.from(r).toHexString();return e[0]==="-"?new sl("-"+e.substring(3),16):new sl(e.substring(2),16)}function Gi(r,e,t){const i={fault:r,operation:e};return t!=null&&(i.value=t),ds.throwError(r,xt.errors.NUMERIC_FAULT,i)}function p4(r){return new sl(r,36).toString(16)}const si=new xt(jg),$c={},Vg=ir.from(0),Gg=ir.from(-1);function Yg(r,e,t,i){const n={fault:e,operation:t};return i!==void 0&&(n.value=i),si.throwError(r,xt.errors.NUMERIC_FAULT,n)}let Nc="0";for(;Nc.length<256;)Nc+=Nc;function od(r){if(typeof r!="number")try{r=ir.from(r).toNumber()}catch{}return typeof r=="number"&&r>=0&&r<=256&&!(r%1)?"1"+Nc.substring(0,r):si.throwArgumentError("invalid decimal size","decimals",r)}function ad(r,e){e==null&&(e=0);const t=od(e);r=ir.from(r);const i=r.lt(Vg);i&&(r=r.mul(Gg));let n=r.mod(t).toString();for(;n.length2&&si.throwArgumentError("too many decimal points","value",r);let s=n[0],a=n[1];for(s||(s="0"),a||(a="0");a[a.length-1]==="0";)a=a.substring(0,a.length-1);for(a.length>t.length-1&&Yg("fractional component exceeds decimals","underflow","parseFixed"),a===""&&(a="0");a.lengthe[a]==null?h:(typeof e[a]!==f&&si.throwArgumentError("invalid fixed format ("+a+" not "+f+")","format."+a,e[a]),e[a]);t=s("signed","boolean",t),i=s("width","number",i),n=s("decimals","number",n)}return i%8&&si.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",i),n>80&&si.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",n),new xa($c,t,i,n)}}class Hr{constructor(e,t,i,n){e!==$c&&si.throwError("cannot use FixedNumber constructor; use FixedNumber.from",xt.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=n,this._hex=t,this._value=i,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&si.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);const t=ps(this._value,this.format.decimals),i=ps(e._value,e.format.decimals);return Hr.fromValue(t.add(i),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);const t=ps(this._value,this.format.decimals),i=ps(e._value,e.format.decimals);return Hr.fromValue(t.sub(i),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);const t=ps(this._value,this.format.decimals),i=ps(e._value,e.format.decimals);return Hr.fromValue(t.mul(i).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);const t=ps(this._value,this.format.decimals),i=ps(e._value,e.format.decimals);return Hr.fromValue(t.mul(this.format._multiplier).div(i),this.format.decimals,this.format)}floor(){const e=this.toString().split(".");e.length===1&&e.push("0");let t=Hr.from(e[0],this.format);const i=!e[1].match(/^(0*)$/);return this.isNegative()&&i&&(t=t.subUnsafe(Jg.toFormat(t.format))),t}ceiling(){const e=this.toString().split(".");e.length===1&&e.push("0");let t=Hr.from(e[0],this.format);const i=!e[1].match(/^(0*)$/);return!this.isNegative()&&i&&(t=t.addUnsafe(Jg.toFormat(t.format))),t}round(e){e==null&&(e=0);const t=this.toString().split(".");if(t.length===1&&t.push("0"),(e<0||e>80||e%1)&&si.throwArgumentError("invalid decimal count","decimals",e),t[1].length<=e)return this;const i=Hr.from("1"+Nc.substring(0,e),this.format),n=g4.toFormat(this.format);return this.mulUnsafe(i).addUnsafe(n).floor().divUnsafe(i)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&si.throwArgumentError("invalid byte width","width",e);const t=ir.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return qn(t,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return Hr.fromString(this._value,e)}static fromValue(e,t,i){return i==null&&t!=null&&!d4(t)&&(i=t,t=null),t==null&&(t=0),i==null&&(i="fixed"),Hr.fromString(ad(e,t),xa.from(i))}static fromString(e,t){t==null&&(t="fixed");const i=xa.from(t),n=ps(e,i.decimals);!i.signed&&n.lt(Vg)&&Yg("unsigned value cannot be negative","overflow","value",e);let s=null;i.signed?s=n.toTwos(i.width).toHexString():(s=n.toHexString(),s=qn(s,i.width/8));const a=ad(n,i.decimals);return new Hr($c,s,a,i)}static fromBytes(e,t){t==null&&(t="fixed");const i=xa.from(t);if(ur(e).length>i.width/8)throw new Error("overflow");let n=ir.from(e);i.signed&&(n=n.fromTwos(i.width));const s=n.toTwos((i.signed?0:1)+i.width).toHexString(),a=ad(n,i.decimals);return new Hr($c,s,a,i)}static from(e,t){if(typeof e=="string")return Hr.fromString(e,t);if(_a(e))return Hr.fromBytes(e,t);try{return Hr.fromValue(e,0,t)}catch(i){if(i.code!==xt.errors.INVALID_ARGUMENT)throw i}return si.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}}const Jg=Hr.from(1),g4=Hr.from("0.5"),v4="strings/5.7.0",Qg=new xt(v4);var ol;(function(r){r.current="",r.NFC="NFC",r.NFD="NFD",r.NFKC="NFKC",r.NFKD="NFKD"})(ol||(ol={}));var Aa;(function(r){r.UNEXPECTED_CONTINUE="unexpected continuation byte",r.BAD_PREFIX="bad codepoint prefix",r.OVERRUN="string overrun",r.MISSING_CONTINUE="missing continuation byte",r.OUT_OF_RANGE="out of UTF-8 range",r.UTF16_SURROGATE="UTF-16 surrogate",r.OVERLONG="overlong representation"})(Aa||(Aa={}));function m4(r,e,t,i,n){return Qg.throwArgumentError(`invalid codepoint at offset ${e}; ${r}`,"bytes",t)}function Zg(r,e,t,i,n){if(r===Aa.BAD_PREFIX||r===Aa.UNEXPECTED_CONTINUE){let s=0;for(let a=e+1;a>6===2;a++)s++;return s}return r===Aa.OVERRUN?t.length-e-1:0}function b4(r,e,t,i,n){return r===Aa.OVERLONG?(i.push(n),0):(i.push(65533),Zg(r,e,t))}Object.freeze({error:m4,ignore:Zg,replace:b4});function cd(r,e=ol.current){e!=ol.current&&(Qg.checkNormalize(),r=r.normalize(e));let t=[];for(let i=0;i>6|192),t.push(n&63|128);else if((n&64512)==55296){i++;const s=r.charCodeAt(i);if(i>=r.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");const a=65536+((n&1023)<<10)+(s&1023);t.push(a>>18|240),t.push(a>>12&63|128),t.push(a>>6&63|128),t.push(a&63|128)}else t.push(n>>12|224),t.push(n>>6&63|128),t.push(n&63|128)}return ur(t)}function w4(r){if(r.length%4!==0)throw new Error("bad data");let e=[];for(let t=0;t{let s=n.split(":");t+=parseInt(s[0],16),i[t]=e(s[1])}),i}function Xg(r){let e=0;return r.split(",").map(t=>{let i=t.split("-");i.length===1?i[1]="0":i[1]===""&&(i[1]="1");let n=e+parseInt(i[0],16);return e=parseInt(i[1],16),{l:n,h:e}})}Xg("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(r=>parseInt(r,16)),fd("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),fd("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),fd("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",w4),Xg("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");const ev="hash/5.7.0";function y4(r){r=atob(r);const e=[];for(let t=0;t0&&Array.isArray(f)?n(f,a-1):t.push(f)})};return n(r,e),t}function _4(r){const e={};for(let t=0;t>--h&1}const w=31,M=Math.pow(2,w),C=M>>>1,O=C>>1,$=M-1;let j=0;for(let z=0;z1;){let oe=W+_>>>1;z>>1|g(),U=U<<1^C,ee=(ee^C)<<1|C|1;F=U,G=1+ee-U}let B=i-4;return H.map(z=>{switch(z-B){case 3:return B+65792+(r[f++]<<16|r[f++]<<8|r[f++]);case 2:return B+256+(r[f++]<<8|r[f++]);case 1:return B+r[f++];default:return z-1}})}function A4(r){let e=0;return()=>r[e++]}function E4(r){return A4(x4(r))}function S4(r){return r&1?~r>>1:r>>1}function I4(r,e){let t=Array(r);for(let i=0;ie[a]):t}function C4(r){let e=[];for(;;){let t=r();if(t==0)break;e.push(D4(t,r))}for(;;){let t=r()-1;if(t<0)break;e.push(O4(t,r))}return _4(tv(e))}function P4(r){let e=[];for(;;){let t=r();if(t==0)break;e.push(t)}return e}function iv(r,e,t){let i=Array(r).fill(void 0).map(()=>[]);for(let n=0;ni[a].push(s));return i}function D4(r,e){let t=1+e(),i=e(),n=P4(e),s=iv(n.length,1+r,e);return tv(s.map((a,f)=>{const h=a[0],u=a.slice(1);return Array(n[f]).fill(void 0).map((g,w)=>{let M=w*i;return[h+w*t,u.map(C=>C+M)]})}))}function O4(r,e){let t=1+e();return iv(t,1+r,e).map(n=>[n[0],n.slice(1)])}function R4(r){let e=al(r).sort((i,n)=>i-n);return t();function t(){let i=[];for(;;){let u=al(r,e);if(u.length==0)break;i.push({set:new Set(u),node:t()})}i.sort((u,g)=>g.set.size-u.set.size);let n=r(),s=n%3;n=n/3|0;let a=!!(n&1);n>>=1;let f=n==1,h=n==2;return{branches:i,valid:s,fe0f:a,save:f,check:h}}}function T4(){return E4(y4("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}const cl=T4();new Set(al(cl)),new Set(al(cl)),C4(cl),R4(cl),new xt(ev),new Uint8Array(32).fill(0);const $4=`Ethereum Signed Message: ++`;function nv(r){return typeof r=="string"&&(r=cd(r)),nd(c4([cd($4),cd(String(r.length)),r]))}const N4="rlp/5.7.0";new xt(N4);const L4="address/5.7.0",Lc=new xt(L4);function sv(r){Oi(r,20)||Lc.throwArgumentError("invalid address","address",r),r=r.toLowerCase();const e=r.substring(2).split(""),t=new Uint8Array(40);for(let n=0;n<40;n++)t[n]=e[n].charCodeAt(0);const i=ur(nd(t));for(let n=0;n<40;n+=2)i[n>>1]>>4>=8&&(e[n]=e[n].toUpperCase()),(i[n>>1]&15)>=8&&(e[n+1]=e[n+1].toUpperCase());return"0x"+e.join("")}const B4=9007199254740991;function F4(r){return Math.log10?Math.log10(r):Math.log(r)/Math.LN10}const ld={};for(let r=0;r<10;r++)ld[String(r)]=String(r);for(let r=0;r<26;r++)ld[String.fromCharCode(65+r)]=String(10+r);const ov=Math.floor(F4(B4));function U4(r){r=r.toUpperCase(),r=r.substring(4)+r.substring(0,2)+"00";let e=r.split("").map(i=>ld[i]).join("");for(;e.length>=ov;){let i=e.substring(0,ov);e=parseInt(i,10)%97+e.substring(i.length)}let t=String(98-parseInt(e,10)%97);for(;t.length<2;)t="0"+t;return t}function q4(r){let e=null;if(typeof r!="string"&&Lc.throwArgumentError("invalid address","address",r),r.match(/^(0x)?[0-9a-fA-F]{40}$/))r.substring(0,2)!=="0x"&&(r="0x"+r),e=sv(r),r.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==r&&Lc.throwArgumentError("bad address checksum","address",r);else if(r.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(r.substring(2,4)!==U4(r)&&Lc.throwArgumentError("bad icap checksum","address",r),e=p4(r.substring(4));e.length<40;)e="0"+e;e=sv("0x"+e)}else Lc.throwArgumentError("invalid address","address",r);return e}const z4="properties/5.7.0";new xt(z4);function Bc(r,e,t){Object.defineProperty(r,e,{enumerable:!0,value:t,writable:!1})}new xt(ev),new Uint8Array(32).fill(0),ir.from(-1);const H4=ir.from(0),k4=ir.from(1);ir.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),qn(k4.toHexString(),32),qn(H4.toHexString(),32);var Ri={},$t={},Eo=av;function av(r,e){if(!r)throw new Error(e||"Assertion failed")}av.equal=function(e,t,i){if(e!=t)throw new Error(i||"Assertion failed: "+e+" != "+t)};var Ea={exports:{}};typeof Object.create=="function"?Ea.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Ea.exports=function(e,t){if(t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}};var j4=Eo,W4=Ea.exports;$t.inherits=W4;function K4(r,e){return(r.charCodeAt(e)&64512)!==55296||e<0||e+1>=r.length?!1:(r.charCodeAt(e+1)&64512)===56320}function V4(r,e){if(Array.isArray(r))return r.slice();if(!r)return[];var t=[];if(typeof r=="string")if(e){if(e==="hex")for(r=r.replace(/[^a-z0-9]+/ig,""),r.length%2!==0&&(r="0"+r),n=0;n>6|192,t[i++]=s&63|128):K4(r,n)?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),t[i++]=s>>18|240,t[i++]=s>>12&63|128,t[i++]=s>>6&63|128,t[i++]=s&63|128):(t[i++]=s>>12|224,t[i++]=s>>6&63|128,t[i++]=s&63|128)}else for(n=0;n>>24|r>>>8&65280|r<<8&16711680|(r&255)<<24;return e>>>0}$t.htonl=cv;function Y4(r,e){for(var t="",i=0;i>>0}return s}$t.join32=J4;function Q4(r,e){for(var t=new Array(r.length*4),i=0,n=0;i>>24,t[n+1]=s>>>16&255,t[n+2]=s>>>8&255,t[n+3]=s&255):(t[n+3]=s>>>24,t[n+2]=s>>>16&255,t[n+1]=s>>>8&255,t[n]=s&255)}return t}$t.split32=Q4;function Z4(r,e){return r>>>e|r<<32-e}$t.rotr32=Z4;function X4(r,e){return r<>>32-e}$t.rotl32=X4;function e8(r,e){return r+e>>>0}$t.sum32=e8;function t8(r,e,t){return r+e+t>>>0}$t.sum32_3=t8;function r8(r,e,t,i){return r+e+t+i>>>0}$t.sum32_4=r8;function i8(r,e,t,i,n){return r+e+t+i+n>>>0}$t.sum32_5=i8;function n8(r,e,t,i){var n=r[e],s=r[e+1],a=i+s>>>0,f=(a>>0,r[e+1]=a}$t.sum64=n8;function s8(r,e,t,i){var n=e+i>>>0,s=(n>>0}$t.sum64_hi=s8;function o8(r,e,t,i){var n=e+i;return n>>>0}$t.sum64_lo=o8;function a8(r,e,t,i,n,s,a,f){var h=0,u=e;u=u+i>>>0,h+=u>>0,h+=u>>0,h+=u>>0}$t.sum64_4_hi=a8;function c8(r,e,t,i,n,s,a,f){var h=e+i+s+f;return h>>>0}$t.sum64_4_lo=c8;function f8(r,e,t,i,n,s,a,f,h,u){var g=0,w=e;w=w+i>>>0,g+=w>>0,g+=w>>0,g+=w>>0,g+=w>>0}$t.sum64_5_hi=f8;function l8(r,e,t,i,n,s,a,f,h,u){var g=e+i+s+f+u;return g>>>0}$t.sum64_5_lo=l8;function h8(r,e,t){var i=e<<32-t|r>>>t;return i>>>0}$t.rotr64_hi=h8;function u8(r,e,t){var i=r<<32-t|e>>>t;return i>>>0}$t.rotr64_lo=u8;function d8(r,e,t){return r>>>t}$t.shr64_hi=d8;function p8(r,e,t){var i=r<<32-t|e>>>t;return i>>>0}$t.shr64_lo=p8;var Sa={},hv=$t,g8=Eo;function fl(){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}Sa.BlockHash=fl,fl.prototype.update=function(e,t){if(e=hv.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){e=this.pending;var i=e.length%this._delta8;this.pending=e.slice(e.length-i,e.length),this.pending.length===0&&(this.pending=null),e=hv.join32(e,0,e.length-i,this.endian);for(var n=0;n>>24&255,n[s++]=e>>>16&255,n[s++]=e>>>8&255,n[s++]=e&255}else for(n[s++]=e&255,n[s++]=e>>>8&255,n[s++]=e>>>16&255,n[s++]=e>>>24&255,n[s++]=0,n[s++]=0,n[s++]=0,n[s++]=0,a=8;a>>3}zn.g0_256=y8;function _8(r){return Hn(r,17)^Hn(r,19)^r>>>10}zn.g1_256=_8;var Ma=$t,x8=Sa,A8=zn,hd=Ma.rotl32,Fc=Ma.sum32,E8=Ma.sum32_5,S8=A8.ft_1,gv=x8.BlockHash,I8=[1518500249,1859775393,2400959708,3395469782];function kn(){if(!(this instanceof kn))return new kn;gv.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ma.inherits(kn,gv);var M8=kn;kn.blockSize=512,kn.outSize=160,kn.hmacStrength=80,kn.padLength=64,kn.prototype._update=function(e,t){for(var i=this.W,n=0;n<16;n++)i[n]=e[t+n];for(;nthis.blockSize&&(e=new this.Hash().update(e).digest()),p_(e.length<=this.blockSize);for(var t=e.length;t>8,M=g&255;w?h.push(w,M):h.push(M)}return h}t.toArray=i;function n(a){return a.length===1?"0"+a:a}t.zero2=n;function s(a){for(var f="",h=0;h(M>>1)-1?$=(M>>1)-j:$=j,C.isubn($)):$=0,w[O]=$,C.iushrn(1)}return w}t.getNAF=i;function n(h,u){var g=[[],[]];h=h.clone(),u=u.clone();for(var w=0,M=0,C;h.cmpn(-w)>0||u.cmpn(-M)>0;){var O=h.andln(3)+w&3,$=u.andln(3)+M&3;O===3&&(O=-1),$===3&&($=-1);var j;O&1?(C=h.andln(7)+w&7,(C===3||C===5)&&$===2?j=-O:j=O):j=0,g[0].push(j);var H;$&1?(C=u.andln(7)+M&7,(C===3||C===5)&&O===2?H=-$:H=$):H=0,g[1].push(H),2*w===j+1&&(w=1-w),2*M===H+1&&(M=1-M),h.iushrn(1),u.iushrn(1)}return g}t.getJSF=n;function s(h,u,g){var w="_"+u;h.prototype[u]=function(){return this[w]!==void 0?this[w]:this[w]=g.call(this)}}t.cachedProperty=s;function a(h){return typeof h=="string"?t.toArray(h,"hex"):h}t.parseBytes=a;function f(h){return new vt(h,"hex","le")}t.intFromLE=f}),hl=Ti.getNAF,m_=Ti.getJSF,ul=Ti.assert;function qs(r,e){this.type=r,this.p=new vt(e.p,16),this.red=e.prime?vt.red(e.prime):vt.mont(this.p),this.zero=new vt(0).toRed(this.red),this.one=new vt(1).toRed(this.red),this.two=new vt(2).toRed(this.red),this.n=e.n&&new vt(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.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 t=this.n&&this.p.div(this.n);!t||t.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Io=qs;qs.prototype.point=function(){throw new Error("Not implemented")},qs.prototype.validate=function(){throw new Error("Not implemented")},qs.prototype._fixedNafMul=function(e,t){ul(e.precomputed);var i=e._getDoubles(),n=hl(t,1,this._bitLength),s=(1<=f;u--)h=(h<<1)+n[u];a.push(h)}for(var g=this.jpoint(null,null,null),w=this.jpoint(null,null,null),M=s;M>0;M--){for(f=0;f=0;h--){for(var u=0;h>=0&&a[h]===0;h--)u++;if(h>=0&&u++,f=f.dblp(u),h<0)break;var g=a[h];ul(g!==0),e.type==="affine"?g>0?f=f.mixedAdd(s[g-1>>1]):f=f.mixedAdd(s[-g-1>>1].neg()):g>0?f=f.add(s[g-1>>1]):f=f.add(s[-g-1>>1].neg())}return e.type==="affine"?f.toP():f},qs.prototype._wnafMulAdd=function(e,t,i,n,s){var a=this._wnafT1,f=this._wnafT2,h=this._wnafT3,u=0,g,w,M;for(g=0;g=1;g-=2){var O=g-1,$=g;if(a[O]!==1||a[$]!==1){h[O]=hl(i[O],a[O],this._bitLength),h[$]=hl(i[$],a[$],this._bitLength),u=Math.max(h[O].length,u),u=Math.max(h[$].length,u);continue}var j=[t[O],null,null,t[$]];t[O].y.cmp(t[$].y)===0?(j[1]=t[O].add(t[$]),j[2]=t[O].toJ().mixedAdd(t[$].neg())):t[O].y.cmp(t[$].y.redNeg())===0?(j[1]=t[O].toJ().mixedAdd(t[$]),j[2]=t[O].add(t[$].neg())):(j[1]=t[O].toJ().mixedAdd(t[$]),j[2]=t[O].toJ().mixedAdd(t[$].neg()));var H=[-3,-1,-5,-7,0,7,5,1,3],F=m_(i[O],i[$]);for(u=Math.max(F[0].length,u),h[O]=new Array(u),h[$]=new Array(u),w=0;w=0;g--){for(var _=0;g>=0;){var U=!0;for(w=0;w=0&&_++,z=z.dblp(_),g<0)break;for(w=0;w0?M=f[w][ee-1>>1]:ee<0&&(M=f[w][-ee-1>>1].neg()),M.type==="affine"?z=z.mixedAdd(M):z=z.add(M))}}for(g=0;g=Math.ceil((e.bitLength()+1)/t.step):!1},Yi.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var i=[this],n=this,s=0;s=0&&(C=u,O=g),w.negative&&(w=w.neg(),M=M.neg()),C.negative&&(C=C.neg(),O=O.neg()),[{a:w,b:M},{a:C,b:O}]},Ji.prototype._endoSplit=function(e){var t=this.endo.basis,i=t[0],n=t[1],s=n.b.mul(e).divRound(this.n),a=i.b.neg().mul(e).divRound(this.n),f=s.mul(i.a),h=a.mul(n.a),u=s.mul(i.b),g=a.mul(n.b),w=e.sub(f).sub(h),M=u.add(g).neg();return{k1:w,k2:M}},Ji.prototype.pointFromX=function(e,t){e=new vt(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=i.redSqrt();if(n.redSqr().redSub(i).cmp(this.zero)!==0)throw new Error("invalid point");var s=n.fromRed().isOdd();return(t&&!s||!t&&s)&&(n=n.redNeg()),this.point(e,n)},Ji.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,i=e.y,n=this.a.redMul(t),s=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return i.redSqr().redISub(s).cmpn(0)===0},Ji.prototype._endoWnafMulAdd=function(e,t,i){for(var n=this._endoWnafT1,s=this._endoWnafT2,a=0;a":""},Or.prototype.isInfinity=function(){return this.inf},Or.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(this.x.cmp(e.x)===0)return this.curve.point(null,null);var t=this.y.redSub(e.y);t.cmpn(0)!==0&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var i=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(i)).redISub(this.y);return this.curve.point(i,n)},Or.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(e.cmpn(0)===0)return this.curve.point(null,null);var t=this.curve.a,i=this.x.redSqr(),n=e.redInvm(),s=i.redAdd(i).redIAdd(i).redIAdd(t).redMul(n),a=s.redSqr().redISub(this.x.redAdd(this.x)),f=s.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,f)},Or.prototype.getX=function(){return this.x.fromRed()},Or.prototype.getY=function(){return this.y.fromRed()},Or.prototype.mul=function(e){return e=new vt(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)},Or.prototype.mulAdd=function(e,t,i){var n=[this,t],s=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,s):this.curve._wnafMulAdd(1,n,s,2)},Or.prototype.jmulAdd=function(e,t,i){var n=[this,t],s=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,s,!0):this.curve._wnafMulAdd(1,n,s,2,!0)},Or.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||this.x.cmp(e.x)===0&&this.y.cmp(e.y)===0)},Or.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var i=this.precomputed,n=function(s){return s.neg()};t.precomputed={naf:i.naf&&{wnd:i.naf.wnd,points:i.naf.points.map(n)},doubles:i.doubles&&{step:i.doubles.step,points:i.doubles.points.map(n)}}}return t},Or.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var e=this.curve.jpoint(this.x,this.y,this.curve.one);return e};function kr(r,e,t,i){Io.BasePoint.call(this,r,"jacobian"),e===null&&t===null&&i===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new vt(0)):(this.x=new vt(e,16),this.y=new vt(t,16),this.z=new vt(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}md(kr,Io.BasePoint),Ji.prototype.jpoint=function(e,t,i){return new kr(this,e,t,i)},kr.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),i=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(i,n)},kr.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},kr.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),i=this.z.redSqr(),n=this.x.redMul(t),s=e.x.redMul(i),a=this.y.redMul(t.redMul(e.z)),f=e.y.redMul(i.redMul(this.z)),h=n.redSub(s),u=a.redSub(f);if(h.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var g=h.redSqr(),w=g.redMul(h),M=n.redMul(g),C=u.redSqr().redIAdd(w).redISub(M).redISub(M),O=u.redMul(M.redISub(C)).redISub(a.redMul(w)),$=this.z.redMul(e.z).redMul(h);return this.curve.jpoint(C,O,$)},kr.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),i=this.x,n=e.x.redMul(t),s=this.y,a=e.y.redMul(t).redMul(this.z),f=i.redSub(n),h=s.redSub(a);if(f.cmpn(0)===0)return h.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var u=f.redSqr(),g=u.redMul(f),w=i.redMul(u),M=h.redSqr().redIAdd(g).redISub(w).redISub(w),C=h.redMul(w.redISub(M)).redISub(s.redMul(g)),O=this.z.redMul(f);return this.curve.jpoint(M,C,O)},kr.prototype.dblp=function(e){if(e===0)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var i=this;for(t=0;t=0)return!1;if(i.redIAdd(s),this.x.cmp(i)===0)return!0}},kr.prototype.inspect=function(){return this.isInfinity()?"":""},kr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var dl=Oa(function(r,e){var t=e;t.base=Io,t.short=w_,t.mont=null,t.edwards=null}),pl=Oa(function(r,e){var t=e,i=Ti.assert;function n(f){f.type==="short"?this.curve=new dl.short(f):f.type==="edwards"?this.curve=new dl.edwards(f):this.curve=new dl.mont(f),this.g=this.curve.g,this.n=this.curve.n,this.hash=f.hash,i(this.g.validate(),"Invalid curve"),i(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}t.PresetCurve=n;function s(f,h){Object.defineProperty(t,f,{configurable:!0,enumerable:!0,get:function(){var u=new n(h);return Object.defineProperty(t,f,{configurable:!0,enumerable:!0,value:u}),u}})}s("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:Ri.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("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:Ri.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("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:Ri.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("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:Ri.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"]}),s("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:Ri.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"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Ri.sha256,gRed:!1,g:["9"]}),s("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:Ri.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var a;try{a=null.crash()}catch{a=void 0}s("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:Ri.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",a]})});function zs(r){if(!(this instanceof zs))return new zs(r);this.hash=r.hash,this.predResist=!!r.predResist,this.outLen=this.hash.outSize,this.minEntropy=r.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=An.toArray(r.entropy,r.entropyEnc||"hex"),t=An.toArray(r.nonce,r.nonceEnc||"hex"),i=An.toArray(r.pers,r.persEnc||"hex");vd(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,t,i)}var Dv=zs;zs.prototype._init=function(e,t,i){var n=e.concat(t).concat(i);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var s=0;s=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(i||[])),this._reseed=1},zs.prototype.generate=function(e,t,i,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof t!="string"&&(n=i,i=t,t=null),i&&(i=An.toArray(i,n||"hex"),this._update(i));for(var s=[];s.length"};var y_=Ti.assert;function gl(r,e){if(r instanceof gl)return r;this._importDER(r,e)||(y_(r.r&&r.s,"Signature without r or s"),this.r=new vt(r.r,16),this.s=new vt(r.s,16),r.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=r.recoveryParam)}var vl=gl;function __(){this.place=0}function yd(r,e){var t=r[e.place++];if(!(t&128))return t;var i=t&15;if(i===0||i>4)return!1;for(var n=0,s=0,a=e.place;s>>=0;return n<=127?!1:(e.place=a,n)}function Ov(r){for(var e=0,t=r.length-1;!r[e]&&!(r[e+1]&128)&&e>>3);for(r.push(t|128);--t;)r.push(e>>>(t<<3)&255);r.push(e)}gl.prototype.toDER=function(e){var t=this.r.toArray(),i=this.s.toArray();for(t[0]&128&&(t=[0].concat(t)),i[0]&128&&(i=[0].concat(i)),t=Ov(t),i=Ov(i);!i[0]&&!(i[1]&128);)i=i.slice(1);var n=[2];_d(n,t.length),n=n.concat(t),n.push(2),_d(n,i.length);var s=n.concat(i),a=[48];return _d(a,s.length),a=a.concat(s),Ti.encode(a,e)};var x_=function(){throw new Error("unsupported")},Rv=Ti.assert;function Qi(r){if(!(this instanceof Qi))return new Qi(r);typeof r=="string"&&(Rv(Object.prototype.hasOwnProperty.call(pl,r),"Unknown curve "+r),r=pl[r]),r instanceof pl.PresetCurve&&(r={curve:r}),this.curve=r.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=r.curve.g,this.g.precompute(r.curve.n.bitLength()+1),this.hash=r.hash||r.curve.hash}var A_=Qi;Qi.prototype.keyPair=function(e){return new wd(this,e)},Qi.prototype.keyFromPrivate=function(e,t){return wd.fromPrivate(this,e,t)},Qi.prototype.keyFromPublic=function(e,t){return wd.fromPublic(this,e,t)},Qi.prototype.genKeyPair=function(e){e||(e={});for(var t=new Dv({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||x_(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),i=this.n.byteLength(),n=this.n.sub(new vt(2));;){var s=new vt(t.generate(i));if(!(s.cmp(n)>0))return s.iaddn(1),this.keyFromPrivate(s)}},Qi.prototype._truncateToN=function(e,t){var i=e.byteLength()*8-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},Qi.prototype.sign=function(e,t,i,n){typeof i=="object"&&(n=i,i=null),n||(n={}),t=this.keyFromPrivate(t,i),e=this._truncateToN(new vt(e,16));for(var s=this.n.byteLength(),a=t.getPrivate().toArray("be",s),f=e.toArray("be",s),h=new Dv({hash:this.hash,entropy:a,nonce:f,pers:n.pers,persEnc:n.persEnc||"utf8"}),u=this.n.sub(new vt(1)),g=0;;g++){var w=n.k?n.k(g):new vt(h.generate(this.n.byteLength()));if(w=this._truncateToN(w,!0),!(w.cmpn(1)<=0||w.cmp(u)>=0)){var M=this.g.mul(w);if(!M.isInfinity()){var C=M.getX(),O=C.umod(this.n);if(O.cmpn(0)!==0){var $=w.invm(this.n).mul(O.mul(t.getPrivate()).iadd(e));if($=$.umod(this.n),$.cmpn(0)!==0){var j=(M.getY().isOdd()?1:0)|(C.cmp(O)!==0?2:0);return n.canonical&&$.cmp(this.nh)>0&&($=this.n.sub($),j^=1),new vl({r:O,s:$,recoveryParam:j})}}}}}},Qi.prototype.verify=function(e,t,i,n){e=this._truncateToN(new vt(e,16)),i=this.keyFromPublic(i,n),t=new vl(t,"hex");var s=t.r,a=t.s;if(s.cmpn(1)<0||s.cmp(this.n)>=0||a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var f=a.invm(this.n),h=f.mul(e).umod(this.n),u=f.mul(s).umod(this.n),g;return this.curve._maxwellTrick?(g=this.g.jmulAdd(h,i.getPublic(),u),g.isInfinity()?!1:g.eqXToP(s)):(g=this.g.mulAdd(h,i.getPublic(),u),g.isInfinity()?!1:g.getX().umod(this.n).cmp(s)===0)},Qi.prototype.recoverPubKey=function(r,e,t,i){Rv((3&t)===t,"The recovery param is more than two bits"),e=new vl(e,i);var n=this.n,s=new vt(r),a=e.r,f=e.s,h=t&1,u=t>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw new Error("Unable to find sencond key candinate");u?a=this.curve.pointFromX(a.add(this.curve.n),h):a=this.curve.pointFromX(a,h);var g=e.r.invm(n),w=n.sub(s).mul(g).umod(n),M=f.mul(g).umod(n);return this.g.mulAdd(w,a,M)},Qi.prototype.getKeyRecoveryParam=function(r,e,t,i){if(e=new vl(e,i),e.recoveryParam!==null)return e.recoveryParam;for(var n=0;n<4;n++){var s;try{s=this.recoverPubKey(r,e,n)}catch{continue}if(s.eq(t))return n}throw new Error("Unable to find valid recovery factor")};var E_=Oa(function(r,e){var t=e;t.version="6.5.4",t.utils=Ti,t.rand=function(){throw new Error("unsupported")},t.curve=dl,t.curves=pl,t.ec=A_,t.eddsa=null}),S_=E_.ec;const I_="signing-key/5.7.0",xd=new xt(I_);let Ad=null;function Gn(){return Ad||(Ad=new S_("secp256k1")),Ad}class M_{constructor(e){Bc(this,"curve","secp256k1"),Bc(this,"privateKey",ni(e)),l4(this.privateKey)!==32&&xd.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const t=Gn().keyFromPrivate(ur(this.privateKey));Bc(this,"publicKey","0x"+t.getPublic(!1,"hex")),Bc(this,"compressedPublicKey","0x"+t.getPublic(!0,"hex")),Bc(this,"_isSigningKey",!0)}_addPoint(e){const t=Gn().keyFromPublic(ur(this.publicKey)),i=Gn().keyFromPublic(ur(e));return"0x"+t.pub.add(i.pub).encodeCompressed("hex")}signDigest(e){const t=Gn().keyFromPrivate(ur(this.privateKey)),i=ur(e);i.length!==32&&xd.throwArgumentError("bad digest length","digest",e);const n=t.sign(i,{canonical:!0});return Hg({recoveryParam:n.recoveryParam,r:qn("0x"+n.r.toString(16),32),s:qn("0x"+n.s.toString(16),32)})}computeSharedSecret(e){const t=Gn().keyFromPrivate(ur(this.privateKey)),i=Gn().keyFromPublic(ur(Tv(e)));return qn("0x"+t.derive(i.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}}function C_(r,e){const t=Hg(e),i={r:ur(t.r),s:ur(t.s)};return"0x"+Gn().recoverPubKey(ur(r),i,t.recoveryParam).encode("hex",!1)}function Tv(r,e){const t=ur(r);if(t.length===32){const i=new M_(t);return e?"0x"+Gn().keyFromPrivate(t).getPublic(!0,"hex"):i.publicKey}else{if(t.length===33)return e?ni(t):"0x"+Gn().keyFromPublic(t).getPublic(!1,"hex");if(t.length===65)return e?"0x"+Gn().keyFromPublic(t).getPublic(!0,"hex"):ni(t)}return xd.throwArgumentError("invalid public or private key","key","[REDACTED]")}const P_="transactions/5.7.0";new xt(P_);var $v;(function(r){r[r.legacy=0]="legacy",r[r.eip2930=1]="eip2930",r[r.eip1559=2]="eip1559"})($v||($v={}));function D_(r){const e=Tv(r);return q4(zg(nd(zg(e,1)),12))}function O_(r,e){return D_(C_(ur(r),e))}var Ed={},ml={},yt={},Nv={};(function(r){Object.defineProperty(r,"__esModule",{value:!0});function e(f,h){var u=f>>>16&65535,g=f&65535,w=h>>>16&65535,M=h&65535;return g*M+(u*M+g*w<<16>>>0)|0}r.mul=Math.imul||e;function t(f,h){return f+h|0}r.add=t;function i(f,h){return f-h|0}r.sub=i;function n(f,h){return f<>>32-h}r.rotl=n;function s(f,h){return f<<32-h|f>>>h}r.rotr=s;function a(f){return typeof f=="number"&&isFinite(f)&&Math.floor(f)===f}r.isInteger=Number.isInteger||a,r.MAX_SAFE_INTEGER=9007199254740991,r.isSafeInteger=function(f){return r.isInteger(f)&&f>=-r.MAX_SAFE_INTEGER&&f<=r.MAX_SAFE_INTEGER}})(Nv),Object.defineProperty(yt,"__esModule",{value:!0});var Lv=Nv;function R_(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])<<16>>16}yt.readInt16BE=R_;function T_(r,e){return e===void 0&&(e=0),(r[e+0]<<8|r[e+1])>>>0}yt.readUint16BE=T_;function $_(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])<<16>>16}yt.readInt16LE=$_;function N_(r,e){return e===void 0&&(e=0),(r[e+1]<<8|r[e])>>>0}yt.readUint16LE=N_;function Bv(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>8,e[t+1]=r>>>0,e}yt.writeUint16BE=Bv,yt.writeInt16BE=Bv;function Fv(r,e,t){return e===void 0&&(e=new Uint8Array(2)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e}yt.writeUint16LE=Fv,yt.writeInt16LE=Fv;function Sd(r,e){return e===void 0&&(e=0),r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}yt.readInt32BE=Sd;function Id(r,e){return e===void 0&&(e=0),(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}yt.readUint32BE=Id;function Md(r,e){return e===void 0&&(e=0),r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e]}yt.readInt32LE=Md;function Cd(r,e){return e===void 0&&(e=0),(r[e+3]<<24|r[e+2]<<16|r[e+1]<<8|r[e])>>>0}yt.readUint32LE=Cd;function bl(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>24,e[t+1]=r>>>16,e[t+2]=r>>>8,e[t+3]=r>>>0,e}yt.writeUint32BE=bl,yt.writeInt32BE=bl;function wl(r,e,t){return e===void 0&&(e=new Uint8Array(4)),t===void 0&&(t=0),e[t+0]=r>>>0,e[t+1]=r>>>8,e[t+2]=r>>>16,e[t+3]=r>>>24,e}yt.writeUint32LE=wl,yt.writeInt32LE=wl;function L_(r,e){e===void 0&&(e=0);var t=Sd(r,e),i=Sd(r,e+4);return t*4294967296+i-(i>>31)*4294967296}yt.readInt64BE=L_;function B_(r,e){e===void 0&&(e=0);var t=Id(r,e),i=Id(r,e+4);return t*4294967296+i}yt.readUint64BE=B_;function F_(r,e){e===void 0&&(e=0);var t=Md(r,e),i=Md(r,e+4);return i*4294967296+t-(t>>31)*4294967296}yt.readInt64LE=F_;function U_(r,e){e===void 0&&(e=0);var t=Cd(r,e),i=Cd(r,e+4);return i*4294967296+t}yt.readUint64LE=U_;function Uv(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),bl(r/4294967296>>>0,e,t),bl(r>>>0,e,t+4),e}yt.writeUint64BE=Uv,yt.writeInt64BE=Uv;function qv(r,e,t){return e===void 0&&(e=new Uint8Array(8)),t===void 0&&(t=0),wl(r>>>0,e,t),wl(r/4294967296>>>0,e,t+4),e}yt.writeUint64LE=qv,yt.writeInt64LE=qv;function q_(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintBE: array is too short for the given bitLength");for(var i=0,n=1,s=r/8+t-1;s>=t;s--)i+=e[s]*n,n*=256;return i}yt.readUintBE=q_;function z_(r,e,t){if(t===void 0&&(t=0),r%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(r/8>e.length-t)throw new Error("readUintLE: array is too short for the given bitLength");for(var i=0,n=1,s=t;s=i;s--)t[s]=e/n&255,n*=256;return t}yt.writeUintBE=H_;function k_(r,e,t,i){if(t===void 0&&(t=new Uint8Array(r/8)),i===void 0&&(i=0),r%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!Lv.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var n=1,s=i;s>>32-16|d<<16,L=L+d|0,_^=L,_=_>>>32-12|_<<12,B=B+U|0,y^=B,y=y>>>32-16|y<<16,b=b+y|0,U^=b,U=U>>>32-12|U<<12,z=z+ee|0,P^=z,P=P>>>32-16|P<<16,m=m+P|0,ee^=m,ee=ee>>>32-12|ee<<12,W=W+oe|0,D^=W,D=D>>>32-16|D<<16,l=l+D|0,oe^=l,oe=oe>>>32-12|oe<<12,z=z+ee|0,P^=z,P=P>>>32-8|P<<8,m=m+P|0,ee^=m,ee=ee>>>32-7|ee<<7,W=W+oe|0,D^=W,D=D>>>32-8|D<<8,l=l+D|0,oe^=l,oe=oe>>>32-7|oe<<7,B=B+U|0,y^=B,y=y>>>32-8|y<<8,b=b+y|0,U^=b,U=U>>>32-7|U<<7,G=G+_|0,d^=G,d=d>>>32-8|d<<8,L=L+d|0,_^=L,_=_>>>32-7|_<<7,G=G+U|0,D^=G,D=D>>>32-16|D<<16,m=m+D|0,U^=m,U=U>>>32-12|U<<12,B=B+ee|0,d^=B,d=d>>>32-16|d<<16,l=l+d|0,ee^=l,ee=ee>>>32-12|ee<<12,z=z+oe|0,y^=z,y=y>>>32-16|y<<16,L=L+y|0,oe^=L,oe=oe>>>32-12|oe<<12,W=W+_|0,P^=W,P=P>>>32-16|P<<16,b=b+P|0,_^=b,_=_>>>32-12|_<<12,z=z+oe|0,y^=z,y=y>>>32-8|y<<8,L=L+y|0,oe^=L,oe=oe>>>32-7|oe<<7,W=W+_|0,P^=W,P=P>>>32-8|P<<8,b=b+P|0,_^=b,_=_>>>32-7|_<<7,B=B+ee|0,d^=B,d=d>>>32-8|d<<8,l=l+d|0,ee^=l,ee=ee>>>32-7|ee<<7,G=G+U|0,D^=G,D=D>>>32-8|D<<8,m=m+D|0,U^=m,U=U>>>32-7|U<<7;Yr.writeUint32LE(G+i|0,r,0),Yr.writeUint32LE(B+n|0,r,4),Yr.writeUint32LE(z+s|0,r,8),Yr.writeUint32LE(W+a|0,r,12),Yr.writeUint32LE(_+f|0,r,16),Yr.writeUint32LE(U+h|0,r,20),Yr.writeUint32LE(ee+u|0,r,24),Yr.writeUint32LE(oe+g|0,r,28),Yr.writeUint32LE(L+w|0,r,32),Yr.writeUint32LE(b+M|0,r,36),Yr.writeUint32LE(m+C|0,r,40),Yr.writeUint32LE(l+O|0,r,44),Yr.writeUint32LE(d+$|0,r,48),Yr.writeUint32LE(y+j|0,r,52),Yr.writeUint32LE(P+H|0,r,56),Yr.writeUint32LE(D+F|0,r,60)}function zv(r,e,t,i,n){if(n===void 0&&(n=0),r.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(i.length>>=8,e++;if(i>0)throw new Error("ChaCha: counter overflow")}var Hv={},Hs={};Object.defineProperty(Hs,"__esModule",{value:!0});function i7(r,e,t){return~(r-1)&e|r-1&t}Hs.select=i7;function n7(r,e){return(r|0)-(e|0)-1>>>31&1}Hs.lessOrEqual=n7;function kv(r,e){if(r.length!==e.length)return 0;for(var t=0,i=0;i>>8}Hs.compare=kv;function s7(r,e){return r.length===0||e.length===0?!1:kv(r,e)!==0}Hs.equal=s7,function(r){Object.defineProperty(r,"__esModule",{value:!0});var e=Hs,t=$i;r.DIGEST_LENGTH=16;var i=function(){function a(f){this.digestLength=r.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 h=f[0]|f[1]<<8;this._r[0]=h&8191;var u=f[2]|f[3]<<8;this._r[1]=(h>>>13|u<<3)&8191;var g=f[4]|f[5]<<8;this._r[2]=(u>>>10|g<<6)&7939;var w=f[6]|f[7]<<8;this._r[3]=(g>>>7|w<<9)&8191;var M=f[8]|f[9]<<8;this._r[4]=(w>>>4|M<<12)&255,this._r[5]=M>>>1&8190;var C=f[10]|f[11]<<8;this._r[6]=(M>>>14|C<<2)&8191;var O=f[12]|f[13]<<8;this._r[7]=(C>>>11|O<<5)&8065;var $=f[14]|f[15]<<8;this._r[8]=(O>>>8|$<<8)&8191,this._r[9]=$>>>5&127,this._pad[0]=f[16]|f[17]<<8,this._pad[1]=f[18]|f[19]<<8,this._pad[2]=f[20]|f[21]<<8,this._pad[3]=f[22]|f[23]<<8,this._pad[4]=f[24]|f[25]<<8,this._pad[5]=f[26]|f[27]<<8,this._pad[6]=f[28]|f[29]<<8,this._pad[7]=f[30]|f[31]<<8}return a.prototype._blocks=function(f,h,u){for(var g=this._fin?0:2048,w=this._h[0],M=this._h[1],C=this._h[2],O=this._h[3],$=this._h[4],j=this._h[5],H=this._h[6],F=this._h[7],G=this._h[8],B=this._h[9],z=this._r[0],W=this._r[1],_=this._r[2],U=this._r[3],ee=this._r[4],oe=this._r[5],L=this._r[6],b=this._r[7],m=this._r[8],l=this._r[9];u>=16;){var d=f[h+0]|f[h+1]<<8;w+=d&8191;var y=f[h+2]|f[h+3]<<8;M+=(d>>>13|y<<3)&8191;var P=f[h+4]|f[h+5]<<8;C+=(y>>>10|P<<6)&8191;var D=f[h+6]|f[h+7]<<8;O+=(P>>>7|D<<9)&8191;var S=f[h+8]|f[h+9]<<8;$+=(D>>>4|S<<12)&8191,j+=S>>>1&8191;var v=f[h+10]|f[h+11]<<8;H+=(S>>>14|v<<2)&8191;var A=f[h+12]|f[h+13]<<8;F+=(v>>>11|A<<5)&8191;var x=f[h+14]|f[h+15]<<8;G+=(A>>>8|x<<8)&8191,B+=x>>>5|g;var N=0,ae=N;ae+=w*z,ae+=M*(5*l),ae+=C*(5*m),ae+=O*(5*b),ae+=$*(5*L),N=ae>>>13,ae&=8191,ae+=j*(5*oe),ae+=H*(5*ee),ae+=F*(5*U),ae+=G*(5*_),ae+=B*(5*W),N+=ae>>>13,ae&=8191;var R=N;R+=w*W,R+=M*z,R+=C*(5*l),R+=O*(5*m),R+=$*(5*b),N=R>>>13,R&=8191,R+=j*(5*L),R+=H*(5*oe),R+=F*(5*ee),R+=G*(5*U),R+=B*(5*_),N+=R>>>13,R&=8191;var X=N;X+=w*_,X+=M*W,X+=C*z,X+=O*(5*l),X+=$*(5*m),N=X>>>13,X&=8191,X+=j*(5*b),X+=H*(5*L),X+=F*(5*oe),X+=G*(5*ee),X+=B*(5*U),N+=X>>>13,X&=8191;var V=N;V+=w*U,V+=M*_,V+=C*W,V+=O*z,V+=$*(5*l),N=V>>>13,V&=8191,V+=j*(5*m),V+=H*(5*b),V+=F*(5*L),V+=G*(5*oe),V+=B*(5*ee),N+=V>>>13,V&=8191;var J=N;J+=w*ee,J+=M*U,J+=C*_,J+=O*W,J+=$*z,N=J>>>13,J&=8191,J+=j*(5*l),J+=H*(5*m),J+=F*(5*b),J+=G*(5*L),J+=B*(5*oe),N+=J>>>13,J&=8191;var K=N;K+=w*oe,K+=M*ee,K+=C*U,K+=O*_,K+=$*W,N=K>>>13,K&=8191,K+=j*z,K+=H*(5*l),K+=F*(5*m),K+=G*(5*b),K+=B*(5*L),N+=K>>>13,K&=8191;var E=N;E+=w*L,E+=M*oe,E+=C*ee,E+=O*U,E+=$*_,N=E>>>13,E&=8191,E+=j*W,E+=H*z,E+=F*(5*l),E+=G*(5*m),E+=B*(5*b),N+=E>>>13,E&=8191;var Y=N;Y+=w*b,Y+=M*L,Y+=C*oe,Y+=O*ee,Y+=$*U,N=Y>>>13,Y&=8191,Y+=j*_,Y+=H*W,Y+=F*z,Y+=G*(5*l),Y+=B*(5*m),N+=Y>>>13,Y&=8191;var re=N;re+=w*m,re+=M*b,re+=C*L,re+=O*oe,re+=$*ee,N=re>>>13,re&=8191,re+=j*U,re+=H*_,re+=F*W,re+=G*z,re+=B*(5*l),N+=re>>>13,re&=8191;var le=N;le+=w*l,le+=M*m,le+=C*b,le+=O*L,le+=$*oe,N=le>>>13,le&=8191,le+=j*ee,le+=H*U,le+=F*_,le+=G*W,le+=B*z,N+=le>>>13,le&=8191,N=(N<<2)+N|0,N=N+ae|0,ae=N&8191,N=N>>>13,R+=N,w=ae,M=R,C=X,O=V,$=J,j=K,H=E,F=Y,G=re,B=le,h+=16,u-=16}this._h[0]=w,this._h[1]=M,this._h[2]=C,this._h[3]=O,this._h[4]=$,this._h[5]=j,this._h[6]=H,this._h[7]=F,this._h[8]=G,this._h[9]=B},a.prototype.finish=function(f,h){h===void 0&&(h=0);var u=new Uint16Array(10),g,w,M,C;if(this._leftover){for(C=this._leftover,this._buffer[C++]=1;C<16;C++)this._buffer[C]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(g=this._h[1]>>>13,this._h[1]&=8191,C=2;C<10;C++)this._h[C]+=g,g=this._h[C]>>>13,this._h[C]&=8191;for(this._h[0]+=g*5,g=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=g,g=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=g,u[0]=this._h[0]+5,g=u[0]>>>13,u[0]&=8191,C=1;C<10;C++)u[C]=this._h[C]+g,g=u[C]>>>13,u[C]&=8191;for(u[9]-=8192,w=(g^1)-1,C=0;C<10;C++)u[C]&=w;for(w=~w,C=0;C<10;C++)this._h[C]=this._h[C]&w|u[C];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,M=this._h[0]+this._pad[0],this._h[0]=M&65535,C=1;C<8;C++)M=(this._h[C]+this._pad[C]|0)+(M>>>16)|0,this._h[C]=M&65535;return f[h+0]=this._h[0]>>>0,f[h+1]=this._h[0]>>>8,f[h+2]=this._h[1]>>>0,f[h+3]=this._h[1]>>>8,f[h+4]=this._h[2]>>>0,f[h+5]=this._h[2]>>>8,f[h+6]=this._h[3]>>>0,f[h+7]=this._h[3]>>>8,f[h+8]=this._h[4]>>>0,f[h+9]=this._h[4]>>>8,f[h+10]=this._h[5]>>>0,f[h+11]=this._h[5]>>>8,f[h+12]=this._h[6]>>>0,f[h+13]=this._h[6]>>>8,f[h+14]=this._h[7]>>>0,f[h+15]=this._h[7]>>>8,this._finished=!0,this},a.prototype.update=function(f){var h=0,u=f.length,g;if(this._leftover){g=16-this._leftover,g>u&&(g=u);for(var w=0;w=16&&(g=u-u%16,this._blocks(f,h,g),h+=g,u-=g),u){for(var w=0;w16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var C=new Uint8Array(16);C.set(u,C.length-u.length);var O=new Uint8Array(32);e.stream(this._key,C,O,4);var $=g.length+this.tagLength,j;if(M){if(M.length!==$)throw new Error("ChaCha20Poly1305: incorrect destination length");j=M}else j=new Uint8Array($);return e.streamXOR(this._key,C,g,j,4),this._authenticate(j.subarray(j.length-this.tagLength,j.length),O,j.subarray(0,j.length-this.tagLength),w),i.wipe(C),j},h.prototype.open=function(u,g,w,M){if(u.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(g.length0&&C.update(a.subarray(M.length%16))),C.update(w),w.length%16>0&&C.update(a.subarray(w.length%16));var O=new Uint8Array(8);M&&n.writeUint64LE(M.length,O),C.update(O),n.writeUint64LE(w.length,O),C.update(O);for(var $=C.digest(),j=0;j<$.length;j++)u[j]=$[j];C.clean(),i.wipe($),i.wipe(O)},h}();r.ChaCha20Poly1305=f}(Ed);var jv={},qc={},Dd={};Object.defineProperty(Dd,"__esModule",{value:!0});function o7(r){return typeof r.saveState<"u"&&typeof r.restoreState<"u"&&typeof r.cleanSavedState<"u"}Dd.isSerializableHash=o7,Object.defineProperty(qc,"__esModule",{value:!0});var Yn=Dd,a7=Hs,c7=$i,Wv=function(){function r(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var i=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(i).clean():i.set(t);for(var n=0;n1&&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},r.prototype.expand=function(e){for(var t=new Uint8Array(e),i=0;i256)throw new Error("randomString charset is too long");let M="";const C=g.length,O=256-256%C;for(;u>0;){const $=n(Math.ceil(u*256/O),w);for(let j=0;j<$.length&&u>0;j++){const H=$[j];H0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=h[g++],u--;this._bufferLength===this.blockSize&&(s(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(u>=this.blockSize&&(g=s(this._temp,this._state,h,g,u),u%=this.blockSize);u>0;)this._buffer[this._bufferLength++]=h[g++],u--;return this},f.prototype.finish=function(h){if(!this._finished){var u=this._bytesHashed,g=this._bufferLength,w=u/536870912|0,M=u<<3,C=u%64<56?64:128;this._buffer[g]=128;for(var O=g+1;O0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},f.prototype.restoreState=function(h){return this._state.set(h.state),this._bufferLength=h.bufferLength,h.buffer&&this._buffer.set(h.buffer),this._bytesHashed=h.bytesHashed,this._finished=!1,this},f.prototype.cleanSavedState=function(h){t.wipe(h.state),h.buffer&&t.wipe(h.buffer),h.bufferLength=0,h.bytesHashed=0},f}();r.SHA256=i;var n=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 s(f,h,u,g,w){for(;w>=64;){for(var M=h[0],C=h[1],O=h[2],$=h[3],j=h[4],H=h[5],F=h[6],G=h[7],B=0;B<16;B++){var z=g+B*4;f[B]=e.readUint32BE(u,z)}for(var B=16;B<64;B++){var W=f[B-2],_=(W>>>17|W<<32-17)^(W>>>19|W<<32-19)^W>>>10;W=f[B-15];var U=(W>>>7|W<<32-7)^(W>>>18|W<<32-18)^W>>>3;f[B]=(_+f[B-7]|0)+(U+f[B-16]|0)}for(var B=0;B<64;B++){var _=(((j>>>6|j<<26)^(j>>>11|j<<21)^(j>>>25|j<<7))+(j&H^~j&F)|0)+(G+(n[B]+f[B]|0)|0)|0,U=((M>>>2|M<<32-2)^(M>>>13|M<<32-13)^(M>>>22|M<<32-22))+(M&C^M&O^C&O)|0;G=F,F=H,H=j,j=$+_|0,$=O,O=C,C=M,M=_+U|0}h[0]+=M,h[1]+=C,h[2]+=O,h[3]+=$,h[4]+=j,h[5]+=H,h[6]+=F,h[7]+=G,g+=64,w-=64}return g}function a(f){var h=new i;h.update(f);var u=h.digest();return h.clean(),u}r.hash=a})(zc);var Od={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.sharedKey=r.generateKeyPair=r.generateKeyPairFromSeed=r.scalarMultBase=r.scalarMult=r.SHARED_KEY_LENGTH=r.SECRET_KEY_LENGTH=r.PUBLIC_KEY_LENGTH=void 0;const e=ks,t=$i;r.PUBLIC_KEY_LENGTH=32,r.SECRET_KEY_LENGTH=32,r.SHARED_KEY_LENGTH=32;function i(B){const z=new Float64Array(16);if(B)for(let W=0;W>16&1),W[oe-1]&=65535;W[15]=_[15]-32767-(W[14]>>16&1);const ee=W[15]>>16&1;W[14]&=65535,f(_,W,1-ee)}for(let U=0;U<16;U++)B[2*U]=_[U]&255,B[2*U+1]=_[U]>>8}function u(B,z){for(let W=0;W<16;W++)B[W]=z[2*W]+(z[2*W+1]<<8);B[15]&=32767}function g(B,z,W){for(let _=0;_<16;_++)B[_]=z[_]+W[_]}function w(B,z,W){for(let _=0;_<16;_++)B[_]=z[_]-W[_]}function M(B,z,W){let _,U,ee=0,oe=0,L=0,b=0,m=0,l=0,d=0,y=0,P=0,D=0,S=0,v=0,A=0,x=0,N=0,ae=0,R=0,X=0,V=0,J=0,K=0,E=0,Y=0,re=0,le=0,he=0,ge=0,He=0,Te=0,Ce=0,Xe=0,$e=W[0],be=W[1],Pe=W[2],De=W[3],ye=W[4],Ie=W[5],Oe=W[6],me=W[7],Me=W[8],Be=W[9],we=W[10],ke=W[11],We=W[12],Ae=W[13],Ve=W[14],Ke=W[15];_=z[0],ee+=_*$e,oe+=_*be,L+=_*Pe,b+=_*De,m+=_*ye,l+=_*Ie,d+=_*Oe,y+=_*me,P+=_*Me,D+=_*Be,S+=_*we,v+=_*ke,A+=_*We,x+=_*Ae,N+=_*Ve,ae+=_*Ke,_=z[1],oe+=_*$e,L+=_*be,b+=_*Pe,m+=_*De,l+=_*ye,d+=_*Ie,y+=_*Oe,P+=_*me,D+=_*Me,S+=_*Be,v+=_*we,A+=_*ke,x+=_*We,N+=_*Ae,ae+=_*Ve,R+=_*Ke,_=z[2],L+=_*$e,b+=_*be,m+=_*Pe,l+=_*De,d+=_*ye,y+=_*Ie,P+=_*Oe,D+=_*me,S+=_*Me,v+=_*Be,A+=_*we,x+=_*ke,N+=_*We,ae+=_*Ae,R+=_*Ve,X+=_*Ke,_=z[3],b+=_*$e,m+=_*be,l+=_*Pe,d+=_*De,y+=_*ye,P+=_*Ie,D+=_*Oe,S+=_*me,v+=_*Me,A+=_*Be,x+=_*we,N+=_*ke,ae+=_*We,R+=_*Ae,X+=_*Ve,V+=_*Ke,_=z[4],m+=_*$e,l+=_*be,d+=_*Pe,y+=_*De,P+=_*ye,D+=_*Ie,S+=_*Oe,v+=_*me,A+=_*Me,x+=_*Be,N+=_*we,ae+=_*ke,R+=_*We,X+=_*Ae,V+=_*Ve,J+=_*Ke,_=z[5],l+=_*$e,d+=_*be,y+=_*Pe,P+=_*De,D+=_*ye,S+=_*Ie,v+=_*Oe,A+=_*me,x+=_*Me,N+=_*Be,ae+=_*we,R+=_*ke,X+=_*We,V+=_*Ae,J+=_*Ve,K+=_*Ke,_=z[6],d+=_*$e,y+=_*be,P+=_*Pe,D+=_*De,S+=_*ye,v+=_*Ie,A+=_*Oe,x+=_*me,N+=_*Me,ae+=_*Be,R+=_*we,X+=_*ke,V+=_*We,J+=_*Ae,K+=_*Ve,E+=_*Ke,_=z[7],y+=_*$e,P+=_*be,D+=_*Pe,S+=_*De,v+=_*ye,A+=_*Ie,x+=_*Oe,N+=_*me,ae+=_*Me,R+=_*Be,X+=_*we,V+=_*ke,J+=_*We,K+=_*Ae,E+=_*Ve,Y+=_*Ke,_=z[8],P+=_*$e,D+=_*be,S+=_*Pe,v+=_*De,A+=_*ye,x+=_*Ie,N+=_*Oe,ae+=_*me,R+=_*Me,X+=_*Be,V+=_*we,J+=_*ke,K+=_*We,E+=_*Ae,Y+=_*Ve,re+=_*Ke,_=z[9],D+=_*$e,S+=_*be,v+=_*Pe,A+=_*De,x+=_*ye,N+=_*Ie,ae+=_*Oe,R+=_*me,X+=_*Me,V+=_*Be,J+=_*we,K+=_*ke,E+=_*We,Y+=_*Ae,re+=_*Ve,le+=_*Ke,_=z[10],S+=_*$e,v+=_*be,A+=_*Pe,x+=_*De,N+=_*ye,ae+=_*Ie,R+=_*Oe,X+=_*me,V+=_*Me,J+=_*Be,K+=_*we,E+=_*ke,Y+=_*We,re+=_*Ae,le+=_*Ve,he+=_*Ke,_=z[11],v+=_*$e,A+=_*be,x+=_*Pe,N+=_*De,ae+=_*ye,R+=_*Ie,X+=_*Oe,V+=_*me,J+=_*Me,K+=_*Be,E+=_*we,Y+=_*ke,re+=_*We,le+=_*Ae,he+=_*Ve,ge+=_*Ke,_=z[12],A+=_*$e,x+=_*be,N+=_*Pe,ae+=_*De,R+=_*ye,X+=_*Ie,V+=_*Oe,J+=_*me,K+=_*Me,E+=_*Be,Y+=_*we,re+=_*ke,le+=_*We,he+=_*Ae,ge+=_*Ve,He+=_*Ke,_=z[13],x+=_*$e,N+=_*be,ae+=_*Pe,R+=_*De,X+=_*ye,V+=_*Ie,J+=_*Oe,K+=_*me,E+=_*Me,Y+=_*Be,re+=_*we,le+=_*ke,he+=_*We,ge+=_*Ae,He+=_*Ve,Te+=_*Ke,_=z[14],N+=_*$e,ae+=_*be,R+=_*Pe,X+=_*De,V+=_*ye,J+=_*Ie,K+=_*Oe,E+=_*me,Y+=_*Me,re+=_*Be,le+=_*we,he+=_*ke,ge+=_*We,He+=_*Ae,Te+=_*Ve,Ce+=_*Ke,_=z[15],ae+=_*$e,R+=_*be,X+=_*Pe,V+=_*De,J+=_*ye,K+=_*Ie,E+=_*Oe,Y+=_*me,re+=_*Me,le+=_*Be,he+=_*we,ge+=_*ke,He+=_*We,Te+=_*Ae,Ce+=_*Ve,Xe+=_*Ke,ee+=38*R,oe+=38*X,L+=38*V,b+=38*J,m+=38*K,l+=38*E,d+=38*Y,y+=38*re,P+=38*le,D+=38*he,S+=38*ge,v+=38*He,A+=38*Te,x+=38*Ce,N+=38*Xe,U=1,_=ee+U+65535,U=Math.floor(_/65536),ee=_-U*65536,_=oe+U+65535,U=Math.floor(_/65536),oe=_-U*65536,_=L+U+65535,U=Math.floor(_/65536),L=_-U*65536,_=b+U+65535,U=Math.floor(_/65536),b=_-U*65536,_=m+U+65535,U=Math.floor(_/65536),m=_-U*65536,_=l+U+65535,U=Math.floor(_/65536),l=_-U*65536,_=d+U+65535,U=Math.floor(_/65536),d=_-U*65536,_=y+U+65535,U=Math.floor(_/65536),y=_-U*65536,_=P+U+65535,U=Math.floor(_/65536),P=_-U*65536,_=D+U+65535,U=Math.floor(_/65536),D=_-U*65536,_=S+U+65535,U=Math.floor(_/65536),S=_-U*65536,_=v+U+65535,U=Math.floor(_/65536),v=_-U*65536,_=A+U+65535,U=Math.floor(_/65536),A=_-U*65536,_=x+U+65535,U=Math.floor(_/65536),x=_-U*65536,_=N+U+65535,U=Math.floor(_/65536),N=_-U*65536,_=ae+U+65535,U=Math.floor(_/65536),ae=_-U*65536,ee+=U-1+37*(U-1),U=1,_=ee+U+65535,U=Math.floor(_/65536),ee=_-U*65536,_=oe+U+65535,U=Math.floor(_/65536),oe=_-U*65536,_=L+U+65535,U=Math.floor(_/65536),L=_-U*65536,_=b+U+65535,U=Math.floor(_/65536),b=_-U*65536,_=m+U+65535,U=Math.floor(_/65536),m=_-U*65536,_=l+U+65535,U=Math.floor(_/65536),l=_-U*65536,_=d+U+65535,U=Math.floor(_/65536),d=_-U*65536,_=y+U+65535,U=Math.floor(_/65536),y=_-U*65536,_=P+U+65535,U=Math.floor(_/65536),P=_-U*65536,_=D+U+65535,U=Math.floor(_/65536),D=_-U*65536,_=S+U+65535,U=Math.floor(_/65536),S=_-U*65536,_=v+U+65535,U=Math.floor(_/65536),v=_-U*65536,_=A+U+65535,U=Math.floor(_/65536),A=_-U*65536,_=x+U+65535,U=Math.floor(_/65536),x=_-U*65536,_=N+U+65535,U=Math.floor(_/65536),N=_-U*65536,_=ae+U+65535,U=Math.floor(_/65536),ae=_-U*65536,ee+=U-1+37*(U-1),B[0]=ee,B[1]=oe,B[2]=L,B[3]=b,B[4]=m,B[5]=l,B[6]=d,B[7]=y,B[8]=P,B[9]=D,B[10]=S,B[11]=v,B[12]=A,B[13]=x,B[14]=N,B[15]=ae}function C(B,z){M(B,z,z)}function O(B,z){const W=i();for(let _=0;_<16;_++)W[_]=z[_];for(let _=253;_>=0;_--)C(W,W),_!==2&&_!==4&&M(W,W,z);for(let _=0;_<16;_++)B[_]=W[_]}function $(B,z){const W=new Uint8Array(32),_=new Float64Array(80),U=i(),ee=i(),oe=i(),L=i(),b=i(),m=i();for(let P=0;P<31;P++)W[P]=B[P];W[31]=B[31]&127|64,W[0]&=248,u(_,z);for(let P=0;P<16;P++)ee[P]=_[P];U[0]=L[0]=1;for(let P=254;P>=0;--P){const D=W[P>>>3]>>>(P&7)&1;f(U,ee,D),f(oe,L,D),g(b,U,oe),w(U,U,oe),g(oe,ee,L),w(ee,ee,L),C(L,b),C(m,U),M(U,oe,U),M(oe,ee,b),g(b,U,oe),w(U,U,oe),C(ee,U),w(oe,L,m),M(U,oe,s),g(U,U,L),M(oe,oe,U),M(U,L,m),M(L,ee,_),C(ee,b),f(U,ee,D),f(oe,L,D)}for(let P=0;P<16;P++)_[P+16]=U[P],_[P+32]=oe[P],_[P+48]=ee[P],_[P+64]=L[P];const l=_.subarray(32),d=_.subarray(16);O(l,l),M(d,d,l);const y=new Uint8Array(32);return h(y,d),y}r.scalarMult=$;function j(B){return $(B,n)}r.scalarMultBase=j;function H(B){if(B.length!==r.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${r.SECRET_KEY_LENGTH} bytes`);const z=new Uint8Array(B);return{publicKey:j(z),secretKey:z}}r.generateKeyPairFromSeed=H;function F(B){const z=(0,e.randomBytes)(32,B),W=H(z);return(0,t.wipe)(z),W}r.generateKeyPair=F;function G(B,z,W=!1){if(B.length!==r.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(z.length!==r.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");const _=$(B,z);if(W){let U=0;for(let ee=0;ee<_.length;ee++)U|=_[ee];if(U===0)throw new Error("X25519: invalid shared key")}return _}r.sharedKey=G})(Od);function Yv(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function Rd(r,e){e||(e=r.reduce((n,s)=>n+s.length,0));const t=Yv(e);let i=0;for(const n of r)t.set(n,i),i+=n.length;return t}function w7(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i>>0,B=new Uint8Array(G);H!==F;){for(var z=O[H],W=0,_=G-1;(z!==0||W>>0,B[_]=z%f>>>0,z=z/f>>>0;if(z!==0)throw new Error("Non-zero carry");j=W,H++}for(var U=G-j;U!==G&&B[U]===0;)U++;for(var ee=h.repeat($);U>>0,G=new Uint8Array(F);O[$];){var B=t[O.charCodeAt($)];if(B===255)return;for(var z=0,W=F-1;(B!==0||z>>0,G[W]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");H=z,$++}if(O[$]!==" "){for(var _=F-H;_!==F&&G[_]===0;)_++;for(var U=new Uint8Array(j+(F-_)),ee=j;_!==F;)U[ee++]=G[_++];return U}}}function C(O){var $=M(O);if($)return $;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:M,decode:C}}var y7=w7,_7=y7;const Jv=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},x7=r=>new TextEncoder().encode(r),A7=r=>new TextDecoder().decode(r);class E7{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class S7{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return Qv(this,e)}}class I7{constructor(e){this.decoders=e}or(e){return Qv(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Qv=(r,e)=>new I7({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class M7{constructor(e,t,i,n){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=n,this.encoder=new E7(e,t,i),this.decoder=new S7(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Al=({name:r,prefix:e,encode:t,decode:i})=>new M7(r,e,t,i),Hc=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:n}=_7(t,e);return Al({prefix:r,name:e,encode:i,decode:s=>Jv(n(s))})},C7=(r,e,t,i)=>{const n={};for(let g=0;g=8&&(f-=8,a[u++]=255&h>>f)}if(f>=t||255&h<<8-f)throw new SyntaxError("Unexpected end of data");return a},P7=(r,e,t)=>{const i=e[e.length-1]==="=",n=(1<t;)a-=t,s+=e[n&f>>a];if(a&&(s+=e[n&f<Al({prefix:e,name:r,encode(n){return P7(n,i,t)},decode(n){return C7(n,i,t,r)}}),D7=Al({prefix:"\0",name:"identity",encode:r=>A7(r),decode:r=>x7(r)});var O7=Object.freeze({__proto__:null,identity:D7});const R7=jr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var T7=Object.freeze({__proto__:null,base2:R7});const $7=jr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var N7=Object.freeze({__proto__:null,base8:$7});const L7=Hc({prefix:"9",name:"base10",alphabet:"0123456789"});var B7=Object.freeze({__proto__:null,base10:L7});const F7=jr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),U7=jr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var q7=Object.freeze({__proto__:null,base16:F7,base16upper:U7});const z7=jr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),H7=jr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),k7=jr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),j7=jr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),W7=jr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K7=jr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),V7=jr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),G7=jr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Y7=jr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var J7=Object.freeze({__proto__:null,base32:z7,base32upper:H7,base32pad:k7,base32padupper:j7,base32hex:W7,base32hexupper:K7,base32hexpad:V7,base32hexpadupper:G7,base32z:Y7});const Q7=Hc({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Z7=Hc({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var X7=Object.freeze({__proto__:null,base36:Q7,base36upper:Z7});const e9=Hc({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),t9=Hc({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var r9=Object.freeze({__proto__:null,base58btc:e9,base58flickr:t9});const i9=jr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),n9=jr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),s9=jr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),o9=jr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var a9=Object.freeze({__proto__:null,base64:i9,base64pad:n9,base64url:s9,base64urlpad:o9});const Zv=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),c9=Zv.reduce((r,e,t)=>(r[t]=e,r),[]),f9=Zv.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function l9(r){return r.reduce((e,t)=>(e+=c9[t],e),"")}function h9(r){const e=[];for(const t of r){const i=f9[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const u9=Al({prefix:"\u{1F680}",name:"base256emoji",encode:l9,decode:h9});var d9=Object.freeze({__proto__:null,base256emoji:u9}),p9=em,Xv=128,g9=127,v9=~g9,m9=Math.pow(2,31);function em(r,e,t){e=e||[],t=t||0;for(var i=t;r>=m9;)e[t++]=r&255|Xv,r/=128;for(;r&v9;)e[t++]=r&255|Xv,r>>>=7;return e[t]=r|0,em.bytes=t-i+1,e}var b9=Td,w9=128,tm=127;function Td(r,i){var t=0,i=i||0,n=0,s=i,a,f=r.length;do{if(s>=f)throw Td.bytes=0,new RangeError("Could not decode varint");a=r[s++],t+=n<28?(a&tm)<=w9);return Td.bytes=s-i,t}var y9=Math.pow(2,7),_9=Math.pow(2,14),x9=Math.pow(2,21),A9=Math.pow(2,28),E9=Math.pow(2,35),S9=Math.pow(2,42),I9=Math.pow(2,49),M9=Math.pow(2,56),C9=Math.pow(2,63),P9=function(r){return r(rm.encode(r,e,t),e),nm=r=>rm.encodingLength(r),$d=(r,e)=>{const t=e.byteLength,i=nm(r),n=i+nm(t),s=new Uint8Array(n+t);return im(r,s,0),im(t,s,i),s.set(e,n),new O9(r,t,e,s)};class O9{constructor(e,t,i,n){this.code=e,this.size=t,this.digest=i,this.bytes=n}}const sm=({name:r,code:e,encode:t})=>new R9(r,e,t);class R9{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?$d(this.code,t):t.then(i=>$d(this.code,i))}else throw Error("Unknown type, must be binary type")}}const om=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),T9=sm({name:"sha2-256",code:18,encode:om("SHA-256")}),$9=sm({name:"sha2-512",code:19,encode:om("SHA-512")});var N9=Object.freeze({__proto__:null,sha256:T9,sha512:$9});const am=0,L9="identity",cm=Jv;var B9=Object.freeze({__proto__:null,identity:{code:am,name:L9,encode:cm,digest:r=>$d(am,cm(r))}});new TextEncoder,new TextDecoder;const Ra={...O7,...T7,...N7,...B7,...q7,...J7,...X7,...r9,...a9,...d9};({...N9,...B9});function fm(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const lm=fm("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Nd=fm("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=Yv(r.length);for(let t=0;t",V9="MIT",G9={url:"https://github.com/indutny/elliptic/issues"},Y9="https://github.com/indutny/elliptic",J9={brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},Q9={"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"},Z9={name:F9,version:U9,description:q9,main:z9,files:H9,scripts:k9,repository:j9,keywords:W9,author:K9,license:V9,bugs:G9,homepage:Y9,devDependencies:J9,dependencies:Q9},Li={},Jn={exports:{}};(function(r){(function(e,t){function i(L,b){if(!L)throw new Error(b||"Assertion failed")}function n(L,b){L.super_=b;var m=function(){};m.prototype=b.prototype,L.prototype=new m,L.prototype.constructor=L}function s(L,b,m){if(s.isBN(L))return L;this.negative=0,this.words=null,this.length=0,this.red=null,L!==null&&((b==="le"||b==="be")&&(m=b,b=10),this._init(L||0,b||10,m||"be"))}typeof e=="object"?e.exports=s:t.BN=s,s.BN=s,s.wordSize=26;var a;try{typeof window<"u"&&typeof window.Buffer<"u"?a=window.Buffer:a=nl.Buffer}catch{}s.isBN=function(b){return b instanceof s?!0:b!==null&&typeof b=="object"&&b.constructor.wordSize===s.wordSize&&Array.isArray(b.words)},s.max=function(b,m){return b.cmp(m)>0?b:m},s.min=function(b,m){return b.cmp(m)<0?b:m},s.prototype._init=function(b,m,l){if(typeof b=="number")return this._initNumber(b,m,l);if(typeof b=="object")return this._initArray(b,m,l);m==="hex"&&(m=16),i(m===(m|0)&&m>=2&&m<=36),b=b.toString().replace(/\s+/g,"");var d=0;b[0]==="-"&&(d++,this.negative=1),d=0;d-=3)P=b[d]|b[d-1]<<8|b[d-2]<<16,this.words[y]|=P<>>26-D&67108863,D+=24,D>=26&&(D-=26,y++);else if(l==="le")for(d=0,y=0;d>>26-D&67108863,D+=24,D>=26&&(D-=26,y++);return this.strip()};function f(L,b){var m=L.charCodeAt(b);return m>=65&&m<=70?m-55:m>=97&&m<=102?m-87:m-48&15}function h(L,b,m){var l=f(L,m);return m-1>=b&&(l|=f(L,m-1)<<4),l}s.prototype._parseHex=function(b,m,l){this.length=Math.ceil((b.length-m)/6),this.words=new Array(this.length);for(var d=0;d=m;d-=2)D=h(b,m,d)<=18?(y-=18,P+=1,this.words[P]|=D>>>26):y+=8;else{var S=b.length-m;for(d=S%2===0?m+1:m;d=18?(y-=18,P+=1,this.words[P]|=D>>>26):y+=8}this.strip()};function u(L,b,m,l){for(var d=0,y=Math.min(L.length,m),P=b;P=49?d+=D-49+10:D>=17?d+=D-17+10:d+=D}return d}s.prototype._parseBase=function(b,m,l){this.words=[0],this.length=1;for(var d=0,y=1;y<=67108863;y*=m)d++;d--,y=y/m|0;for(var P=b.length-l,D=P%d,S=Math.min(P,P-D)+l,v=0,A=l;A1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},s.prototype.inspect=function(){return(this.red?""};var g=["","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"],w=[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],M=[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];s.prototype.toString=function(b,m){b=b||10,m=m|0||1;var l;if(b===16||b==="hex"){l="";for(var d=0,y=0,P=0;P>>24-d&16777215,d+=2,d>=26&&(d-=26,P--),y!==0||P!==this.length-1?l=g[6-S.length]+S+l:l=S+l}for(y!==0&&(l=y.toString(16)+l);l.length%m!==0;)l="0"+l;return this.negative!==0&&(l="-"+l),l}if(b===(b|0)&&b>=2&&b<=36){var v=w[b],A=M[b];l="";var x=this.clone();for(x.negative=0;!x.isZero();){var N=x.modn(A).toString(b);x=x.idivn(A),x.isZero()?l=N+l:l=g[v-N.length]+N+l}for(this.isZero()&&(l="0"+l);l.length%m!==0;)l="0"+l;return this.negative!==0&&(l="-"+l),l}i(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var b=this.words[0];return this.length===2?b+=this.words[1]*67108864:this.length===3&&this.words[2]===1?b+=4503599627370496+this.words[1]*67108864:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-b:b},s.prototype.toJSON=function(){return this.toString(16)},s.prototype.toBuffer=function(b,m){return i(typeof a<"u"),this.toArrayLike(a,b,m)},s.prototype.toArray=function(b,m){return this.toArrayLike(Array,b,m)},s.prototype.toArrayLike=function(b,m,l){var d=this.byteLength(),y=l||Math.max(1,d);i(d<=y,"byte array longer than desired length"),i(y>0,"Requested array length <= 0"),this.strip();var P=m==="le",D=new b(y),S,v,A=this.clone();if(P){for(v=0;!A.isZero();v++)S=A.andln(255),A.iushrn(8),D[v]=S;for(;v=4096&&(l+=13,m>>>=13),m>=64&&(l+=7,m>>>=7),m>=8&&(l+=4,m>>>=4),m>=2&&(l+=2,m>>>=2),l+m},s.prototype._zeroBits=function(b){if(b===0)return 26;var m=b,l=0;return m&8191||(l+=13,m>>>=13),m&127||(l+=7,m>>>=7),m&15||(l+=4,m>>>=4),m&3||(l+=2,m>>>=2),m&1||l++,l},s.prototype.bitLength=function(){var b=this.words[this.length-1],m=this._countBits(b);return(this.length-1)*26+m};function C(L){for(var b=new Array(L.bitLength()),m=0;m>>d}return b}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var b=0,m=0;mb.length?this.clone().ior(b):b.clone().ior(this)},s.prototype.uor=function(b){return this.length>b.length?this.clone().iuor(b):b.clone().iuor(this)},s.prototype.iuand=function(b){var m;this.length>b.length?m=b:m=this;for(var l=0;lb.length?this.clone().iand(b):b.clone().iand(this)},s.prototype.uand=function(b){return this.length>b.length?this.clone().iuand(b):b.clone().iuand(this)},s.prototype.iuxor=function(b){var m,l;this.length>b.length?(m=this,l=b):(m=b,l=this);for(var d=0;db.length?this.clone().ixor(b):b.clone().ixor(this)},s.prototype.uxor=function(b){return this.length>b.length?this.clone().iuxor(b):b.clone().iuxor(this)},s.prototype.inotn=function(b){i(typeof b=="number"&&b>=0);var m=Math.ceil(b/26)|0,l=b%26;this._expand(m),l>0&&m--;for(var d=0;d0&&(this.words[d]=~this.words[d]&67108863>>26-l),this.strip()},s.prototype.notn=function(b){return this.clone().inotn(b)},s.prototype.setn=function(b,m){i(typeof b=="number"&&b>=0);var l=b/26|0,d=b%26;return this._expand(l+1),m?this.words[l]=this.words[l]|1<b.length?(l=this,d=b):(l=b,d=this);for(var y=0,P=0;P>>26;for(;y!==0&&P>>26;if(this.length=l.length,y!==0)this.words[this.length]=y,this.length++;else if(l!==this)for(;Pb.length?this.clone().iadd(b):b.clone().iadd(this)},s.prototype.isub=function(b){if(b.negative!==0){b.negative=0;var m=this.iadd(b);return b.negative=1,m._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(b),this.negative=1,this._normSign();var l=this.cmp(b);if(l===0)return this.negative=0,this.length=1,this.words[0]=0,this;var d,y;l>0?(d=this,y=b):(d=b,y=this);for(var P=0,D=0;D>26,this.words[D]=m&67108863;for(;P!==0&&D>26,this.words[D]=m&67108863;if(P===0&&D>>26,x=S&67108863,N=Math.min(v,b.length-1),ae=Math.max(0,v-L.length+1);ae<=N;ae++){var R=v-ae|0;d=L.words[R]|0,y=b.words[ae]|0,P=d*y+x,A+=P/67108864|0,x=P&67108863}m.words[v]=x|0,S=A|0}return S!==0?m.words[v]=S|0:m.length--,m.strip()}var $=function(b,m,l){var d=b.words,y=m.words,P=l.words,D=0,S,v,A,x=d[0]|0,N=x&8191,ae=x>>>13,R=d[1]|0,X=R&8191,V=R>>>13,J=d[2]|0,K=J&8191,E=J>>>13,Y=d[3]|0,re=Y&8191,le=Y>>>13,he=d[4]|0,ge=he&8191,He=he>>>13,Te=d[5]|0,Ce=Te&8191,Xe=Te>>>13,$e=d[6]|0,be=$e&8191,Pe=$e>>>13,De=d[7]|0,ye=De&8191,Ie=De>>>13,Oe=d[8]|0,me=Oe&8191,Me=Oe>>>13,Be=d[9]|0,we=Be&8191,ke=Be>>>13,We=y[0]|0,Ae=We&8191,Ve=We>>>13,Ke=y[1]|0,Ge=Ke&8191,mt=Ke>>>13,It=y[2]|0,Ye=It&8191,Pt=It>>>13,Ot=y[3]|0,Ze=Ot&8191,rt=Ot>>>13,et=y[4]|0,Ne=et&8191,it=et>>>13,tt=y[5]|0,Re=tt&8191,lt=tt>>>13,ht=y[6]|0,Le=ht&8191,ut=ht>>>13,nt=y[7]|0,Fe=nt&8191,st=nt>>>13,Qe=y[8]|0,qe=Qe&8191,dt=Qe>>>13,Ht=y[9]|0,at=Ht&8191,kt=Ht>>>13;l.negative=b.negative^m.negative,l.length=19,S=Math.imul(N,Ae),v=Math.imul(N,Ve),v=v+Math.imul(ae,Ae)|0,A=Math.imul(ae,Ve);var _t=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(_t>>>26)|0,_t&=67108863,S=Math.imul(X,Ae),v=Math.imul(X,Ve),v=v+Math.imul(V,Ae)|0,A=Math.imul(V,Ve),S=S+Math.imul(N,Ge)|0,v=v+Math.imul(N,mt)|0,v=v+Math.imul(ae,Ge)|0,A=A+Math.imul(ae,mt)|0;var qt=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(qt>>>26)|0,qt&=67108863,S=Math.imul(K,Ae),v=Math.imul(K,Ve),v=v+Math.imul(E,Ae)|0,A=Math.imul(E,Ve),S=S+Math.imul(X,Ge)|0,v=v+Math.imul(X,mt)|0,v=v+Math.imul(V,Ge)|0,A=A+Math.imul(V,mt)|0,S=S+Math.imul(N,Ye)|0,v=v+Math.imul(N,Pt)|0,v=v+Math.imul(ae,Ye)|0,A=A+Math.imul(ae,Pt)|0;var Zr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,S=Math.imul(re,Ae),v=Math.imul(re,Ve),v=v+Math.imul(le,Ae)|0,A=Math.imul(le,Ve),S=S+Math.imul(K,Ge)|0,v=v+Math.imul(K,mt)|0,v=v+Math.imul(E,Ge)|0,A=A+Math.imul(E,mt)|0,S=S+Math.imul(X,Ye)|0,v=v+Math.imul(X,Pt)|0,v=v+Math.imul(V,Ye)|0,A=A+Math.imul(V,Pt)|0,S=S+Math.imul(N,Ze)|0,v=v+Math.imul(N,rt)|0,v=v+Math.imul(ae,Ze)|0,A=A+Math.imul(ae,rt)|0;var Xr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,S=Math.imul(ge,Ae),v=Math.imul(ge,Ve),v=v+Math.imul(He,Ae)|0,A=Math.imul(He,Ve),S=S+Math.imul(re,Ge)|0,v=v+Math.imul(re,mt)|0,v=v+Math.imul(le,Ge)|0,A=A+Math.imul(le,mt)|0,S=S+Math.imul(K,Ye)|0,v=v+Math.imul(K,Pt)|0,v=v+Math.imul(E,Ye)|0,A=A+Math.imul(E,Pt)|0,S=S+Math.imul(X,Ze)|0,v=v+Math.imul(X,rt)|0,v=v+Math.imul(V,Ze)|0,A=A+Math.imul(V,rt)|0,S=S+Math.imul(N,Ne)|0,v=v+Math.imul(N,it)|0,v=v+Math.imul(ae,Ne)|0,A=A+Math.imul(ae,it)|0;var ei=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(ei>>>26)|0,ei&=67108863,S=Math.imul(Ce,Ae),v=Math.imul(Ce,Ve),v=v+Math.imul(Xe,Ae)|0,A=Math.imul(Xe,Ve),S=S+Math.imul(ge,Ge)|0,v=v+Math.imul(ge,mt)|0,v=v+Math.imul(He,Ge)|0,A=A+Math.imul(He,mt)|0,S=S+Math.imul(re,Ye)|0,v=v+Math.imul(re,Pt)|0,v=v+Math.imul(le,Ye)|0,A=A+Math.imul(le,Pt)|0,S=S+Math.imul(K,Ze)|0,v=v+Math.imul(K,rt)|0,v=v+Math.imul(E,Ze)|0,A=A+Math.imul(E,rt)|0,S=S+Math.imul(X,Ne)|0,v=v+Math.imul(X,it)|0,v=v+Math.imul(V,Ne)|0,A=A+Math.imul(V,it)|0,S=S+Math.imul(N,Re)|0,v=v+Math.imul(N,lt)|0,v=v+Math.imul(ae,Re)|0,A=A+Math.imul(ae,lt)|0;var ti=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(ti>>>26)|0,ti&=67108863,S=Math.imul(be,Ae),v=Math.imul(be,Ve),v=v+Math.imul(Pe,Ae)|0,A=Math.imul(Pe,Ve),S=S+Math.imul(Ce,Ge)|0,v=v+Math.imul(Ce,mt)|0,v=v+Math.imul(Xe,Ge)|0,A=A+Math.imul(Xe,mt)|0,S=S+Math.imul(ge,Ye)|0,v=v+Math.imul(ge,Pt)|0,v=v+Math.imul(He,Ye)|0,A=A+Math.imul(He,Pt)|0,S=S+Math.imul(re,Ze)|0,v=v+Math.imul(re,rt)|0,v=v+Math.imul(le,Ze)|0,A=A+Math.imul(le,rt)|0,S=S+Math.imul(K,Ne)|0,v=v+Math.imul(K,it)|0,v=v+Math.imul(E,Ne)|0,A=A+Math.imul(E,it)|0,S=S+Math.imul(X,Re)|0,v=v+Math.imul(X,lt)|0,v=v+Math.imul(V,Re)|0,A=A+Math.imul(V,lt)|0,S=S+Math.imul(N,Le)|0,v=v+Math.imul(N,ut)|0,v=v+Math.imul(ae,Le)|0,A=A+Math.imul(ae,ut)|0;var vr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(vr>>>26)|0,vr&=67108863,S=Math.imul(ye,Ae),v=Math.imul(ye,Ve),v=v+Math.imul(Ie,Ae)|0,A=Math.imul(Ie,Ve),S=S+Math.imul(be,Ge)|0,v=v+Math.imul(be,mt)|0,v=v+Math.imul(Pe,Ge)|0,A=A+Math.imul(Pe,mt)|0,S=S+Math.imul(Ce,Ye)|0,v=v+Math.imul(Ce,Pt)|0,v=v+Math.imul(Xe,Ye)|0,A=A+Math.imul(Xe,Pt)|0,S=S+Math.imul(ge,Ze)|0,v=v+Math.imul(ge,rt)|0,v=v+Math.imul(He,Ze)|0,A=A+Math.imul(He,rt)|0,S=S+Math.imul(re,Ne)|0,v=v+Math.imul(re,it)|0,v=v+Math.imul(le,Ne)|0,A=A+Math.imul(le,it)|0,S=S+Math.imul(K,Re)|0,v=v+Math.imul(K,lt)|0,v=v+Math.imul(E,Re)|0,A=A+Math.imul(E,lt)|0,S=S+Math.imul(X,Le)|0,v=v+Math.imul(X,ut)|0,v=v+Math.imul(V,Le)|0,A=A+Math.imul(V,ut)|0,S=S+Math.imul(N,Fe)|0,v=v+Math.imul(N,st)|0,v=v+Math.imul(ae,Fe)|0,A=A+Math.imul(ae,st)|0;var Ai=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Ai>>>26)|0,Ai&=67108863,S=Math.imul(me,Ae),v=Math.imul(me,Ve),v=v+Math.imul(Me,Ae)|0,A=Math.imul(Me,Ve),S=S+Math.imul(ye,Ge)|0,v=v+Math.imul(ye,mt)|0,v=v+Math.imul(Ie,Ge)|0,A=A+Math.imul(Ie,mt)|0,S=S+Math.imul(be,Ye)|0,v=v+Math.imul(be,Pt)|0,v=v+Math.imul(Pe,Ye)|0,A=A+Math.imul(Pe,Pt)|0,S=S+Math.imul(Ce,Ze)|0,v=v+Math.imul(Ce,rt)|0,v=v+Math.imul(Xe,Ze)|0,A=A+Math.imul(Xe,rt)|0,S=S+Math.imul(ge,Ne)|0,v=v+Math.imul(ge,it)|0,v=v+Math.imul(He,Ne)|0,A=A+Math.imul(He,it)|0,S=S+Math.imul(re,Re)|0,v=v+Math.imul(re,lt)|0,v=v+Math.imul(le,Re)|0,A=A+Math.imul(le,lt)|0,S=S+Math.imul(K,Le)|0,v=v+Math.imul(K,ut)|0,v=v+Math.imul(E,Le)|0,A=A+Math.imul(E,ut)|0,S=S+Math.imul(X,Fe)|0,v=v+Math.imul(X,st)|0,v=v+Math.imul(V,Fe)|0,A=A+Math.imul(V,st)|0,S=S+Math.imul(N,qe)|0,v=v+Math.imul(N,dt)|0,v=v+Math.imul(ae,qe)|0,A=A+Math.imul(ae,dt)|0;var Pn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Pn>>>26)|0,Pn&=67108863,S=Math.imul(we,Ae),v=Math.imul(we,Ve),v=v+Math.imul(ke,Ae)|0,A=Math.imul(ke,Ve),S=S+Math.imul(me,Ge)|0,v=v+Math.imul(me,mt)|0,v=v+Math.imul(Me,Ge)|0,A=A+Math.imul(Me,mt)|0,S=S+Math.imul(ye,Ye)|0,v=v+Math.imul(ye,Pt)|0,v=v+Math.imul(Ie,Ye)|0,A=A+Math.imul(Ie,Pt)|0,S=S+Math.imul(be,Ze)|0,v=v+Math.imul(be,rt)|0,v=v+Math.imul(Pe,Ze)|0,A=A+Math.imul(Pe,rt)|0,S=S+Math.imul(Ce,Ne)|0,v=v+Math.imul(Ce,it)|0,v=v+Math.imul(Xe,Ne)|0,A=A+Math.imul(Xe,it)|0,S=S+Math.imul(ge,Re)|0,v=v+Math.imul(ge,lt)|0,v=v+Math.imul(He,Re)|0,A=A+Math.imul(He,lt)|0,S=S+Math.imul(re,Le)|0,v=v+Math.imul(re,ut)|0,v=v+Math.imul(le,Le)|0,A=A+Math.imul(le,ut)|0,S=S+Math.imul(K,Fe)|0,v=v+Math.imul(K,st)|0,v=v+Math.imul(E,Fe)|0,A=A+Math.imul(E,st)|0,S=S+Math.imul(X,qe)|0,v=v+Math.imul(X,dt)|0,v=v+Math.imul(V,qe)|0,A=A+Math.imul(V,dt)|0,S=S+Math.imul(N,at)|0,v=v+Math.imul(N,kt)|0,v=v+Math.imul(ae,at)|0,A=A+Math.imul(ae,kt)|0;var Ei=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Ei>>>26)|0,Ei&=67108863,S=Math.imul(we,Ge),v=Math.imul(we,mt),v=v+Math.imul(ke,Ge)|0,A=Math.imul(ke,mt),S=S+Math.imul(me,Ye)|0,v=v+Math.imul(me,Pt)|0,v=v+Math.imul(Me,Ye)|0,A=A+Math.imul(Me,Pt)|0,S=S+Math.imul(ye,Ze)|0,v=v+Math.imul(ye,rt)|0,v=v+Math.imul(Ie,Ze)|0,A=A+Math.imul(Ie,rt)|0,S=S+Math.imul(be,Ne)|0,v=v+Math.imul(be,it)|0,v=v+Math.imul(Pe,Ne)|0,A=A+Math.imul(Pe,it)|0,S=S+Math.imul(Ce,Re)|0,v=v+Math.imul(Ce,lt)|0,v=v+Math.imul(Xe,Re)|0,A=A+Math.imul(Xe,lt)|0,S=S+Math.imul(ge,Le)|0,v=v+Math.imul(ge,ut)|0,v=v+Math.imul(He,Le)|0,A=A+Math.imul(He,ut)|0,S=S+Math.imul(re,Fe)|0,v=v+Math.imul(re,st)|0,v=v+Math.imul(le,Fe)|0,A=A+Math.imul(le,st)|0,S=S+Math.imul(K,qe)|0,v=v+Math.imul(K,dt)|0,v=v+Math.imul(E,qe)|0,A=A+Math.imul(E,dt)|0,S=S+Math.imul(X,at)|0,v=v+Math.imul(X,kt)|0,v=v+Math.imul(V,at)|0,A=A+Math.imul(V,kt)|0;var Dn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Dn>>>26)|0,Dn&=67108863,S=Math.imul(we,Ye),v=Math.imul(we,Pt),v=v+Math.imul(ke,Ye)|0,A=Math.imul(ke,Pt),S=S+Math.imul(me,Ze)|0,v=v+Math.imul(me,rt)|0,v=v+Math.imul(Me,Ze)|0,A=A+Math.imul(Me,rt)|0,S=S+Math.imul(ye,Ne)|0,v=v+Math.imul(ye,it)|0,v=v+Math.imul(Ie,Ne)|0,A=A+Math.imul(Ie,it)|0,S=S+Math.imul(be,Re)|0,v=v+Math.imul(be,lt)|0,v=v+Math.imul(Pe,Re)|0,A=A+Math.imul(Pe,lt)|0,S=S+Math.imul(Ce,Le)|0,v=v+Math.imul(Ce,ut)|0,v=v+Math.imul(Xe,Le)|0,A=A+Math.imul(Xe,ut)|0,S=S+Math.imul(ge,Fe)|0,v=v+Math.imul(ge,st)|0,v=v+Math.imul(He,Fe)|0,A=A+Math.imul(He,st)|0,S=S+Math.imul(re,qe)|0,v=v+Math.imul(re,dt)|0,v=v+Math.imul(le,qe)|0,A=A+Math.imul(le,dt)|0,S=S+Math.imul(K,at)|0,v=v+Math.imul(K,kt)|0,v=v+Math.imul(E,at)|0,A=A+Math.imul(E,kt)|0;var On=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(On>>>26)|0,On&=67108863,S=Math.imul(we,Ze),v=Math.imul(we,rt),v=v+Math.imul(ke,Ze)|0,A=Math.imul(ke,rt),S=S+Math.imul(me,Ne)|0,v=v+Math.imul(me,it)|0,v=v+Math.imul(Me,Ne)|0,A=A+Math.imul(Me,it)|0,S=S+Math.imul(ye,Re)|0,v=v+Math.imul(ye,lt)|0,v=v+Math.imul(Ie,Re)|0,A=A+Math.imul(Ie,lt)|0,S=S+Math.imul(be,Le)|0,v=v+Math.imul(be,ut)|0,v=v+Math.imul(Pe,Le)|0,A=A+Math.imul(Pe,ut)|0,S=S+Math.imul(Ce,Fe)|0,v=v+Math.imul(Ce,st)|0,v=v+Math.imul(Xe,Fe)|0,A=A+Math.imul(Xe,st)|0,S=S+Math.imul(ge,qe)|0,v=v+Math.imul(ge,dt)|0,v=v+Math.imul(He,qe)|0,A=A+Math.imul(He,dt)|0,S=S+Math.imul(re,at)|0,v=v+Math.imul(re,kt)|0,v=v+Math.imul(le,at)|0,A=A+Math.imul(le,kt)|0;var Si=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Si>>>26)|0,Si&=67108863,S=Math.imul(we,Ne),v=Math.imul(we,it),v=v+Math.imul(ke,Ne)|0,A=Math.imul(ke,it),S=S+Math.imul(me,Re)|0,v=v+Math.imul(me,lt)|0,v=v+Math.imul(Me,Re)|0,A=A+Math.imul(Me,lt)|0,S=S+Math.imul(ye,Le)|0,v=v+Math.imul(ye,ut)|0,v=v+Math.imul(Ie,Le)|0,A=A+Math.imul(Ie,ut)|0,S=S+Math.imul(be,Fe)|0,v=v+Math.imul(be,st)|0,v=v+Math.imul(Pe,Fe)|0,A=A+Math.imul(Pe,st)|0,S=S+Math.imul(Ce,qe)|0,v=v+Math.imul(Ce,dt)|0,v=v+Math.imul(Xe,qe)|0,A=A+Math.imul(Xe,dt)|0,S=S+Math.imul(ge,at)|0,v=v+Math.imul(ge,kt)|0,v=v+Math.imul(He,at)|0,A=A+Math.imul(He,kt)|0;var fn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(fn>>>26)|0,fn&=67108863,S=Math.imul(we,Re),v=Math.imul(we,lt),v=v+Math.imul(ke,Re)|0,A=Math.imul(ke,lt),S=S+Math.imul(me,Le)|0,v=v+Math.imul(me,ut)|0,v=v+Math.imul(Me,Le)|0,A=A+Math.imul(Me,ut)|0,S=S+Math.imul(ye,Fe)|0,v=v+Math.imul(ye,st)|0,v=v+Math.imul(Ie,Fe)|0,A=A+Math.imul(Ie,st)|0,S=S+Math.imul(be,qe)|0,v=v+Math.imul(be,dt)|0,v=v+Math.imul(Pe,qe)|0,A=A+Math.imul(Pe,dt)|0,S=S+Math.imul(Ce,at)|0,v=v+Math.imul(Ce,kt)|0,v=v+Math.imul(Xe,at)|0,A=A+Math.imul(Xe,kt)|0;var ln=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(ln>>>26)|0,ln&=67108863,S=Math.imul(we,Le),v=Math.imul(we,ut),v=v+Math.imul(ke,Le)|0,A=Math.imul(ke,ut),S=S+Math.imul(me,Fe)|0,v=v+Math.imul(me,st)|0,v=v+Math.imul(Me,Fe)|0,A=A+Math.imul(Me,st)|0,S=S+Math.imul(ye,qe)|0,v=v+Math.imul(ye,dt)|0,v=v+Math.imul(Ie,qe)|0,A=A+Math.imul(Ie,dt)|0,S=S+Math.imul(be,at)|0,v=v+Math.imul(be,kt)|0,v=v+Math.imul(Pe,at)|0,A=A+Math.imul(Pe,kt)|0;var Cr=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,S=Math.imul(we,Fe),v=Math.imul(we,st),v=v+Math.imul(ke,Fe)|0,A=Math.imul(ke,st),S=S+Math.imul(me,qe)|0,v=v+Math.imul(me,dt)|0,v=v+Math.imul(Me,qe)|0,A=A+Math.imul(Me,dt)|0,S=S+Math.imul(ye,at)|0,v=v+Math.imul(ye,kt)|0,v=v+Math.imul(Ie,at)|0,A=A+Math.imul(Ie,kt)|0;var Rn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Rn>>>26)|0,Rn&=67108863,S=Math.imul(we,qe),v=Math.imul(we,dt),v=v+Math.imul(ke,qe)|0,A=Math.imul(ke,dt),S=S+Math.imul(me,at)|0,v=v+Math.imul(me,kt)|0,v=v+Math.imul(Me,at)|0,A=A+Math.imul(Me,kt)|0;var Tn=(D+S|0)+((v&8191)<<13)|0;D=(A+(v>>>13)|0)+(Tn>>>26)|0,Tn&=67108863,S=Math.imul(we,at),v=Math.imul(we,kt),v=v+Math.imul(ke,at)|0,A=Math.imul(ke,kt);var $n=(D+S|0)+((v&8191)<<13)|0;return D=(A+(v>>>13)|0)+($n>>>26)|0,$n&=67108863,P[0]=_t,P[1]=qt,P[2]=Zr,P[3]=Xr,P[4]=ei,P[5]=ti,P[6]=vr,P[7]=Ai,P[8]=Pn,P[9]=Ei,P[10]=Dn,P[11]=On,P[12]=Si,P[13]=fn,P[14]=ln,P[15]=Cr,P[16]=Rn,P[17]=Tn,P[18]=$n,D!==0&&(P[19]=D,l.length++),l};Math.imul||($=O);function j(L,b,m){m.negative=b.negative^L.negative,m.length=L.length+b.length;for(var l=0,d=0,y=0;y>>26)|0,d+=P>>>26,P&=67108863}m.words[y]=D,l=P,P=d}return l!==0?m.words[y]=l:m.length--,m.strip()}function H(L,b,m){var l=new F;return l.mulp(L,b,m)}s.prototype.mulTo=function(b,m){var l,d=this.length+b.length;return this.length===10&&b.length===10?l=$(this,b,m):d<63?l=O(this,b,m):d<1024?l=j(this,b,m):l=H(this,b,m),l};function F(L,b){this.x=L,this.y=b}F.prototype.makeRBT=function(b){for(var m=new Array(b),l=s.prototype._countBits(b)-1,d=0;d>=1;return d},F.prototype.permute=function(b,m,l,d,y,P){for(var D=0;D>>1)y++;return 1<>>13,l[2*P+1]=y&8191,y=y>>>13;for(P=2*m;P>=26,m+=d/67108864|0,m+=y>>>26,this.words[l]=y&67108863}return m!==0&&(this.words[l]=m,this.length++),this},s.prototype.muln=function(b){return this.clone().imuln(b)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(b){var m=C(b);if(m.length===0)return new s(1);for(var l=this,d=0;d=0);var m=b%26,l=(b-m)/26,d=67108863>>>26-m<<26-m,y;if(m!==0){var P=0;for(y=0;y>>26-m}P&&(this.words[y]=P,this.length++)}if(l!==0){for(y=this.length-1;y>=0;y--)this.words[y+l]=this.words[y];for(y=0;y=0);var d;m?d=(m-m%26)/26:d=0;var y=b%26,P=Math.min((b-y)/26,this.length),D=67108863^67108863>>>y<P)for(this.length-=P,v=0;v=0&&(A!==0||v>=d);v--){var x=this.words[v]|0;this.words[v]=A<<26-y|x>>>y,A=x&D}return S&&A!==0&&(S.words[S.length++]=A),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},s.prototype.ishrn=function(b,m,l){return i(this.negative===0),this.iushrn(b,m,l)},s.prototype.shln=function(b){return this.clone().ishln(b)},s.prototype.ushln=function(b){return this.clone().iushln(b)},s.prototype.shrn=function(b){return this.clone().ishrn(b)},s.prototype.ushrn=function(b){return this.clone().iushrn(b)},s.prototype.testn=function(b){i(typeof b=="number"&&b>=0);var m=b%26,l=(b-m)/26,d=1<=0);var m=b%26,l=(b-m)/26;if(i(this.negative===0,"imaskn works only with positive numbers"),this.length<=l)return this;if(m!==0&&l++,this.length=Math.min(l,this.length),m!==0){var d=67108863^67108863>>>m<=67108864;m++)this.words[m]-=67108864,m===this.length-1?this.words[m+1]=1:this.words[m+1]++;return this.length=Math.max(this.length,m+1),this},s.prototype.isubn=function(b){if(i(typeof b=="number"),i(b<67108864),b<0)return this.iaddn(-b);if(this.negative!==0)return this.negative=0,this.iaddn(b),this.negative=1,this;if(this.words[0]-=b,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var m=0;m>26)-(S/67108864|0),this.words[y+l]=P&67108863}for(;y>26,this.words[y+l]=P&67108863;if(D===0)return this.strip();for(i(D===-1),D=0,y=0;y>26,this.words[y]=P&67108863;return this.negative=1,this.strip()},s.prototype._wordDiv=function(b,m){var l=this.length-b.length,d=this.clone(),y=b,P=y.words[y.length-1]|0,D=this._countBits(P);l=26-D,l!==0&&(y=y.ushln(l),d.iushln(l),P=y.words[y.length-1]|0);var S=d.length-y.length,v;if(m!=="mod"){v=new s(null),v.length=S+1,v.words=new Array(v.length);for(var A=0;A=0;N--){var ae=(d.words[y.length+N]|0)*67108864+(d.words[y.length+N-1]|0);for(ae=Math.min(ae/P|0,67108863),d._ishlnsubmul(y,ae,N);d.negative!==0;)ae--,d.negative=0,d._ishlnsubmul(y,1,N),d.isZero()||(d.negative^=1);v&&(v.words[N]=ae)}return v&&v.strip(),d.strip(),m!=="div"&&l!==0&&d.iushrn(l),{div:v||null,mod:d}},s.prototype.divmod=function(b,m,l){if(i(!b.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var d,y,P;return this.negative!==0&&b.negative===0?(P=this.neg().divmod(b,m),m!=="mod"&&(d=P.div.neg()),m!=="div"&&(y=P.mod.neg(),l&&y.negative!==0&&y.iadd(b)),{div:d,mod:y}):this.negative===0&&b.negative!==0?(P=this.divmod(b.neg(),m),m!=="mod"&&(d=P.div.neg()),{div:d,mod:P.mod}):this.negative&b.negative?(P=this.neg().divmod(b.neg(),m),m!=="div"&&(y=P.mod.neg(),l&&y.negative!==0&&y.isub(b)),{div:P.div,mod:y}):b.length>this.length||this.cmp(b)<0?{div:new s(0),mod:this}:b.length===1?m==="div"?{div:this.divn(b.words[0]),mod:null}:m==="mod"?{div:null,mod:new s(this.modn(b.words[0]))}:{div:this.divn(b.words[0]),mod:new s(this.modn(b.words[0]))}:this._wordDiv(b,m)},s.prototype.div=function(b){return this.divmod(b,"div",!1).div},s.prototype.mod=function(b){return this.divmod(b,"mod",!1).mod},s.prototype.umod=function(b){return this.divmod(b,"mod",!0).mod},s.prototype.divRound=function(b){var m=this.divmod(b);if(m.mod.isZero())return m.div;var l=m.div.negative!==0?m.mod.isub(b):m.mod,d=b.ushrn(1),y=b.andln(1),P=l.cmp(d);return P<0||y===1&&P===0?m.div:m.div.negative!==0?m.div.isubn(1):m.div.iaddn(1)},s.prototype.modn=function(b){i(b<=67108863);for(var m=(1<<26)%b,l=0,d=this.length-1;d>=0;d--)l=(m*l+(this.words[d]|0))%b;return l},s.prototype.idivn=function(b){i(b<=67108863);for(var m=0,l=this.length-1;l>=0;l--){var d=(this.words[l]|0)+m*67108864;this.words[l]=d/b|0,m=d%b}return this.strip()},s.prototype.divn=function(b){return this.clone().idivn(b)},s.prototype.egcd=function(b){i(b.negative===0),i(!b.isZero());var m=this,l=b.clone();m.negative!==0?m=m.umod(b):m=m.clone();for(var d=new s(1),y=new s(0),P=new s(0),D=new s(1),S=0;m.isEven()&&l.isEven();)m.iushrn(1),l.iushrn(1),++S;for(var v=l.clone(),A=m.clone();!m.isZero();){for(var x=0,N=1;!(m.words[0]&N)&&x<26;++x,N<<=1);if(x>0)for(m.iushrn(x);x-- >0;)(d.isOdd()||y.isOdd())&&(d.iadd(v),y.isub(A)),d.iushrn(1),y.iushrn(1);for(var ae=0,R=1;!(l.words[0]&R)&&ae<26;++ae,R<<=1);if(ae>0)for(l.iushrn(ae);ae-- >0;)(P.isOdd()||D.isOdd())&&(P.iadd(v),D.isub(A)),P.iushrn(1),D.iushrn(1);m.cmp(l)>=0?(m.isub(l),d.isub(P),y.isub(D)):(l.isub(m),P.isub(d),D.isub(y))}return{a:P,b:D,gcd:l.iushln(S)}},s.prototype._invmp=function(b){i(b.negative===0),i(!b.isZero());var m=this,l=b.clone();m.negative!==0?m=m.umod(b):m=m.clone();for(var d=new s(1),y=new s(0),P=l.clone();m.cmpn(1)>0&&l.cmpn(1)>0;){for(var D=0,S=1;!(m.words[0]&S)&&D<26;++D,S<<=1);if(D>0)for(m.iushrn(D);D-- >0;)d.isOdd()&&d.iadd(P),d.iushrn(1);for(var v=0,A=1;!(l.words[0]&A)&&v<26;++v,A<<=1);if(v>0)for(l.iushrn(v);v-- >0;)y.isOdd()&&y.iadd(P),y.iushrn(1);m.cmp(l)>=0?(m.isub(l),d.isub(y)):(l.isub(m),y.isub(d))}var x;return m.cmpn(1)===0?x=d:x=y,x.cmpn(0)<0&&x.iadd(b),x},s.prototype.gcd=function(b){if(this.isZero())return b.abs();if(b.isZero())return this.abs();var m=this.clone(),l=b.clone();m.negative=0,l.negative=0;for(var d=0;m.isEven()&&l.isEven();d++)m.iushrn(1),l.iushrn(1);do{for(;m.isEven();)m.iushrn(1);for(;l.isEven();)l.iushrn(1);var y=m.cmp(l);if(y<0){var P=m;m=l,l=P}else if(y===0||l.cmpn(1)===0)break;m.isub(l)}while(!0);return l.iushln(d)},s.prototype.invm=function(b){return this.egcd(b).a.umod(b)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(b){return this.words[0]&b},s.prototype.bincn=function(b){i(typeof b=="number");var m=b%26,l=(b-m)/26,d=1<>>26,D&=67108863,this.words[P]=D}return y!==0&&(this.words[P]=y,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(b){var m=b<0;if(this.negative!==0&&!m)return-1;if(this.negative===0&&m)return 1;this.strip();var l;if(this.length>1)l=1;else{m&&(b=-b),i(b<=67108863,"Number is too big");var d=this.words[0]|0;l=d===b?0:db.length)return 1;if(this.length=0;l--){var d=this.words[l]|0,y=b.words[l]|0;if(d!==y){dy&&(m=1);break}}return m},s.prototype.gtn=function(b){return this.cmpn(b)===1},s.prototype.gt=function(b){return this.cmp(b)===1},s.prototype.gten=function(b){return this.cmpn(b)>=0},s.prototype.gte=function(b){return this.cmp(b)>=0},s.prototype.ltn=function(b){return this.cmpn(b)===-1},s.prototype.lt=function(b){return this.cmp(b)===-1},s.prototype.lten=function(b){return this.cmpn(b)<=0},s.prototype.lte=function(b){return this.cmp(b)<=0},s.prototype.eqn=function(b){return this.cmpn(b)===0},s.prototype.eq=function(b){return this.cmp(b)===0},s.red=function(b){return new ee(b)},s.prototype.toRed=function(b){return i(!this.red,"Already a number in reduction context"),i(this.negative===0,"red works only with positives"),b.convertTo(this)._forceRed(b)},s.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(b){return this.red=b,this},s.prototype.forceRed=function(b){return i(!this.red,"Already a number in reduction context"),this._forceRed(b)},s.prototype.redAdd=function(b){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,b)},s.prototype.redIAdd=function(b){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,b)},s.prototype.redSub=function(b){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,b)},s.prototype.redISub=function(b){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,b)},s.prototype.redShl=function(b){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,b)},s.prototype.redMul=function(b){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,b),this.red.mul(this,b)},s.prototype.redIMul=function(b){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,b),this.red.imul(this,b)},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(b){return i(this.red&&!b.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,b)};var G={k256:null,p224:null,p192:null,p25519:null};function B(L,b){this.name=L,this.p=new s(b,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}B.prototype._tmp=function(){var b=new s(null);return b.words=new Array(Math.ceil(this.n/13)),b},B.prototype.ireduce=function(b){var m=b,l;do this.split(m,this.tmp),m=this.imulK(m),m=m.iadd(this.tmp),l=m.bitLength();while(l>this.n);var d=l0?m.isub(this.p):m.strip!==void 0?m.strip():m._strip(),m},B.prototype.split=function(b,m){b.iushrn(this.n,0,m)},B.prototype.imulK=function(b){return b.imul(this.k)};function z(){B.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(z,B),z.prototype.split=function(b,m){for(var l=4194303,d=Math.min(b.length,9),y=0;y>>22,P=D}P>>>=22,b.words[y-10]=P,P===0&&b.length>10?b.length-=10:b.length-=9},z.prototype.imulK=function(b){b.words[b.length]=0,b.words[b.length+1]=0,b.length+=2;for(var m=0,l=0;l>>=26,b.words[l]=y,m=d}return m!==0&&(b.words[b.length++]=m),b},s._prime=function(b){if(G[b])return G[b];var m;if(b==="k256")m=new z;else if(b==="p224")m=new W;else if(b==="p192")m=new _;else if(b==="p25519")m=new U;else throw new Error("Unknown prime "+b);return G[b]=m,m};function ee(L){if(typeof L=="string"){var b=s._prime(L);this.m=b.p,this.prime=b}else i(L.gtn(1),"modulus must be greater than 1"),this.m=L,this.prime=null}ee.prototype._verify1=function(b){i(b.negative===0,"red works only with positives"),i(b.red,"red works only with red numbers")},ee.prototype._verify2=function(b,m){i((b.negative|m.negative)===0,"red works only with positives"),i(b.red&&b.red===m.red,"red works only with red numbers")},ee.prototype.imod=function(b){return this.prime?this.prime.ireduce(b)._forceRed(this):b.umod(this.m)._forceRed(this)},ee.prototype.neg=function(b){return b.isZero()?b.clone():this.m.sub(b)._forceRed(this)},ee.prototype.add=function(b,m){this._verify2(b,m);var l=b.add(m);return l.cmp(this.m)>=0&&l.isub(this.m),l._forceRed(this)},ee.prototype.iadd=function(b,m){this._verify2(b,m);var l=b.iadd(m);return l.cmp(this.m)>=0&&l.isub(this.m),l},ee.prototype.sub=function(b,m){this._verify2(b,m);var l=b.sub(m);return l.cmpn(0)<0&&l.iadd(this.m),l._forceRed(this)},ee.prototype.isub=function(b,m){this._verify2(b,m);var l=b.isub(m);return l.cmpn(0)<0&&l.iadd(this.m),l},ee.prototype.shl=function(b,m){return this._verify1(b),this.imod(b.ushln(m))},ee.prototype.imul=function(b,m){return this._verify2(b,m),this.imod(b.imul(m))},ee.prototype.mul=function(b,m){return this._verify2(b,m),this.imod(b.mul(m))},ee.prototype.isqr=function(b){return this.imul(b,b.clone())},ee.prototype.sqr=function(b){return this.mul(b,b)},ee.prototype.sqrt=function(b){if(b.isZero())return b.clone();var m=this.m.andln(3);if(i(m%2===1),m===3){var l=this.m.add(new s(1)).iushrn(2);return this.pow(b,l)}for(var d=this.m.subn(1),y=0;!d.isZero()&&d.andln(1)===0;)y++,d.iushrn(1);i(!d.isZero());var P=new s(1).toRed(this),D=P.redNeg(),S=this.m.subn(1).iushrn(1),v=this.m.bitLength();for(v=new s(2*v*v).toRed(this);this.pow(v,S).cmp(D)!==0;)v.redIAdd(D);for(var A=this.pow(v,d),x=this.pow(b,d.addn(1).iushrn(1)),N=this.pow(b,d),ae=y;N.cmp(P)!==0;){for(var R=N,X=0;R.cmp(P)!==0;X++)R=R.redSqr();i(X=0;y--){for(var A=m.words[y],x=v-1;x>=0;x--){var N=A>>x&1;if(P!==d[0]&&(P=this.sqr(P)),N===0&&D===0){S=0;continue}D<<=1,D|=N,S++,!(S!==l&&(y!==0||x!==0))&&(P=this.mul(P,d[D]),S=0,D=0)}v=26}return P},ee.prototype.convertTo=function(b){var m=b.umod(this.m);return m===b?m.clone():m},ee.prototype.convertFrom=function(b){var m=b.clone();return m.red=null,m},s.mont=function(b){return new oe(b)};function oe(L){ee.call(this,L),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)}n(oe,ee),oe.prototype.convertTo=function(b){return this.imod(b.ushln(this.shift))},oe.prototype.convertFrom=function(b){var m=this.imod(b.mul(this.rinv));return m.red=null,m},oe.prototype.imul=function(b,m){if(b.isZero()||m.isZero())return b.words[0]=0,b.length=1,b;var l=b.imul(m),d=l.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),y=l.isub(d).iushrn(this.shift),P=y;return y.cmp(this.m)>=0?P=y.isub(this.m):y.cmpn(0)<0&&(P=y.iadd(this.m)),P._forceRed(this)},oe.prototype.mul=function(b,m){if(b.isZero()||m.isZero())return new s(0)._forceRed(this);var l=b.mul(m),d=l.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),y=l.isub(d).iushrn(this.shift),P=y;return y.cmp(this.m)>=0?P=y.isub(this.m):y.cmpn(0)<0&&(P=y.iadd(this.m)),P._forceRed(this)},oe.prototype.invm=function(b){var m=this.imod(b._invmp(this.m).mul(this.r2));return m._forceRed(this)}})(r,fr)})(Jn);var Ld={};(function(r){var e=r;function t(s,a){if(Array.isArray(s))return s.slice();if(!s)return[];var f=[];if(typeof s!="string"){for(var h=0;h>8,w=u&255;g?f.push(g,w):f.push(w)}return f}e.toArray=t;function i(s){return s.length===1?"0"+s:s}e.zero2=i;function n(s){for(var a="",f=0;f($>>1)-1?H=($>>1)-F:H=F,j.isubn(H)):H=0,C[O]=H,j.iushrn(1)}return C}e.getNAF=s;function a(g,w){var M=[[],[]];g=g.clone(),w=w.clone();for(var C=0,O=0,$;g.cmpn(-C)>0||w.cmpn(-O)>0;){var j=g.andln(3)+C&3,H=w.andln(3)+O&3;j===3&&(j=-1),H===3&&(H=-1);var F;j&1?($=g.andln(7)+C&7,($===3||$===5)&&H===2?F=-j:F=j):F=0,M[0].push(F);var G;H&1?($=w.andln(7)+O&7,($===3||$===5)&&j===2?G=-H:G=H):G=0,M[1].push(G),2*C===F+1&&(C=1-C),2*O===G+1&&(O=1-O),g.iushrn(1),w.iushrn(1)}return M}e.getJSF=a;function f(g,w,M){var C="_"+w;g.prototype[w]=function(){return this[C]!==void 0?this[C]:this[C]=M.call(this)}}e.cachedProperty=f;function h(g){return typeof g=="string"?e.toArray(g,"hex"):g}e.parseBytes=h;function u(g){return new t(g,"hex","le")}e.intFromLE=u}(Li);var El={exports:{}},Bd;El.exports=function(e){return Bd||(Bd=new js(null)),Bd.generate(e)};function js(r){this.rand=r}if(El.exports.Rand=js,js.prototype.generate=function(e){return this._rand(e)},js.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),i=0;i0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Ml=Ws;Ws.prototype.point=function(){throw new Error("Not implemented")},Ws.prototype.validate=function(){throw new Error("Not implemented")},Ws.prototype._fixedNafMul=function(e,t){Il(e.precomputed);var i=e._getDoubles(),n=Sl(t,1,this._bitLength),s=(1<=f;u--)h=(h<<1)+n[u];a.push(h)}for(var g=this.jpoint(null,null,null),w=this.jpoint(null,null,null),M=s;M>0;M--){for(f=0;f=0;h--){for(var u=0;h>=0&&a[h]===0;h--)u++;if(h>=0&&u++,f=f.dblp(u),h<0)break;var g=a[h];Il(g!==0),e.type==="affine"?g>0?f=f.mixedAdd(s[g-1>>1]):f=f.mixedAdd(s[-g-1>>1].neg()):g>0?f=f.add(s[g-1>>1]):f=f.add(s[-g-1>>1].neg())}return e.type==="affine"?f.toP():f},Ws.prototype._wnafMulAdd=function(e,t,i,n,s){var a=this._wnafT1,f=this._wnafT2,h=this._wnafT3,u=0,g,w,M;for(g=0;g=1;g-=2){var O=g-1,$=g;if(a[O]!==1||a[$]!==1){h[O]=Sl(i[O],a[O],this._bitLength),h[$]=Sl(i[$],a[$],this._bitLength),u=Math.max(h[O].length,u),u=Math.max(h[$].length,u);continue}var j=[t[O],null,null,t[$]];t[O].y.cmp(t[$].y)===0?(j[1]=t[O].add(t[$]),j[2]=t[O].toJ().mixedAdd(t[$].neg())):t[O].y.cmp(t[$].y.redNeg())===0?(j[1]=t[O].toJ().mixedAdd(t[$]),j[2]=t[O].add(t[$].neg())):(j[1]=t[O].toJ().mixedAdd(t[$]),j[2]=t[O].toJ().mixedAdd(t[$].neg()));var H=[-3,-1,-5,-7,0,7,5,1,3],F=X9(i[O],i[$]);for(u=Math.max(F[0].length,u),h[O]=new Array(u),h[$]=new Array(u),w=0;w=0;g--){for(var _=0;g>=0;){var U=!0;for(w=0;w=0&&_++,z=z.dblp(_),g<0)break;for(w=0;w0?M=f[w][ee-1>>1]:ee<0&&(M=f[w][-ee-1>>1].neg()),M.type==="affine"?z=z.mixedAdd(M):z=z.add(M))}}for(g=0;g=Math.ceil((e.bitLength()+1)/t.step):!1},Xi.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var i=[this],n=this,s=0;s=0&&(C=u,O=g),w.negative&&(w=w.neg(),M=M.neg()),C.negative&&(C=C.neg(),O=O.neg()),[{a:w,b:M},{a:C,b:O}]},en.prototype._endoSplit=function(e){var t=this.endo.basis,i=t[0],n=t[1],s=n.b.mul(e).divRound(this.n),a=i.b.neg().mul(e).divRound(this.n),f=s.mul(i.a),h=a.mul(n.a),u=s.mul(i.b),g=a.mul(n.b),w=e.sub(f).sub(h),M=u.add(g).neg();return{k1:w,k2:M}},en.prototype.pointFromX=function(e,t){e=new dr(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=i.redSqrt();if(n.redSqr().redSub(i).cmp(this.zero)!==0)throw new Error("invalid point");var s=n.fromRed().isOdd();return(t&&!s||!t&&s)&&(n=n.redNeg()),this.point(e,n)},en.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,i=e.y,n=this.a.redMul(t),s=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return i.redSqr().redISub(s).cmpn(0)===0},en.prototype._endoWnafMulAdd=function(e,t,i){for(var n=this._endoWnafT1,s=this._endoWnafT2,a=0;a":""},Rr.prototype.isInfinity=function(){return this.inf},Rr.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(this.x.cmp(e.x)===0)return this.curve.point(null,null);var t=this.y.redSub(e.y);t.cmpn(0)!==0&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var i=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(i)).redISub(this.y);return this.curve.point(i,n)},Rr.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(e.cmpn(0)===0)return this.curve.point(null,null);var t=this.curve.a,i=this.x.redSqr(),n=e.redInvm(),s=i.redAdd(i).redIAdd(i).redIAdd(t).redMul(n),a=s.redSqr().redISub(this.x.redAdd(this.x)),f=s.redMul(this.x.redSub(a)).redISub(this.y);return this.curve.point(a,f)},Rr.prototype.getX=function(){return this.x.fromRed()},Rr.prototype.getY=function(){return this.y.fromRed()},Rr.prototype.mul=function(e){return e=new dr(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)},Rr.prototype.mulAdd=function(e,t,i){var n=[this,t],s=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,s):this.curve._wnafMulAdd(1,n,s,2)},Rr.prototype.jmulAdd=function(e,t,i){var n=[this,t],s=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,s,!0):this.curve._wnafMulAdd(1,n,s,2,!0)},Rr.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||this.x.cmp(e.x)===0&&this.y.cmp(e.y)===0)},Rr.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var i=this.precomputed,n=function(s){return s.neg()};t.precomputed={naf:i.naf&&{wnd:i.naf.wnd,points:i.naf.points.map(n)},doubles:i.doubles&&{step:i.doubles.step,points:i.doubles.points.map(n)}}}return t},Rr.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var e=this.curve.jpoint(this.x,this.y,this.curve.one);return e};function Wr(r,e,t,i){Ta.BasePoint.call(this,r,"jacobian"),e===null&&t===null&&i===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new dr(0)):(this.x=new dr(e,16),this.y=new dr(t,16),this.z=new dr(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}Ud(Wr,Ta.BasePoint),en.prototype.jpoint=function(e,t,i){return new Wr(this,e,t,i)},Wr.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),i=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(i,n)},Wr.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Wr.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),i=this.z.redSqr(),n=this.x.redMul(t),s=e.x.redMul(i),a=this.y.redMul(t.redMul(e.z)),f=e.y.redMul(i.redMul(this.z)),h=n.redSub(s),u=a.redSub(f);if(h.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var g=h.redSqr(),w=g.redMul(h),M=n.redMul(g),C=u.redSqr().redIAdd(w).redISub(M).redISub(M),O=u.redMul(M.redISub(C)).redISub(a.redMul(w)),$=this.z.redMul(e.z).redMul(h);return this.curve.jpoint(C,O,$)},Wr.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),i=this.x,n=e.x.redMul(t),s=this.y,a=e.y.redMul(t).redMul(this.z),f=i.redSub(n),h=s.redSub(a);if(f.cmpn(0)===0)return h.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var u=f.redSqr(),g=u.redMul(f),w=i.redMul(u),M=h.redSqr().redIAdd(g).redISub(w).redISub(w),C=h.redMul(w.redISub(M)).redISub(s.redMul(g)),O=this.z.redMul(f);return this.curve.jpoint(M,C,O)},Wr.prototype.dblp=function(e){if(e===0)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var i=this;for(t=0;t=0)return!1;if(i.redIAdd(s),this.x.cmp(i)===0)return!0}},Wr.prototype.inspect=function(){return this.isInfinity()?"":""},Wr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var $a=Jn.exports,pm=Ea.exports,Cl=Ml,ix=Li;function Na(r){Cl.call(this,"mont",r),this.a=new $a(r.a,16).toRed(this.red),this.b=new $a(r.b,16).toRed(this.red),this.i4=new $a(4).toRed(this.red).redInvm(),this.two=new $a(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}pm(Na,Cl);var nx=Na;Na.prototype.validate=function(e){var t=e.normalize().x,i=t.redSqr(),n=i.redMul(t).redAdd(i.redMul(this.a)).redAdd(t),s=n.redSqrt();return s.redSqr().cmp(n)===0};function Tr(r,e,t){Cl.BasePoint.call(this,r,"projective"),e===null&&t===null?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new $a(e,16),this.z=new $a(t,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}pm(Tr,Cl.BasePoint),Na.prototype.decodePoint=function(e,t){return this.point(ix.toArray(e,t),1)},Na.prototype.point=function(e,t){return new Tr(this,e,t)},Na.prototype.pointFromJSON=function(e){return Tr.fromJSON(this,e)},Tr.prototype.precompute=function(){},Tr.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Tr.fromJSON=function(e,t){return new Tr(e,t[0],t[1]||e.one)},Tr.prototype.inspect=function(){return this.isInfinity()?"":""},Tr.prototype.isInfinity=function(){return this.z.cmpn(0)===0},Tr.prototype.dbl=function(){var e=this.x.redAdd(this.z),t=e.redSqr(),i=this.x.redSub(this.z),n=i.redSqr(),s=t.redSub(n),a=t.redMul(n),f=s.redMul(n.redAdd(this.curve.a24.redMul(s)));return this.curve.point(a,f)},Tr.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Tr.prototype.diffAdd=function(e,t){var i=this.x.redAdd(this.z),n=this.x.redSub(this.z),s=e.x.redAdd(e.z),a=e.x.redSub(e.z),f=a.redMul(i),h=s.redMul(n),u=t.z.redMul(f.redAdd(h).redSqr()),g=t.x.redMul(f.redISub(h).redSqr());return this.curve.point(u,g)},Tr.prototype.mul=function(e){for(var t=e.clone(),i=this,n=this.curve.point(null,null),s=this,a=[];t.cmpn(0)!==0;t.iushrn(1))a.push(t.andln(1));for(var f=a.length-1;f>=0;f--)a[f]===0?(i=i.diffAdd(n,s),n=n.dbl()):(n=i.diffAdd(n,s),i=i.dbl());return n},Tr.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Tr.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Tr.prototype.eq=function(e){return this.getX().cmp(e.getX())===0},Tr.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Tr.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var sx=Li,ms=Jn.exports,gm=Ea.exports,Pl=Ml,ox=sx.assert;function Qn(r){this.twisted=(r.a|0)!==1,this.mOneA=this.twisted&&(r.a|0)===-1,this.extended=this.mOneA,Pl.call(this,"edwards",r),this.a=new ms(r.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new ms(r.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new ms(r.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),ox(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(r.c|0)===1}gm(Qn,Pl);var ax=Qn;Qn.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},Qn.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},Qn.prototype.jpoint=function(e,t,i,n){return this.point(e,t,i,n)},Qn.prototype.pointFromX=function(e,t){e=new ms(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr(),n=this.c2.redSub(this.a.redMul(i)),s=this.one.redSub(this.c2.redMul(this.d).redMul(i)),a=n.redMul(s.redInvm()),f=a.redSqrt();if(f.redSqr().redSub(a).cmp(this.zero)!==0)throw new Error("invalid point");var h=f.fromRed().isOdd();return(t&&!h||!t&&h)&&(f=f.redNeg()),this.point(e,f)},Qn.prototype.pointFromY=function(e,t){e=new ms(e,16),e.red||(e=e.toRed(this.red));var i=e.redSqr(),n=i.redSub(this.c2),s=i.redMul(this.d).redMul(this.c2).redSub(this.a),a=n.redMul(s.redInvm());if(a.cmp(this.zero)===0){if(t)throw new Error("invalid point");return this.point(this.zero,e)}var f=a.redSqrt();if(f.redSqr().redSub(a).cmp(this.zero)!==0)throw new Error("invalid point");return f.fromRed().isOdd()!==t&&(f=f.redNeg()),this.point(f,e)},Qn.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),i=e.y.redSqr(),n=t.redMul(this.a).redAdd(i),s=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(i)));return n.cmp(s)===0};function nr(r,e,t,i,n){Pl.BasePoint.call(this,r,"projective"),e===null&&t===null&&i===null?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new ms(e,16),this.y=new ms(t,16),this.z=i?new ms(i,16):this.curve.one,this.t=n&&new ms(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}gm(nr,Pl.BasePoint),Qn.prototype.pointFromJSON=function(e){return nr.fromJSON(this,e)},Qn.prototype.point=function(e,t,i,n){return new nr(this,e,t,i,n)},nr.fromJSON=function(e,t){return new nr(e,t[0],t[1],t[2])},nr.prototype.inspect=function(){return this.isInfinity()?"":""},nr.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)},nr.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),i=this.z.redSqr();i=i.redIAdd(i);var n=this.curve._mulA(e),s=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),a=n.redAdd(t),f=a.redSub(i),h=n.redSub(t),u=s.redMul(f),g=a.redMul(h),w=s.redMul(h),M=f.redMul(a);return this.curve.point(u,g,M,w)},nr.prototype._projDbl=function(){var e=this.x.redAdd(this.y).redSqr(),t=this.x.redSqr(),i=this.y.redSqr(),n,s,a,f,h,u;if(this.curve.twisted){f=this.curve._mulA(t);var g=f.redAdd(i);this.zOne?(n=e.redSub(t).redSub(i).redMul(g.redSub(this.curve.two)),s=g.redMul(f.redSub(i)),a=g.redSqr().redSub(g).redSub(g)):(h=this.z.redSqr(),u=g.redSub(h).redISub(h),n=e.redSub(t).redISub(i).redMul(u),s=g.redMul(f.redSub(i)),a=g.redMul(u))}else f=t.redAdd(i),h=this.curve._mulC(this.z).redSqr(),u=f.redSub(h).redSub(h),n=this.curve._mulC(e.redISub(f)).redMul(u),s=this.curve._mulC(f).redMul(t.redISub(i)),a=f.redMul(u);return this.curve.point(n,s,a)},nr.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},nr.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),i=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),s=this.z.redMul(e.z.redAdd(e.z)),a=i.redSub(t),f=s.redSub(n),h=s.redAdd(n),u=i.redAdd(t),g=a.redMul(f),w=h.redMul(u),M=a.redMul(u),C=f.redMul(h);return this.curve.point(g,w,C,M)},nr.prototype._projAdd=function(e){var t=this.z.redMul(e.z),i=t.redSqr(),n=this.x.redMul(e.x),s=this.y.redMul(e.y),a=this.curve.d.redMul(n).redMul(s),f=i.redSub(a),h=i.redAdd(a),u=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(n).redISub(s),g=t.redMul(f).redMul(u),w,M;return this.curve.twisted?(w=t.redMul(h).redMul(s.redSub(this.curve._mulA(n))),M=f.redMul(h)):(w=t.redMul(h).redMul(s.redSub(n)),M=this.curve._mulC(f).redMul(h)),this.curve.point(g,w,M)},nr.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},nr.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},nr.prototype.mulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!1)},nr.prototype.jmulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!0)},nr.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},nr.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},nr.prototype.getX=function(){return this.normalize(),this.x.fromRed()},nr.prototype.getY=function(){return this.normalize(),this.y.fromRed()},nr.prototype.eq=function(e){return this===e||this.getX().cmp(e.getX())===0&&this.getY().cmp(e.getY())===0},nr.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(t)===0)return!0;for(var i=e.clone(),n=this.curve.redN.redMul(this.z);;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),this.x.cmp(t)===0)return!0}},nr.prototype.toP=nr.prototype.normalize,nr.prototype.mixedAdd=nr.prototype.add,function(r){var e=r;e.base=Ml,e.short=rx,e.mont=nx,e.edwards=ax}(Fd);var Dl={},qd,vm;function cx(){return vm||(vm=1,qd={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}),qd}(function(r){var e=r,t=Ri,i=Fd,n=Li,s=n.assert;function a(u){u.type==="short"?this.curve=new i.short(u):u.type==="edwards"?this.curve=new i.edwards(u):this.curve=new i.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,s(this.g.validate(),"Invalid curve"),s(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}e.PresetCurve=a;function f(u,g){Object.defineProperty(e,u,{configurable:!0,enumerable:!0,get:function(){var w=new a(g);return Object.defineProperty(e,u,{configurable:!0,enumerable:!0,value:w}),w}})}f("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:t.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),f("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:t.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),f("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:t.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),f("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:t.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"]}),f("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:t.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"]}),f("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:t.sha256,gRed:!1,g:["9"]}),f("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:t.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var h;try{h=cx()}catch{h=void 0}f("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:t.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",h]})})(Dl);var fx=Ri,Co=Ld,mm=Eo;function Ks(r){if(!(this instanceof Ks))return new Ks(r);this.hash=r.hash,this.predResist=!!r.predResist,this.outLen=this.hash.outSize,this.minEntropy=r.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=Co.toArray(r.entropy,r.entropyEnc||"hex"),t=Co.toArray(r.nonce,r.nonceEnc||"hex"),i=Co.toArray(r.pers,r.persEnc||"hex");mm(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,t,i)}var lx=Ks;Ks.prototype._init=function(e,t,i){var n=e.concat(t).concat(i);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var s=0;s=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(i||[])),this._reseed=1},Ks.prototype.generate=function(e,t,i,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof t!="string"&&(n=i,i=t,t=null),i&&(i=Co.toArray(i,n||"hex"),this._update(i));for(var s=[];s.length"};var Ol=Jn.exports,Hd=Li,px=Hd.assert;function Rl(r,e){if(r instanceof Rl)return r;this._importDER(r,e)||(px(r.r&&r.s,"Signature without r or s"),this.r=new Ol(r.r,16),this.s=new Ol(r.s,16),r.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=r.recoveryParam)}var gx=Rl;function vx(){this.place=0}function kd(r,e){var t=r[e.place++];if(!(t&128))return t;var i=t&15;if(i===0||i>4||r[e.place]===0)return!1;for(var n=0,s=0,a=e.place;s>>=0;return n<=127?!1:(e.place=a,n)}function bm(r){for(var e=0,t=r.length-1;!r[e]&&!(r[e+1]&128)&&e>>3);for(r.push(t|128);--t;)r.push(e>>>(t<<3)&255);r.push(e)}Rl.prototype.toDER=function(e){var t=this.r.toArray(),i=this.s.toArray();for(t[0]&128&&(t=[0].concat(t)),i[0]&128&&(i=[0].concat(i)),t=bm(t),i=bm(i);!i[0]&&!(i[1]&128);)i=i.slice(1);var n=[2];jd(n,t.length),n=n.concat(t),n.push(2),jd(n,i.length);var s=n.concat(i),a=[48];return jd(a,s.length),a=a.concat(s),Hd.encode(a,e)};var En=Jn.exports,wm=lx,mx=Li,Wd=Dl,bx=El.exports,Po=mx.assert,Kd=dx,Tl=gx;function tn(r){if(!(this instanceof tn))return new tn(r);typeof r=="string"&&(Po(Object.prototype.hasOwnProperty.call(Wd,r),"Unknown curve "+r),r=Wd[r]),r instanceof Wd.PresetCurve&&(r={curve:r}),this.curve=r.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=r.curve.g,this.g.precompute(r.curve.n.bitLength()+1),this.hash=r.hash||r.curve.hash}var wx=tn;tn.prototype.keyPair=function(e){return new Kd(this,e)},tn.prototype.keyFromPrivate=function(e,t){return Kd.fromPrivate(this,e,t)},tn.prototype.keyFromPublic=function(e,t){return Kd.fromPublic(this,e,t)},tn.prototype.genKeyPair=function(e){e||(e={});for(var t=new wm({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||bx(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),i=this.n.byteLength(),n=this.n.sub(new En(2));;){var s=new En(t.generate(i));if(!(s.cmp(n)>0))return s.iaddn(1),this.keyFromPrivate(s)}},tn.prototype._truncateToN=function(e,t,i){var n;if(En.isBN(e)||typeof e=="number")e=new En(e,16),n=e.byteLength();else if(typeof e=="object")n=e.length,e=new En(e,16);else{var s=e.toString();n=s.length+1>>>1,e=new En(s,16)}typeof i!="number"&&(i=n*8);var a=i-this.n.bitLength();return a>0&&(e=e.ushrn(a)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},tn.prototype.sign=function(e,t,i,n){if(typeof i=="object"&&(n=i,i=null),n||(n={}),typeof e!="string"&&typeof e!="number"&&!En.isBN(e)){Po(typeof e=="object"&&e&&typeof e.length=="number","Expected message to be an array-like, a hex string, or a BN instance"),Po(e.length>>>0===e.length);for(var s=0;s=0)){var C=this.g.mul(M);if(!C.isInfinity()){var O=C.getX(),$=O.umod(this.n);if($.cmpn(0)!==0){var j=M.invm(this.n).mul($.mul(t.getPrivate()).iadd(e));if(j=j.umod(this.n),j.cmpn(0)!==0){var H=(C.getY().isOdd()?1:0)|(O.cmp($)!==0?2:0);return n.canonical&&j.cmp(this.nh)>0&&(j=this.n.sub(j),H^=1),new Tl({r:$,s:j,recoveryParam:H})}}}}}},tn.prototype.verify=function(e,t,i,n,s){s||(s={}),e=this._truncateToN(e,!1,s.msgBitLength),i=this.keyFromPublic(i,n),t=new Tl(t,"hex");var a=t.r,f=t.s;if(a.cmpn(1)<0||a.cmp(this.n)>=0||f.cmpn(1)<0||f.cmp(this.n)>=0)return!1;var h=f.invm(this.n),u=h.mul(e).umod(this.n),g=h.mul(a).umod(this.n),w;return this.curve._maxwellTrick?(w=this.g.jmulAdd(u,i.getPublic(),g),w.isInfinity()?!1:w.eqXToP(a)):(w=this.g.mulAdd(u,i.getPublic(),g),w.isInfinity()?!1:w.getX().umod(this.n).cmp(a)===0)},tn.prototype.recoverPubKey=function(r,e,t,i){Po((3&t)===t,"The recovery param is more than two bits"),e=new Tl(e,i);var n=this.n,s=new En(r),a=e.r,f=e.s,h=t&1,u=t>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&u)throw new Error("Unable to find sencond key candinate");u?a=this.curve.pointFromX(a.add(this.curve.n),h):a=this.curve.pointFromX(a,h);var g=e.r.invm(n),w=n.sub(s).mul(g).umod(n),M=f.mul(g).umod(n);return this.g.mulAdd(w,a,M)},tn.prototype.getKeyRecoveryParam=function(r,e,t,i){if(e=new Tl(e,i),e.recoveryParam!==null)return e.recoveryParam;for(var n=0;n<4;n++){var s;try{s=this.recoverPubKey(r,e,n)}catch{continue}if(s.eq(t))return n}throw new Error("Unable to find valid recovery factor")};var jc=Li,ym=jc.assert,_m=jc.parseBytes,La=jc.cachedProperty;function $r(r,e){this.eddsa=r,this._secret=_m(e.secret),r.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=_m(e.pub)}$r.fromPublic=function(e,t){return t instanceof $r?t:new $r(e,{pub:t})},$r.fromSecret=function(e,t){return t instanceof $r?t:new $r(e,{secret:t})},$r.prototype.secret=function(){return this._secret},La($r,"pubBytes",function(){return this.eddsa.encodePoint(this.pub())}),La($r,"pub",function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())}),La($r,"privBytes",function(){var e=this.eddsa,t=this.hash(),i=e.encodingLength-1,n=t.slice(0,e.encodingLength);return n[0]&=248,n[i]&=127,n[i]|=64,n}),La($r,"priv",function(){return this.eddsa.decodeInt(this.privBytes())}),La($r,"hash",function(){return this.eddsa.hash().update(this.secret()).digest()}),La($r,"messagePrefix",function(){return this.hash().slice(this.eddsa.encodingLength)}),$r.prototype.sign=function(e){return ym(this._secret,"KeyPair can only verify"),this.eddsa.sign(e,this)},$r.prototype.verify=function(e,t){return this.eddsa.verify(e,t,this)},$r.prototype.getSecret=function(e){return ym(this._secret,"KeyPair is public only"),jc.encode(this.secret(),e)},$r.prototype.getPublic=function(e){return jc.encode(this.pubBytes(),e)};var yx=$r,_x=Jn.exports,$l=Li,xm=$l.assert,Nl=$l.cachedProperty,xx=$l.parseBytes;function Do(r,e){this.eddsa=r,typeof e!="object"&&(e=xx(e)),Array.isArray(e)&&(xm(e.length===r.encodingLength*2,"Signature has invalid size"),e={R:e.slice(0,r.encodingLength),S:e.slice(r.encodingLength)}),xm(e.R&&e.S,"Signature without R or S"),r.isPoint(e.R)&&(this._R=e.R),e.S instanceof _x&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}Nl(Do,"S",function(){return this.eddsa.decodeInt(this.Sencoded())}),Nl(Do,"R",function(){return this.eddsa.decodePoint(this.Rencoded())}),Nl(Do,"Rencoded",function(){return this.eddsa.encodePoint(this.R())}),Nl(Do,"Sencoded",function(){return this.eddsa.encodeInt(this.S())}),Do.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Do.prototype.toHex=function(){return $l.encode(this.toBytes(),"hex").toUpperCase()};var Ax=Do,Ex=Ri,Sx=Dl,Ba=Li,Ix=Ba.assert,Am=Ba.parseBytes,Em=yx,Sm=Ax;function mi(r){if(Ix(r==="ed25519","only tested with ed25519 so far"),!(this instanceof mi))return new mi(r);r=Sx[r].curve,this.curve=r,this.g=r.g,this.g.precompute(r.n.bitLength()+1),this.pointClass=r.point().constructor,this.encodingLength=Math.ceil(r.n.bitLength()/8),this.hash=Ex.sha512}var Mx=mi;mi.prototype.sign=function(e,t){e=Am(e);var i=this.keyFromSecret(t),n=this.hashInt(i.messagePrefix(),e),s=this.g.mul(n),a=this.encodePoint(s),f=this.hashInt(a,i.pubBytes(),e).mul(i.priv()),h=n.add(f).umod(this.curve.n);return this.makeSignature({R:s,S:h,Rencoded:a})},mi.prototype.verify=function(e,t,i){if(e=Am(e),t=this.makeSignature(t),t.S().gte(t.eddsa.curve.n)||t.S().isNeg())return!1;var n=this.keyFromPublic(i),s=this.hashInt(t.Rencoded(),n.pubBytes(),e),a=this.g.mul(t.S()),f=t.R().add(n.pub().mul(s));return f.eq(a)},mi.prototype.hashInt=function(){for(var e=this.hash(),t=0;t0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=h[g++],u--;this._bufferLength===this.blockSize&&(s(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(u>=this.blockSize&&(g=s(this._tempHi,this._tempLo,this._stateHi,this._stateLo,h,g,u),u%=this.blockSize);u>0;)this._buffer[this._bufferLength++]=h[g++],u--;return this},f.prototype.finish=function(h){if(!this._finished){var u=this._bytesHashed,g=this._bufferLength,w=u/536870912|0,M=u<<3,C=u%128<112?128:256;this._buffer[g]=128;for(var O=g+1;O0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},f.prototype.restoreState=function(h){return this._stateHi.set(h.stateHi),this._stateLo.set(h.stateLo),this._bufferLength=h.bufferLength,h.buffer&&this._buffer.set(h.buffer),this._bytesHashed=h.bytesHashed,this._finished=!1,this},f.prototype.cleanSavedState=function(h){t.wipe(h.stateHi),t.wipe(h.stateLo),h.buffer&&t.wipe(h.buffer),h.bufferLength=0,h.bytesHashed=0},f}();r.SHA512=i;var n=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 s(f,h,u,g,w,M,C){for(var O=u[0],$=u[1],j=u[2],H=u[3],F=u[4],G=u[5],B=u[6],z=u[7],W=g[0],_=g[1],U=g[2],ee=g[3],oe=g[4],L=g[5],b=g[6],m=g[7],l,d,y,P,D,S,v,A;C>=128;){for(var x=0;x<16;x++){var N=8*x+M;f[x]=e.readUint32BE(w,N),h[x]=e.readUint32BE(w,N+4)}for(var x=0;x<80;x++){var ae=O,R=$,X=j,V=H,J=F,K=G,E=B,Y=z,re=W,le=_,he=U,ge=ee,He=oe,Te=L,Ce=b,Xe=m;if(l=z,d=m,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=(F>>>14|oe<<32-14)^(F>>>18|oe<<32-18)^(oe>>>41-32|F<<32-(41-32)),d=(oe>>>14|F<<32-14)^(oe>>>18|F<<32-18)^(F>>>41-32|oe<<32-(41-32)),D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,l=F&G^~F&B,d=oe&L^~oe&b,D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,l=n[x*2],d=n[x*2+1],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,l=f[x%16],d=h[x%16],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,y=v&65535|A<<16,P=D&65535|S<<16,l=y,d=P,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=(O>>>28|W<<32-28)^(W>>>34-32|O<<32-(34-32))^(W>>>39-32|O<<32-(39-32)),d=(W>>>28|O<<32-28)^(O>>>34-32|W<<32-(34-32))^(O>>>39-32|W<<32-(39-32)),D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,l=O&$^O&j^$&j,d=W&_^W&U^_&U,D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,Y=v&65535|A<<16,Xe=D&65535|S<<16,l=V,d=ge,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=y,d=P,D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,V=v&65535|A<<16,ge=D&65535|S<<16,$=ae,j=R,H=X,F=V,G=J,B=K,z=E,O=Y,_=re,U=le,ee=he,oe=ge,L=He,b=Te,m=Ce,W=Xe,x%16===15)for(var N=0;N<16;N++)l=f[N],d=h[N],D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=f[(N+9)%16],d=h[(N+9)%16],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,y=f[(N+1)%16],P=h[(N+1)%16],l=(y>>>1|P<<32-1)^(y>>>8|P<<32-8)^y>>>7,d=(P>>>1|y<<32-1)^(P>>>8|y<<32-8)^(P>>>7|y<<32-7),D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,y=f[(N+14)%16],P=h[(N+14)%16],l=(y>>>19|P<<32-19)^(P>>>61-32|y<<32-(61-32))^y>>>6,d=(P>>>19|y<<32-19)^(y>>>61-32|P<<32-(61-32))^(P>>>6|y<<32-6),D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,f[N]=v&65535|A<<16,h[N]=D&65535|S<<16}l=O,d=W,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[0],d=g[0],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[0]=O=v&65535|A<<16,g[0]=W=D&65535|S<<16,l=$,d=_,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[1],d=g[1],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[1]=$=v&65535|A<<16,g[1]=_=D&65535|S<<16,l=j,d=U,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[2],d=g[2],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[2]=j=v&65535|A<<16,g[2]=U=D&65535|S<<16,l=H,d=ee,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[3],d=g[3],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[3]=H=v&65535|A<<16,g[3]=ee=D&65535|S<<16,l=F,d=oe,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[4],d=g[4],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[4]=F=v&65535|A<<16,g[4]=oe=D&65535|S<<16,l=G,d=L,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[5],d=g[5],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[5]=G=v&65535|A<<16,g[5]=L=D&65535|S<<16,l=B,d=b,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[6],d=g[6],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[6]=B=v&65535|A<<16,g[6]=b=D&65535|S<<16,l=z,d=m,D=d&65535,S=d>>>16,v=l&65535,A=l>>>16,l=u[7],d=g[7],D+=d&65535,S+=d>>>16,v+=l&65535,A+=l>>>16,S+=D>>>16,v+=S>>>16,A+=v>>>16,u[7]=z=v&65535|A<<16,g[7]=m=D&65535|S<<16,M+=128,C-=128}return M}function a(f){var h=new i;h.update(f);var u=h.digest();return h.clean(),u}r.hash=a})(Im),function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.convertSecretKeyToX25519=r.convertPublicKeyToX25519=r.verify=r.sign=r.extractPublicKeyFromSecretKey=r.generateKeyPair=r.generateKeyPairFromSeed=r.SEED_LENGTH=r.SECRET_KEY_LENGTH=r.PUBLIC_KEY_LENGTH=r.SIGNATURE_LENGTH=void 0;const e=ks,t=Im,i=$i;r.SIGNATURE_LENGTH=64,r.PUBLIC_KEY_LENGTH=32,r.SECRET_KEY_LENGTH=64,r.SEED_LENGTH=32;function n(V){const J=new Float64Array(16);if(V)for(let K=0;K>16&1),K[le-1]&=65535;K[15]=E[15]-32767-(K[14]>>16&1);const re=K[15]>>16&1;K[14]&=65535,$(E,K,1-re)}for(let Y=0;Y<16;Y++)V[2*Y]=E[Y]&255,V[2*Y+1]=E[Y]>>8}function H(V,J){let K=0;for(let E=0;E<32;E++)K|=V[E]^J[E];return(1&K-1>>>8)-1}function F(V,J){const K=new Uint8Array(32),E=new Uint8Array(32);return j(K,V),j(E,J),H(K,E)}function G(V){const J=new Uint8Array(32);return j(J,V),J[0]&1}function B(V,J){for(let K=0;K<16;K++)V[K]=J[2*K]+(J[2*K+1]<<8);V[15]&=32767}function z(V,J,K){for(let E=0;E<16;E++)V[E]=J[E]+K[E]}function W(V,J,K){for(let E=0;E<16;E++)V[E]=J[E]-K[E]}function _(V,J,K){let E,Y,re=0,le=0,he=0,ge=0,He=0,Te=0,Ce=0,Xe=0,$e=0,be=0,Pe=0,De=0,ye=0,Ie=0,Oe=0,me=0,Me=0,Be=0,we=0,ke=0,We=0,Ae=0,Ve=0,Ke=0,Ge=0,mt=0,It=0,Ye=0,Pt=0,Ot=0,Ze=0,rt=K[0],et=K[1],Ne=K[2],it=K[3],tt=K[4],Re=K[5],lt=K[6],ht=K[7],Le=K[8],ut=K[9],nt=K[10],Fe=K[11],st=K[12],Qe=K[13],qe=K[14],dt=K[15];E=J[0],re+=E*rt,le+=E*et,he+=E*Ne,ge+=E*it,He+=E*tt,Te+=E*Re,Ce+=E*lt,Xe+=E*ht,$e+=E*Le,be+=E*ut,Pe+=E*nt,De+=E*Fe,ye+=E*st,Ie+=E*Qe,Oe+=E*qe,me+=E*dt,E=J[1],le+=E*rt,he+=E*et,ge+=E*Ne,He+=E*it,Te+=E*tt,Ce+=E*Re,Xe+=E*lt,$e+=E*ht,be+=E*Le,Pe+=E*ut,De+=E*nt,ye+=E*Fe,Ie+=E*st,Oe+=E*Qe,me+=E*qe,Me+=E*dt,E=J[2],he+=E*rt,ge+=E*et,He+=E*Ne,Te+=E*it,Ce+=E*tt,Xe+=E*Re,$e+=E*lt,be+=E*ht,Pe+=E*Le,De+=E*ut,ye+=E*nt,Ie+=E*Fe,Oe+=E*st,me+=E*Qe,Me+=E*qe,Be+=E*dt,E=J[3],ge+=E*rt,He+=E*et,Te+=E*Ne,Ce+=E*it,Xe+=E*tt,$e+=E*Re,be+=E*lt,Pe+=E*ht,De+=E*Le,ye+=E*ut,Ie+=E*nt,Oe+=E*Fe,me+=E*st,Me+=E*Qe,Be+=E*qe,we+=E*dt,E=J[4],He+=E*rt,Te+=E*et,Ce+=E*Ne,Xe+=E*it,$e+=E*tt,be+=E*Re,Pe+=E*lt,De+=E*ht,ye+=E*Le,Ie+=E*ut,Oe+=E*nt,me+=E*Fe,Me+=E*st,Be+=E*Qe,we+=E*qe,ke+=E*dt,E=J[5],Te+=E*rt,Ce+=E*et,Xe+=E*Ne,$e+=E*it,be+=E*tt,Pe+=E*Re,De+=E*lt,ye+=E*ht,Ie+=E*Le,Oe+=E*ut,me+=E*nt,Me+=E*Fe,Be+=E*st,we+=E*Qe,ke+=E*qe,We+=E*dt,E=J[6],Ce+=E*rt,Xe+=E*et,$e+=E*Ne,be+=E*it,Pe+=E*tt,De+=E*Re,ye+=E*lt,Ie+=E*ht,Oe+=E*Le,me+=E*ut,Me+=E*nt,Be+=E*Fe,we+=E*st,ke+=E*Qe,We+=E*qe,Ae+=E*dt,E=J[7],Xe+=E*rt,$e+=E*et,be+=E*Ne,Pe+=E*it,De+=E*tt,ye+=E*Re,Ie+=E*lt,Oe+=E*ht,me+=E*Le,Me+=E*ut,Be+=E*nt,we+=E*Fe,ke+=E*st,We+=E*Qe,Ae+=E*qe,Ve+=E*dt,E=J[8],$e+=E*rt,be+=E*et,Pe+=E*Ne,De+=E*it,ye+=E*tt,Ie+=E*Re,Oe+=E*lt,me+=E*ht,Me+=E*Le,Be+=E*ut,we+=E*nt,ke+=E*Fe,We+=E*st,Ae+=E*Qe,Ve+=E*qe,Ke+=E*dt,E=J[9],be+=E*rt,Pe+=E*et,De+=E*Ne,ye+=E*it,Ie+=E*tt,Oe+=E*Re,me+=E*lt,Me+=E*ht,Be+=E*Le,we+=E*ut,ke+=E*nt,We+=E*Fe,Ae+=E*st,Ve+=E*Qe,Ke+=E*qe,Ge+=E*dt,E=J[10],Pe+=E*rt,De+=E*et,ye+=E*Ne,Ie+=E*it,Oe+=E*tt,me+=E*Re,Me+=E*lt,Be+=E*ht,we+=E*Le,ke+=E*ut,We+=E*nt,Ae+=E*Fe,Ve+=E*st,Ke+=E*Qe,Ge+=E*qe,mt+=E*dt,E=J[11],De+=E*rt,ye+=E*et,Ie+=E*Ne,Oe+=E*it,me+=E*tt,Me+=E*Re,Be+=E*lt,we+=E*ht,ke+=E*Le,We+=E*ut,Ae+=E*nt,Ve+=E*Fe,Ke+=E*st,Ge+=E*Qe,mt+=E*qe,It+=E*dt,E=J[12],ye+=E*rt,Ie+=E*et,Oe+=E*Ne,me+=E*it,Me+=E*tt,Be+=E*Re,we+=E*lt,ke+=E*ht,We+=E*Le,Ae+=E*ut,Ve+=E*nt,Ke+=E*Fe,Ge+=E*st,mt+=E*Qe,It+=E*qe,Ye+=E*dt,E=J[13],Ie+=E*rt,Oe+=E*et,me+=E*Ne,Me+=E*it,Be+=E*tt,we+=E*Re,ke+=E*lt,We+=E*ht,Ae+=E*Le,Ve+=E*ut,Ke+=E*nt,Ge+=E*Fe,mt+=E*st,It+=E*Qe,Ye+=E*qe,Pt+=E*dt,E=J[14],Oe+=E*rt,me+=E*et,Me+=E*Ne,Be+=E*it,we+=E*tt,ke+=E*Re,We+=E*lt,Ae+=E*ht,Ve+=E*Le,Ke+=E*ut,Ge+=E*nt,mt+=E*Fe,It+=E*st,Ye+=E*Qe,Pt+=E*qe,Ot+=E*dt,E=J[15],me+=E*rt,Me+=E*et,Be+=E*Ne,we+=E*it,ke+=E*tt,We+=E*Re,Ae+=E*lt,Ve+=E*ht,Ke+=E*Le,Ge+=E*ut,mt+=E*nt,It+=E*Fe,Ye+=E*st,Pt+=E*Qe,Ot+=E*qe,Ze+=E*dt,re+=38*Me,le+=38*Be,he+=38*we,ge+=38*ke,He+=38*We,Te+=38*Ae,Ce+=38*Ve,Xe+=38*Ke,$e+=38*Ge,be+=38*mt,Pe+=38*It,De+=38*Ye,ye+=38*Pt,Ie+=38*Ot,Oe+=38*Ze,Y=1,E=re+Y+65535,Y=Math.floor(E/65536),re=E-Y*65536,E=le+Y+65535,Y=Math.floor(E/65536),le=E-Y*65536,E=he+Y+65535,Y=Math.floor(E/65536),he=E-Y*65536,E=ge+Y+65535,Y=Math.floor(E/65536),ge=E-Y*65536,E=He+Y+65535,Y=Math.floor(E/65536),He=E-Y*65536,E=Te+Y+65535,Y=Math.floor(E/65536),Te=E-Y*65536,E=Ce+Y+65535,Y=Math.floor(E/65536),Ce=E-Y*65536,E=Xe+Y+65535,Y=Math.floor(E/65536),Xe=E-Y*65536,E=$e+Y+65535,Y=Math.floor(E/65536),$e=E-Y*65536,E=be+Y+65535,Y=Math.floor(E/65536),be=E-Y*65536,E=Pe+Y+65535,Y=Math.floor(E/65536),Pe=E-Y*65536,E=De+Y+65535,Y=Math.floor(E/65536),De=E-Y*65536,E=ye+Y+65535,Y=Math.floor(E/65536),ye=E-Y*65536,E=Ie+Y+65535,Y=Math.floor(E/65536),Ie=E-Y*65536,E=Oe+Y+65535,Y=Math.floor(E/65536),Oe=E-Y*65536,E=me+Y+65535,Y=Math.floor(E/65536),me=E-Y*65536,re+=Y-1+37*(Y-1),Y=1,E=re+Y+65535,Y=Math.floor(E/65536),re=E-Y*65536,E=le+Y+65535,Y=Math.floor(E/65536),le=E-Y*65536,E=he+Y+65535,Y=Math.floor(E/65536),he=E-Y*65536,E=ge+Y+65535,Y=Math.floor(E/65536),ge=E-Y*65536,E=He+Y+65535,Y=Math.floor(E/65536),He=E-Y*65536,E=Te+Y+65535,Y=Math.floor(E/65536),Te=E-Y*65536,E=Ce+Y+65535,Y=Math.floor(E/65536),Ce=E-Y*65536,E=Xe+Y+65535,Y=Math.floor(E/65536),Xe=E-Y*65536,E=$e+Y+65535,Y=Math.floor(E/65536),$e=E-Y*65536,E=be+Y+65535,Y=Math.floor(E/65536),be=E-Y*65536,E=Pe+Y+65535,Y=Math.floor(E/65536),Pe=E-Y*65536,E=De+Y+65535,Y=Math.floor(E/65536),De=E-Y*65536,E=ye+Y+65535,Y=Math.floor(E/65536),ye=E-Y*65536,E=Ie+Y+65535,Y=Math.floor(E/65536),Ie=E-Y*65536,E=Oe+Y+65535,Y=Math.floor(E/65536),Oe=E-Y*65536,E=me+Y+65535,Y=Math.floor(E/65536),me=E-Y*65536,re+=Y-1+37*(Y-1),V[0]=re,V[1]=le,V[2]=he,V[3]=ge,V[4]=He,V[5]=Te,V[6]=Ce,V[7]=Xe,V[8]=$e,V[9]=be,V[10]=Pe,V[11]=De,V[12]=ye,V[13]=Ie,V[14]=Oe,V[15]=me}function U(V,J){_(V,J,J)}function ee(V,J){const K=n();let E;for(E=0;E<16;E++)K[E]=J[E];for(E=253;E>=0;E--)U(K,K),E!==2&&E!==4&&_(K,K,J);for(E=0;E<16;E++)V[E]=K[E]}function oe(V,J){const K=n();let E;for(E=0;E<16;E++)K[E]=J[E];for(E=250;E>=0;E--)U(K,K),E!==1&&_(K,K,J);for(E=0;E<16;E++)V[E]=K[E]}function L(V,J){const K=n(),E=n(),Y=n(),re=n(),le=n(),he=n(),ge=n(),He=n(),Te=n();W(K,V[1],V[0]),W(Te,J[1],J[0]),_(K,K,Te),z(E,V[0],V[1]),z(Te,J[0],J[1]),_(E,E,Te),_(Y,V[3],J[3]),_(Y,Y,u),_(re,V[2],J[2]),z(re,re,re),W(le,E,K),W(he,re,Y),z(ge,re,Y),z(He,E,K),_(V[0],le,he),_(V[1],He,ge),_(V[2],ge,he),_(V[3],le,He)}function b(V,J,K){for(let E=0;E<4;E++)$(V[E],J[E],K)}function m(V,J){const K=n(),E=n(),Y=n();ee(Y,J[2]),_(K,J[0],Y),_(E,J[1],Y),j(V,E),V[31]^=G(K)<<7}function l(V,J,K){C(V[0],a),C(V[1],f),C(V[2],f),C(V[3],a);for(let E=255;E>=0;--E){const Y=K[E/8|0]>>(E&7)&1;b(V,J,Y),L(J,V),L(V,V),b(V,J,Y)}}function d(V,J){const K=[n(),n(),n(),n()];C(K[0],g),C(K[1],w),C(K[2],f),_(K[3],g,w),l(V,K,J)}function y(V){if(V.length!==r.SEED_LENGTH)throw new Error(`ed25519: seed must be ${r.SEED_LENGTH} bytes`);const J=(0,t.hash)(V);J[0]&=248,J[31]&=127,J[31]|=64;const K=new Uint8Array(32),E=[n(),n(),n(),n()];d(E,J),m(K,E);const Y=new Uint8Array(64);return Y.set(V),Y.set(K,32),{publicKey:K,secretKey:Y}}r.generateKeyPairFromSeed=y;function P(V){const J=(0,e.randomBytes)(32,V),K=y(J);return(0,i.wipe)(J),K}r.generateKeyPair=P;function D(V){if(V.length!==r.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${r.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(V.subarray(32))}r.extractPublicKeyFromSecretKey=D;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 v(V,J){let K,E,Y,re;for(E=63;E>=32;--E){for(K=0,Y=E-32,re=E-12;Y>4)*S[Y],K=J[Y]>>8,J[Y]&=255;for(Y=0;Y<32;Y++)J[Y]-=K*S[Y];for(E=0;E<32;E++)J[E+1]+=J[E]>>8,V[E]=J[E]&255}function A(V){const J=new Float64Array(64);for(let K=0;K<64;K++)J[K]=V[K];for(let K=0;K<64;K++)V[K]=0;v(V,J)}function x(V,J){const K=new Float64Array(64),E=[n(),n(),n(),n()],Y=(0,t.hash)(V.subarray(0,32));Y[0]&=248,Y[31]&=127,Y[31]|=64;const re=new Uint8Array(64);re.set(Y.subarray(32),32);const le=new t.SHA512;le.update(re.subarray(32)),le.update(J);const he=le.digest();le.clean(),A(he),d(E,he),m(re,E),le.reset(),le.update(re.subarray(0,32)),le.update(V.subarray(32)),le.update(J);const ge=le.digest();A(ge);for(let He=0;He<32;He++)K[He]=he[He];for(let He=0;He<32;He++)for(let Te=0;Te<32;Te++)K[He+Te]+=ge[He]*Y[Te];return v(re.subarray(32),K),re}r.sign=x;function N(V,J){const K=n(),E=n(),Y=n(),re=n(),le=n(),he=n(),ge=n();return C(V[2],f),B(V[1],J),U(Y,V[1]),_(re,Y,h),W(Y,Y,V[2]),z(re,V[2],re),U(le,re),U(he,le),_(ge,he,le),_(K,ge,Y),_(K,K,re),oe(K,K),_(K,K,Y),_(K,K,re),_(K,K,re),_(V[0],K,re),U(E,V[0]),_(E,E,re),F(E,Y)&&_(V[0],V[0],M),U(E,V[0]),_(E,E,re),F(E,Y)?-1:(G(V[0])===J[31]>>7&&W(V[0],a,V[0]),_(V[3],V[0],V[1]),0)}function ae(V,J,K){const E=new Uint8Array(32),Y=[n(),n(),n(),n()],re=[n(),n(),n(),n()];if(K.length!==r.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${r.SIGNATURE_LENGTH} bytes`);if(N(re,V))return!1;const le=new t.SHA512;le.update(K.subarray(0,32)),le.update(V),le.update(J);const he=le.digest();return A(he),l(Y,re,he),d(re,K.subarray(32)),L(Y,re),m(E,Y),!H(K,E)}r.verify=ae;function R(V){let J=[n(),n(),n(),n()];if(N(J,V))throw new Error("Ed25519: invalid public key");let K=n(),E=n(),Y=J[1];z(K,f,Y),W(E,f,Y),ee(E,E),_(K,K,E);let re=new Uint8Array(32);return j(re,K),re}r.convertPublicKeyToX25519=R;function X(V){const J=(0,t.hash)(V.subarray(0,32));J[0]&=248,J[31]&=127,J[31]|=64;const K=new Uint8Array(J.subarray(0,32));return(0,i.wipe)(J),K}r.convertSecretKeyToX25519=X}(Vd);const Cx="EdDSA",Px="JWT",Ll=".",Bl="base64url",Mm="utf8",Cm="utf8",Dx=":",Ox="did",Rx="key",Pm="base58btc",Tx="z",$x="K36",Nx=32;function Gd(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Dm(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Gd(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Lx(r,e){e||(e=r.reduce((n,s)=>n+s.length,0));const t=Dm(e);let i=0;for(const n of r)t.set(n,i),i+=n.length;return Gd(t)}function Om(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const Rm=Om("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Yd=Om("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=Dm(r.length);for(let t=0;tJSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString()+"n":t),Fx=r=>{const e=/([\[:])?(\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,t=r.replace(e,'$1"$2n"$3');return JSON.parse(t,(i,n)=>typeof n=="string"&&n.match(/^\d+n$/)?BigInt(n.substring(0,n.length-1)):n)};function Oo(r){if(typeof r!="string")throw new Error(`Cannot safe json parse value of type ${typeof r}`);try{return Fx(r)}catch{return r}}function bs(r){return typeof r=="string"?r:Bx(r)||""}function $m(r){return Oo(Fl(Fa(r,Bl),Mm))}function Ul(r){return Fl(Fa(bs(r),Mm),Bl)}function Nm(r){const e=Fa($x,Pm),t=Tx+Fl(Lx([e,r]),Pm);return[Ox,Rx,t].join(Dx)}function Ux(r){return Fl(r,Bl)}function qx(r){return Fa(r,Bl)}function zx(r){return Fa([Ul(r.header),Ul(r.payload)].join(Ll),Cm)}function Hx(r){return[Ul(r.header),Ul(r.payload),Ux(r.signature)].join(Ll)}function Jd(r){const e=r.split(Ll),t=$m(e[0]),i=$m(e[1]),n=qx(e[2]),s=Fa(e.slice(0,2).join(Ll),Cm);return{header:t,payload:i,signature:n,data:s}}function Lm(r=ks.randomBytes(Nx)){return Vd.generateKeyPairFromSeed(r)}async function kx(r,e,t,i,n=_e.fromMiliseconds(Date.now())){const s={alg:Cx,typ:Px},a=Nm(i.publicKey),f=n+t,h={iss:a,sub:r,aud:e,iat:n,exp:f},u=zx({header:s,payload:h}),g=Vd.sign(i.secretKey,u);return Hx({header:s,payload:h,signature:g})}const jx={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}},Wx=":";function Ua(r){const[e,t]=r.split(Wx);return{namespace:e,reference:t}}function Bm(r,e=[]){const t=[];return Object.keys(r).forEach(i=>{if(e.length&&!e.includes(i))return;const n=r[i];t.push(...n.accounts)}),t}function Fm(r,e){return r.includes(":")?[r]:e.chains||[]}var Kx=Object.defineProperty,Um=Object.getOwnPropertySymbols,Vx=Object.prototype.hasOwnProperty,Gx=Object.prototype.propertyIsEnumerable,qm=(r,e,t)=>e in r?Kx(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zm=(r,e)=>{for(var t in e||(e={}))Vx.call(e,t)&&qm(r,t,e[t]);if(Um)for(var t of Um(e))Gx.call(e,t)&&qm(r,t,e[t]);return r};const Yx="ReactNative",Bi={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Jx="js";function ql(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function qa(){return!Oc()&&!!Zu()&&navigator.product===Yx}function Wc(){return!ql()&&!!Zu()&&!!Oc()}function Kc(){return qa()?Bi.reactNative:ql()?Bi.node:Wc()?Bi.browser:Bi.unknown}function Qx(){var r;try{return qa()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(r=global.Application)==null?void 0:r.applicationId:void 0}catch{return}}function Zx(r,e){let t=Rc.parse(r);return t=zm(zm({},t),e),r=Rc.stringify(t),r}function Hm(){return Cg()||{name:"",description:"",url:"",icons:[""]}}function Xx(){if(Kc()===Bi.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:t,Version:i}=global.Platform;return[t,i].join("-")}const r=a5();if(r===null)return"unknown";const e=r.os?r.os.replace(" ","").toLowerCase():"unknown";return r.type==="browser"?[e,r.name,r.version].join("-"):[e,r.version].join("-")}function eA(){var r;const e=Kc();return e===Bi.browser?[e,((r=Mg())==null?void 0:r.host)||"unknown"].join(":"):e}function km(r,e,t){const i=Xx(),n=eA();return[[r,e].join("-"),[Jx,t].join("-"),i,n].join("/")}function tA({protocol:r,version:e,relayUrl:t,sdkVersion:i,auth:n,projectId:s,useOnCloseEvent:a,bundleId:f}){const h=t.split("?"),u=km(r,e,i),g={auth:n,ua:u,projectId:s,useOnCloseEvent:a||void 0,origin:f||void 0},w=Zx(h[1]||"",g);return h[0]+"?"+w}function Ro(r,e){return r.filter(t=>e.includes(t)).length===r.length}function jm(r){return Object.fromEntries(r.entries())}function Wm(r){return new Map(Object.entries(r))}function To(r=_e.FIVE_MINUTES,e){const t=_e.toMiliseconds(r||_e.FIVE_MINUTES);let i,n,s,a;return{resolve:f=>{s&&i&&(clearTimeout(s),i(f),a=Promise.resolve(f))},reject:f=>{s&&n&&(clearTimeout(s),n(f))},done:()=>new Promise((f,h)=>{if(a)return f(a);s=setTimeout(()=>{const u=new Error(e);a=Promise.reject(u),h(u)},t),i=f,n=h})}}function Vs(r,e,t){return new Promise(async(i,n)=>{const s=setTimeout(()=>n(new Error(t)),e);try{const a=await r;i(a)}catch(a){n(a)}clearTimeout(s)})}function Km(r,e){if(typeof e=="string"&&e.startsWith(`${r}:`))return e;if(r.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(r.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${r}`)}function rA(r){return Km("topic",r)}function iA(r){return Km("id",r)}function Vm(r){const[e,t]=r.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function Ir(r,e){return _e.fromMiliseconds((e||Date.now())+_e.toMiliseconds(r))}function Gs(r){return Date.now()>=_e.toMiliseconds(r)}function Dt(r,e){return`${r}${e?`:${e}`:""}`}function zl(r=[],e=[]){return[...new Set([...r,...e])]}async function nA({id:r,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const n=typeof t=="string"?JSON.parse(t):t,s=n?.href;if(typeof s!="string")return;const a=sA(s,r,e),f=Kc();if(f===Bi.browser){if(!((i=Oc())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}a.startsWith("https://")||a.startsWith("http://")?window.open(a,"_blank","noreferrer noopener"):window.open(a,aA()?"_blank":"_self","noreferrer noopener")}else f===Bi.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(a)}catch(n){console.error(n)}}function sA(r,e,t){const i=`requestId=${e}&sessionTopic=${t}`;r.endsWith("/")&&(r=r.slice(0,-1));let n=`${r}`;if(r.startsWith("https://t.me")){const s=r.includes("?")?"&startapp=":"?startapp=";n=`${n}${s}${cA(i,!0)}`}else n=`${n}/wc?${i}`;return n}async function oA(r,e){let t="";try{if(Wc()&&(t=localStorage.getItem(e),t))return t;t=await r.getItem(e)}catch(i){console.error(i)}return t}function Gm(r,e){if(!r.includes(e))return null;const t=r.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Ym(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Qd(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function aA(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function cA(r,e=!1){const t=Buffer.from(r).toString("base64");return e?t.replace(/[=]/g,""):t}function Jm(r){return Buffer.from(r,"base64").toString("utf-8")}function fA(r){return new Promise(e=>setTimeout(e,r))}const lA="https://rpc.walletconnect.org/v1";async function hA(r,e,t,i,n,s){switch(t.t){case"eip191":return uA(r,e,t.s);case"eip1271":return await dA(r,e,t.s,i,n,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}function uA(r,e,t){return O_(nv(e),t).toLowerCase()===r.toLowerCase()}async function dA(r,e,t,i,n,s){const a=Ua(i);if(!a.namespace||!a.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const f="0x1626ba7e",h="0000000000000000000000000000000000000000000000000000000000000040",u="0000000000000000000000000000000000000000000000000000000000000041",g=t.substring(2),w=nv(e).substring(2),M=f+w+h+u+g,C=await fetch(`${s||lA}/?chainId=${i}&projectId=${n}`,{method:"POST",body:JSON.stringify({id:pA(),jsonrpc:"2.0",method:"eth_call",params:[{to:r,data:M},"latest"]})}),{result:O}=await C.json();return O?O.slice(0,f.length).toLowerCase()===f.toLowerCase():!1}catch(f){return console.error("isValidEip1271Signature: ",f),!1}}function pA(){return Date.now()+Math.floor(Math.random()*1e3)}var gA=Object.defineProperty,vA=Object.defineProperties,mA=Object.getOwnPropertyDescriptors,Qm=Object.getOwnPropertySymbols,bA=Object.prototype.hasOwnProperty,wA=Object.prototype.propertyIsEnumerable,Zm=(r,e,t)=>e in r?gA(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,yA=(r,e)=>{for(var t in e||(e={}))bA.call(e,t)&&Zm(r,t,e[t]);if(Qm)for(var t of Qm(e))wA.call(e,t)&&Zm(r,t,e[t]);return r},_A=(r,e)=>vA(r,mA(e));const xA="did:pkh:",Zd=r=>r?.split(":"),AA=r=>{const e=r&&Zd(r);if(e)return r.includes(xA)?e[3]:e[1]},Xd=r=>{const e=r&&Zd(r);if(e)return e[2]+":"+e[3]},Hl=r=>{const e=r&&Zd(r);if(e)return e.pop()};async function Xm(r){const{cacao:e,projectId:t}=r,{s:i,p:n}=e,s=eb(n,n.iss),a=Hl(n.iss);return await hA(a,s,i,Xd(n.iss),t)}const eb=(r,e)=>{const t=`${r.domain} wants you to sign in with your Ethereum account:`,i=Hl(e);if(!r.aud&&!r.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=r.statement||void 0;const s=`URI: ${r.aud||r.uri}`,a=`Version: ${r.version}`,f=`Chain ID: ${AA(e)}`,h=`Nonce: ${r.nonce}`,u=`Issued At: ${r.iat}`,g=r.exp?`Expiration Time: ${r.exp}`:void 0,w=r.nbf?`Not Before: ${r.nbf}`:void 0,M=r.requestId?`Request ID: ${r.requestId}`:void 0,C=r.resources?`Resources:${r.resources.map($=>` ++- ${$}`).join("")}`:void 0,O=kl(r.resources);if(O){const $=Vc(O);n=RA(n,$)}return[t,i,"",n,"",s,a,f,h,u,g,w,M,C].filter($=>$!=null).join(` ++`)};function EA(r){return Buffer.from(JSON.stringify(r)).toString("base64")}function SA(r){return JSON.parse(Buffer.from(r,"base64").toString("utf-8"))}function $o(r){if(!r)throw new Error("No recap provided, value is undefined");if(!r.att)throw new Error("No `att` property found");const e=Object.keys(r.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=r.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(n=>{const s=i[n];if(!Array.isArray(s))throw new Error(`Ability limits ${n} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${n} is empty array, must be an array with objects`);s.forEach(a=>{if(typeof a!="object")throw new Error(`Ability limits (${n}) must be an array of objects, found: ${a}`)})})})}function IA(r,e,t,i={}){return t?.sort((n,s)=>n.localeCompare(s)),{att:{[r]:MA(e,t,i)}}}function MA(r,e,t={}){e=e?.sort((n,s)=>n.localeCompare(s));const i=e.map(n=>({[`${r}/${n}`]:[t]}));return Object.assign({},...i)}function tb(r){return $o(r),`urn:recap:${EA(r).replace(/=/g,"")}`}function Vc(r){const e=SA(r.replace("urn:recap:",""));return $o(e),e}function CA(r,e,t){const i=IA(r,e,t);return tb(i)}function PA(r){return r&&r.includes("urn:recap:")}function DA(r,e){const t=Vc(r),i=Vc(e),n=OA(t,i);return tb(n)}function OA(r,e){$o(r),$o(e);const t=Object.keys(r.att).concat(Object.keys(e.att)).sort((n,s)=>n.localeCompare(s)),i={att:{}};return t.forEach(n=>{var s,a;Object.keys(((s=r.att)==null?void 0:s[n])||{}).concat(Object.keys(((a=e.att)==null?void 0:a[n])||{})).sort((f,h)=>f.localeCompare(h)).forEach(f=>{var h,u;i.att[n]=_A(yA({},i.att[n]),{[f]:((h=r.att[n])==null?void 0:h[f])||((u=e.att[n])==null?void 0:u[f])})})}),i}function RA(r="",e){$o(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(r.includes(t))return r;const i=[];let n=0;Object.keys(e.att).forEach(f=>{const h=Object.keys(e.att[f]).map(w=>({ability:w.split("/")[0],action:w.split("/")[1]}));h.sort((w,M)=>w.action.localeCompare(M.action));const u={};h.forEach(w=>{u[w.ability]||(u[w.ability]=[]),u[w.ability].push(w.action)});const g=Object.keys(u).map(w=>(n++,`(${n}) '${w}': '${u[w].join("', '")}' for '${f}'.`));i.push(g.join(", ").replace(".,","."))});const s=i.join(" "),a=`${t}${s}`;return`${r?r+" ":""}${a}`}function rb(r){var e;const t=Vc(r);$o(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(n=>n.split("/")[1]):[]}function ib(r){const e=Vc(r);$o(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(n=>{var s;(s=n?.[0])!=null&&s.chains&&t.push(n[0].chains)})}),[...new Set(t.flat())]}function kl(r){if(!r)return;const e=r?.[r.length-1];return PA(e)?e:void 0}const nb="base10",oi="base16",Ys="base64pad",Gc="base64url",Yc="utf8",sb=0,ws=1,Jc=2,TA=0,ob=1,Qc=12,e0=32;function $A(){const r=Od.generateKeyPair();return{privateKey:Ni(r.secretKey,oi),publicKey:Ni(r.publicKey,oi)}}function t0(){const r=ks.randomBytes(e0);return Ni(r,oi)}function NA(r,e){const t=Od.sharedKey(Zi(r,oi),Zi(e,oi),!0),i=new h7(zc.SHA256,t).expand(e0);return Ni(i,oi)}function jl(r){const e=zc.hash(Zi(r,oi));return Ni(e,oi)}function ys(r){const e=zc.hash(Zi(r,Yc));return Ni(e,oi)}function ab(r){return Zi(`${r}`,nb)}function No(r){return Number(Ni(r,nb))}function LA(r){const e=ab(typeof r.type<"u"?r.type:sb);if(No(e)===ws&&typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof r.senderPublicKey<"u"?Zi(r.senderPublicKey,oi):void 0,i=typeof r.iv<"u"?Zi(r.iv,oi):ks.randomBytes(Qc),n=new Ed.ChaCha20Poly1305(Zi(r.symKey,oi)).seal(i,Zi(r.message,Yc));return cb({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:r.encoding})}function BA(r,e){const t=ab(Jc),i=ks.randomBytes(Qc),n=Zi(r,Yc);return cb({type:t,sealed:n,iv:i,encoding:e})}function FA(r){const e=new Ed.ChaCha20Poly1305(Zi(r.symKey,oi)),{sealed:t,iv:i}=Zc({encoded:r.encoded,encoding:r?.encoding}),n=e.open(i,t);if(n===null)throw new Error("Failed to decrypt");return Ni(n,Yc)}function UA(r,e){const{sealed:t}=Zc({encoded:r,encoding:e});return Ni(t,Yc)}function cb(r){const{encoding:e=Ys}=r;if(No(r.type)===Jc)return Ni(Rd([r.type,r.sealed]),e);if(No(r.type)===ws){if(typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ni(Rd([r.type,r.senderPublicKey,r.iv,r.sealed]),e)}return Ni(Rd([r.type,r.iv,r.sealed]),e)}function Zc(r){const{encoded:e,encoding:t=Ys}=r,i=Zi(e,t),n=i.slice(TA,ob),s=ob;if(No(n)===ws){const u=s+e0,g=u+Qc,w=i.slice(s,u),M=i.slice(u,g),C=i.slice(g);return{type:n,sealed:C,iv:M,senderPublicKey:w}}if(No(n)===Jc){const u=i.slice(s),g=ks.randomBytes(Qc);return{type:n,sealed:u,iv:g}}const a=s+Qc,f=i.slice(s,a),h=i.slice(a);return{type:n,sealed:h,iv:f}}function qA(r,e){const t=Zc({encoded:r,encoding:e?.encoding});return fb({type:No(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Ni(t.senderPublicKey,oi):void 0,receiverPublicKey:e?.receiverPublicKey})}function fb(r){const e=r?.type||sb;if(e===ws){if(typeof r?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof r?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:r?.senderPublicKey,receiverPublicKey:r?.receiverPublicKey}}function lb(r){return r.type===ws&&typeof r.senderPublicKey=="string"&&typeof r.receiverPublicKey=="string"}function hb(r){return r.type===Jc}function zA(r){return new um.ec("p256").keyFromPublic({x:Buffer.from(r.x,"base64").toString("hex"),y:Buffer.from(r.y,"base64").toString("hex")},"hex")}function HA(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function kA(r){return Buffer.from(HA(r),"base64")}function jA(r,e){const[t,i,n]=r.split("."),s=kA(n);if(s.length!==64)throw new Error("Invalid signature length");const a=s.slice(0,32).toString("hex"),f=s.slice(32,64).toString("hex"),h=`${t}.${i}`,u=new zc.SHA256().update(Buffer.from(h)).digest(),g=zA(e),w=Buffer.from(u).toString("hex");if(!g.verify(w,{r:a,s:f}))throw new Error("Invalid signature");return Jd(r).payload}const WA="irn";function Wl(r){return r?.relay||{protocol:WA}}function Xc(r){const e=jx[r];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${r}`);return e}var KA=Object.defineProperty,VA=Object.defineProperties,GA=Object.getOwnPropertyDescriptors,ub=Object.getOwnPropertySymbols,YA=Object.prototype.hasOwnProperty,JA=Object.prototype.propertyIsEnumerable,db=(r,e,t)=>e in r?KA(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pb=(r,e)=>{for(var t in e||(e={}))YA.call(e,t)&&db(r,t,e[t]);if(ub)for(var t of ub(e))JA.call(e,t)&&db(r,t,e[t]);return r},QA=(r,e)=>VA(r,GA(e));function ZA(r,e="-"){const t={},i="relay"+e;return Object.keys(r).forEach(n=>{if(n.startsWith(i)){const s=n.replace(i,""),a=r[n];t[s]=a}}),t}function gb(r){if(!r.includes("wc:")){const h=Jm(r);h!=null&&h.includes("wc:")&&(r=h)}r=r.includes("wc://")?r.replace("wc://",""):r,r=r.includes("wc:")?r.replace("wc:",""):r;const e=r.indexOf(":"),t=r.indexOf("?")!==-1?r.indexOf("?"):void 0,i=r.substring(0,e),n=r.substring(e+1,t).split("@"),s=typeof t<"u"?r.substring(t):"",a=Rc.parse(s),f=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:XA(n[0]),version:parseInt(n[1],10),symKey:a.symKey,relay:ZA(a),methods:f,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function XA(r){return r.startsWith("//")?r.substring(2):r}function eE(r,e="-"){const t="relay",i={};return Object.keys(r).forEach(n=>{const s=t+e+n;r[n]&&(i[s]=r[n])}),i}function vb(r){return`${r.protocol}:${r.topic}@${r.version}?`+Rc.stringify(pb(QA(pb({symKey:r.symKey},eE(r.relay)),{expiryTimestamp:r.expiryTimestamp}),r.methods?{methods:r.methods.join(",")}:{}))}function Kl(r,e,t){return`${r}?wc_ev=${t}&topic=${e}`}function za(r){const e=[];return r.forEach(t=>{const[i,n]=t.split(":");e.push(`${i}:${n}`)}),e}function tE(r){const e=[];return Object.values(r).forEach(t=>{e.push(...za(t.accounts))}),e}function rE(r,e){const t=[];return Object.values(r).forEach(i=>{za(i.accounts).includes(e)&&t.push(...i.methods)}),t}function iE(r,e){const t=[];return Object.values(r).forEach(i=>{za(i.accounts).includes(e)&&t.push(...i.events)}),t}function r0(r){return r.includes(":")}function ef(r){return r0(r)?r.split(":")[0]:r}function nE(r){const e={};return r?.forEach(t=>{const[i,n]=t.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[]}),e[i].accounts.push(t),e[i].chains.push(`${i}:${n}`)}),e}function mb(r,e){e=e.map(i=>i.replace("did:pkh:",""));const t=nE(e);for(const[i,n]of Object.entries(t))n.methods?n.methods=zl(n.methods,r):n.methods=r,n.events=["chainChanged","accountsChanged"];return t}const sE={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}},oE={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 xe(r,e){const{message:t,code:i}=oE[r];return{message:e?`${t} ${e}`:t,code:i}}function Gt(r,e){const{message:t,code:i}=sE[r];return{message:e?`${t} ${e}`:t,code:i}}function _s(r,e){return Array.isArray(r)?typeof e<"u"&&r.length?r.every(e):!0:!1}function tf(r){return Object.getPrototypeOf(r)===Object.prototype&&Object.keys(r).length}function ai(r){return typeof r>"u"}function wr(r,e){return e&&ai(r)?!0:typeof r=="string"&&!!r.trim().length}function i0(r,e){return e&&ai(r)?!0:typeof r=="number"&&!isNaN(r)}function aE(r,e){const{requiredNamespaces:t}=e,i=Object.keys(r.namespaces),n=Object.keys(t);let s=!0;return Ro(n,i)?(i.forEach(a=>{const{accounts:f,methods:h,events:u}=r.namespaces[a],g=za(f),w=t[a];(!Ro(Fm(a,w),g)||!Ro(w.methods,h)||!Ro(w.events,u))&&(s=!1)}),s):!1}function Vl(r){return wr(r,!1)&&r.includes(":")?r.split(":").length===2:!1}function cE(r){if(wr(r,!1)&&r.includes(":")){const e=r.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Vl(t)}}return!1}function fE(r){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(wr(r,!1)){if(e(r))return!0;const t=Jm(r);return e(t)}}catch{}return!1}function lE(r){var e;return(e=r?.proposer)==null?void 0:e.publicKey}function hE(r){return r?.topic}function uE(r,e){let t=null;return wr(r?.publicKey,!1)||(t=xe("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function bb(r){let e=!0;return _s(r)?r.length&&(e=r.every(t=>wr(t,!1))):e=!1,e}function dE(r,e,t){let i=null;return _s(e)&&e.length?e.forEach(n=>{i||Vl(n)||(i=Gt("UNSUPPORTED_CHAINS",`${t}, chain ${n} should be a string and conform to "namespace:chainId" format`))}):Vl(r)||(i=Gt("UNSUPPORTED_CHAINS",`${t}, 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}function pE(r,e,t){let i=null;return Object.entries(r).forEach(([n,s])=>{if(i)return;const a=dE(n,Fm(n,s),`${e} ${t}`);a&&(i=a)}),i}function gE(r,e){let t=null;return _s(r)?r.forEach(i=>{t||cE(i)||(t=Gt("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Gt("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function vE(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const n=gE(i?.accounts,`${e} namespace`);n&&(t=n)}),t}function mE(r,e){let t=null;return bb(r?.methods)?bb(r?.events)||(t=Gt("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Gt("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function wb(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const n=mE(i,`${e}, namespace`);n&&(t=n)}),t}function bE(r,e,t){let i=null;if(r&&tf(r)){const n=wb(r,e);n&&(i=n);const s=pE(r,e,t);s&&(i=s)}else i=xe("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function n0(r,e){let t=null;if(r&&tf(r)){const i=wb(r,e);i&&(t=i);const n=vE(r,e);n&&(t=n)}else t=xe("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function yb(r){return wr(r.protocol,!0)}function wE(r,e){let t=!1;return e&&!r?t=!0:r&&_s(r)&&r.length&&r.forEach(i=>{t=yb(i)}),t}function yE(r){return typeof r=="number"}function bi(r){return typeof r<"u"&&typeof r!==null}function _E(r){return!(!r||typeof r!="object"||!r.code||!i0(r.code,!1)||!r.message||!wr(r.message,!1))}function xE(r){return!(ai(r)||!wr(r.method,!1))}function AE(r){return!(ai(r)||ai(r.result)&&ai(r.error)||!i0(r.id,!1)||!wr(r.jsonrpc,!1))}function EE(r){return!(ai(r)||!wr(r.name,!1))}function _b(r,e){return!(!Vl(e)||!tE(r).includes(e))}function SE(r,e,t){return wr(t,!1)?rE(r,e).includes(t):!1}function IE(r,e,t){return wr(t,!1)?iE(r,e).includes(t):!1}function xb(r,e,t){let i=null;const n=ME(r),s=CE(e),a=Object.keys(n),f=Object.keys(s),h=Ab(Object.keys(r)),u=Ab(Object.keys(e)),g=h.filter(w=>!u.includes(w));return g.length&&(i=xe("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces. + Required: ${g.toString()} +- Received: ${Object.keys(e).toString()}`)),Do(a,f)||(i=_e("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces. ++ Received: ${Object.keys(e).toString()}`)),Ro(a,f)||(i=xe("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces. + Required: ${a.toString()} +- Approved: ${f.toString()}`)),Object.keys(e).forEach(w=>{if(!w.includes(":")||i)return;const P=qa(e[w].accounts);P.includes(w)||(i=_e("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${w} ++ Approved: ${f.toString()}`)),Object.keys(e).forEach(w=>{if(!w.includes(":")||i)return;const M=za(e[w].accounts);M.includes(w)||(i=xe("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${w} + Required: ${w} +- Approved: ${P.toString()}`))}),a.forEach(w=>{i||(Do(n[w].methods,s[w].methods)?Do(n[w].events,s[w].events)||(i=_e("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${w}`)):i=_e("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${w}`))}),i}function _E(r){const e={};return Object.keys(r).forEach(t=>{var i;t.includes(":")?e[t]=r[t]:(i=r[t].chains)==null||i.forEach(n=>{e[n]={methods:r[t].methods,events:r[t].events}})}),e}function Ab(r){return[...new Set(r.map(e=>e.includes(":")?e.split(":")[0]:e))]}function xE(r){const e={};return Object.keys(r).forEach(t=>{if(t.includes(":"))e[t]=r[t];else{const i=qa(r[t].accounts);i?.forEach(n=>{e[n]={accounts:r[t].accounts.filter(s=>s.includes(`${n}:`)),methods:r[t].methods,events:r[t].events}})}}),e}function AE(r,e){return t0(r,!1)&&r<=e.max&&r>=e.min}function Eb(){const r=Wc();return new Promise(e=>{switch(r){case Bi.browser:e(EE());break;case Bi.reactNative:e(SE());break;case Bi.node:e(IE());break;default:e(!0)}})}function EE(){return jc()&&navigator?.onLine}async function SE(){if(Fa()&&typeof global<"u"&&global!=null&&global.NetInfo){const r=await(global==null?void 0:global.NetInfo.fetch());return r?.isConnected}return!0}function IE(){return!0}function ME(r){switch(Wc()){case Bi.browser:CE(r);break;case Bi.reactNative:PE(r);break}}function CE(r){!Fa()&&jc()&&(window.addEventListener("online",()=>r(!0)),window.addEventListener("offline",()=>r(!1)))}function PE(r){Fa()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>r(e?.isConnected))}const i0={};class tf{static get(e){return i0[e]}static set(e,t){i0[e]=t}static delete(e){delete i0[e]}}class $o{}class DE extends $o{constructor(e){super()}}const Sb=Ae.FIVE_SECONDS,za={pulse:"heartbeat_pulse"};class n0 extends DE{constructor(e){super(e),this.events=new qr.exports.EventEmitter,this.interval=Sb,this.interval=e?.interval||Sb}static async init(e){const t=new n0(e);return await t.init(),t}async init(){await 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)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),Ae.toMiliseconds(this.interval))}pulse(){this.events.emit(za.pulse)}}const OE=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,RE=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,TE=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function $E(r,e){if(r==="__proto__"||r==="constructor"&&e&&typeof e=="object"&&"prototype"in e){NE(r);return}return e}function NE(r){console.warn(`[destr] Dropping "${r}" key to prevent prototype pollution.`)}function Kl(r,e={}){if(typeof r!="string")return r;const t=r.trim();if(r[0]==='"'&&r.at(-1)==='"'&&!r.includes("\\"))return t.slice(1,-1);if(t.length<=9){const i=t.toLowerCase();if(i==="true")return!0;if(i==="false")return!1;if(i==="undefined")return;if(i==="null")return null;if(i==="nan")return Number.NaN;if(i==="infinity")return Number.POSITIVE_INFINITY;if(i==="-infinity")return Number.NEGATIVE_INFINITY}if(!TE.test(r)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return r}try{if(OE.test(r)||RE.test(r)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(r,$E)}return JSON.parse(r)}catch(i){if(e.strict)throw i;return r}}function LE(r){return!r||typeof r.then!="function"?Promise.resolve(r):r}function Nr(r,...e){try{return LE(r(...e))}catch(t){return Promise.reject(t)}}function BE(r){const e=typeof r;return r===null||e!=="object"&&e!=="function"}function FE(r){const e=Object.getPrototypeOf(r);return!e||e.isPrototypeOf(Object)}function Vl(r){if(BE(r))return String(r);if(FE(r)||Array.isArray(r))return JSON.stringify(r);if(typeof r.toJSON=="function")return Vl(r.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function Ib(){if(typeof Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}const s0="base64:";function UE(r){if(typeof r=="string")return r;Ib();const e=Buffer.from(r).toString("base64");return s0+e}function qE(r){return typeof r!="string"||!r.startsWith(s0)?r:(Ib(),Buffer.from(r.slice(s0.length),"base64"))}function wi(r){return r?r.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function zE(...r){return wi(r.join(":"))}function Gl(r){return r=wi(r),r?r+":":""}function rH(r){return r}const HE="memory",kE=()=>{const r=new Map;return{name:HE,options:{},hasItem(e){return r.has(e)},getItem(e){return r.get(e)||null},getItemRaw(e){return r.get(e)||null},setItem(e,t){r.set(e,t)},setItemRaw(e,t){r.set(e,t)},removeItem(e){r.delete(e)},getKeys(){return Array.from(r.keys())},clear(){r.clear()},dispose(){r.clear()}}};function jE(r={}){const e={mounts:{"":r.driver||kE()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=u=>{for(const g of e.mountpoints)if(u.startsWith(g))return{base:g,relativeKey:u.slice(g.length),driver:e.mounts[g]};return{base:"",relativeKey:u,driver:e.mounts[""]}},i=(u,g)=>e.mountpoints.filter(w=>w.startsWith(u)||g&&u.startsWith(w)).map(w=>({relativeBase:u.length>w.length?u.slice(w.length):void 0,mountpoint:w,driver:e.mounts[w]})),n=(u,g)=>{if(e.watching){g=wi(g);for(const w of e.watchListeners)w(u,g)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await Mb(e.mounts[u],n,u)}},a=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},f=(u,g,w)=>{const P=new Map,M=O=>{let $=P.get(O.base);return $||($={driver:O.driver,base:O.base,items:[]},P.set(O.base,$)),$};for(const O of u){const $=typeof O=="string",W=wi($?O:O.key),H=$?void 0:O.value,F=$||!O.options?g:{...g,...O.options},Y=t(W);M(Y).items.push({key:W,value:H,relativeKey:Y.relativeKey,options:F})}return Promise.all([...P.values()].map(O=>w(O))).then(O=>O.flat())},h={hasItem(u,g={}){u=wi(u);const{relativeKey:w,driver:P}=t(u);return Nr(P.hasItem,w,g)},getItem(u,g={}){u=wi(u);const{relativeKey:w,driver:P}=t(u);return Nr(P.getItem,w,g).then(M=>Kl(M))},getItems(u,g){return f(u,g,w=>w.driver.getItems?Nr(w.driver.getItems,w.items.map(P=>({key:P.relativeKey,options:P.options})),g).then(P=>P.map(M=>({key:zE(w.base,M.key),value:Kl(M.value)}))):Promise.all(w.items.map(P=>Nr(w.driver.getItem,P.relativeKey,P.options).then(M=>({key:P.key,value:Kl(M)})))))},getItemRaw(u,g={}){u=wi(u);const{relativeKey:w,driver:P}=t(u);return P.getItemRaw?Nr(P.getItemRaw,w,g):Nr(P.getItem,w,g).then(M=>qE(M))},async setItem(u,g,w={}){if(g===void 0)return h.removeItem(u);u=wi(u);const{relativeKey:P,driver:M}=t(u);M.setItem&&(await Nr(M.setItem,P,Vl(g),w),M.watch||n("update",u))},async setItems(u,g){await f(u,g,async w=>{w.driver.setItems&&await Nr(w.driver.setItems,w.items.map(P=>({key:P.relativeKey,value:Vl(P.value),options:P.options})),g),w.driver.setItem&&await Promise.all(w.items.map(P=>Nr(w.driver.setItem,P.relativeKey,Vl(P.value),P.options)))})},async setItemRaw(u,g,w={}){if(g===void 0)return h.removeItem(u,w);u=wi(u);const{relativeKey:P,driver:M}=t(u);if(M.setItemRaw)await Nr(M.setItemRaw,P,g,w);else if(M.setItem)await Nr(M.setItem,P,UE(g),w);else return;M.watch||n("update",u)},async removeItem(u,g={}){typeof g=="boolean"&&(g={removeMeta:g}),u=wi(u);const{relativeKey:w,driver:P}=t(u);P.removeItem&&(await Nr(P.removeItem,w,g),(g.removeMeta||g.removeMata)&&await Nr(P.removeItem,w+"$",g),P.watch||n("remove",u))},async getMeta(u,g={}){typeof g=="boolean"&&(g={nativeOnly:g}),u=wi(u);const{relativeKey:w,driver:P}=t(u),M=Object.create(null);if(P.getMeta&&Object.assign(M,await Nr(P.getMeta,w,g)),!g.nativeOnly){const O=await Nr(P.getItem,w+"$",g).then($=>Kl($));O&&typeof O=="object"&&(typeof O.atime=="string"&&(O.atime=new Date(O.atime)),typeof O.mtime=="string"&&(O.mtime=new Date(O.mtime)),Object.assign(M,O))}return M},setMeta(u,g,w={}){return this.setItem(u+"$",g,w)},removeMeta(u,g={}){return this.removeItem(u+"$",g)},async getKeys(u,g={}){u=Gl(u);const w=i(u,!0);let P=[];const M=[];for(const O of w){const W=(await Nr(O.driver.getKeys,O.relativeBase,g)).map(H=>O.mountpoint+wi(H)).filter(H=>!P.some(F=>H.startsWith(F)));M.push(...W),P=[O.mountpoint,...P.filter(H=>!H.startsWith(O.mountpoint))]}return u?M.filter(O=>O.startsWith(u)&&!O.endsWith("$")):M.filter(O=>!O.endsWith("$"))},async clear(u,g={}){u=Gl(u),await Promise.all(i(u,!1).map(async w=>{if(w.driver.clear)return Nr(w.driver.clear,w.relativeBase,g);if(w.driver.removeItem){const P=await w.driver.getKeys(w.relativeBase||"",g);return Promise.all(P.map(M=>w.driver.removeItem(M,g)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Cb(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(g=>g!==u),e.watchListeners.length===0&&await a()}},async unwatch(){e.watchListeners=[],await a()},mount(u,g){if(u=Gl(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((w,P)=>P.length-w.length)),e.mounts[u]=g,e.watching&&Promise.resolve(Mb(g,n,u)).then(w=>{e.unwatch[u]=w}).catch(console.error),h},async unmount(u,g=!0){u=Gl(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u](),delete e.unwatch[u]),g&&await Cb(e.mounts[u]),e.mountpoints=e.mountpoints.filter(w=>w!==u),delete e.mounts[u])},getMount(u=""){u=wi(u)+":";const g=t(u);return{driver:g.driver,base:g.base}},getMounts(u="",g={}){return u=wi(u),i(u,g.parents).map(P=>({driver:P.driver,base:P.mountpoint}))}};return h}function Mb(r,e,t){return r.watch?r.watch((i,n)=>e(i,t+n)):()=>{}}async function Cb(r){typeof r.dispose=="function"&&await Nr(r.dispose)}function No(r){return new Promise((e,t)=>{r.oncomplete=r.onsuccess=()=>e(r.result),r.onabort=r.onerror=()=>t(r.error)})}function Pb(r,e){const t=indexedDB.open(r);t.onupgradeneeded=()=>t.result.createObjectStore(e);const i=No(t);return(n,s)=>i.then(a=>s(a.transaction(e,n).objectStore(e)))}let o0;function rf(){return o0||(o0=Pb("keyval-store","keyval")),o0}function Db(r,e=rf()){return e("readonly",t=>No(t.get(r)))}function WE(r,e,t=rf()){return t("readwrite",i=>(i.put(e,r),No(i.transaction)))}function KE(r,e=rf()){return e("readwrite",t=>(t.delete(r),No(t.transaction)))}function VE(r=rf()){return r("readwrite",e=>(e.clear(),No(e.transaction)))}function GE(r,e){return r.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},No(r.transaction)}function YE(r=rf()){return r("readonly",e=>{if(e.getAllKeys)return No(e.getAllKeys());const t=[];return GE(e,i=>t.push(i.key)).then(()=>t)})}const JE="idb-keyval";var QE=(r={})=>{const e=r.base&&r.base.length>0?`${r.base}:`:"",t=n=>e+n;let i;return r.dbName&&r.storeName&&(i=Pb(r.dbName,r.storeName)),{name:JE,options:r,async hasItem(n){return!(typeof await Db(t(n),i)>"u")},async getItem(n){return await Db(t(n),i)??null},setItem(n,s){return WE(t(n),s,i)},removeItem(n){return KE(t(n),i)},getKeys(){return YE(i)},clear(){return VE(i)}}};const ZE="WALLET_CONNECT_V2_INDEXED_DB",XE="keyvaluestorage";class eS{constructor(){this.indexedDb=jE({driver:QE({dbName:ZE,storeName:XE})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,ws(t))}async removeItem(e){await this.indexedDb.removeItem(e)}}var a0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Yl={exports:{}};(function(){let r;function e(){}r=e,r.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},r.prototype.setItem=function(t,i){this[t]=String(i)},r.prototype.removeItem=function(t){delete this[t]},r.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(i){t[i]=void 0,delete t[i]})},r.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},r.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof a0<"u"&&a0.localStorage?Yl.exports=a0.localStorage:typeof window<"u"&&window.localStorage?Yl.exports=window.localStorage:Yl.exports=new e})();function tS(r){var e;return[r[0],Po((e=r[1])!=null?e:"")]}class rS{constructor(){this.localStorage=Yl.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(tS)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return Po(t)}async setItem(e,t){this.localStorage.setItem(e,ws(t))}async removeItem(e){this.localStorage.removeItem(e)}}const iS="wc_storage_version",Ob=1,nS=async(r,e,t)=>{const i=iS,n=await e.getItem(i);if(n&&n>=Ob){t(e);return}const s=await r.getKeys();if(!s.length){t(e);return}const a=[];for(;s.length;){const f=s.shift();if(!f)continue;const h=f.toLowerCase();if(h.includes("wc@")||h.includes("walletconnect")||h.includes("wc_")||h.includes("wallet_connect")){const u=await r.getItem(f);await e.setItem(f,u),a.push(f)}}await e.setItem(i,Ob),t(e),sS(r,a)},sS=async(r,e)=>{e.length&&e.forEach(async t=>{await r.removeItem(t)})};class oS{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new rS;this.storage=e;try{const t=new eS;nS(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}}function aS(r){try{return JSON.stringify(r)}catch{return'"[Circular]"'}}var cS=fS;function fS(r,e,t){var i=t&&t.stringify||aS,n=1;if(typeof r=="object"&&r!==null){var s=e.length+n;if(s===1)return r;var a=new Array(s);a[0]=i(r);for(var f=1;f-1?w:0,r.charCodeAt(M+1)){case 100:case 102:if(g>=h||e[g]==null)break;w=h||e[g]==null)break;w=h||e[g]===void 0)break;w",w=M+2,M++;break}u+=i(e[g]),w=M+2,M++;break;case 115:if(g>=h)break;w-1&&(s=!1);const a=["error","fatal","warn","info","debug","trace"];typeof t=="function"&&(t.error=t.fatal=t.warn=t.info=t.debug=t.trace=t),r.enabled===!1&&(r.level="silent");const f=r.level||"info",h=Object.create(t);h.log||(h.log=sf),Object.defineProperty(h,"levelVal",{get:g}),Object.defineProperty(h,"level",{get:w,set:P});const u={transmit:e,serialize:n,asObject:r.browser.asObject,levels:a,timestamp:vS(r)};h.levels=Zn.levels,h.level=f,h.setMaxListeners=h.getMaxListeners=h.emit=h.addListener=h.on=h.prependListener=h.once=h.prependOnceListener=h.removeListener=h.removeAllListeners=h.listeners=h.listenerCount=h.eventNames=h.write=h.flush=sf,h.serializers=i,h._serialize=n,h._stdErrSerialize=s,h.child=M,e&&(h._logEvent=c0());function g(){return this.level==="silent"?1/0:this.levels.values[this.level]}function w(){return this._level}function P(O){if(O!=="silent"&&!this.levels.values[O])throw Error("unknown level "+O);this._level=O,Ha(u,h,"error","log"),Ha(u,h,"fatal","error"),Ha(u,h,"warn","error"),Ha(u,h,"info","log"),Ha(u,h,"debug","log"),Ha(u,h,"trace","log")}function M(O,$){if(!O)throw new Error("missing bindings for child Pino");$=$||{},n&&O.serializers&&($.serializers=O.serializers);const W=$.serializers;if(n&&W){var H=Object.assign({},i,W),F=r.browser.serialize===!0?Object.keys(H):n;delete O.serializers,Jl([O],F,H,this._stdErrSerialize)}function Y(B){this._childLevel=(B._childLevel|0)+1,this.error=ka(B,O,"error"),this.fatal=ka(B,O,"fatal"),this.warn=ka(B,O,"warn"),this.info=ka(B,O,"info"),this.debug=ka(B,O,"debug"),this.trace=ka(B,O,"trace"),H&&(this.serializers=H,this._serialize=F),e&&(this._logEvent=c0([].concat(B._logEvent.bindings,O)))}return Y.prototype=this,new Y(this)}return h}Zn.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},Zn.stdSerializers=lS,Zn.stdTimeFunctions=Object.assign({},{nullTime:Tb,epochTime:$b,unixTime:mS,isoTime:bS});function Ha(r,e,t,i){const n=Object.getPrototypeOf(e);e[t]=e.levelVal>e.levels.values[t]?sf:n[t]?n[t]:nf[t]||nf[i]||sf,uS(r,e,t)}function uS(r,e,t){!r.transmit&&e[t]===sf||(e[t]=function(i){return function(){const s=r.timestamp(),a=new Array(arguments.length),f=Object.getPrototypeOf&&Object.getPrototypeOf(this)===nf?nf:this;for(var h=0;h-1&&s in t&&(r[n][s]=t[s](r[n][s]))}function ka(r,e,t){return function(){const i=new Array(1+arguments.length);i[0]=e;for(var n=1;nthis.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}}class Lb{constructor(e,t=l0){this.level=e??"error",this.levelValue=Qn.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Nb(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===Qn.levels.values.error?console.error(e):t===Qn.levels.values.warn?console.warn(e):t===Qn.levels.values.debug?console.debug(e):t===Qn.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(ws({timestamp:new Date().toISOString(),log:e}));const t=typeof e=="string"?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new Nb(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(ws({extraMetadata:e})),new Blob(t,{type:"application/json"})}}class xS{constructor(e,t=l0){this.baseChunkLogger=new Lb(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=t,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}}class AS{constructor(e,t=l0){this.baseChunkLogger=new Lb(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var ES=Object.defineProperty,SS=Object.defineProperties,IS=Object.getOwnPropertyDescriptors,Bb=Object.getOwnPropertySymbols,MS=Object.prototype.hasOwnProperty,CS=Object.prototype.propertyIsEnumerable,Fb=(r,e,t)=>e in r?ES(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Zl=(r,e)=>{for(var t in e||(e={}))MS.call(e,t)&&Fb(r,t,e[t]);if(Bb)for(var t of Bb(e))CS.call(e,t)&&Fb(r,t,e[t]);return r},Xl=(r,e)=>SS(r,IS(e));function eh(r){return Xl(Zl({},r),{level:r?.level||yS.level})}function PS(r,e=of){return r[e]||""}function DS(r,e,t=of){return r[t]=e,r}function yi(r,e=of){let t="";return typeof r.bindings>"u"?t=PS(r,e):t=r.bindings().context||"",t}function OS(r,e,t=of){const i=yi(r,t);return i.trim()?`${i}/${e}`:e}function ai(r,e,t=of){const i=OS(r,e,t),n=r.child({context:i});return DS(n,i,t)}function RS(r){var e,t;const i=new xS((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:Qn(Xl(Zl({},r.opts),{level:"trace",browser:Xl(Zl({},(t=r.opts)==null?void 0:t.browser),{write:n=>i.write(n)})})),chunkLoggerController:i}}function TS(r){var e;const t=new AS((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:Qn(Xl(Zl({},r.opts),{level:"trace"})),chunkLoggerController:t}}function $S(r){return typeof r.loggerOverride<"u"&&typeof r.loggerOverride!="string"?{logger:r.loggerOverride,chunkLoggerController:null}:typeof window<"u"?RS(r):TS(r)}class NS extends $o{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class LS extends $o{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}}class BS{constructor(e,t){this.logger=e,this.core=t}}class FS extends $o{constructor(e,t){super(),this.relayer=e,this.logger=t}}class US extends $o{constructor(e){super()}}class qS{constructor(e,t,i,n){this.core=e,this.logger=t,this.name=i}}class zS extends $o{constructor(e,t){super(),this.relayer=e,this.logger=t}}class HS extends $o{constructor(e,t){super(),this.core=e,this.logger=t}}class kS{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}}class jS{constructor(e,t){this.projectId=e,this.logger=t}}class WS{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}}class KS{constructor(e){this.opts=e,this.protocol="wc",this.version=2}}class VS{constructor(e){this.client=e}}function GS(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function Ub(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const qb=Ub("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),h0=Ub("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=GS(r.length);for(let t=0;tt.code===r);return e||af[Hb]}function jb(r,e,t){return r.message.includes("getaddrinfo ENOTFOUND")||r.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${t} RPC url at ${e}`):r}var Wb={};/*! ***************************************************************************** ++ Approved: ${M.toString()}`))}),a.forEach(w=>{i||(Ro(n[w].methods,s[w].methods)?Ro(n[w].events,s[w].events)||(i=xe("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${w}`)):i=xe("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${w}`))}),i}function ME(r){const e={};return Object.keys(r).forEach(t=>{var i;t.includes(":")?e[t]=r[t]:(i=r[t].chains)==null||i.forEach(n=>{e[n]={methods:r[t].methods,events:r[t].events}})}),e}function Ab(r){return[...new Set(r.map(e=>e.includes(":")?e.split(":")[0]:e))]}function CE(r){const e={};return Object.keys(r).forEach(t=>{if(t.includes(":"))e[t]=r[t];else{const i=za(r[t].accounts);i?.forEach(n=>{e[n]={accounts:r[t].accounts.filter(s=>s.includes(`${n}:`)),methods:r[t].methods,events:r[t].events}})}}),e}function PE(r,e){return i0(r,!1)&&r<=e.max&&r>=e.min}function Eb(){const r=Kc();return new Promise(e=>{switch(r){case Bi.browser:e(DE());break;case Bi.reactNative:e(OE());break;case Bi.node:e(RE());break;default:e(!0)}})}function DE(){return Wc()&&navigator?.onLine}async function OE(){if(qa()&&typeof global<"u"&&global!=null&&global.NetInfo){const r=await(global==null?void 0:global.NetInfo.fetch());return r?.isConnected}return!0}function RE(){return!0}function TE(r){switch(Kc()){case Bi.browser:$E(r);break;case Bi.reactNative:NE(r);break}}function $E(r){!qa()&&Wc()&&(window.addEventListener("online",()=>r(!0)),window.addEventListener("offline",()=>r(!1)))}function NE(r){qa()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>r(e?.isConnected))}const s0={};class rf{static get(e){return s0[e]}static set(e,t){s0[e]=t}static delete(e){delete s0[e]}}class Lo{}class LE extends Lo{constructor(e){super()}}const Sb=_e.FIVE_SECONDS,Ha={pulse:"heartbeat_pulse"};class o0 extends LE{constructor(e){super(e),this.events=new zr.exports.EventEmitter,this.interval=Sb,this.interval=e?.interval||Sb}static async init(e){const t=new o0(e);return await t.init(),t}async init(){await 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)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),_e.toMiliseconds(this.interval))}pulse(){this.events.emit(Ha.pulse)}}const BE=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,FE=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,UE=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function qE(r,e){if(r==="__proto__"||r==="constructor"&&e&&typeof e=="object"&&"prototype"in e){zE(r);return}return e}function zE(r){console.warn(`[destr] Dropping "${r}" key to prevent prototype pollution.`)}function Gl(r,e={}){if(typeof r!="string")return r;const t=r.trim();if(r[0]==='"'&&r.at(-1)==='"'&&!r.includes("\\"))return t.slice(1,-1);if(t.length<=9){const i=t.toLowerCase();if(i==="true")return!0;if(i==="false")return!1;if(i==="undefined")return;if(i==="null")return null;if(i==="nan")return Number.NaN;if(i==="infinity")return Number.POSITIVE_INFINITY;if(i==="-infinity")return Number.NEGATIVE_INFINITY}if(!UE.test(r)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return r}try{if(BE.test(r)||FE.test(r)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(r,qE)}return JSON.parse(r)}catch(i){if(e.strict)throw i;return r}}function HE(r){return!r||typeof r.then!="function"?Promise.resolve(r):r}function Nr(r,...e){try{return HE(r(...e))}catch(t){return Promise.reject(t)}}function kE(r){const e=typeof r;return r===null||e!=="object"&&e!=="function"}function jE(r){const e=Object.getPrototypeOf(r);return!e||e.isPrototypeOf(Object)}function Yl(r){if(kE(r))return String(r);if(jE(r)||Array.isArray(r))return JSON.stringify(r);if(typeof r.toJSON=="function")return Yl(r.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function Ib(){if(typeof Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}const a0="base64:";function WE(r){if(typeof r=="string")return r;Ib();const e=Buffer.from(r).toString("base64");return a0+e}function KE(r){return typeof r!="string"||!r.startsWith(a0)?r:(Ib(),Buffer.from(r.slice(a0.length),"base64"))}function wi(r){return r?r.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function VE(...r){return wi(r.join(":"))}function Jl(r){return r=wi(r),r?r+":":""}function uH(r){return r}const GE="memory",YE=()=>{const r=new Map;return{name:GE,options:{},hasItem(e){return r.has(e)},getItem(e){return r.get(e)||null},getItemRaw(e){return r.get(e)||null},setItem(e,t){r.set(e,t)},setItemRaw(e,t){r.set(e,t)},removeItem(e){r.delete(e)},getKeys(){return Array.from(r.keys())},clear(){r.clear()},dispose(){r.clear()}}};function JE(r={}){const e={mounts:{"":r.driver||YE()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=u=>{for(const g of e.mountpoints)if(u.startsWith(g))return{base:g,relativeKey:u.slice(g.length),driver:e.mounts[g]};return{base:"",relativeKey:u,driver:e.mounts[""]}},i=(u,g)=>e.mountpoints.filter(w=>w.startsWith(u)||g&&u.startsWith(w)).map(w=>({relativeBase:u.length>w.length?u.slice(w.length):void 0,mountpoint:w,driver:e.mounts[w]})),n=(u,g)=>{if(e.watching){g=wi(g);for(const w of e.watchListeners)w(u,g)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await Mb(e.mounts[u],n,u)}},a=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},f=(u,g,w)=>{const M=new Map,C=O=>{let $=M.get(O.base);return $||($={driver:O.driver,base:O.base,items:[]},M.set(O.base,$)),$};for(const O of u){const $=typeof O=="string",j=wi($?O:O.key),H=$?void 0:O.value,F=$||!O.options?g:{...g,...O.options},G=t(j);C(G).items.push({key:j,value:H,relativeKey:G.relativeKey,options:F})}return Promise.all([...M.values()].map(O=>w(O))).then(O=>O.flat())},h={hasItem(u,g={}){u=wi(u);const{relativeKey:w,driver:M}=t(u);return Nr(M.hasItem,w,g)},getItem(u,g={}){u=wi(u);const{relativeKey:w,driver:M}=t(u);return Nr(M.getItem,w,g).then(C=>Gl(C))},getItems(u,g){return f(u,g,w=>w.driver.getItems?Nr(w.driver.getItems,w.items.map(M=>({key:M.relativeKey,options:M.options})),g).then(M=>M.map(C=>({key:VE(w.base,C.key),value:Gl(C.value)}))):Promise.all(w.items.map(M=>Nr(w.driver.getItem,M.relativeKey,M.options).then(C=>({key:M.key,value:Gl(C)})))))},getItemRaw(u,g={}){u=wi(u);const{relativeKey:w,driver:M}=t(u);return M.getItemRaw?Nr(M.getItemRaw,w,g):Nr(M.getItem,w,g).then(C=>KE(C))},async setItem(u,g,w={}){if(g===void 0)return h.removeItem(u);u=wi(u);const{relativeKey:M,driver:C}=t(u);C.setItem&&(await Nr(C.setItem,M,Yl(g),w),C.watch||n("update",u))},async setItems(u,g){await f(u,g,async w=>{w.driver.setItems&&await Nr(w.driver.setItems,w.items.map(M=>({key:M.relativeKey,value:Yl(M.value),options:M.options})),g),w.driver.setItem&&await Promise.all(w.items.map(M=>Nr(w.driver.setItem,M.relativeKey,Yl(M.value),M.options)))})},async setItemRaw(u,g,w={}){if(g===void 0)return h.removeItem(u,w);u=wi(u);const{relativeKey:M,driver:C}=t(u);if(C.setItemRaw)await Nr(C.setItemRaw,M,g,w);else if(C.setItem)await Nr(C.setItem,M,WE(g),w);else return;C.watch||n("update",u)},async removeItem(u,g={}){typeof g=="boolean"&&(g={removeMeta:g}),u=wi(u);const{relativeKey:w,driver:M}=t(u);M.removeItem&&(await Nr(M.removeItem,w,g),(g.removeMeta||g.removeMata)&&await Nr(M.removeItem,w+"$",g),M.watch||n("remove",u))},async getMeta(u,g={}){typeof g=="boolean"&&(g={nativeOnly:g}),u=wi(u);const{relativeKey:w,driver:M}=t(u),C=Object.create(null);if(M.getMeta&&Object.assign(C,await Nr(M.getMeta,w,g)),!g.nativeOnly){const O=await Nr(M.getItem,w+"$",g).then($=>Gl($));O&&typeof O=="object"&&(typeof O.atime=="string"&&(O.atime=new Date(O.atime)),typeof O.mtime=="string"&&(O.mtime=new Date(O.mtime)),Object.assign(C,O))}return C},setMeta(u,g,w={}){return this.setItem(u+"$",g,w)},removeMeta(u,g={}){return this.removeItem(u+"$",g)},async getKeys(u,g={}){u=Jl(u);const w=i(u,!0);let M=[];const C=[];for(const O of w){const j=(await Nr(O.driver.getKeys,O.relativeBase,g)).map(H=>O.mountpoint+wi(H)).filter(H=>!M.some(F=>H.startsWith(F)));C.push(...j),M=[O.mountpoint,...M.filter(H=>!H.startsWith(O.mountpoint))]}return u?C.filter(O=>O.startsWith(u)&&!O.endsWith("$")):C.filter(O=>!O.endsWith("$"))},async clear(u,g={}){u=Jl(u),await Promise.all(i(u,!1).map(async w=>{if(w.driver.clear)return Nr(w.driver.clear,w.relativeBase,g);if(w.driver.removeItem){const M=await w.driver.getKeys(w.relativeBase||"",g);return Promise.all(M.map(C=>w.driver.removeItem(C,g)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Cb(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(g=>g!==u),e.watchListeners.length===0&&await a()}},async unwatch(){e.watchListeners=[],await a()},mount(u,g){if(u=Jl(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((w,M)=>M.length-w.length)),e.mounts[u]=g,e.watching&&Promise.resolve(Mb(g,n,u)).then(w=>{e.unwatch[u]=w}).catch(console.error),h},async unmount(u,g=!0){u=Jl(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u](),delete e.unwatch[u]),g&&await Cb(e.mounts[u]),e.mountpoints=e.mountpoints.filter(w=>w!==u),delete e.mounts[u])},getMount(u=""){u=wi(u)+":";const g=t(u);return{driver:g.driver,base:g.base}},getMounts(u="",g={}){return u=wi(u),i(u,g.parents).map(M=>({driver:M.driver,base:M.mountpoint}))}};return h}function Mb(r,e,t){return r.watch?r.watch((i,n)=>e(i,t+n)):()=>{}}async function Cb(r){typeof r.dispose=="function"&&await Nr(r.dispose)}function Bo(r){return new Promise((e,t)=>{r.oncomplete=r.onsuccess=()=>e(r.result),r.onabort=r.onerror=()=>t(r.error)})}function Pb(r,e){const t=indexedDB.open(r);t.onupgradeneeded=()=>t.result.createObjectStore(e);const i=Bo(t);return(n,s)=>i.then(a=>s(a.transaction(e,n).objectStore(e)))}let c0;function nf(){return c0||(c0=Pb("keyval-store","keyval")),c0}function Db(r,e=nf()){return e("readonly",t=>Bo(t.get(r)))}function QE(r,e,t=nf()){return t("readwrite",i=>(i.put(e,r),Bo(i.transaction)))}function ZE(r,e=nf()){return e("readwrite",t=>(t.delete(r),Bo(t.transaction)))}function XE(r=nf()){return r("readwrite",e=>(e.clear(),Bo(e.transaction)))}function eS(r,e){return r.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Bo(r.transaction)}function tS(r=nf()){return r("readonly",e=>{if(e.getAllKeys)return Bo(e.getAllKeys());const t=[];return eS(e,i=>t.push(i.key)).then(()=>t)})}const rS="idb-keyval";var iS=(r={})=>{const e=r.base&&r.base.length>0?`${r.base}:`:"",t=n=>e+n;let i;return r.dbName&&r.storeName&&(i=Pb(r.dbName,r.storeName)),{name:rS,options:r,async hasItem(n){return!(typeof await Db(t(n),i)>"u")},async getItem(n){return await Db(t(n),i)??null},setItem(n,s){return QE(t(n),s,i)},removeItem(n){return ZE(t(n),i)},getKeys(){return tS(i)},clear(){return XE(i)}}};const nS="WALLET_CONNECT_V2_INDEXED_DB",sS="keyvaluestorage";class oS{constructor(){this.indexedDb=JE({driver:iS({dbName:nS,storeName:sS})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,bs(t))}async removeItem(e){await this.indexedDb.removeItem(e)}}var f0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ql={exports:{}};(function(){let r;function e(){}r=e,r.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},r.prototype.setItem=function(t,i){this[t]=String(i)},r.prototype.removeItem=function(t){delete this[t]},r.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(i){t[i]=void 0,delete t[i]})},r.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},r.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof f0<"u"&&f0.localStorage?Ql.exports=f0.localStorage:typeof window<"u"&&window.localStorage?Ql.exports=window.localStorage:Ql.exports=new e})();function aS(r){var e;return[r[0],Oo((e=r[1])!=null?e:"")]}class cS{constructor(){this.localStorage=Ql.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(aS)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return Oo(t)}async setItem(e,t){this.localStorage.setItem(e,bs(t))}async removeItem(e){this.localStorage.removeItem(e)}}const fS="wc_storage_version",Ob=1,lS=async(r,e,t)=>{const i=fS,n=await e.getItem(i);if(n&&n>=Ob){t(e);return}const s=await r.getKeys();if(!s.length){t(e);return}const a=[];for(;s.length;){const f=s.shift();if(!f)continue;const h=f.toLowerCase();if(h.includes("wc@")||h.includes("walletconnect")||h.includes("wc_")||h.includes("wallet_connect")){const u=await r.getItem(f);await e.setItem(f,u),a.push(f)}}await e.setItem(i,Ob),t(e),hS(r,a)},hS=async(r,e)=>{e.length&&e.forEach(async t=>{await r.removeItem(t)})};class uS{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new cS;this.storage=e;try{const t=new oS;lS(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}}function dS(r){try{return JSON.stringify(r)}catch{return'"[Circular]"'}}var pS=gS;function gS(r,e,t){var i=t&&t.stringify||dS,n=1;if(typeof r=="object"&&r!==null){var s=e.length+n;if(s===1)return r;var a=new Array(s);a[0]=i(r);for(var f=1;f-1?w:0,r.charCodeAt(C+1)){case 100:case 102:if(g>=h||e[g]==null)break;w=h||e[g]==null)break;w=h||e[g]===void 0)break;w",w=C+2,C++;break}u+=i(e[g]),w=C+2,C++;break;case 115:if(g>=h)break;w-1&&(s=!1);const a=["error","fatal","warn","info","debug","trace"];typeof t=="function"&&(t.error=t.fatal=t.warn=t.info=t.debug=t.trace=t),r.enabled===!1&&(r.level="silent");const f=r.level||"info",h=Object.create(t);h.log||(h.log=of),Object.defineProperty(h,"levelVal",{get:g}),Object.defineProperty(h,"level",{get:w,set:M});const u={transmit:e,serialize:n,asObject:r.browser.asObject,levels:a,timestamp:xS(r)};h.levels=Xn.levels,h.level=f,h.setMaxListeners=h.getMaxListeners=h.emit=h.addListener=h.on=h.prependListener=h.once=h.prependOnceListener=h.removeListener=h.removeAllListeners=h.listeners=h.listenerCount=h.eventNames=h.write=h.flush=of,h.serializers=i,h._serialize=n,h._stdErrSerialize=s,h.child=C,e&&(h._logEvent=l0());function g(){return this.level==="silent"?1/0:this.levels.values[this.level]}function w(){return this._level}function M(O){if(O!=="silent"&&!this.levels.values[O])throw Error("unknown level "+O);this._level=O,ka(u,h,"error","log"),ka(u,h,"fatal","error"),ka(u,h,"warn","error"),ka(u,h,"info","log"),ka(u,h,"debug","log"),ka(u,h,"trace","log")}function C(O,$){if(!O)throw new Error("missing bindings for child Pino");$=$||{},n&&O.serializers&&($.serializers=O.serializers);const j=$.serializers;if(n&&j){var H=Object.assign({},i,j),F=r.browser.serialize===!0?Object.keys(H):n;delete O.serializers,Zl([O],F,H,this._stdErrSerialize)}function G(B){this._childLevel=(B._childLevel|0)+1,this.error=ja(B,O,"error"),this.fatal=ja(B,O,"fatal"),this.warn=ja(B,O,"warn"),this.info=ja(B,O,"info"),this.debug=ja(B,O,"debug"),this.trace=ja(B,O,"trace"),H&&(this.serializers=H,this._serialize=F),e&&(this._logEvent=l0([].concat(B._logEvent.bindings,O)))}return G.prototype=this,new G(this)}return h}Xn.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},Xn.stdSerializers=vS,Xn.stdTimeFunctions=Object.assign({},{nullTime:Tb,epochTime:$b,unixTime:AS,isoTime:ES});function ka(r,e,t,i){const n=Object.getPrototypeOf(e);e[t]=e.levelVal>e.levels.values[t]?of:n[t]?n[t]:sf[t]||sf[i]||of,bS(r,e,t)}function bS(r,e,t){!r.transmit&&e[t]===of||(e[t]=function(i){return function(){const s=r.timestamp(),a=new Array(arguments.length),f=Object.getPrototypeOf&&Object.getPrototypeOf(this)===sf?sf:this;for(var h=0;h-1&&s in t&&(r[n][s]=t[s](r[n][s]))}function ja(r,e,t){return function(){const i=new Array(1+arguments.length);i[0]=e;for(var n=1;nthis.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}}class Lb{constructor(e,t=u0){this.level=e??"error",this.levelValue=Zn.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Nb(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===Zn.levels.values.error?console.error(e):t===Zn.levels.values.warn?console.warn(e):t===Zn.levels.values.debug?console.debug(e):t===Zn.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(bs({timestamp:new Date().toISOString(),log:e}));const t=typeof e=="string"?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new Nb(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(bs({extraMetadata:e})),new Blob(t,{type:"application/json"})}}class CS{constructor(e,t=u0){this.baseChunkLogger=new Lb(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=t,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}}class PS{constructor(e,t=u0){this.baseChunkLogger=new Lb(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var DS=Object.defineProperty,OS=Object.defineProperties,RS=Object.getOwnPropertyDescriptors,Bb=Object.getOwnPropertySymbols,TS=Object.prototype.hasOwnProperty,$S=Object.prototype.propertyIsEnumerable,Fb=(r,e,t)=>e in r?DS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,eh=(r,e)=>{for(var t in e||(e={}))TS.call(e,t)&&Fb(r,t,e[t]);if(Bb)for(var t of Bb(e))$S.call(e,t)&&Fb(r,t,e[t]);return r},th=(r,e)=>OS(r,RS(e));function rh(r){return th(eh({},r),{level:r?.level||IS.level})}function NS(r,e=af){return r[e]||""}function LS(r,e,t=af){return r[t]=e,r}function yi(r,e=af){let t="";return typeof r.bindings>"u"?t=NS(r,e):t=r.bindings().context||"",t}function BS(r,e,t=af){const i=yi(r,t);return i.trim()?`${i}/${e}`:e}function ci(r,e,t=af){const i=BS(r,e,t),n=r.child({context:i});return LS(n,i,t)}function FS(r){var e,t;const i=new CS((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:Zn(th(eh({},r.opts),{level:"trace",browser:th(eh({},(t=r.opts)==null?void 0:t.browser),{write:n=>i.write(n)})})),chunkLoggerController:i}}function US(r){var e;const t=new PS((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:Zn(th(eh({},r.opts),{level:"trace"})),chunkLoggerController:t}}function qS(r){return typeof r.loggerOverride<"u"&&typeof r.loggerOverride!="string"?{logger:r.loggerOverride,chunkLoggerController:null}:typeof window<"u"?FS(r):US(r)}class zS extends Lo{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class HS extends Lo{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}}class kS{constructor(e,t){this.logger=e,this.core=t}}class jS extends Lo{constructor(e,t){super(),this.relayer=e,this.logger=t}}class WS extends Lo{constructor(e){super()}}class KS{constructor(e,t,i,n){this.core=e,this.logger=t,this.name=i}}class VS extends Lo{constructor(e,t){super(),this.relayer=e,this.logger=t}}class GS extends Lo{constructor(e,t){super(),this.core=e,this.logger=t}}class YS{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}}class JS{constructor(e,t){this.projectId=e,this.logger=t}}class QS{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}}class ZS{constructor(e){this.opts=e,this.protocol="wc",this.version=2}}class XS{constructor(e){this.client=e}}function eI(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function Ub(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const qb=Ub("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),d0=Ub("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=eI(r.length);for(let t=0;tt.code===r);return e||cf[Hb]}function jb(r,e,t){return r.message.includes("getaddrinfo ENOTFOUND")||r.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${t} RPC url at ${e}`):r}var Wb={};/*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any +@@ -40,23 +40,23 @@ + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. +- ***************************************************************************** */var d0=function(r,e){return d0=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])},d0(r,e)};function nI(r,e){d0(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var p0=function(){return p0=Object.assign||function(e){for(var t,i=1,n=arguments.length;i=0;f--)(a=r[f])&&(s=(n<3?a(s):n>3?a(e,t,s):a(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}function aI(r,e){return function(t,i){e(t,i,r)}}function cI(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function fI(r,e,t,i){function n(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function f(g){try{u(i.next(g))}catch(w){a(w)}}function h(g){try{u(i.throw(g))}catch(w){a(w)}}function u(g){g.done?s(g.value):n(g.value).then(f,h)}u((i=i.apply(r,e||[])).next())})}function lI(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,a;return a={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function f(u){return function(g){return h([u,g])}}function h(u){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,n=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Kb(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(f){a={error:f}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s}function dI(){for(var r=[],e=0;e1||f(P,M)})})}function f(P,M){try{h(i[P](M))}catch(O){w(s[0][3],O)}}function h(P){P.value instanceof cf?Promise.resolve(P.value.v).then(u,g):w(s[0][2],P)}function u(P){f("next",P)}function g(P){f("throw",P)}function w(P,M){P(M),s.shift(),s.length&&f(s[0][0],s[0][1])}}function vI(r){var e,t;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=r[n]?function(a){return(t=!t)?{value:cf(r[n](a)),done:n==="return"}:s?s(a):a}:s}}function mI(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof g0=="function"?g0(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=r[s]&&function(a){return new Promise(function(f,h){a=r[s](a),n(f,h,a.done,a.value)})}}function n(s,a,f,h){Promise.resolve(h).then(function(u){s({value:u,done:f})},a)}}function bI(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function wI(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function yI(r){return r&&r.__esModule?r:{default:r}}function _I(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function xI(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var AI=Object.freeze({__proto__:null,__extends:nI,get __assign(){return p0},__rest:sI,__decorate:oI,__param:aI,__metadata:cI,__awaiter:fI,__generator:lI,__createBinding:hI,__exportStar:uI,__values:g0,__read:Kb,__spread:dI,__spreadArrays:pI,__await:cf,__asyncGenerator:gI,__asyncDelegator:vI,__asyncValues:mI,__makeTemplateObject:bI,__importStar:wI,__importDefault:yI,__classPrivateFieldGet:_I,__classPrivateFieldSet:xI}),EI=zu(AI),xs={},Vb;function SI(){if(Vb)return xs;Vb=1,Object.defineProperty(xs,"__esModule",{value:!0}),xs.isBrowserCryptoAvailable=xs.getSubtleCrypto=xs.getBrowerCrypto=void 0;function r(){return fr?.crypto||fr?.msCrypto||{}}xs.getBrowerCrypto=r;function e(){const i=r();return i.subtle||i.webkitSubtle}xs.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return xs.isBrowserCryptoAvailable=t,xs}var As={},Gb;function II(){if(Gb)return As;Gb=1,Object.defineProperty(As,"__esModule",{value:!0}),As.isBrowser=As.isNode=As.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}As.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}As.isNode=e;function t(){return!r()&&!e()}return As.isBrowser=t,As}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=EI;e.__exportStar(SI(),r),e.__exportStar(II(),r)})(Wb);function Gs(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function Lo(r=6){return BigInt(Gs(r))}function Ys(r,e,t){return{id:t||Gs(),jsonrpc:"2.0",method:r,params:e}}function th(r,e){return{id:r,jsonrpc:"2.0",result:e}}function rh(r,e,t){return{id:r,jsonrpc:"2.0",error:MI(e,t)}}function MI(r,e){return typeof r>"u"?kb(zb):(typeof r=="string"&&(r=Object.assign(Object.assign({},kb(u0)),{message:r})),typeof e<"u"&&(r.data=e),rI(r.code)&&(r=iI(r.code)),r)}class CI{}class PI extends CI{constructor(){super()}}class DI extends PI{constructor(e){super()}}const OI="^https?:",RI="^wss?:";function TI(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Yb(r,e){const t=TI(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Jb(r){return Yb(r,OI)}function Qb(r){return Yb(r,RI)}function $I(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function Zb(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function v0(r){return Zb(r)&&"method"in r}function ih(r){return Zb(r)&&(Xn(r)||tn(r))}function Xn(r){return"result"in r}function tn(r){return"error"in r}class rn extends DI{constructor(e){super(e),this.events=new qr.exports.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(Ys(e.method,e.params||[],e.id||Lo().toString()),t)}async requestStrict(e,t){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{tn(s)?n(s.error):i(s.result)});try{await this.connection.send(e,t)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ih(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&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(),typeof e=="string"&&(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 NI=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),LI=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Xb=r=>r.split("?")[0],e2=10,BI=NI();class FI{constructor(e){if(this.url=e,this.events=new qr.exports.EventEmitter,this.registering=!1,!Qb(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}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)=>{if(typeof this.socket>"u"){t(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ws(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Qb(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const n=new URLSearchParams(e).get("origin"),s=Wb.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!$I(e)},a=new BI(e,[],s);LI()?a.onerror=f=>{const h=f;i(this.emitError(h.error))}:a.on("error",f=>{i(this.emitError(f))}),a.onopen=()=>{this.onOpen(a),t(a)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),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(typeof e.data>"u")return;const t=typeof e.data=="string"?Po(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),n=i.message||i.toString(),s=rh(e,n);this.events.emit("payload",s)}parseError(e,t=this.url){return jb(e,Xb(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>e2&&this.events.setMaxListeners(e2)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Xb(this.url)}`));return this.events.emit("register_error",t),t}}var m0={exports:{}};(function(r,e){var t=200,i="__lodash_hash_undefined__",n=1,s=2,a=9007199254740991,f="[object Arguments]",h="[object Array]",u="[object AsyncFunction]",g="[object Boolean]",w="[object Date]",P="[object Error]",M="[object Function]",O="[object GeneratorFunction]",$="[object Map]",W="[object Number]",H="[object Null]",F="[object Object]",Y="[object Promise]",B="[object Proxy]",z="[object RegExp]",j="[object Set]",_="[object String]",U="[object Symbol]",ee="[object Undefined]",oe="[object WeakMap]",L="[object ArrayBuffer]",b="[object DataView]",m="[object Float32Array]",l="[object Float64Array]",d="[object Int8Array]",y="[object Int16Array]",C="[object Int32Array]",D="[object Uint8Array]",S="[object Uint8ClampedArray]",v="[object Uint16Array]",A="[object Uint32Array]",x=/[\\^$.*+?()[\]{}|]/g,N=/^\[object .+?Constructor\]$/,ae=/^(?:0|[1-9]\d*)$/,R={};R[m]=R[l]=R[d]=R[y]=R[C]=R[D]=R[S]=R[v]=R[A]=!0,R[f]=R[h]=R[L]=R[g]=R[b]=R[w]=R[P]=R[M]=R[$]=R[W]=R[F]=R[z]=R[j]=R[_]=R[oe]=!1;var X=typeof fr=="object"&&fr&&fr.Object===Object&&fr,V=typeof self=="object"&&self&&self.Object===Object&&self,J=X||V||Function("return this")(),K=e&&!e.nodeType&&e,E=K&&!0&&r&&!r.nodeType&&r,G=E&&E.exports===K,re=G&&X.process,le=function(){try{return re&&re.binding&&re.binding("util")}catch{}}(),he=le&&le.isTypedArray;function ge(Q,ne){for(var pe=-1,Ue=Q==null?0:Q.length,Xt=0,bt=[];++pe-1}function ei(Q,ne){var pe=this.__data__,Ue=ra(pe,Q);return Ue<0?(++this.size,pe.push([Q,ne])):pe[Ue][1]=ne,this}_t.prototype.clear=qt,_t.prototype.delete=Qr,_t.prototype.get=Zr,_t.prototype.has=Xr,_t.prototype.set=ei;function vr(Q){var ne=-1,pe=Q==null?0:Q.length;for(this.clear();++neEr))return!1;var er=bt.get(Q);if(er&&bt.get(ne))return er==ne;var _r=-1,Ii=!0,Sr=pe&s?new Si:void 0;for(bt.set(Q,ne),bt.set(ne,Q);++_r-1&&Q%1==0&&Q-1&&Q%1==0&&Q<=a}function eu(Q){var ne=typeof Q;return Q!=null&&(ne=="object"||ne=="function")}function sa(Q){return Q!=null&&typeof Q=="object"}var tu=he?Xe(he):Hh;function Qp(Q){return Yp(Q)?qh(Q):kh(Q)}function Zt(){return[]}function Qt(){return!1}r.exports=Jp})(m0,m0.exports);var UI=m0.exports,qI=Object.defineProperty,t2=Object.getOwnPropertySymbols,zI=Object.prototype.hasOwnProperty,HI=Object.prototype.propertyIsEnumerable,r2=(r,e,t)=>e in r?qI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ci=(r,e)=>{for(var t in e||(e={}))zI.call(e,t)&&r2(r,t,e[t]);if(t2)for(var t of t2(e))HI.call(e,t)&&r2(r,t,e[t]);return r};const i2="wc",n2=2,b0="core",es=`${i2}@2:${b0}:`,kI={name:b0,logger:"error"},jI={database:":memory:"},WI="crypto",s2="client_ed25519_seed",KI=Ae.ONE_DAY,VI="keychain",GI="0.3",YI="messages",JI="0.3",QI=Ae.SIX_HOURS,ZI="publisher",o2="irn",XI="error",a2="wss://relay.walletconnect.org",eM="relayer",fi={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},tM="_subscription",nn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},rM=.1,w0="2.17.2",sr={link_mode:"link_mode",relay:"relay"},iM="0.3",nM="WALLETCONNECT_CLIENT_ID",c2="WALLETCONNECT_LINK_MODE_APPS",ts={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},sM="subscription",oM="0.3",aM=Ae.FIVE_SECONDS*1e3,cM="pairing",fM="0.3",ff={wc_pairingDelete:{req:{ttl:Ae.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Ae.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Ae.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Ae.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Ae.ONE_DAY,prompt:!1,tag:0},res:{ttl:Ae.ONE_DAY,prompt:!1,tag:0}}},Bo={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},An={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},lM="history",hM="0.3",uM="expirer",sn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},dM="0.3",pM="verify-api",gM="https://verify.walletconnect.com",f2="https://verify.walletconnect.org",lf=f2,vM=`${lf}/v3`,mM=[gM,f2],bM="echo",wM="https://echo.walletconnect.com",rs={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Es={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},En={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Fo={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Uo={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},hf={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},yM=.1,_M="event-client",xM=86400,AM="https://pulse.walletconnect.org/batch";function EM(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i>>0,B=new Uint8Array(Y);H!==F;){for(var z=O[H],j=0,_=Y-1;(z!==0||j>>0,B[_]=z%f>>>0,z=z/f>>>0;if(z!==0)throw new Error("Non-zero carry");W=j,H++}for(var U=Y-W;U!==Y&&B[U]===0;)U++;for(var ee=h.repeat($);U>>0,Y=new Uint8Array(F);O[$];){var B=t[O.charCodeAt($)];if(B===255)return;for(var z=0,j=F-1;(B!==0||z>>0,Y[j]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");H=z,$++}if(O[$]!==" "){for(var _=F-H;_!==F&&Y[_]===0;)_++;for(var U=new Uint8Array(W+(F-_)),ee=W;_!==F;)U[ee++]=Y[_++];return U}}}function M(O){var $=P(O);if($)return $;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:P,decode:M}}var SM=EM,IM=SM;const l2=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},MM=r=>new TextEncoder().encode(r),CM=r=>new TextDecoder().decode(r);class PM{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class DM{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return h2(this,e)}}class OM{constructor(e){this.decoders=e}or(e){return h2(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const h2=(r,e)=>new OM(ci(ci({},r.decoders||{[r.prefix]:r}),e.decoders||{[e.prefix]:e}));class RM{constructor(e,t,i,n){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=n,this.encoder=new PM(e,t,i),this.decoder=new DM(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const nh=({name:r,prefix:e,encode:t,decode:i})=>new RM(r,e,t,i),uf=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:n}=IM(t,e);return nh({prefix:r,name:e,encode:i,decode:s=>l2(n(s))})},TM=(r,e,t,i)=>{const n={};for(let g=0;g=8&&(f-=8,a[u++]=255&h>>f)}if(f>=t||255&h<<8-f)throw new SyntaxError("Unexpected end of data");return a},$M=(r,e,t)=>{const i=e[e.length-1]==="=",n=(1<t;)a-=t,s+=e[n&f>>a];if(a&&(s+=e[n&f<nh({prefix:e,name:r,encode(n){return $M(n,i,t)},decode(n){return TM(n,i,t,r)}}),NM=nh({prefix:"\0",name:"identity",encode:r=>CM(r),decode:r=>MM(r)});var LM=Object.freeze({__proto__:null,identity:NM});const BM=Wr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var FM=Object.freeze({__proto__:null,base2:BM});const UM=Wr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qM=Object.freeze({__proto__:null,base8:UM});const zM=uf({prefix:"9",name:"base10",alphabet:"0123456789"});var HM=Object.freeze({__proto__:null,base10:zM});const kM=Wr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),jM=Wr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var WM=Object.freeze({__proto__:null,base16:kM,base16upper:jM});const KM=Wr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),VM=Wr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),GM=Wr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),YM=Wr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),JM=Wr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),QM=Wr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ZM=Wr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),XM=Wr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),eC=Wr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var tC=Object.freeze({__proto__:null,base32:KM,base32upper:VM,base32pad:GM,base32padupper:YM,base32hex:JM,base32hexupper:QM,base32hexpad:ZM,base32hexpadupper:XM,base32z:eC});const rC=uf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),iC=uf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var nC=Object.freeze({__proto__:null,base36:rC,base36upper:iC});const sC=uf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),oC=uf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var aC=Object.freeze({__proto__:null,base58btc:sC,base58flickr:oC});const cC=Wr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fC=Wr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lC=Wr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hC=Wr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var uC=Object.freeze({__proto__:null,base64:cC,base64pad:fC,base64url:lC,base64urlpad:hC});const u2=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),dC=u2.reduce((r,e,t)=>(r[t]=e,r),[]),pC=u2.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function gC(r){return r.reduce((e,t)=>(e+=dC[t],e),"")}function vC(r){const e=[];for(const t of r){const i=pC[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const mC=nh({prefix:"\u{1F680}",name:"base256emoji",encode:gC,decode:vC});var bC=Object.freeze({__proto__:null,base256emoji:mC}),wC=p2,d2=128,yC=127,_C=~yC,xC=Math.pow(2,31);function p2(r,e,t){e=e||[],t=t||0;for(var i=t;r>=xC;)e[t++]=r&255|d2,r/=128;for(;r&_C;)e[t++]=r&255|d2,r>>>=7;return e[t]=r|0,p2.bytes=t-i+1,e}var AC=y0,EC=128,g2=127;function y0(r,i){var t=0,i=i||0,n=0,s=i,a,f=r.length;do{if(s>=f)throw y0.bytes=0,new RangeError("Could not decode varint");a=r[s++],t+=n<28?(a&g2)<=EC);return y0.bytes=s-i,t}var SC=Math.pow(2,7),IC=Math.pow(2,14),MC=Math.pow(2,21),CC=Math.pow(2,28),PC=Math.pow(2,35),DC=Math.pow(2,42),OC=Math.pow(2,49),RC=Math.pow(2,56),TC=Math.pow(2,63),$C=function(r){return r(v2.encode(r,e,t),e),b2=r=>v2.encodingLength(r),_0=(r,e)=>{const t=e.byteLength,i=b2(r),n=i+b2(t),s=new Uint8Array(n+t);return m2(r,s,0),m2(t,s,i),s.set(e,n),new LC(r,t,e,s)};class LC{constructor(e,t,i,n){this.code=e,this.size=t,this.digest=i,this.bytes=n}}const w2=({name:r,code:e,encode:t})=>new BC(r,e,t);class BC{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?_0(this.code,t):t.then(i=>_0(this.code,i))}else throw Error("Unknown type, must be binary type")}}const y2=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),FC=w2({name:"sha2-256",code:18,encode:y2("SHA-256")}),UC=w2({name:"sha2-512",code:19,encode:y2("SHA-512")});var qC=Object.freeze({__proto__:null,sha256:FC,sha512:UC});const _2=0,zC="identity",x2=l2;var HC=Object.freeze({__proto__:null,identity:{code:_2,name:zC,encode:x2,digest:r=>_0(_2,x2(r))}});new TextEncoder,new TextDecoder;const A2=ci(ci(ci(ci(ci(ci(ci(ci(ci(ci({},LM),FM),qM),HM),WM),tC),nC),aC),uC),bC);ci(ci({},qC),HC);function kC(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function E2(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const S2=E2("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),x0=E2("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=kC(r.length);for(let t=0;t{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()},this.get=i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=_e("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=ai(t,this.name)}get context(){return yi(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,jm(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Wm(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class VC{constructor(e,t,i){this.core=e,this.logger=t,this.name=WI,this.randomSessionIdentifier=Zd(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=n=>(this.isInitialized(),this.keychain.has(n)),this.getClientId=async()=>{this.isInitialized();const n=await this.getClientSeed(),s=Lm(n);return Nm(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=CA();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const s=await this.getClientSeed(),a=Lm(s),f=this.randomSessionIdentifier;return await Fx(f,n,KI,a)},this.generateSharedKey=(n,s,a)=>{this.isInitialized();const f=this.getPrivateKey(n),h=PA(f,s);return this.setSymKey(h,a)},this.setSymKey=async(n,s)=>{this.isInitialized();const a=s||kl(n);return await this.keychain.set(a,n),a},this.deleteKeyPair=async n=>{this.isInitialized(),await this.keychain.del(n)},this.deleteSymKey=async n=>{this.isInitialized(),await this.keychain.del(n)},this.encode=async(n,s,a)=>{this.isInitialized();const f=fb(a),h=ws(s);if(hb(f))return OA(h,a?.encoding);if(lb(f)){const P=f.senderPublicKey,M=f.receiverPublicKey;n=await this.generateSharedKey(P,M)}const u=this.getSymKey(n),{type:g,senderPublicKey:w}=f;return DA({type:g,symKey:u,message:h,senderPublicKey:w,encoding:a?.encoding})},this.decode=async(n,s,a)=>{this.isInitialized();const f=$A(s,a);if(hb(f)){const h=TA(s,a?.encoding);return Po(h)}if(lb(f)){const h=f.receiverPublicKey,u=f.senderPublicKey;n=await this.generateSharedKey(h,u)}try{const h=this.getSymKey(n),u=RA({symKey:h,encoded:s,encoding:a?.encoding});return Po(u)}catch(h){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=(n,s=Vs)=>{const a=Qc({encoded:n,encoding:s});return To(a.type)},this.getPayloadSenderPublicKey=(n,s=Vs)=>{const a=Qc({encoded:n,encoding:s});return a.senderPublicKey?JS(a.senderPublicKey,si):void 0},this.core=e,this.logger=ai(t,this.name),this.keychain=i||new KC(this.core,this.logger)}get context(){return yi(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(s2)}catch{e=Zd(),await this.keychain.set(s2,e)}return WC(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class GC extends BS{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=YI,this.version=JI,this.initialized=!1,this.storagePrefix=es,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,n)=>{this.isInitialized();const s=_s(n);let a=this.messages.get(i);return typeof a>"u"&&(a={}),typeof a[s]<"u"||(a[s]=n,this.messages.set(i,a),await this.persist()),s},this.get=i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n},this.has=(i,n)=>{this.isInitialized();const s=this.get(i),a=_s(n);return typeof s[a]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=ai(e,this.name),this.core=t}get context(){return yi(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,jm(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Wm(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class YC extends FS{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new qr.exports.EventEmitter,this.name=ZI,this.queue=new Map,this.publishTimeout=Ae.toMiliseconds(Ae.ONE_MINUTE),this.failedPublishTimeout=Ae.toMiliseconds(Ae.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(i,n,s)=>{var a;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const f=s?.ttl||QI,h=Xd(s),u=s?.prompt||!1,g=s?.tag||0,w=s?.id||Lo().toString(),P={topic:i,message:n,opts:{ttl:f,relay:h,prompt:u,tag:g,id:w,attestation:s?.attestation}},M=`Failed to publish payload, please try again. id:${w} tag:${g}`,O=Date.now();let $,W=1;try{for(;$===void 0;){if(Date.now()-O>this.publishTimeout)throw new Error(M);this.logger.trace({id:w,attempts:W},`publisher.publish - attempt ${W}`),$=await await Ua(this.rpcPublish(i,n,f,h,u,g,w,s?.attestation).catch(H=>this.logger.warn(H)),this.publishTimeout,M),W++,$||await new Promise(H=>setTimeout(H,this.failedPublishTimeout))}this.relayer.events.emit(fi.publish,P),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:w,topic:i,message:n,opts:s}})}catch(H){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(H),(a=s?.internal)!=null&&a.throwOnFailedPublish)throw H;this.queue.set(w,P)}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.relayer=e,this.logger=ai(t,this.name),this.registerEventListeners()}get context(){return yi(this.logger)}rpcPublish(e,t,i,n,s,a,f,h){var u,g,w,P;const M={method:Zc(n.protocol).publish,params:{topic:e,message:t,ttl:i,prompt:s,tag:a,attestation:h},id:f};return oi((u=M.params)==null?void 0:u.prompt)&&((g=M.params)==null||delete g.prompt),oi((w=M.params)==null?void 0:w.tag)&&((P=M.params)==null||delete P.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:M}),this.relayer.request(M)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:t,message:i,opts:n}=e;await this.publish(t,i,n)})}registerEventListeners(){this.relayer.core.heartbeat.on(za.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(fi.connection_stalled);return}this.checkQueue()}),this.relayer.on(fi.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class JC{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,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"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const n=i.filter(s=>s!==t);if(!n.length){this.map.delete(e);return}this.map.set(e,n)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var QC=Object.defineProperty,ZC=Object.defineProperties,XC=Object.getOwnPropertyDescriptors,I2=Object.getOwnPropertySymbols,eP=Object.prototype.hasOwnProperty,tP=Object.prototype.propertyIsEnumerable,M2=(r,e,t)=>e in r?QC(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,df=(r,e)=>{for(var t in e||(e={}))eP.call(e,t)&&M2(r,t,e[t]);if(I2)for(var t of I2(e))tP.call(e,t)&&M2(r,t,e[t]);return r},A0=(r,e)=>ZC(r,XC(e));class rP extends zS{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new JC,this.events=new qr.exports.EventEmitter,this.name=sM,this.version=oM,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=es,this.subscribeTimeout=Ae.toMiliseconds(Ae.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId(),await this.restore()),this.initialized=!0},this.subscribe=async(i,n)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=Xd(n),a={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,a);const f=await this.rpcSubscribe(i,s,n);return typeof f=="string"&&(this.onSubscribe(f,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),f}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)},this.isSubscribed=async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((s,a)=>{const f=new Ae.Watch;f.start(n);const h=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(h),f.stop(n),s(!0)),f.elapsed(n)>=aM&&(clearInterval(h),f.stop(n),a(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=ai(t,this.name),this.clientId=""}get context(){return yi(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 i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const n=Xd(i);await this.rpcUnsubscribe(e,t,n);const s=Gt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,t,i){var n;i?.transportType===sr.relay&&await this.restartToComplete();const s={method:Zc(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const a=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{const f=_s(e+this.clientId);if(i?.transportType===sr.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},Ae.toMiliseconds(Ae.ONE_SECOND)),f;const h=await Ua(this.relayer.request(s).catch(u=>this.logger.warn(u)),this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&a)throw new Error(`Subscribing to ${e} failed, please try again`);return h?f:null}catch(f){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(fi.connection_stalled),a)throw f}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:Zc(t.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await Ua(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)}catch{this.relayer.events.emit(fi.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:Zc(t.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Ua(this.relayer.request(i).catch(s=>this.logger.warn(s)),this.subscribeTimeout)}catch{this.relayer.events.emit(fi.connection_stalled)}return n}rpcUnsubscribe(e,t,i){const n={method:Zc(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,t){this.setSubscription(e,A0(df({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,df({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),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.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,df({},t)),this.topicMap.set(t.topic,e),this.events.emit(ts.created,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:i}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(ts.deleted,A0(df({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ts.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:t}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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);Jn(t)&&this.onBatchSubscribe(t.map((i,n)=>A0(df({},e[n]),{id:i})))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(t.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(za.pulse,async()=>{await this.checkPending()}),this.events.on(ts.created,async e=>{const t=ts.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(ts.deleted,async e=>{const t=ts.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen(),this.restartInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.restartInProgress||(clearInterval(t),e())},this.pollingInterval)})}}var iP=Object.defineProperty,C2=Object.getOwnPropertySymbols,nP=Object.prototype.hasOwnProperty,sP=Object.prototype.propertyIsEnumerable,P2=(r,e,t)=>e in r?iP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,D2=(r,e)=>{for(var t in e||(e={}))nP.call(e,t)&&P2(r,t,e[t]);if(C2)for(var t of C2(e))sP.call(e,t)&&P2(r,t,e[t]);return r};class oP extends US{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new qr.exports.EventEmitter,this.name=eM,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=Ae.toMiliseconds(Ae.THIRTY_SECONDS+Ae.ONE_SECOND),this.request=async t=>{var i,n;this.logger.debug("Publishing Request Payload");const s=t.id||Lo().toString();await this.toEstablishConnection();try{const a=this.provider.request(t);this.requestsInFlight.set(s,{promise:a,request:t}),this.logger.trace({id:s,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - attempt to publish...");const f=await new Promise(async(h,u)=>{const g=()=>{u(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(nn.disconnect,g);const w=await a;this.provider.off(nn.disconnect,g),h(w)});return this.logger.trace({id:s,method:t.method,topic:(n=t.params)==null?void 0:n.topic},"relayer.request - published"),f}catch(a){throw this.logger.debug(`Failed to Publish Request: ${s}`),a}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(Ul())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,n;(n=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null||n.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t)}},this.onPayloadHandler=t=>{this.onProviderPayload(t),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.trace("relayer connected"),this.startPingTimeout(),this.events.emit(fi.connect)},this.onDisconnectHandler=()=>{this.logger.trace("relayer disconnected"),this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.error(t),this.events.emit(fi.error,t),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(nn.payload,this.onPayloadHandler),this.provider.on(nn.connect,this.onConnectHandler),this.provider.on(nn.disconnect,this.onDisconnectHandler),this.provider.on(nn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ai(e.logger,this.name):Qn(eh({level:e.logger||XI})),this.messages=new GC(this.logger,e.core),this.subscriber=new rP(this,this.logger),this.publisher=new YC(this,this.logger),this.relayUrl=e?.relayUrl||a2,this.projectId=e.projectId,this.bundleId=Kx(),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e)}}get context(){return yi(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:sr.relay})}async subscribe(e,t){var i,n,s;this.isInitialized(),t?.transportType==="relay"&&await this.toEstablishConnection();const a=typeof((i=t?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=t?.internal)==null?void 0:n.throwOnFailedPublish;let f=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",h;const u=g=>{g.topic===e&&(this.subscriber.off(ts.created,u),h())};return await Promise.all([new Promise(g=>{h=g,this.subscriber.on(ts.created,u)}),new Promise(async(g,w)=>{f=await this.subscriber.subscribe(e,D2({internal:{throwOnFailedPublish:a}},t)).catch(P=>{a&&w(P)})||f,g()})]),f}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 transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Ua(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(t,i)=>{const n=()=>{this.provider.off(nn.disconnect,n),i(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(nn.disconnect,n),await Ua(this.provider.connect(),Ae.toMiliseconds(Ae.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{i(s)}).finally(()=>{clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),this.subscriber.start().catch(s=>{this.logger.error(s),this.onDisconnectHandler()}),this.hasExperiencedNetworkDisruption=!1,t()})}catch(t){this.logger.error(t);const i=t;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(i.message))throw t}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Eb())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.trace(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const n=Ir(Ae.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(fi.message,e),await this.recordMessageEvent(e)}startPingTimeout(){var e,t,i,n,s;if(Ul())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(a){this.logger.warn(a)}}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 rn(new FI(Jx({sdkVersion:w0,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const n=this.messages.has(t,i);return n&&this.logger.debug(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),v0(e)){if(!e.method.endsWith(tM))return;const t=e.params,{topic:i,message:n,publishedAt:s,attestation:a}=t.data,f={topic:i,message:n,publishedAt:s,transportType:sr.relay,attestation:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(D2({type:"event",event:t.id},f)),this.events.emit(t.id,f),await this.acknowledgePayload(e),await this.onMessageEvent(f)}else ih(e)&&this.events.emit(fi.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(fi.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=th(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(nn.payload,this.onPayloadHandler),this.provider.off(nn.connect,this.onConnectHandler),this.provider.off(nn.disconnect,this.onDisconnectHandler),this.provider.off(nn.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Eb();ME(async t=>{e!==t&&(e=t,t?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(fi.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Ae.toMiliseconds(rM))))}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.connected&&(clearInterval(t),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var aP=Object.defineProperty,O2=Object.getOwnPropertySymbols,cP=Object.prototype.hasOwnProperty,fP=Object.prototype.propertyIsEnumerable,R2=(r,e,t)=>e in r?aP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,T2=(r,e)=>{for(var t in e||(e={}))cP.call(e,t)&&R2(r,t,e[t]);if(O2)for(var t of O2(e))fP.call(e,t)&&R2(r,t,e[t]);return r};class qo extends qS{constructor(e,t,i,n=es,s=void 0){super(e,t,i,n),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version=iM,this.cached=[],this.initialized=!1,this.storagePrefix=es,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(a=>{this.getKey&&a!==null&&!oi(a)?this.map.set(this.getKey(a),a):nE(a)?this.map.set(a.id,a):sE(a)&&this.map.set(a.topic,a)}),this.cached=[],this.initialized=!0)},this.set=async(a,f)=>{this.isInitialized(),this.map.has(a)?await this.update(a,f):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:a,value:f}),this.map.set(a,f),await this.persist())},this.get=a=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:a}),this.getData(a)),this.getAll=a=>(this.isInitialized(),a?this.values.filter(f=>Object.keys(a).every(h=>UI(f[h],a[h]))):this.values),this.update=async(a,f)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:a,update:f});const h=T2(T2({},this.getData(a)),f);this.map.set(a,h),await this.persist()},this.delete=async(a,f)=>{this.isInitialized(),this.map.has(a)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:a,reason:f}),this.map.delete(a),this.addToRecentlyDeleted(a),await this.persist())},this.logger=ai(t,this.name),this.storagePrefix=n,this.getKey=s}get context(){return yi(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())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}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){if(this.recentlyDeleted.includes(e)){const{message:n}=_e("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}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:t}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class lP{constructor(e,t){this.core=e,this.logger=t,this.name=cM,this.version=fM,this.events=new qr.exports,this.initialized=!1,this.storagePrefix=es,this.ignoredPayloadTypes=[ys],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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async i=>{this.isInitialized();const n=Zd(),s=await this.core.crypto.setSymKey(n),a=Ir(Ae.FIVE_MINUTES),f={protocol:o2},h={topic:s,expiry:a,relay:f,active:!1,methods:i?.methods},u=vb({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:f,expiryTimestamp:a,methods:i?.methods});return this.events.emit(Bo.create,h),this.core.expirer.set(s,a),await this.pairings.set(s,h),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:u}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[rs.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:a,relay:f,expiryTimestamp:h,methods:u}=gb(i.uri);n.props.properties.topic=s,n.addTrace(rs.pairing_uri_validation_success),n.addTrace(rs.pairing_uri_not_expired);let g;if(this.pairings.keys.includes(s)){if(g=this.pairings.get(s),n.addTrace(rs.existing_pairing),g.active)throw n.setError(Es.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(rs.pairing_not_expired)}const w=h||Ir(Ae.FIVE_MINUTES),P={topic:s,relay:f,expiry:w,active:!1,methods:u};this.core.expirer.set(s,w),await this.pairings.set(s,P),n.addTrace(rs.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Bo.create,P),n.addTrace(rs.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(a,s),n.addTrace(rs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Es.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:f})}catch(M){throw n.setError(Es.subscribe_pairing_topic_failure),M}return n.addTrace(rs.subscribe_pairing_topic_success),P},this.activate=async({topic:i})=>{this.isInitialized();const n=Ir(Ae.THIRTY_DAYS);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:a,resolve:f,reject:h}=Oo();this.events.once(Dt("pairing_ping",s),({error:u})=>{u?h(u):f()}),await a()}},this.updateExpiry=async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})},this.updateMetadata=async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",Gt("USER_DISCONNECTED")),await this.deletePairing(n))},this.formatUriFromPairing=i=>{this.isInitialized();const{topic:n,relay:s,expiry:a,methods:f}=i,h=this.core.crypto.keychain.get(n);return vb({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:h,relay:s,expiryTimestamp:a,methods:f})},this.sendRequest=async(i,n,s)=>{const a=Ys(n,s),f=await this.core.crypto.encode(i,a),h=ff[n].req;return this.core.history.set(i,a),this.core.relayer.publish(i,f,h),a.id},this.sendResult=async(i,n,s)=>{const a=th(i,s),f=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),u=ff[h.request.method].res;await this.core.relayer.publish(n,f,u),await this.core.history.resolve(a)},this.sendError=async(i,n,s)=>{const a=rh(i,s),f=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),u=ff[h.request.method]?ff[h.request.method].res:ff.unregistered_method.res;await this.core.relayer.publish(n,f,u),await this.core.history.resolve(a)},this.deletePairing=async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(n=>Ks(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))},this.onRelayEventRequest=i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(n,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(n,s);default:return this.onUnknownRpcMethodRequest(n,s)}},this.onRelayEventResponse=async i=>{const{topic:n,payload:s}=i,a=(await this.core.history.get(n,s.id)).request.method;switch(a){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(a)}},this.onPairingPingRequest=async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Bo.ping,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onPairingPingResponse=(i,n)=>{const{id:s}=n;setTimeout(()=>{Xn(n)?this.events.emit(Dt("pairing_ping",s),{}):tn(n)&&this.events.emit(Dt("pairing_ping",s),{error:n.error})},500)},this.onPairingDeleteRequest=async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Bo.delete,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onUnknownRpcMethodRequest=async(i,n)=>{const{id:s,method:a}=n;try{if(this.registeredMethods.includes(a))return;const f=Gt("WC_METHOD_UNSUPPORTED",a);await this.sendError(s,i,f),this.logger.error(f)}catch(f){await this.sendError(s,i,f),this.logger.error(f)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=(i,n)=>{var s;if(!bi(i)){const{message:f}=_e("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Es.malformed_pairing_uri),new Error(f)}if(!iE(i.uri)){const{message:f}=_e("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Es.malformed_pairing_uri),new Error(f)}const a=gb(i?.uri);if(!((s=a?.relay)!=null&&s.protocol)){const{message:f}=_e("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Es.malformed_pairing_uri),new Error(f)}if(!(a!=null&&a.symKey)){const{message:f}=_e("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Es.malformed_pairing_uri),new Error(f)}if(a!=null&&a.expiryTimestamp&&Ae.toMiliseconds(a?.expiryTimestamp){if(!bi(i)){const{message:s}=_e("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidDisconnect=async i=>{if(!bi(i)){const{message:s}=_e("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidPairingTopic=async i=>{if(!wr(i,!1)){const{message:n}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(Ks(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=_e("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}},this.core=e,this.logger=ai(t,this.name),this.pairings=new qo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yi(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(fi.message,async e=>{const{topic:t,message:i,transportType:n}=e;if(!this.pairings.keys.includes(t)||n===sr.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(t,i);try{v0(s)?(this.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):ih(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:t,payload:s}),this.core.history.delete(t,s.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(sn.expired,async e=>{const{topic:t}=Vm(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Bo.expire,{topic:t}))})}}class hP extends LS{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new qr.exports.EventEmitter,this.name=lM,this.version=hM,this.cached=[],this.initialized=!1,this.storagePrefix=es,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const a={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:Ir(Ae.THIRTY_DAYS)};this.records.set(a.id,a),this.persist(),this.events.emit(An.created,a)},this.resolve=async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=tn(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(An.updated,n))},this.get=async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n)),this.delete=(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(An.deleted,s)}}),this.persist()},this.exists=async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ai(t,this.name)}get context(){return yi(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 i={topic:t.topic,request:Ys(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),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:i}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(An.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(An.created,e=>{const t=An.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(An.updated,e=>{const t=An.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(An.deleted,e=>{const t=An.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(za.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{Ae.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(An.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class uP extends HS{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new qr.exports.EventEmitter,this.name=uM,this.version=dM,this.cached=[],this.initialized=!1,this.storagePrefix=es,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}},this.set=(i,n)=>{this.isInitialized();const s=this.formatTarget(i),a={target:s,expiry:n};this.expirations.set(s,a),this.checkExpiry(s,a),this.events.emit(sn.created,{target:s,expiration:a})},this.get=i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)},this.del=i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(sn.deleted,{target:n,expiration:s})}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ai(t,this.name)}get context(){return yi(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(typeof e=="string")return Qx(e);if(typeof e=="number")return Zx(e);const{message:t}=_e("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(sn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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:i}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;Ae.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(sn.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(za.pulse,()=>this.checkExpirations()),this.events.on(sn.created,e=>{const t=sn.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(sn.expired,e=>{const t=sn.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(sn.deleted,e=>{const t=sn.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class dP extends kS{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,this.name=pM,this.verifyUrlV3=vM,this.storagePrefix=es,this.version=n2,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&Ae.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt){if(!jc()||this.isDevEnv)return;const s=window.location.origin,{id:a,decryptedId:f}=n,h=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${a}&decryptedId=${f}`;try{const u=Dc(),g=this.startAbortTimer(Ae.ONE_SECOND*5),w=await new Promise((P,M)=>{const O=()=>{window.removeEventListener("message",W),u.body.removeChild($),M("attestation aborted")};this.abortController.signal.addEventListener("abort",O);const $=u.createElement("iframe");$.src=h,$.style.display="none",$.addEventListener("error",O,{signal:this.abortController.signal});const W=H=>{if(H.data&&typeof H.data=="string")try{const F=JSON.parse(H.data);if(F.type==="verify_attestation"){if(Vd(F.attestation).payload.id!==a)return;clearInterval(g),u.body.removeChild($),this.abortController.signal.removeEventListener("abort",O),window.removeEventListener("message",W),P(F.attestation===null?"":F.attestation)}}catch(F){this.logger.warn(F)}};u.body.appendChild($),window.addEventListener("message",W,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",w),w}catch(u){this.logger.warn(u)}return""},this.resolve=async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:a,encryptedId:f}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Vd(s).payload.id!==f)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!a)return;const h=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(a,h)},this.fetchAttestation=async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const a=this.startAbortTimer(Ae.ONE_SECOND*5),f=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(a),f.status===200?await f.json():void 0},this.getVerifyUrl=n=>{let s=n||lf;return mM.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${lf}`),s=lf),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(Ae.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}},this.persistPublicKey=async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(f){this.logger.error(f),this.logger.warn("error validating attestation")}const a=await this.fetchAndPersistPublicKey();try{if(a)return this.validateAttestation(n,a)}catch(f){this.logger.error(f),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const a=await this.fetchPublicKey();a&&(await this.persistPublicKey(a),s(a))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n},this.validateAttestation=(n,s)=>{const a=FA(n,s.publicKey),f={hasExpired:Ae.toMiliseconds(a.exp)this.abortController.abort(),Ae.toMiliseconds(e))}}class pP extends jS{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=bM,this.registerDeviceToken=async i=>{const{clientId:n,token:s,notificationType:a,enableEncrypted:f=!1}=i,h=`${wM}/${this.projectId}/clients`;await fetch(h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:a,token:s,always_raw:f})})},this.logger=ai(t,this.context)}}var gP=Object.defineProperty,$2=Object.getOwnPropertySymbols,vP=Object.prototype.hasOwnProperty,mP=Object.prototype.propertyIsEnumerable,N2=(r,e,t)=>e in r?gP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pf=(r,e)=>{for(var t in e||(e={}))vP.call(e,t)&&N2(r,t,e[t]);if($2)for(var t of $2(e))mP.call(e,t)&&N2(r,t,e[t]);return r};class bP extends WS{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,this.context=_M,this.storagePrefix=es,this.storageVersion=yM,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!Gd())try{const n={eventId:Ym(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:km(this.core.relayer.protocol,this.core.relayer.version,w0)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}},this.createEvent=n=>{const{event:s="ERROR",type:a="",properties:{topic:f,trace:h}}=n,u=Ym(),g=this.core.projectId||"",w=Date.now(),P=pf({eventId:u,timestamp:w,props:{event:s,type:a,properties:{topic:f,trace:h}},bundleId:g,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,P),this.shouldPersist=!0),P},this.getEvent=n=>{const{eventId:s,topic:a}=n;if(s)return this.events.get(s);const f=Array.from(this.events.values()).find(h=>h.props.properties.topic===a);if(f)return pf(pf({},f),this.setMethods(f.eventId))},this.deleteEvent=n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(za.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{Ae.fromMiliseconds(Date.now())-Ae.fromMiliseconds(n.timestamp)>xM&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})},this.setMethods=n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)}),this.addTrace=(n,s)=>{const a=this.events.get(n);a&&(a.props.properties.trace.push(s),this.events.set(n,a),this.shouldPersist=!0)},this.setError=(n,s)=>{const a=this.events.get(n);a&&(a.props.type=s,a.timestamp=Date.now(),this.events.set(n,a),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,pf(pf({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,a]of this.events)a.props.type&&n.push(a);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.sendEvent=async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${AM}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${w0}${s}`,{method:"POST",body:JSON.stringify(n)})},this.getAppDomain=()=>Hm().url,this.logger=ai(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var wP=Object.defineProperty,L2=Object.getOwnPropertySymbols,yP=Object.prototype.hasOwnProperty,_P=Object.prototype.propertyIsEnumerable,B2=(r,e,t)=>e in r?wP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,F2=(r,e)=>{for(var t in e||(e={}))yP.call(e,t)&&B2(r,t,e[t]);if(L2)for(var t of L2(e))_P.call(e,t)&&B2(r,t,e[t]);return r};class E0 extends NS{constructor(e){var t;super(e),this.protocol=i2,this.version=n2,this.name=b0,this.events=new qr.exports.EventEmitter,this.initialized=!1,this.on=(a,f)=>this.events.on(a,f),this.once=(a,f)=>this.events.once(a,f),this.off=(a,f)=>this.events.off(a,f),this.removeListener=(a,f)=>this.events.removeListener(a,f),this.dispatchEnvelope=({topic:a,message:f,sessionExists:h})=>{if(!a||!f)return;const u={topic:a,message:f,publishedAt:Date.now(),transportType:sr.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:h})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||a2,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=eh({level:typeof e?.logger=="string"&&e.logger?e.logger:kI.logger}),{logger:n,chunkLoggerController:s}=$S({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,f;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((f=this.logChunkController)==null||f.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ai(n,this.name),this.heartbeat=new n0,this.crypto=new VC(this,this.logger,e?.keychain),this.history=new hP(this,this.logger),this.expirer=new uP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new oS(F2(F2({},jI),e?.storageOptions)),this.relayer=new oP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new lP(this,this.logger),this.verify=new dP(this,this.logger,this.storage),this.echoClient=new pP(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new bP(this,this.logger,e?.telemetryEnabled)}static async init(e){const t=new E0(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(nM,i),t}get context(){return yi(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(c2,this.linkModeSupportedApps))}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.eventClient.init(),this.linkModeSupportedApps=await this.storage.getItem(c2)||[],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 xP=E0,U2="wc",q2=2,z2="client",S0=`${U2}@${q2}:${z2}:`,I0={name:z2,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},H2="WALLETCONNECT_DEEPLINK_CHOICE",AP="proposal",k2="Proposal expired",EP="session",ja=Ae.SEVEN_DAYS,SP="engine",Lr={wc_sessionPropose:{req:{ttl:Ae.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Ae.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Ae.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Ae.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Ae.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Ae.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Ae.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Ae.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Ae.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Ae.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Ae.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Ae.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Ae.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Ae.FIVE_MINUTES,prompt:!1,tag:1119}}},M0={min:Ae.FIVE_MINUTES,max:Ae.SEVEN_DAYS},is={idle:"IDLE",active:"ACTIVE"},IP="request",MP=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],CP="wc",PP="auth",DP="authKeys",OP="pairingTopics",RP="requests",sh=`${CP}@${1.5}:${PP}:`,oh=`${sh}:PUB_KEY`;var TP=Object.defineProperty,$P=Object.defineProperties,NP=Object.getOwnPropertyDescriptors,j2=Object.getOwnPropertySymbols,LP=Object.prototype.hasOwnProperty,BP=Object.prototype.propertyIsEnumerable,W2=(r,e,t)=>e in r?TP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pr=(r,e)=>{for(var t in e||(e={}))LP.call(e,t)&&W2(r,t,e[t]);if(j2)for(var t of j2(e))BP.call(e,t)&&W2(r,t,e[t]);return r},Sn=(r,e)=>$P(r,NP(e));class FP extends VS{constructor(e){super(e),this.name=SP,this.events=new qr.exports,this.initialized=!1,this.requestQueue={state:is.idle,queue:[]},this.sessionRequestQueue={state:is.idle,queue:[]},this.requestQueueDelay=Ae.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Lr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Ae.toMiliseconds(this.requestQueueDelay)))},this.connect=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Sn(pr({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:a,sessionProperties:f,relays:h}=i;let u=n,g,w=!1;try{u&&(w=this.client.core.pairing.pairings.get(u).active)}catch(B){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),B}if(!u||!w){const{topic:B,uri:z}=await this.client.core.pairing.create();u=B,g=z}if(!u){const{message:B}=_e("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(B)}const P=await this.client.core.crypto.generateKeyPair(),M=Lr.wc_sessionPropose.req.ttl||Ae.FIVE_MINUTES,O=Ir(M),$=pr({requiredNamespaces:s,optionalNamespaces:a,relays:h??[{protocol:o2}],proposer:{publicKey:P,metadata:this.client.metadata},expiryTimestamp:O,pairingTopic:u},f&&{sessionProperties:f}),{reject:W,resolve:H,done:F}=Oo(M,k2);this.events.once(Dt("session_connect"),async({error:B,session:z})=>{if(B)W(B);else if(z){z.self.publicKey=P;const j=Sn(pr({},z),{pairingTopic:$.pairingTopic,requiredNamespaces:$.requiredNamespaces,optionalNamespaces:$.optionalNamespaces,transportType:sr.relay});await this.client.session.set(z.topic,j),await this.setExpiry(z.topic,z.expiry),u&&await this.client.core.pairing.updateMetadata({topic:u,metadata:z.peer.metadata}),this.cleanupDuplicatePairings(j),H(j)}});const Y=await this.sendRequest({topic:u,method:"wc_sessionPropose",params:$,throwOnFailedPublish:!0});return await this.setProposal(Y,pr({id:Y},$)),{uri:g,approval:F}},this.pair=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}},this.approve=async t=>{var i,n,s;const a=this.client.core.eventClient.createEvent({properties:{topic:(i=t?.id)==null?void 0:i.toString(),trace:[En.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw a.setError(Fo.no_internet_connection),U}try{await this.isValidProposalId(t?.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),a.setError(Fo.proposal_not_found),U}try{await this.isValidApprove(t)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),a.setError(Fo.session_approve_namespace_validation_failure),U}const{id:f,relayProtocol:h,namespaces:u,sessionProperties:g,sessionConfig:w}=t,P=this.client.proposal.get(f);this.client.core.eventClient.deleteEvent({eventId:a.eventId});const{pairingTopic:M,proposer:O,requiredNamespaces:$,optionalNamespaces:W}=P;let H=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:M});H||(H=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:En.session_approve_started,properties:{topic:M,trace:[En.session_approve_started,En.session_namespaces_validation_success]}}));const F=await this.client.core.crypto.generateKeyPair(),Y=O.publicKey,B=await this.client.core.crypto.generateSharedKey(F,Y),z=pr(pr({relay:{protocol:h??"irn"},namespaces:u,controller:{publicKey:F,metadata:this.client.metadata},expiry:Ir(ja)},g&&{sessionProperties:g}),w&&{sessionConfig:w}),j=sr.relay;H.addTrace(En.subscribing_session_topic);try{await this.client.core.relayer.subscribe(B,{transportType:j})}catch(U){throw H.setError(Fo.subscribe_session_topic_failure),U}H.addTrace(En.subscribe_session_topic_success);const _=Sn(pr({},z),{topic:B,requiredNamespaces:$,optionalNamespaces:W,pairingTopic:M,acknowledged:!1,self:z.controller,peer:{publicKey:O.publicKey,metadata:O.metadata},controller:F,transportType:sr.relay});await this.client.session.set(B,_),H.addTrace(En.store_session);try{H.addTrace(En.publishing_session_settle),await this.sendRequest({topic:B,method:"wc_sessionSettle",params:z,throwOnFailedPublish:!0}).catch(U=>{throw H?.setError(Fo.session_settle_publish_failure),U}),H.addTrace(En.session_settle_publish_success),H.addTrace(En.publishing_session_approve),await this.sendResult({id:f,topic:M,result:{relay:{protocol:h??"irn"},responderPublicKey:F},throwOnFailedPublish:!0}).catch(U=>{throw H?.setError(Fo.session_approve_publish_failure),U}),H.addTrace(En.session_approve_publish_success)}catch(U){throw this.client.logger.error(U),this.client.session.delete(B,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(B),U}return this.client.core.eventClient.deleteEvent({eventId:H.eventId}),await this.client.core.pairing.updateMetadata({topic:M,metadata:O.metadata}),await this.client.proposal.delete(f,Gt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:M}),await this.setExpiry(B,Ir(ja)),{topic:B,acknowledged:()=>Promise.resolve(this.client.session.get(B))}},this.reject=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(a){throw this.client.logger.error("reject() -> isValidReject() failed"),a}const{id:i,reason:n}=t;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(a){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),a}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:Lr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED")))},this.update=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(w){throw this.client.logger.error("update() -> isValidUpdate() failed"),w}const{topic:i,namespaces:n}=t,{done:s,resolve:a,reject:f}=Oo(),h=Gs(),u=Lo().toString(),g=this.client.session.get(i).namespaces;return this.events.once(Dt("session_update",h),({error:w})=>{w?f(w):a()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:h,relayRpcId:u}).catch(w=>{this.client.logger.error(w),this.client.session.update(i,{namespaces:g}),f(w)}),{acknowledged:s}},this.extend=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(h){throw this.client.logger.error("extend() -> isValidExtend() failed"),h}const{topic:i}=t,n=Gs(),{done:s,resolve:a,reject:f}=Oo();return this.events.once(Dt("session_extend",n),({error:h})=>{h?f(h):a()}),await this.setExpiry(i,Ir(ja)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(h=>{f(h)}),{acknowledged:s}},this.request=async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(O){throw this.client.logger.error("request() -> isValidRequest() failed"),O}const{chainId:i,request:n,topic:s,expiry:a=Lr.wc_sessionRequest.req.ttl}=t,f=this.client.session.get(s);f?.transportType===sr.relay&&await this.confirmOnlineStateOrThrow();const h=Gs(),u=Lo().toString(),{done:g,resolve:w,reject:P}=Oo(a,"Request expired. Please try again.");this.events.once(Dt("session_request",h),({error:O,result:$})=>{O?P(O):w($)});const M=this.getAppLinkIfEnabled(f.peer.metadata,f.transportType);return M?(await this.sendRequest({clientRpcId:h,relayRpcId:u,topic:s,method:"wc_sessionRequest",params:{request:Sn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0,appLink:M}).catch(O=>P(O)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),await g()):await Promise.all([new Promise(async O=>{await this.sendRequest({clientRpcId:h,relayRpcId:u,topic:s,method:"wc_sessionRequest",params:{request:Sn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0}).catch($=>P($)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),O()}),new Promise(async O=>{var $;if(!(($=f.sessionConfig)!=null&&$.disableDeepLink)){const W=await tA(this.client.core.storage,H2);await Xx({id:h,topic:s,wcDeepLink:W})}O()}),g()]).then(O=>O[2])},this.respond=async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:n}=t,{id:s}=n,a=this.client.session.get(i);a.transportType===sr.relay&&await this.confirmOnlineStateOrThrow();const f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);Xn(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:f}):tn(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:f}),this.cleanupAfterResponse(t)},this.ping=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=t;if(this.client.session.keys.includes(i)){const n=Gs(),s=Lo().toString(),{done:a,resolve:f,reject:h}=Oo();this.events.once(Dt("session_ping",n),({error:u})=>{u?h(u):f()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),a()])}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:n,chainId:s}=t,a=Lo().toString();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:a})},this.disconnect=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Gt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=_e("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}},this.find=t=>(this.isInitialized(),this.client.session.getAll().filter(i=>tE(i,t))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(t,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(t);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),a=s?sr.link_mode:sr.relay;a===sr.relay&&await this.confirmOnlineStateOrThrow();const{chains:f,statement:h="",uri:u,domain:g,nonce:w,type:P,exp:M,nbf:O,methods:$=[],expiry:W}=t,H=[...t.resources||[]],{topic:F,uri:Y}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:a});this.client.logger.info({message:"Generated new pairing",pairing:{topic:F,uri:Y}});const B=await this.client.core.crypto.generateKeyPair(),z=kl(B);if(await Promise.all([this.client.auth.authKeys.set(oh,{responseTopic:z,publicKey:B}),this.client.auth.pairingTopics.set(z,{topic:z,pairingTopic:F})]),await this.client.core.relayer.subscribe(z,{transportType:a}),this.client.logger.info(`sending request to new pairing topic: ${F}`),$.length>0){const{namespace:D}=Ba(f[0]);let S=xA(D,"request",$);Hl(H)&&(S=EA(S,H.pop())),H.push(S)}const j=W&&W>Lr.wc_sessionAuthenticate.req.ttl?W:Lr.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:P??"caip122",chains:f,statement:h,aud:u,domain:g,version:"1",nonce:w,iat:new Date().toISOString(),exp:M,nbf:O,resources:H},requester:{publicKey:B,metadata:this.client.metadata},expiryTimestamp:Ir(j)},U={eip155:{chains:f,methods:[...new Set(["personal_sign",...$])],events:["chainChanged","accountsChanged"]}},ee={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:F,proposer:{publicKey:B,metadata:this.client.metadata},expiryTimestamp:Ir(Lr.wc_sessionPropose.req.ttl)},{done:oe,resolve:L,reject:b}=Oo(j,"Request expired"),m=async({error:D,session:S})=>{if(this.events.off(Dt("session_request",d),l),D)b(D);else if(S){S.self.publicKey=B,await this.client.session.set(S.topic,S),await this.setExpiry(S.topic,S.expiry),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:S.peer.metadata});const v=this.client.session.get(S.topic);await this.deleteProposal(y),L({session:v})}},l=async D=>{var S,v,A;if(await this.deletePendingAuthRequest(d,{message:"fulfilled",code:0}),D.error){const J=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return D.error.code===J.code?void 0:(this.events.off(Dt("session_connect"),m),b(D.error.message))}await this.deleteProposal(y),this.events.off(Dt("session_connect"),m);const{cacaos:x,responder:N}=D.result,ae=[],R=[];for(const J of x){await Xm({cacao:J,projectId:this.client.core.projectId})||(this.client.logger.error(J,"Signature verification failed"),b(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:K}=J,E=Hl(K.resources),G=[Jd(K.iss)],re=zl(K.iss);if(E){const le=rb(E),he=ib(E);ae.push(...le),G.push(...he)}for(const le of G)R.push(`${le}:${re}`)}const X=await this.client.core.crypto.generateSharedKey(B,N.publicKey);let V;ae.length>0&&(V={topic:X,acknowledged:!0,self:{publicKey:B,metadata:this.client.metadata},peer:N,controller:N.publicKey,expiry:Ir(ja),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:F,namespaces:mb([...new Set(ae)],[...new Set(R)]),transportType:a},await this.client.core.relayer.subscribe(X,{transportType:a}),await this.client.session.set(X,V),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:N.metadata}),V=this.client.session.get(X)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(v=N.metadata.redirect)!=null&&v.linkMode&&(A=N.metadata.redirect)!=null&&A.universal&&i&&(this.client.core.addLinkModeSupportedApp(N.metadata.redirect.universal),this.client.session.update(X,{transportType:sr.link_mode})),L({auths:x,session:V})},d=Gs(),y=Gs();this.events.once(Dt("session_connect"),m),this.events.once(Dt("session_request",d),l);let C;try{if(s){const D=Ys("wc_sessionAuthenticate",_,d);this.client.core.history.set(F,D);const S=await this.client.core.crypto.encode("",D,{type:Yc,encoding:Vc});C=jl(i,F,S)}else await Promise.all([this.sendRequest({topic:F,method:"wc_sessionAuthenticate",params:_,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:d}),this.sendRequest({topic:F,method:"wc_sessionPropose",params:ee,expiry:Lr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:y})])}catch(D){throw this.events.off(Dt("session_connect"),m),this.events.off(Dt("session_request",d),l),D}return await this.setProposal(y,pr({id:y},ee)),await this.setAuthRequest(d,{request:Sn(pr({},_),{verifyContext:{}}),pairingTopic:F,transportType:a}),{uri:C??Y,response:oe}},this.approveSessionAuthenticate=async t=>{const{id:i,auths:n}=t,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Uo.authenticated_session_approve_started]}});try{this.isInitialized()}catch(W){throw s.setError(hf.no_internet_connection),W}const a=this.getPendingAuthRequest(i);if(!a)throw s.setError(hf.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const f=a.transportType||sr.relay;f===sr.relay&&await this.confirmOnlineStateOrThrow();const h=a.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),g=kl(h),w={type:ys,receiverPublicKey:h,senderPublicKey:u},P=[],M=[];for(const W of n){if(!await Xm({cacao:W,projectId:this.client.core.projectId})){s.setError(hf.invalid_cacao);const z=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:g,error:z,encodeOpts:w}),new Error(z.message)}s.addTrace(Uo.cacaos_verified);const{p:H}=W,F=Hl(H.resources),Y=[Jd(H.iss)],B=zl(H.iss);if(F){const z=rb(F),j=ib(F);P.push(...z),Y.push(...j)}for(const z of Y)M.push(`${z}:${B}`)}const O=await this.client.core.crypto.generateSharedKey(u,h);s.addTrace(Uo.create_authenticated_session_topic);let $;if(P?.length>0){$={topic:O,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:h,metadata:a.requester.metadata},controller:h,expiry:Ir(ja),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:a.pairingTopic,namespaces:mb([...new Set(P)],[...new Set(M)]),transportType:f},s.addTrace(Uo.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:f})}catch(W){throw s.setError(hf.subscribe_authenticated_session_topic_failure),W}s.addTrace(Uo.subscribe_authenticated_session_topic_success),await this.client.session.set(O,$),s.addTrace(Uo.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:a.pairingTopic,metadata:a.requester.metadata})}s.addTrace(Uo.publishing_authenticated_session_approve);try{await this.sendResult({topic:g,id:i,result:{cacaos:n,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:w,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(a.requester.metadata,f)})}catch(W){throw s.setError(hf.authenticated_session_approve_publish_failure),W}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:a.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:$}},this.rejectSessionAuthenticate=async t=>{this.isInitialized();const{id:i,reason:n}=t,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===sr.relay&&await this.confirmOnlineStateOrThrow();const a=s.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),h=kl(a),u={type:ys,receiverPublicKey:a,senderPublicKey:f};await this.sendError({id:i,topic:h,error:n,encodeOpts:u,rpcOpts:Lr.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED"))},this.formatAuthMessage=t=>{this.isInitialized();const{request:i,iss:n}=t;return eb(i,n)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)},this.cleanupDuplicatePairings=async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var a,f;return((a=s.peerMetadata)==null?void 0:a.url)&&((f=s.peerMetadata)==null?void 0:f.url)===t.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}},this.deleteSession=async t=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:a=!0,id:f=0}=t,{self:h}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(h.publicKey)&&await this.client.core.crypto.deleteKeyPair(h.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(H2).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===n&&this.deletePendingSessionRequest(u.id,Gt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=is.idle),a&&this.client.events.emit("session_delete",{id:f,topic:n})},this.deleteProposal=async(t,i)=>{if(i)try{const n=this.client.proposal.get(t),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s?.setError(Fo.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Gt("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")},this.deletePendingSessionRequest=async(t,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),n?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==t),n&&(this.sessionRequestQueue.state=is.idle,this.client.events.emit("session_request_expire",{id:t}))},this.deletePendingAuthRequest=async(t,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),n?Promise.resolve():this.client.core.expirer.del(t)])},this.setExpiry=async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))},this.setProposal=async(t,i)=>{this.client.core.expirer.set(t,Ir(Lr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)},this.setAuthRequest=async(t,i)=>{const{request:n,pairingTopic:s,transportType:a=sr.relay}=i;this.client.core.expirer.set(t,n.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:t,pairingTopic:s,verifyContext:n.verifyContext,transportType:a})},this.setPendingSessionRequest=async t=>{const{id:i,topic:n,params:s,verifyContext:a}=t,f=s.request.expiryTimestamp||Ir(Lr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,f),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:a})},this.sendRequest=async t=>{const{topic:i,method:n,params:s,expiry:a,relayRpcId:f,clientRpcId:h,throwOnFailedPublish:u,appLink:g}=t,w=Ys(n,s,h);let P;const M=!!g;try{const W=M?Vc:Vs;P=await this.client.core.crypto.encode(i,w,{encoding:W})}catch(W){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),W}let O;if(MP.includes(n)){const W=_s(JSON.stringify(w)),H=_s(P);O=await this.client.core.verify.register({id:H,decryptedId:W})}const $=Lr[n].req;if($.attestation=O,a&&($.ttl=a),f&&($.id=f),this.client.core.history.set(i,w),M){const W=jl(g,i,P);await global.Linking.openURL(W,this.client.name)}else{const W=Lr[n].req;a&&(W.ttl=a),f&&(W.id=f),u?(W.internal=Sn(pr({},W.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,P,W)):this.client.core.relayer.publish(i,P,W).catch(H=>this.client.logger.error(H))}return w.id},this.sendResult=async t=>{const{id:i,topic:n,result:s,throwOnFailedPublish:a,encodeOpts:f,appLink:h}=t,u=th(i,s);let g;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const M=w?Vc:Vs;g=await this.client.core.crypto.encode(n,u,Sn(pr({},f||{}),{encoding:M}))}catch(M){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),M}let P;try{P=await this.client.core.history.get(n,i)}catch(M){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),M}if(w){const M=jl(h,n,g);await global.Linking.openURL(M,this.client.name)}else{const M=Lr[P.request.method].res;a?(M.internal=Sn(pr({},M.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,g,M)):this.client.core.relayer.publish(n,g,M).catch(O=>this.client.logger.error(O))}await this.client.core.history.resolve(u)},this.sendError=async t=>{const{id:i,topic:n,error:s,encodeOpts:a,rpcOpts:f,appLink:h}=t,u=rh(i,s);let g;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const M=w?Vc:Vs;g=await this.client.core.crypto.encode(n,u,Sn(pr({},a||{}),{encoding:M}))}catch(M){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),M}let P;try{P=await this.client.core.history.get(n,i)}catch(M){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),M}if(w){const M=jl(h,n,g);await global.Linking.openURL(M,this.client.name)}else{const M=f||Lr[P.request.method].res;this.client.core.relayer.publish(n,g,M)}await this.client.core.history.resolve(u)},this.cleanup=async()=>{const t=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;Ks(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&t.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{Ks(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...t.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])},this.onRelayEventRequest=async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===is.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=is.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=is.idle},this.processRequest=async t=>{const{topic:i,payload:n,attestation:s,transportType:a,encryptedId:f}=t,h=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:h}))switch(h){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:f});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:f,transportType:a});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:f,transportType:a});default:return this.client.logger.info(`Unsupported request method ${h}`)}},this.onRelayEventResponse=async t=>{const{topic:i,payload:n,transportType:s}=t,a=(await this.client.core.history.get(i,n.id)).request.method;switch(a){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${a}`)}},this.onRelayEventUnknownPayload=t=>{const{topic:i}=t,{message:n}=_e("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},this.shouldIgnorePairingRequest=t=>{const{topic:i,requestMethod:n}=t,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async t=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=t,{params:f,id:h}=n;try{const u=this.client.core.eventClient.getEvent({topic:i});this.isValidConnect(pr({},n.params));const g=f.expiryTimestamp||Ir(Lr.wc_sessionPropose.req.ttl),w=pr({id:h,pairingTopic:i,expiryTimestamp:g},f);await this.setProposal(h,w);const P=await this.getVerifyContext({attestationId:s,hash:_s(JSON.stringify(n)),encryptedId:a,metadata:w.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Es.proposal_listener_not_found)),u?.addTrace(rs.emit_session_proposal),this.client.events.emit("session_proposal",{id:h,params:w,verifyContext:P})}catch(u){await this.sendError({id:h,topic:i,error:u,rpcOpts:Lr.wc_sessionPropose.autoReject}),this.client.logger.error(u)}},this.onSessionProposeResponse=async(t,i,n)=>{const{id:s}=i;if(Xn(i)){const{result:a}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const f=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:f});const h=f.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:h});const u=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const g=await this.client.core.crypto.generateSharedKey(h,u);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:g});const w=await this.client.core.relayer.subscribe(g,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:t})}else if(tn(i)){await this.client.proposal.delete(s,Gt("USER_DISCONNECTED"));const a=Dt("session_connect");if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners, 954`);this.events.emit(Dt("session_connect"),{error:i.error})}},this.onSessionSettleRequest=async(t,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:a,controller:f,expiry:h,namespaces:u,sessionProperties:g,sessionConfig:w}=i.params,P=Sn(pr(pr({topic:t,relay:a,expiry:h,namespaces:u,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:f.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:f.publicKey,metadata:f.metadata}},g&&{sessionProperties:g}),w&&{sessionConfig:w}),{transportType:sr.relay}),M=Dt("session_connect");if(this.events.listenerCount(M)===0)throw new Error(`emitting ${M} without any listeners 997`);this.events.emit(Dt("session_connect"),{session:P}),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(a){await this.sendError({id:n,topic:t,error:a}),this.client.logger.error(a)}},this.onSessionSettleResponse=async(t,i)=>{const{id:n}=i;Xn(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Dt("session_approve",n),{})):tn(i)&&(await this.client.session.delete(t,Gt("USER_DISCONNECTED")),this.events.emit(Dt("session_approve",n),{error:i.error}))},this.onSessionUpdateRequest=async(t,i)=>{const{params:n,id:s}=i;try{const a=`${t}_session_update`,f=tf.get(a);if(f&&this.isRequestOutOfSync(f,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:t,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(pr({topic:t},n));try{tf.set(a,s),await this.client.session.update(t,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0})}catch(h){throw tf.delete(a),h}this.client.events.emit("session_update",{id:s,topic:t,params:n})}catch(a){await this.sendError({id:s,topic:t,error:a}),this.client.logger.error(a)}},this.isRequestOutOfSync=(t,i)=>parseInt(i.toString().slice(0,-3))<=parseInt(t.toString().slice(0,-3)),this.onSessionUpdateResponse=(t,i)=>{const{id:n}=i,s=Dt("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Xn(i)?this.events.emit(Dt("session_update",n),{}):tn(i)&&this.events.emit(Dt("session_update",n),{error:i.error})},this.onSessionExtendRequest=async(t,i)=>{const{id:n}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,Ir(ja)),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:n,topic:t})}catch(s){await this.sendError({id:n,topic:t,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(t,i)=>{const{id:n}=i,s=Dt("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Xn(i)?this.events.emit(Dt("session_extend",n),{}):tn(i)&&this.events.emit(Dt("session_extend",n),{error:i.error})},this.onSessionPingRequest=async(t,i)=>{const{id:n}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:t})}catch(s){await this.sendError({id:n,topic:t,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(t,i)=>{const{id:n}=i,s=Dt("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{Xn(i)?this.events.emit(Dt("session_ping",n),{}):tn(i)&&this.events.emit(Dt("session_ping",n),{error:i.error})},500)},this.onSessionDeleteRequest=async(t,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(fi.publish,async()=>{s(await this.deleteSession({topic:t,id:n}))})}),this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Gt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async t=>{var i,n,s;const{topic:a,payload:f,attestation:h,encryptedId:u,transportType:g}=t,{id:w,params:P}=f;try{await this.isValidRequest(pr({topic:a},P));const M=this.client.session.get(a),O=await this.getVerifyContext({attestationId:h,hash:_s(JSON.stringify(Ys("wc_sessionRequest",P,w))),encryptedId:u,metadata:M.peer.metadata,transportType:g}),$={id:w,topic:a,params:P,verifyContext:O};await this.setPendingSessionRequest($),g===sr.link_mode&&(i=M.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=M.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest($):(this.addSessionRequestToSessionRequestQueue($),this.processSessionRequestQueue())}catch(M){await this.sendError({id:w,topic:a,error:M}),this.client.logger.error(M)}},this.onSessionRequestResponse=(t,i)=>{const{id:n}=i,s=Dt("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Xn(i)?this.events.emit(Dt("session_request",n),{result:i.result}):tn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionEventRequest=async(t,i)=>{const{id:n,params:s}=i;try{const a=`${t}_session_event_${s.event.name}`,f=tf.get(a);if(f&&this.isRequestOutOfSync(f,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(pr({topic:t},s)),this.client.events.emit("session_event",{id:n,topic:t,params:s}),tf.set(a,n)}catch(a){await this.sendError({id:n,topic:t,error:a}),this.client.logger.error(a)}},this.onSessionAuthenticateResponse=(t,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),Xn(i)?this.events.emit(Dt("session_request",n),{result:i.result}):tn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async t=>{var i;const{topic:n,payload:s,attestation:a,encryptedId:f,transportType:h}=t;try{const{requester:u,authPayload:g,expiryTimestamp:w}=s.params,P=await this.getVerifyContext({attestationId:a,hash:_s(JSON.stringify(s)),encryptedId:f,metadata:u.metadata,transportType:h}),M={requester:u,pairingTopic:n,id:s.id,authPayload:g,verifyContext:P,expiryTimestamp:w};await this.setAuthRequest(s.id,{request:M,pairingTopic:n,transportType:h}),h===sr.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:P})}catch(u){this.client.logger.error(u);const g=s.params.requester.publicKey,w=await this.client.core.crypto.generateKeyPair(),P=this.getAppLinkIfEnabled(s.params.requester.metadata,h),M={type:ys,receiverPublicKey:g,senderPublicKey:w};await this.sendError({id:s.id,topic:n,error:u,encodeOpts:M,rpcOpts:Lr.wc_sessionAuthenticate.autoReject,appLink:P})}},this.addSessionRequestToSessionRequestQueue=t=>{this.sessionRequestQueue.queue.push(t)},this.cleanupAfterResponse=t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=is.idle,this.processSessionRequestQueue()},Ae.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:t,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===t&&s.request.method==="wc_sessionRequest").forEach(s=>{const a=s.request.id,f=Dt("session_request",a);if(this.events.listenerCount(f)===0)throw new Error(`emitting ${f} without any listeners`);this.events.emit(Dt("session_request",s.request.id),{error:i})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===is.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=is.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}},this.emitSessionRequest=t=>{this.client.events.emit("session_request",t)},this.onPairingCreated=t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:Ys("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async t=>{if(!bi(t)){const{message:h}=_e("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:a,relays:f}=t;if(oi(i)||await this.isValidPairingTopic(i),!dE(f,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${f}`);throw new Error(h)}!oi(n)&&ef(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!oi(s)&&ef(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),oi(a)||this.validateSessionProps(a,"sessionProperties")},this.validateNamespaces=(t,i)=>{const n=uE(t,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async t=>{if(!bi(t))throw new Error(_e("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const f=this.client.proposal.get(i),h=r0(n,"approve()");if(h)throw new Error(h.message);const u=xb(f.requiredNamespaces,n,"approve()");if(u)throw new Error(u.message);if(!wr(s,!0)){const{message:g}=_e("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(g)}oi(a)||this.validateSessionProps(a,"sessionProperties")},this.isValidReject=async t=>{if(!bi(t)){const{message:s}=_e("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(s)}const{id:i,reason:n}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!gE(n)){const{message:s}=_e("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}},this.isValidSessionSettleRequest=t=>{if(!bi(t)){const{message:u}=_e("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(u)}const{relay:i,controller:n,namespaces:s,expiry:a}=t;if(!yb(i)){const{message:u}=_e("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const f=oE(n,"onSessionSettleRequest()");if(f)throw new Error(f.message);const h=r0(s,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(Ks(a)){const{message:u}=_e("EXPIRED","onSessionSettleRequest()");throw new Error(u)}},this.isValidUpdate=async t=>{if(!bi(t)){const{message:h}=_e("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(h)}const{topic:i,namespaces:n}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),a=r0(n,"update()");if(a)throw new Error(a.message);const f=xb(s.requiredNamespaces,n,"update()");if(f)throw new Error(f.message)},this.isValidExtend=async t=>{if(!bi(t)){const{message:n}=_e("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(n)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)},this.isValidRequest=async t=>{if(!bi(t)){const{message:h}=_e("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(h)}const{topic:i,request:n,chainId:s,expiry:a}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:f}=this.client.session.get(i);if(!_b(f,s)){const{message:h}=_e("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(h)}if(!vE(n)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(h)}if(!wE(f,s,n.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(h)}if(a&&!AE(a,M0)){const{message:h}=_e("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${M0.min} and ${M0.max}`);throw new Error(h)}},this.isValidRespond=async t=>{var i;if(!bi(t)){const{message:a}=_e("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(a)}const{topic:n,response:s}=t;try{await this.isValidSessionTopic(n)}catch(a){throw(i=t?.response)!=null&&i.id&&this.cleanupAfterResponse(t),a}if(!mE(s)){const{message:a}=_e("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidPing=async t=>{if(!bi(t)){const{message:n}=_e("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(n)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async t=>{if(!bi(t)){const{message:f}=_e("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(f)}const{topic:i,event:n,chainId:s}=t;await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!_b(a,s)){const{message:f}=_e("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(f)}if(!bE(n)){const{message:f}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(f)}if(!yE(a,s,n.name)){const{message:f}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(f)}},this.isValidDisconnect=async t=>{if(!bi(t)){const{message:n}=_e("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(n)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidAuthenticate=t=>{const{chains:i,uri:n,domain:s,nonce:a}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!wr(n,!1))throw new Error("uri is required parameter");if(!wr(s,!1))throw new Error("domain is required parameter");if(!wr(a,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(h=>Ba(h).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:f}=Ba(i[0]);if(f!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async t=>{const{attestationId:i,hash:n,encryptedId:s,metadata:a,transportType:f}=t,h={verified:{verifyUrl:a.verifyUrl||lf,validation:"UNKNOWN",origin:a.url||""}};try{if(f===sr.link_mode){const g=this.getAppLinkIfEnabled(a,f);return h.verified.validation=g&&new URL(g).origin===new URL(a.url).origin?"VALID":"INVALID",h}const u=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:a.verifyUrl});u&&(h.verified.origin=u.origin,h.verified.isScam=u.isScam,h.verified.validation=u.origin===new URL(a.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(h)}`),h},this.validateSessionProps=(t,i)=>{Object.values(t).forEach(n=>{if(!wr(n,!1)){const{message:s}=_e("MISSING_OR_INVALID",`${i} must be in Record format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})},this.getPendingAuthRequest=t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0},this.addToRecentlyDeleted=(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const a of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(a)}}},this.checkRecentlyDeleted=t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:n}=_e("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(n)}},this.isLinkModeEnabled=(t,i)=>{var n,s,a,f,h,u,g,w,P;return!t||i!==sr.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((f=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:f.universal)!==void 0&&((u=(h=this.client.metadata)==null?void 0:h.redirect)==null?void 0:u.universal)!==""&&((g=t?.redirect)==null?void 0:g.universal)!==void 0&&((w=t?.redirect)==null?void 0:w.universal)!==""&&((P=t?.redirect)==null?void 0:P.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(t,i)=>{var n;return this.isLinkModeEnabled(t,i)?(n=t?.redirect)==null?void 0:n.universal:void 0},this.handleLinkModeMessage=({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Gm(t,"topic")||"",n=decodeURIComponent(Gm(t,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:sr.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})},this.registerLinkModeListeners=async()=>{var t;if(Gd()||Fa()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(fi.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:n,transportType:s}=e,{publicKey:a}=this.client.auth.authKeys.keys.includes(oh)?this.client.auth.authKeys.get(oh):{responseTopic:void 0,publicKey:void 0},f=await this.client.core.crypto.decode(t,i,{receiverPublicKey:a,encoding:s===sr.link_mode?Vc:Vs});try{v0(f)?(this.client.core.history.set(t,f),this.onRelayEventRequest({topic:t,payload:f,attestation:n,transportType:s,encryptedId:_s(i)})):ih(f)?(await this.client.core.history.resolve(f),await this.onRelayEventResponse({topic:t,payload:f,transportType:s}),this.client.core.history.delete(t,f.id)):this.onRelayEventUnknownPayload({topic:t,payload:f,transportType:s})}catch(h){this.client.logger.error(h)}}registerExpirerEvents(){this.client.core.expirer.on(sn.expired,async e=>{const{topic:t,id:i}=Vm(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,_e("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,_e("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Bo.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Bo.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!wr(e,!1)){const{message:t}=_e("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}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ks(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=_e("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!wr(e,!1)){const{message:t}=_e("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=_e("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Ks(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=_e("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=_e("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(wr(e,!1)){const{message:t}=_e("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=_e("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!pE(e)){const{message:t}=_e("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=_e("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Ks(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=_e("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class UP extends qo{constructor(e,t){super(e,t,AP,S0),this.core=e,this.logger=t}}class qP extends qo{constructor(e,t){super(e,t,EP,S0),this.core=e,this.logger=t}}class zP extends qo{constructor(e,t){super(e,t,IP,S0,i=>i.id),this.core=e,this.logger=t}}class HP extends qo{constructor(e,t){super(e,t,DP,sh,()=>oh),this.core=e,this.logger=t}}class kP extends qo{constructor(e,t){super(e,t,OP,sh),this.core=e,this.logger=t}}class jP extends qo{constructor(e,t){super(e,t,RP,sh,i=>i.id),this.core=e,this.logger=t}}class WP{constructor(e,t){this.core=e,this.logger=t,this.authKeys=new HP(this.core,this.logger),this.pairingTopics=new kP(this.core,this.logger),this.requests=new jP(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class C0 extends KS{constructor(e){super(e),this.protocol=U2,this.version=q2,this.name=I0.name,this.events=new qr.exports.EventEmitter,this.on=(i,n)=>this.events.on(i,n),this.once=(i,n)=>this.events.once(i,n),this.off=(i,n)=>this.events.off(i,n),this.removeListener=(i,n)=>this.events.removeListener(i,n),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}},this.update=async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}},this.request=async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}},this.find=i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.authenticate=async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||I0.name,this.metadata=e?.metadata||Hm(),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Qn(eh({level:e?.logger||I0.logger}));this.core=e?.core||new xP(e),this.logger=ai(t,this.name),this.session=new qP(this.core,this.logger),this.proposal=new UP(this.core,this.logger),this.pendingRequest=new zP(this.core,this.logger),this.engine=new FP(this),this.auth=new WP(this.core,this.logger)}static async init(e){const t=new C0(e);return await t.initialize(),t}get context(){return yi(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.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),this.engine.processRelayMessageCache()}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var P0={exports:{}};/** ++ ***************************************************************************** */var g0=function(r,e){return g0=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])},g0(r,e)};function lI(r,e){g0(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var v0=function(){return v0=Object.assign||function(e){for(var t,i=1,n=arguments.length;i=0;f--)(a=r[f])&&(s=(n<3?a(s):n>3?a(e,t,s):a(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}function dI(r,e){return function(t,i){e(t,i,r)}}function pI(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function gI(r,e,t,i){function n(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function f(g){try{u(i.next(g))}catch(w){a(w)}}function h(g){try{u(i.throw(g))}catch(w){a(w)}}function u(g){g.done?s(g.value):n(g.value).then(f,h)}u((i=i.apply(r,e||[])).next())})}function vI(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,a;return a={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function f(u){return function(g){return h([u,g])}}function h(u){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,n=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Kb(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(f){a={error:f}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(a)throw a.error}}return s}function wI(){for(var r=[],e=0;e1||f(M,C)})})}function f(M,C){try{h(i[M](C))}catch(O){w(s[0][3],O)}}function h(M){M.value instanceof ff?Promise.resolve(M.value.v).then(u,g):w(s[0][2],M)}function u(M){f("next",M)}function g(M){f("throw",M)}function w(M,C){M(C),s.shift(),s.length&&f(s[0][0],s[0][1])}}function xI(r){var e,t;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=r[n]?function(a){return(t=!t)?{value:ff(r[n](a)),done:n==="return"}:s?s(a):a}:s}}function AI(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof m0=="function"?m0(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=r[s]&&function(a){return new Promise(function(f,h){a=r[s](a),n(f,h,a.done,a.value)})}}function n(s,a,f,h){Promise.resolve(h).then(function(u){s({value:u,done:f})},a)}}function EI(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function SI(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function II(r){return r&&r.__esModule?r:{default:r}}function MI(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function CI(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var PI=Object.freeze({__proto__:null,__extends:lI,get __assign(){return v0},__rest:hI,__decorate:uI,__param:dI,__metadata:pI,__awaiter:gI,__generator:vI,__createBinding:mI,__exportStar:bI,__values:m0,__read:Kb,__spread:wI,__spreadArrays:yI,__await:ff,__asyncGenerator:_I,__asyncDelegator:xI,__asyncValues:AI,__makeTemplateObject:EI,__importStar:SI,__importDefault:II,__classPrivateFieldGet:MI,__classPrivateFieldSet:CI}),DI=ju(PI),xs={},Vb;function OI(){if(Vb)return xs;Vb=1,Object.defineProperty(xs,"__esModule",{value:!0}),xs.isBrowserCryptoAvailable=xs.getSubtleCrypto=xs.getBrowerCrypto=void 0;function r(){return fr?.crypto||fr?.msCrypto||{}}xs.getBrowerCrypto=r;function e(){const i=r();return i.subtle||i.webkitSubtle}xs.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return xs.isBrowserCryptoAvailable=t,xs}var As={},Gb;function RI(){if(Gb)return As;Gb=1,Object.defineProperty(As,"__esModule",{value:!0}),As.isBrowser=As.isNode=As.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}As.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}As.isNode=e;function t(){return!r()&&!e()}return As.isBrowser=t,As}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=DI;e.__exportStar(OI(),r),e.__exportStar(RI(),r)})(Wb);function Es(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function Fo(r=6){return BigInt(Es(r))}function Js(r,e,t){return{id:t||Es(),jsonrpc:"2.0",method:r,params:e}}function ih(r,e){return{id:r,jsonrpc:"2.0",result:e}}function nh(r,e,t){return{id:r,jsonrpc:"2.0",error:TI(e,t)}}function TI(r,e){return typeof r>"u"?kb(zb):(typeof r=="string"&&(r=Object.assign(Object.assign({},kb(p0)),{message:r})),typeof e<"u"&&(r.data=e),cI(r.code)&&(r=fI(r.code)),r)}class $I{}class NI extends $I{constructor(){super()}}class LI extends NI{constructor(e){super()}}const BI="^https?:",FI="^wss?:";function UI(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Yb(r,e){const t=UI(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Jb(r){return Yb(r,BI)}function Qb(r){return Yb(r,FI)}function qI(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function Zb(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function b0(r){return Zb(r)&&"method"in r}function sh(r){return Zb(r)&&(es(r)||rn(r))}function es(r){return"result"in r}function rn(r){return"error"in r}class nn extends LI{constructor(e){super(e),this.events=new zr.exports.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(Js(e.method,e.params||[],e.id||Fo().toString()),t)}async requestStrict(e,t){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{rn(s)?n(s.error):i(s.result)});try{await this.connection.send(e,t)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),sh(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&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(),typeof e=="string"&&(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=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),HI=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Xb=r=>r.split("?")[0],e2=10,kI=zI();class jI{constructor(e){if(this.url=e,this.events=new zr.exports.EventEmitter,this.registering=!1,!Qb(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}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)=>{if(typeof this.socket>"u"){t(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(bs(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Qb(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const n=new URLSearchParams(e).get("origin"),s=Wb.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!qI(e)},a=new kI(e,[],s);HI()?a.onerror=f=>{const h=f;i(this.emitError(h.error))}:a.on("error",f=>{i(this.emitError(f))}),a.onopen=()=>{this.onOpen(a),t(a)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),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(typeof e.data>"u")return;const t=typeof e.data=="string"?Oo(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),n=i.message||i.toString(),s=nh(e,n);this.events.emit("payload",s)}parseError(e,t=this.url){return jb(e,Xb(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>e2&&this.events.setMaxListeners(e2)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Xb(this.url)}`));return this.events.emit("register_error",t),t}}var w0={exports:{}};(function(r,e){var t=200,i="__lodash_hash_undefined__",n=1,s=2,a=9007199254740991,f="[object Arguments]",h="[object Array]",u="[object AsyncFunction]",g="[object Boolean]",w="[object Date]",M="[object Error]",C="[object Function]",O="[object GeneratorFunction]",$="[object Map]",j="[object Number]",H="[object Null]",F="[object Object]",G="[object Promise]",B="[object Proxy]",z="[object RegExp]",W="[object Set]",_="[object String]",U="[object Symbol]",ee="[object Undefined]",oe="[object WeakMap]",L="[object ArrayBuffer]",b="[object DataView]",m="[object Float32Array]",l="[object Float64Array]",d="[object Int8Array]",y="[object Int16Array]",P="[object Int32Array]",D="[object Uint8Array]",S="[object Uint8ClampedArray]",v="[object Uint16Array]",A="[object Uint32Array]",x=/[\\^$.*+?()[\]{}|]/g,N=/^\[object .+?Constructor\]$/,ae=/^(?:0|[1-9]\d*)$/,R={};R[m]=R[l]=R[d]=R[y]=R[P]=R[D]=R[S]=R[v]=R[A]=!0,R[f]=R[h]=R[L]=R[g]=R[b]=R[w]=R[M]=R[C]=R[$]=R[j]=R[F]=R[z]=R[W]=R[_]=R[oe]=!1;var X=typeof fr=="object"&&fr&&fr.Object===Object&&fr,V=typeof self=="object"&&self&&self.Object===Object&&self,J=X||V||Function("return this")(),K=e&&!e.nodeType&&e,E=K&&!0&&r&&!r.nodeType&&r,Y=E&&E.exports===K,re=Y&&X.process,le=function(){try{return re&&re.binding&&re.binding("util")}catch{}}(),he=le&&le.isTypedArray;function ge(Q,ne){for(var pe=-1,Ue=Q==null?0:Q.length,Xt=0,bt=[];++pe-1}function ti(Q,ne){var pe=this.__data__,Ue=na(pe,Q);return Ue<0?(++this.size,pe.push([Q,ne])):pe[Ue][1]=ne,this}_t.prototype.clear=qt,_t.prototype.delete=Zr,_t.prototype.get=Xr,_t.prototype.has=ei,_t.prototype.set=ti;function vr(Q){var ne=-1,pe=Q==null?0:Q.length;for(this.clear();++neEr))return!1;var er=bt.get(Q);if(er&&bt.get(ne))return er==ne;var _r=-1,Ii=!0,Sr=pe&s?new Si:void 0;for(bt.set(Q,ne),bt.set(ne,Q);++_r-1&&Q%1==0&&Q-1&&Q%1==0&&Q<=a}function iu(Q){var ne=typeof Q;return Q!=null&&(ne=="object"||ne=="function")}function aa(Q){return Q!=null&&typeof Q=="object"}var nu=he?Xe(he):Wh;function Zp(Q){return Jp(Q)?kh(Q):Kh(Q)}function Zt(){return[]}function Qt(){return!1}r.exports=Qp})(w0,w0.exports);var WI=w0.exports,KI=Object.defineProperty,t2=Object.getOwnPropertySymbols,VI=Object.prototype.hasOwnProperty,GI=Object.prototype.propertyIsEnumerable,r2=(r,e,t)=>e in r?KI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,fi=(r,e)=>{for(var t in e||(e={}))VI.call(e,t)&&r2(r,t,e[t]);if(t2)for(var t of t2(e))GI.call(e,t)&&r2(r,t,e[t]);return r};const i2="wc",n2=2,oh="core",ts=`${i2}@2:${oh}:`,YI={name:oh,logger:"error"},JI={database:":memory:"},QI="crypto",s2="client_ed25519_seed",ZI=_e.ONE_DAY,XI="keychain",eM="0.3",tM="messages",rM="0.3",o2=_e.SIX_HOURS,iM="publisher",a2="irn",nM="error",c2="wss://relay.walletconnect.org",sM="relayer",Lr={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},oM="_subscription",sn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},aM=.1,y0="2.17.2",sr={link_mode:"link_mode",relay:"relay"},cM="0.3",fM="WALLETCONNECT_CLIENT_ID",f2="WALLETCONNECT_LINK_MODE_APPS",Fi={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},lM="subscription",hM="0.3",uM=_e.FIVE_SECONDS*1e3,dM="pairing",pM="0.3",lf={wc_pairingDelete:{req:{ttl:_e.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:_e.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:_e.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:_e.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:_e.ONE_DAY,prompt:!1,tag:0},res:{ttl:_e.ONE_DAY,prompt:!1,tag:0}}},Uo={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Sn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},gM="history",vM="0.3",mM="expirer",on={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},bM="0.3",wM="verify-api",yM="https://verify.walletconnect.com",l2="https://verify.walletconnect.org",hf=l2,_M=`${hf}/v3`,xM=[yM,l2],AM="echo",EM="https://echo.walletconnect.com",rs={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Ss={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},In={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},qo={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},zo={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},uf={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},SM=.1,IM="event-client",MM=86400,CM="https://pulse.walletconnect.org/batch";function PM(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i>>0,B=new Uint8Array(G);H!==F;){for(var z=O[H],W=0,_=G-1;(z!==0||W>>0,B[_]=z%f>>>0,z=z/f>>>0;if(z!==0)throw new Error("Non-zero carry");j=W,H++}for(var U=G-j;U!==G&&B[U]===0;)U++;for(var ee=h.repeat($);U>>0,G=new Uint8Array(F);O[$];){var B=t[O.charCodeAt($)];if(B===255)return;for(var z=0,W=F-1;(B!==0||z>>0,G[W]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");H=z,$++}if(O[$]!==" "){for(var _=F-H;_!==F&&G[_]===0;)_++;for(var U=new Uint8Array(j+(F-_)),ee=j;_!==F;)U[ee++]=G[_++];return U}}}function C(O){var $=M(O);if($)return $;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:M,decode:C}}var DM=PM,OM=DM;const h2=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},RM=r=>new TextEncoder().encode(r),TM=r=>new TextDecoder().decode(r);class $M{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class NM{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return u2(this,e)}}class LM{constructor(e){this.decoders=e}or(e){return u2(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const u2=(r,e)=>new LM(fi(fi({},r.decoders||{[r.prefix]:r}),e.decoders||{[e.prefix]:e}));class BM{constructor(e,t,i,n){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=n,this.encoder=new $M(e,t,i),this.decoder=new NM(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ah=({name:r,prefix:e,encode:t,decode:i})=>new BM(r,e,t,i),df=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:n}=OM(t,e);return ah({prefix:r,name:e,encode:i,decode:s=>h2(n(s))})},FM=(r,e,t,i)=>{const n={};for(let g=0;g=8&&(f-=8,a[u++]=255&h>>f)}if(f>=t||255&h<<8-f)throw new SyntaxError("Unexpected end of data");return a},UM=(r,e,t)=>{const i=e[e.length-1]==="=",n=(1<t;)a-=t,s+=e[n&f>>a];if(a&&(s+=e[n&f<ah({prefix:e,name:r,encode(n){return UM(n,i,t)},decode(n){return FM(n,i,t,r)}}),qM=ah({prefix:"\0",name:"identity",encode:r=>TM(r),decode:r=>RM(r)});var zM=Object.freeze({__proto__:null,identity:qM});const HM=Kr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var kM=Object.freeze({__proto__:null,base2:HM});const jM=Kr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var WM=Object.freeze({__proto__:null,base8:jM});const KM=df({prefix:"9",name:"base10",alphabet:"0123456789"});var VM=Object.freeze({__proto__:null,base10:KM});const GM=Kr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),YM=Kr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var JM=Object.freeze({__proto__:null,base16:GM,base16upper:YM});const QM=Kr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ZM=Kr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),XM=Kr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),eC=Kr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),tC=Kr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),rC=Kr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),iC=Kr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),nC=Kr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sC=Kr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var oC=Object.freeze({__proto__:null,base32:QM,base32upper:ZM,base32pad:XM,base32padupper:eC,base32hex:tC,base32hexupper:rC,base32hexpad:iC,base32hexpadupper:nC,base32z:sC});const aC=df({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cC=df({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fC=Object.freeze({__proto__:null,base36:aC,base36upper:cC});const lC=df({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hC=df({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var uC=Object.freeze({__proto__:null,base58btc:lC,base58flickr:hC});const dC=Kr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),pC=Kr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),gC=Kr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vC=Kr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mC=Object.freeze({__proto__:null,base64:dC,base64pad:pC,base64url:gC,base64urlpad:vC});const d2=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),bC=d2.reduce((r,e,t)=>(r[t]=e,r),[]),wC=d2.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function yC(r){return r.reduce((e,t)=>(e+=bC[t],e),"")}function _C(r){const e=[];for(const t of r){const i=wC[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const xC=ah({prefix:"\u{1F680}",name:"base256emoji",encode:yC,decode:_C});var AC=Object.freeze({__proto__:null,base256emoji:xC}),EC=g2,p2=128,SC=127,IC=~SC,MC=Math.pow(2,31);function g2(r,e,t){e=e||[],t=t||0;for(var i=t;r>=MC;)e[t++]=r&255|p2,r/=128;for(;r&IC;)e[t++]=r&255|p2,r>>>=7;return e[t]=r|0,g2.bytes=t-i+1,e}var CC=_0,PC=128,v2=127;function _0(r,i){var t=0,i=i||0,n=0,s=i,a,f=r.length;do{if(s>=f)throw _0.bytes=0,new RangeError("Could not decode varint");a=r[s++],t+=n<28?(a&v2)<=PC);return _0.bytes=s-i,t}var DC=Math.pow(2,7),OC=Math.pow(2,14),RC=Math.pow(2,21),TC=Math.pow(2,28),$C=Math.pow(2,35),NC=Math.pow(2,42),LC=Math.pow(2,49),BC=Math.pow(2,56),FC=Math.pow(2,63),UC=function(r){return r(m2.encode(r,e,t),e),w2=r=>m2.encodingLength(r),x0=(r,e)=>{const t=e.byteLength,i=w2(r),n=i+w2(t),s=new Uint8Array(n+t);return b2(r,s,0),b2(t,s,i),s.set(e,n),new zC(r,t,e,s)};class zC{constructor(e,t,i,n){this.code=e,this.size=t,this.digest=i,this.bytes=n}}const y2=({name:r,code:e,encode:t})=>new HC(r,e,t);class HC{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?x0(this.code,t):t.then(i=>x0(this.code,i))}else throw Error("Unknown type, must be binary type")}}const _2=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),kC=y2({name:"sha2-256",code:18,encode:_2("SHA-256")}),jC=y2({name:"sha2-512",code:19,encode:_2("SHA-512")});var WC=Object.freeze({__proto__:null,sha256:kC,sha512:jC});const x2=0,KC="identity",A2=h2;var VC=Object.freeze({__proto__:null,identity:{code:x2,name:KC,encode:A2,digest:r=>x0(x2,A2(r))}});new TextEncoder,new TextDecoder;const E2=fi(fi(fi(fi(fi(fi(fi(fi(fi(fi({},zM),kM),WM),VM),JM),oC),fC),uC),mC),AC);fi(fi({},WC),VC);function GC(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function S2(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const I2=S2("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),A0=S2("ascii","a",r=>{let e="a";for(let t=0;t{r=r.substring(1);const e=GC(r.length);for(let t=0;t{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()},this.get=i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=xe("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=ci(t,this.name)}get context(){return yi(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,jm(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Wm(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ZC{constructor(e,t,i){this.core=e,this.logger=t,this.name=QI,this.randomSessionIdentifier=t0(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=n=>(this.isInitialized(),this.keychain.has(n)),this.getClientId=async()=>{this.isInitialized();const n=await this.getClientSeed(),s=Lm(n);return Nm(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=$A();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const s=await this.getClientSeed(),a=Lm(s),f=this.randomSessionIdentifier;return await kx(f,n,ZI,a)},this.generateSharedKey=(n,s,a)=>{this.isInitialized();const f=this.getPrivateKey(n),h=NA(f,s);return this.setSymKey(h,a)},this.setSymKey=async(n,s)=>{this.isInitialized();const a=s||jl(n);return await this.keychain.set(a,n),a},this.deleteKeyPair=async n=>{this.isInitialized(),await this.keychain.del(n)},this.deleteSymKey=async n=>{this.isInitialized(),await this.keychain.del(n)},this.encode=async(n,s,a)=>{this.isInitialized();const f=fb(a),h=bs(s);if(hb(f))return BA(h,a?.encoding);if(lb(f)){const M=f.senderPublicKey,C=f.receiverPublicKey;n=await this.generateSharedKey(M,C)}const u=this.getSymKey(n),{type:g,senderPublicKey:w}=f;return LA({type:g,symKey:u,message:h,senderPublicKey:w,encoding:a?.encoding})},this.decode=async(n,s,a)=>{this.isInitialized();const f=qA(s,a);if(hb(f)){const h=UA(s,a?.encoding);return Oo(h)}if(lb(f)){const h=f.receiverPublicKey,u=f.senderPublicKey;n=await this.generateSharedKey(h,u)}try{const h=this.getSymKey(n),u=FA({symKey:h,encoded:s,encoding:a?.encoding});return Oo(u)}catch(h){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=(n,s=Ys)=>{const a=Zc({encoded:n,encoding:s});return No(a.type)},this.getPayloadSenderPublicKey=(n,s=Ys)=>{const a=Zc({encoded:n,encoding:s});return a.senderPublicKey?rI(a.senderPublicKey,oi):void 0},this.core=e,this.logger=ci(t,this.name),this.keychain=i||new QC(this.core,this.logger)}get context(){return yi(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(s2)}catch{e=t0(),await this.keychain.set(s2,e)}return JC(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}}class XC extends kS{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=tM,this.version=rM,this.initialized=!1,this.storagePrefix=ts,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,n)=>{this.isInitialized();const s=ys(n);let a=this.messages.get(i);return typeof a>"u"&&(a={}),typeof a[s]<"u"||(a[s]=n,this.messages.set(i,a),await this.persist()),s},this.get=i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n},this.has=(i,n)=>{this.isInitialized();const s=this.get(i),a=ys(n);return typeof s[a]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=ci(e,this.name),this.core=t}get context(){return yi(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,jm(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Wm(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}}var eP=Object.defineProperty,tP=Object.defineProperties,rP=Object.getOwnPropertyDescriptors,M2=Object.getOwnPropertySymbols,iP=Object.prototype.hasOwnProperty,nP=Object.prototype.propertyIsEnumerable,C2=(r,e,t)=>e in r?eP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,P2=(r,e)=>{for(var t in e||(e={}))iP.call(e,t)&&C2(r,t,e[t]);if(M2)for(var t of M2(e))nP.call(e,t)&&C2(r,t,e[t]);return r},D2=(r,e)=>tP(r,rP(e));class sP extends jS{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new zr.exports.EventEmitter,this.name=iM,this.queue=new Map,this.publishTimeout=_e.toMiliseconds(_e.ONE_MINUTE),this.initialPublishTimeout=_e.toMiliseconds(_e.ONE_SECOND*15),this.needsTransportRestart=!1,this.publish=async(i,n,s)=>{var a;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const f=s?.ttl||o2,h=Wl(s),u=s?.prompt||!1,g=s?.tag||0,w=s?.id||Fo().toString(),M={topic:i,message:n,opts:{ttl:f,relay:h,prompt:u,tag:g,id:w,attestation:s?.attestation}},C=`Failed to publish payload, please try again. id:${w} tag:${g}`;try{const O=new Promise(async $=>{const j=({id:F})=>{M.opts.id===F&&(this.removeRequestFromQueue(F),this.relayer.events.removeListener(Lr.publish,j),$(M))};this.relayer.events.on(Lr.publish,j);const H=Vs(new Promise((F,G)=>{this.rpcPublish({topic:i,message:n,ttl:f,prompt:u,tag:g,id:w,attestation:s?.attestation}).then(F).catch(B=>{this.logger.warn(B,B?.message),G(B)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${w} tag:${g}`);try{await H,this.events.removeListener(Lr.publish,j)}catch(F){this.queue.set(w,D2(P2({},M),{attempt:1})),this.logger.warn(F,F?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:w,topic:i,message:n,opts:s}}),await Vs(O,this.publishTimeout,C)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(a=s?.internal)!=null&&a.throwOnFailedPublish)throw O}finally{this.queue.delete(w)}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.relayer=e,this.logger=ci(t,this.name),this.registerEventListeners()}get context(){return yi(this.logger)}async rpcPublish(e){var t,i,n,s;const{topic:a,message:f,ttl:h=o2,prompt:u,tag:g,id:w,attestation:M}=e,C={method:Xc(Wl().protocol).publish,params:{topic:a,message:f,ttl:h,prompt:u,tag:g,attestation:M},id:w};ai((t=C.params)==null?void 0:t.prompt)&&((i=C.params)==null||delete i.prompt),ai((n=C.params)==null?void 0:n.tag)&&((s=C.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:C});const O=await this.relayer.request(C);return this.relayer.events.emit(Lr.publish,e),this.logger.debug("Successfully Published Payload"),O}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,D2(P2({},e),{attempt:i}));const{topic:n,message:s,opts:a,attestation:f}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish({topic:n,message:s,ttl:a.ttl,prompt:a.prompt,tag:a.tag,id:a.id,attestation:f}),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ha.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Lr.connection_stalled);return}this.checkQueue()}),this.relayer.on(Lr.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class oP{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,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"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const n=i.filter(s=>s!==t);if(!n.length){this.map.delete(e);return}this.map.set(e,n)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var aP=Object.defineProperty,cP=Object.defineProperties,fP=Object.getOwnPropertyDescriptors,O2=Object.getOwnPropertySymbols,lP=Object.prototype.hasOwnProperty,hP=Object.prototype.propertyIsEnumerable,R2=(r,e,t)=>e in r?aP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pf=(r,e)=>{for(var t in e||(e={}))lP.call(e,t)&&R2(r,t,e[t]);if(O2)for(var t of O2(e))hP.call(e,t)&&R2(r,t,e[t]);return r},E0=(r,e)=>cP(r,fP(e));class uP extends VS{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new oP,this.events=new zr.exports.EventEmitter,this.name=lM,this.version=hM,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=ts,this.subscribeTimeout=_e.toMiliseconds(_e.ONE_MINUTE),this.initialSubscribeTimeout=_e.toMiliseconds(_e.ONE_SECOND*15),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId(),await this.restore()),this.initialized=!0},this.subscribe=async(i,n)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=Wl(n),a={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,a);const f=await this.rpcSubscribe(i,s,n);return typeof f=="string"&&(this.onSubscribe(f,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),f}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)},this.isSubscribed=async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((s,a)=>{const f=new _e.Watch;f.start(n);const h=setInterval(()=>{(!this.pending.has(i)&&this.topics.includes(i)||this.cached.some(u=>u.topic===i))&&(clearInterval(h),f.stop(n),s(!0)),f.elapsed(n)>=uM&&(clearInterval(h),f.stop(n),a(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(Ha.pulse,async()=>{await this.checkPending()}),this.events.on(Fi.created,async i=>{const n=Fi.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(Fi.deleted,async i=>{const n=Fi.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})},this.relayer=e,this.logger=ci(t,this.name),this.clientId=""}get context(){return yi(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 i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const n=Wl(i);await this.rpcUnsubscribe(e,t,n);const s=Gt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,t,i){var n;i?.transportType===sr.relay&&await this.restartToComplete();const s={method:Xc(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const a=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{const f=this.getSubscriptionId(e);if(i?.transportType===sr.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(g=>this.logger.warn(g))},_e.toMiliseconds(_e.ONE_SECOND)),f;const h=new Promise(async g=>{const w=M=>{M.topic===e&&(this.events.removeListener(Fi.created,w),g(M.id))};this.events.on(Fi.created,w);try{const M=await Vs(new Promise((C,O)=>{this.relayer.request(s).catch($=>{this.logger.warn($,$?.message),O($)}).then(C)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Fi.created,w),g(M)}catch{}}),u=await Vs(h,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&a)throw new Error(`Subscribing to ${e} failed, please try again`);return u?f:null}catch(f){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Lr.connection_stalled),a)throw f}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:Xc(t.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Vs(new Promise(n=>{this.relayer.request(i).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Lr.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:Xc(t.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Vs(new Promise((s,a)=>{this.relayer.request(i).catch(f=>{this.logger.warn(f),a(f)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Lr.connection_stalled)}return n}rpcUnsubscribe(e,t,i){const n={method:Xc(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,t){this.setSubscription(e,E0(pf({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,pf({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),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.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,pf({},t)),this.topicMap.set(t.topic,e),this.events.emit(Fi.created,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:i}=xe("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Fi.deleted,E0(pf({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Fi.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=xe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(e.map(t=>E0(pf({},t),{id:this.getSubscriptionId(t.topic)}))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await fA(_e.toMiliseconds(_e.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen()}getSubscriptionId(e){return ys(e+this.clientId)}}var dP=Object.defineProperty,T2=Object.getOwnPropertySymbols,pP=Object.prototype.hasOwnProperty,gP=Object.prototype.propertyIsEnumerable,$2=(r,e,t)=>e in r?dP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,N2=(r,e)=>{for(var t in e||(e={}))pP.call(e,t)&&$2(r,t,e[t]);if(T2)for(var t of T2(e))gP.call(e,t)&&$2(r,t,e[t]);return r};class vP extends WS{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new zr.exports.EventEmitter,this.name=sM,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=_e.toMiliseconds(_e.THIRTY_SECONDS+_e.ONE_SECOND),this.requestsInFlight=[],this.connectTimeout=_e.toMiliseconds(_e.ONE_SECOND*15),this.request=async t=>{var i,n;this.logger.debug("Publishing Request Payload");const s=t.id||Fo().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const a=`${s}:${((n=t.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(a);const f=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(h=>h!==a),f}catch(a){throw this.logger.debug(`Failed to Publish Request: ${s}`),a}},this.resetPingTimeout=()=>{if(ql())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,n;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null||n.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t,t?.message)}},this.onPayloadHandler=t=>{this.onProviderPayload(t),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Lr.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.fatal(t,`Fatal socket error: ${t?.message}`),this.events.emit(Lr.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(sn.payload,this.onPayloadHandler),this.provider.on(sn.connect,this.onConnectHandler),this.provider.on(sn.disconnect,this.onDisconnectHandler),this.provider.on(sn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ci(e.logger,this.name):Zn(rh({level:e.logger||nM})),this.messages=new XC(this.logger,e.core),this.subscriber=new uP(this,this.logger),this.publisher=new sP(this,this.logger),this.relayUrl=e?.relayUrl||c2,this.projectId=e.projectId,this.bundleId=Qx(),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return yi(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:sr.relay})}async subscribe(e,t){var i,n,s;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const a=typeof((i=t?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=t?.internal)==null?void 0:n.throwOnFailedPublish;let f=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",h;const u=g=>{g.topic===e&&(this.subscriber.off(Fi.created,u),h())};return await Promise.all([new Promise(g=>{h=g,this.subscriber.on(Fi.created,u)}),new Promise(async(g,w)=>{f=await this.subscriber.subscribe(e,N2({internal:{throwOnFailedPublish:a}},t)).catch(M=>{a&&w(M)})||f,g()})]),f}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 transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Vs(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,i)=>{await this.connect(e).then(t).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Eb())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+n?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const n=Ir(_e.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(Lr.message,e),await this.recordMessageEvent(e)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(sn.disconnect,s),await Vs(new Promise((a,f)=>{this.provider.connect().then(a).catch(f)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(a=>{n(a)}).finally(()=>{this.provider.off(sn.disconnect,s),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),await new Promise(async(a,f)=>{const h=()=>{f(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(sn.disconnect,h),await this.subscriber.start().then(a).catch(f).finally(()=>{this.provider.off(sn.disconnect,h)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const n=i;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,_e.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,n,s;if(ql())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(a){this.logger.warn(a,a?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new nn(new jI(tA({sdkVersion:y0,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.warn(`Ignoring message for non-subscribed topic ${t}`),!0;const n=this.messages.has(t,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),b0(e)){if(!e.method.endsWith(oM))return;const t=e.params,{topic:i,message:n,publishedAt:s,attestation:a}=t.data,f={topic:i,message:n,publishedAt:s,transportType:sr.relay,attestation:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(N2({type:"event",event:t.id},f)),this.events.emit(t.id,f),await this.acknowledgePayload(e),await this.onMessageEvent(f)}else sh(e)&&this.events.emit(Lr.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Lr.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=ih(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(sn.payload,this.onPayloadHandler),this.provider.off(sn.connect,this.onConnectHandler),this.provider.off(sn.disconnect,this.onDisconnectHandler),this.provider.off(sn.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Eb();TE(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),clearTimeout(this.pingTimeout),this.events.emit(Lr.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||this.connectPromise||(this.reconnectTimeout=setTimeout(async()=>{clearTimeout(this.reconnectTimeout),await this.transportOpen().catch(e=>this.logger.error(e,e?.message))},_e.toMiliseconds(aM))))}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.transportOpen()}}var mP=Object.defineProperty,L2=Object.getOwnPropertySymbols,bP=Object.prototype.hasOwnProperty,wP=Object.prototype.propertyIsEnumerable,B2=(r,e,t)=>e in r?mP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,F2=(r,e)=>{for(var t in e||(e={}))bP.call(e,t)&&B2(r,t,e[t]);if(L2)for(var t of L2(e))wP.call(e,t)&&B2(r,t,e[t]);return r};class Ho extends KS{constructor(e,t,i,n=ts,s=void 0){super(e,t,i,n),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version=cM,this.cached=[],this.initialized=!1,this.storagePrefix=ts,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(a=>{this.getKey&&a!==null&&!ai(a)?this.map.set(this.getKey(a),a):lE(a)?this.map.set(a.id,a):hE(a)&&this.map.set(a.topic,a)}),this.cached=[],this.initialized=!0)},this.set=async(a,f)=>{this.isInitialized(),this.map.has(a)?await this.update(a,f):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:a,value:f}),this.map.set(a,f),await this.persist())},this.get=a=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:a}),this.getData(a)),this.getAll=a=>(this.isInitialized(),a?this.values.filter(f=>Object.keys(a).every(h=>WI(f[h],a[h]))):this.values),this.update=async(a,f)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:a,update:f});const h=F2(F2({},this.getData(a)),f);this.map.set(a,h),await this.persist()},this.delete=async(a,f)=>{this.isInitialized(),this.map.has(a)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:a,reason:f}),this.map.delete(a),this.addToRecentlyDeleted(a),await this.persist())},this.logger=ci(t,this.name),this.storagePrefix=n,this.getKey=s}get context(){return yi(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())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}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){if(this.recentlyDeleted.includes(e)){const{message:n}=xe("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=xe("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}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:t}=xe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}}class yP{constructor(e,t){this.core=e,this.logger=t,this.name=dM,this.version=pM,this.events=new zr.exports,this.initialized=!1,this.storagePrefix=ts,this.ignoredPayloadTypes=[ws],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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async i=>{this.isInitialized();const n=t0(),s=await this.core.crypto.setSymKey(n),a=Ir(_e.FIVE_MINUTES),f={protocol:a2},h={topic:s,expiry:a,relay:f,active:!1,methods:i?.methods},u=vb({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:f,expiryTimestamp:a,methods:i?.methods});return this.events.emit(Uo.create,h),this.core.expirer.set(s,a),await this.pairings.set(s,h),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:u}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[rs.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:a,relay:f,expiryTimestamp:h,methods:u}=gb(i.uri);n.props.properties.topic=s,n.addTrace(rs.pairing_uri_validation_success),n.addTrace(rs.pairing_uri_not_expired);let g;if(this.pairings.keys.includes(s)){if(g=this.pairings.get(s),n.addTrace(rs.existing_pairing),g.active)throw n.setError(Ss.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(rs.pairing_not_expired)}const w=h||Ir(_e.FIVE_MINUTES),M={topic:s,relay:f,expiry:w,active:!1,methods:u};this.core.expirer.set(s,w),await this.pairings.set(s,M),n.addTrace(rs.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Uo.create,M),n.addTrace(rs.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(a,s),n.addTrace(rs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Ss.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:f})}catch(C){throw n.setError(Ss.subscribe_pairing_topic_failure),C}return n.addTrace(rs.subscribe_pairing_topic_success),M},this.activate=async({topic:i})=>{this.isInitialized();const n=Ir(_e.THIRTY_DAYS);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:a,resolve:f,reject:h}=To();this.events.once(Dt("pairing_ping",s),({error:u})=>{u?h(u):f()}),await a()}},this.updateExpiry=async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})},this.updateMetadata=async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",Gt("USER_DISCONNECTED")),await this.deletePairing(n))},this.formatUriFromPairing=i=>{this.isInitialized();const{topic:n,relay:s,expiry:a,methods:f}=i,h=this.core.crypto.keychain.get(n);return vb({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:h,relay:s,expiryTimestamp:a,methods:f})},this.sendRequest=async(i,n,s)=>{const a=Js(n,s),f=await this.core.crypto.encode(i,a),h=lf[n].req;return this.core.history.set(i,a),this.core.relayer.publish(i,f,h),a.id},this.sendResult=async(i,n,s)=>{const a=ih(i,s),f=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),u=lf[h.request.method].res;await this.core.relayer.publish(n,f,u),await this.core.history.resolve(a)},this.sendError=async(i,n,s)=>{const a=nh(i,s),f=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),u=lf[h.request.method]?lf[h.request.method].res:lf.unregistered_method.res;await this.core.relayer.publish(n,f,u),await this.core.history.resolve(a)},this.deletePairing=async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(n=>Gs(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))},this.onRelayEventRequest=i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(n,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(n,s);default:return this.onUnknownRpcMethodRequest(n,s)}},this.onRelayEventResponse=async i=>{const{topic:n,payload:s}=i,a=(await this.core.history.get(n,s.id)).request.method;switch(a){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(a)}},this.onPairingPingRequest=async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Uo.ping,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onPairingPingResponse=(i,n)=>{const{id:s}=n;setTimeout(()=>{es(n)?this.events.emit(Dt("pairing_ping",s),{}):rn(n)&&this.events.emit(Dt("pairing_ping",s),{error:n.error})},500)},this.onPairingDeleteRequest=async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Uo.delete,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onUnknownRpcMethodRequest=async(i,n)=>{const{id:s,method:a}=n;try{if(this.registeredMethods.includes(a))return;const f=Gt("WC_METHOD_UNSUPPORTED",a);await this.sendError(s,i,f),this.logger.error(f)}catch(f){await this.sendError(s,i,f),this.logger.error(f)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=(i,n)=>{var s;if(!bi(i)){const{message:f}=xe("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Ss.malformed_pairing_uri),new Error(f)}if(!fE(i.uri)){const{message:f}=xe("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Ss.malformed_pairing_uri),new Error(f)}const a=gb(i?.uri);if(!((s=a?.relay)!=null&&s.protocol)){const{message:f}=xe("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Ss.malformed_pairing_uri),new Error(f)}if(!(a!=null&&a.symKey)){const{message:f}=xe("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Ss.malformed_pairing_uri),new Error(f)}if(a!=null&&a.expiryTimestamp&&_e.toMiliseconds(a?.expiryTimestamp){if(!bi(i)){const{message:s}=xe("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidDisconnect=async i=>{if(!bi(i)){const{message:s}=xe("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidPairingTopic=async i=>{if(!wr(i,!1)){const{message:n}=xe("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=xe("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(Gs(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=xe("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}},this.core=e,this.logger=ci(t,this.name),this.pairings=new Ho(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yi(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Lr.message,async e=>{const{topic:t,message:i,transportType:n}=e;if(!this.pairings.keys.includes(t)||n===sr.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(t,i);try{b0(s)?(this.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):sh(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:t,payload:s}),this.core.history.delete(t,s.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(on.expired,async e=>{const{topic:t}=Vm(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Uo.expire,{topic:t}))})}}class _P extends HS{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new zr.exports.EventEmitter,this.name=gM,this.version=vM,this.cached=[],this.initialized=!1,this.storagePrefix=ts,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const a={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:Ir(_e.THIRTY_DAYS)};this.records.set(a.id,a),this.persist(),this.events.emit(Sn.created,a)},this.resolve=async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=rn(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Sn.updated,n))},this.get=async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n)),this.delete=(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Sn.deleted,s)}}),this.persist()},this.exists=async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ci(t,this.name)}get context(){return yi(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 i={topic:t.topic,request:Js(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),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:i}=xe("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Sn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=xe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(Sn.created,e=>{const t=Sn.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Sn.updated,e=>{const t=Sn.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Sn.deleted,e=>{const t=Sn.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(Ha.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{_e.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Sn.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}}class xP extends GS{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new zr.exports.EventEmitter,this.name=mM,this.version=bM,this.cached=[],this.initialized=!1,this.storagePrefix=ts,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}},this.set=(i,n)=>{this.isInitialized();const s=this.formatTarget(i),a={target:s,expiry:n};this.expirations.set(s,a),this.checkExpiry(s,a),this.events.emit(on.created,{target:s,expiration:a})},this.get=i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)},this.del=i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(on.deleted,{target:n,expiration:s})}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ci(t,this.name)}get context(){return yi(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(typeof e=="string")return rA(e);if(typeof e=="number")return iA(e);const{message:t}=xe("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(on.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=xe("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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:i}=xe("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;_e.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(on.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Ha.pulse,()=>this.checkExpirations()),this.events.on(on.created,e=>{const t=on.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(on.expired,e=>{const t=on.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(on.deleted,e=>{const t=on.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}}class AP extends YS{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,this.name=wM,this.verifyUrlV3=_M,this.storagePrefix=ts,this.version=n2,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&_e.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt){if(!Wc()||this.isDevEnv)return;const s=window.location.origin,{id:a,decryptedId:f}=n,h=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${a}&decryptedId=${f}`;try{const u=Oc(),g=this.startAbortTimer(_e.ONE_SECOND*5),w=await new Promise((M,C)=>{const O=()=>{window.removeEventListener("message",j),u.body.removeChild($),C("attestation aborted")};this.abortController.signal.addEventListener("abort",O);const $=u.createElement("iframe");$.src=h,$.style.display="none",$.addEventListener("error",O,{signal:this.abortController.signal});const j=H=>{if(H.data&&typeof H.data=="string")try{const F=JSON.parse(H.data);if(F.type==="verify_attestation"){if(Jd(F.attestation).payload.id!==a)return;clearInterval(g),u.body.removeChild($),this.abortController.signal.removeEventListener("abort",O),window.removeEventListener("message",j),M(F.attestation===null?"":F.attestation)}}catch(F){this.logger.warn(F)}};u.body.appendChild($),window.addEventListener("message",j,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",w),w}catch(u){this.logger.warn(u)}return""},this.resolve=async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:a,encryptedId:f}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Jd(s).payload.id!==f)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!a)return;const h=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(a,h)},this.fetchAttestation=async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const a=this.startAbortTimer(_e.ONE_SECOND*5),f=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(a),f.status===200?await f.json():void 0},this.getVerifyUrl=n=>{let s=n||hf;return xM.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${hf}`),s=hf),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(_e.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}},this.persistPublicKey=async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(f){this.logger.error(f),this.logger.warn("error validating attestation")}const a=await this.fetchAndPersistPublicKey();try{if(a)return this.validateAttestation(n,a)}catch(f){this.logger.error(f),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const a=await this.fetchPublicKey();a&&(await this.persistPublicKey(a),s(a))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n},this.validateAttestation=(n,s)=>{const a=jA(n,s.publicKey),f={hasExpired:_e.toMiliseconds(a.exp)this.abortController.abort(),_e.toMiliseconds(e))}}class EP extends JS{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=AM,this.registerDeviceToken=async i=>{const{clientId:n,token:s,notificationType:a,enableEncrypted:f=!1}=i,h=`${EM}/${this.projectId}/clients`;await fetch(h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:a,token:s,always_raw:f})})},this.logger=ci(t,this.context)}}var SP=Object.defineProperty,U2=Object.getOwnPropertySymbols,IP=Object.prototype.hasOwnProperty,MP=Object.prototype.propertyIsEnumerable,q2=(r,e,t)=>e in r?SP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gf=(r,e)=>{for(var t in e||(e={}))IP.call(e,t)&&q2(r,t,e[t]);if(U2)for(var t of U2(e))MP.call(e,t)&&q2(r,t,e[t]);return r};class CP extends QS{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,this.context=IM,this.storagePrefix=ts,this.storageVersion=SM,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!Qd())try{const n={eventId:Ym(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:km(this.core.relayer.protocol,this.core.relayer.version,y0)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}},this.createEvent=n=>{const{event:s="ERROR",type:a="",properties:{topic:f,trace:h}}=n,u=Ym(),g=this.core.projectId||"",w=Date.now(),M=gf({eventId:u,timestamp:w,props:{event:s,type:a,properties:{topic:f,trace:h}},bundleId:g,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,M),this.shouldPersist=!0),M},this.getEvent=n=>{const{eventId:s,topic:a}=n;if(s)return this.events.get(s);const f=Array.from(this.events.values()).find(h=>h.props.properties.topic===a);if(f)return gf(gf({},f),this.setMethods(f.eventId))},this.deleteEvent=n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(Ha.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{_e.fromMiliseconds(Date.now())-_e.fromMiliseconds(n.timestamp)>MM&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})},this.setMethods=n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)}),this.addTrace=(n,s)=>{const a=this.events.get(n);a&&(a.props.properties.trace.push(s),this.events.set(n,a),this.shouldPersist=!0)},this.setError=(n,s)=>{const a=this.events.get(n);a&&(a.props.type=s,a.timestamp=Date.now(),this.events.set(n,a),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,gf(gf({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,a]of this.events)a.props.type&&n.push(a);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.sendEvent=async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${CM}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${y0}${s}`,{method:"POST",body:JSON.stringify(n)})},this.getAppDomain=()=>Hm().url,this.logger=ci(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var PP=Object.defineProperty,z2=Object.getOwnPropertySymbols,DP=Object.prototype.hasOwnProperty,OP=Object.prototype.propertyIsEnumerable,H2=(r,e,t)=>e in r?PP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k2=(r,e)=>{for(var t in e||(e={}))DP.call(e,t)&&H2(r,t,e[t]);if(z2)for(var t of z2(e))OP.call(e,t)&&H2(r,t,e[t]);return r};class S0 extends zS{constructor(e){var t;super(e),this.protocol=i2,this.version=n2,this.name=oh,this.events=new zr.exports.EventEmitter,this.initialized=!1,this.on=(a,f)=>this.events.on(a,f),this.once=(a,f)=>this.events.once(a,f),this.off=(a,f)=>this.events.off(a,f),this.removeListener=(a,f)=>this.events.removeListener(a,f),this.dispatchEnvelope=({topic:a,message:f,sessionExists:h})=>{if(!a||!f)return;const u={topic:a,message:f,publishedAt:Date.now(),transportType:sr.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:h})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||c2,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=rh({level:typeof e?.logger=="string"&&e.logger?e.logger:YI.logger,name:oh}),{logger:n,chunkLoggerController:s}=qS({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,f;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((f=this.logChunkController)==null||f.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ci(n,this.name),this.heartbeat=new o0,this.crypto=new ZC(this,this.logger,e?.keychain),this.history=new _P(this,this.logger),this.expirer=new xP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new uS(k2(k2({},JI),e?.storageOptions)),this.relayer=new vP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new yP(this,this.logger),this.verify=new AP(this,this.logger,this.storage),this.echoClient=new EP(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new CP(this,this.logger,e?.telemetryEnabled)}static async init(e){const t=new S0(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(fM,i),t}get context(){return yi(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(f2,this.linkModeSupportedApps))}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.eventClient.init(),this.linkModeSupportedApps=await this.storage.getItem(f2)||[],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 RP=S0,j2="wc",W2=2,K2="client",I0=`${j2}@${W2}:${K2}:`,M0={name:K2,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},V2="WALLETCONNECT_DEEPLINK_CHOICE",TP="proposal",G2="Proposal expired",$P="session",Wa=_e.SEVEN_DAYS,NP="engine",Br={wc_sessionPropose:{req:{ttl:_e.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:_e.ONE_DAY,prompt:!1,tag:1104},res:{ttl:_e.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:_e.ONE_DAY,prompt:!1,tag:1106},res:{ttl:_e.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:_e.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:_e.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:_e.ONE_DAY,prompt:!1,tag:1112},res:{ttl:_e.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:_e.ONE_DAY,prompt:!1,tag:1114},res:{ttl:_e.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:_e.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:_e.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:_e.FIVE_MINUTES,prompt:!1,tag:1119}}},C0={min:_e.FIVE_MINUTES,max:_e.SEVEN_DAYS},is={idle:"IDLE",active:"ACTIVE"},LP="request",BP=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],FP="wc",UP="auth",qP="authKeys",zP="pairingTopics",HP="requests",ch=`${FP}@${1.5}:${UP}:`,fh=`${ch}:PUB_KEY`;var kP=Object.defineProperty,jP=Object.defineProperties,WP=Object.getOwnPropertyDescriptors,Y2=Object.getOwnPropertySymbols,KP=Object.prototype.hasOwnProperty,VP=Object.prototype.propertyIsEnumerable,J2=(r,e,t)=>e in r?kP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pr=(r,e)=>{for(var t in e||(e={}))KP.call(e,t)&&J2(r,t,e[t]);if(Y2)for(var t of Y2(e))VP.call(e,t)&&J2(r,t,e[t]);return r},Mn=(r,e)=>jP(r,WP(e));class GP extends XS{constructor(e){super(e),this.name=NP,this.events=new zr.exports,this.initialized=!1,this.requestQueue={state:is.idle,queue:[]},this.sessionRequestQueue={state:is.idle,queue:[]},this.requestQueueDelay=_e.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Br)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},_e.toMiliseconds(this.requestQueueDelay)))},this.connect=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Mn(pr({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:a,sessionProperties:f,relays:h}=i;let u=n,g,w=!1;try{u&&(w=this.client.core.pairing.pairings.get(u).active)}catch(B){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),B}if(!u||!w){const{topic:B,uri:z}=await this.client.core.pairing.create();u=B,g=z}if(!u){const{message:B}=xe("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(B)}const M=await this.client.core.crypto.generateKeyPair(),C=Br.wc_sessionPropose.req.ttl||_e.FIVE_MINUTES,O=Ir(C),$=pr({requiredNamespaces:s,optionalNamespaces:a,relays:h??[{protocol:a2}],proposer:{publicKey:M,metadata:this.client.metadata},expiryTimestamp:O,pairingTopic:u},f&&{sessionProperties:f}),{reject:j,resolve:H,done:F}=To(C,G2);this.events.once(Dt("session_connect"),async({error:B,session:z})=>{if(B)j(B);else if(z){z.self.publicKey=M;const W=Mn(pr({},z),{pairingTopic:$.pairingTopic,requiredNamespaces:$.requiredNamespaces,optionalNamespaces:$.optionalNamespaces,transportType:sr.relay});await this.client.session.set(z.topic,W),await this.setExpiry(z.topic,z.expiry),u&&await this.client.core.pairing.updateMetadata({topic:u,metadata:z.peer.metadata}),this.cleanupDuplicatePairings(W),H(W)}});const G=await this.sendRequest({topic:u,method:"wc_sessionPropose",params:$,throwOnFailedPublish:!0});return await this.setProposal(G,pr({id:G},$)),{uri:g,approval:F}},this.pair=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}},this.approve=async t=>{var i,n,s;const a=this.client.core.eventClient.createEvent({properties:{topic:(i=t?.id)==null?void 0:i.toString(),trace:[In.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw a.setError(qo.no_internet_connection),U}try{await this.isValidProposalId(t?.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),a.setError(qo.proposal_not_found),U}try{await this.isValidApprove(t)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),a.setError(qo.session_approve_namespace_validation_failure),U}const{id:f,relayProtocol:h,namespaces:u,sessionProperties:g,sessionConfig:w}=t,M=this.client.proposal.get(f);this.client.core.eventClient.deleteEvent({eventId:a.eventId});const{pairingTopic:C,proposer:O,requiredNamespaces:$,optionalNamespaces:j}=M;let H=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:C});H||(H=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:In.session_approve_started,properties:{topic:C,trace:[In.session_approve_started,In.session_namespaces_validation_success]}}));const F=await this.client.core.crypto.generateKeyPair(),G=O.publicKey,B=await this.client.core.crypto.generateSharedKey(F,G),z=pr(pr({relay:{protocol:h??"irn"},namespaces:u,controller:{publicKey:F,metadata:this.client.metadata},expiry:Ir(Wa)},g&&{sessionProperties:g}),w&&{sessionConfig:w}),W=sr.relay;H.addTrace(In.subscribing_session_topic);try{await this.client.core.relayer.subscribe(B,{transportType:W})}catch(U){throw H.setError(qo.subscribe_session_topic_failure),U}H.addTrace(In.subscribe_session_topic_success);const _=Mn(pr({},z),{topic:B,requiredNamespaces:$,optionalNamespaces:j,pairingTopic:C,acknowledged:!1,self:z.controller,peer:{publicKey:O.publicKey,metadata:O.metadata},controller:F,transportType:sr.relay});await this.client.session.set(B,_),H.addTrace(In.store_session);try{H.addTrace(In.publishing_session_settle),await this.sendRequest({topic:B,method:"wc_sessionSettle",params:z,throwOnFailedPublish:!0}).catch(U=>{throw H?.setError(qo.session_settle_publish_failure),U}),H.addTrace(In.session_settle_publish_success),H.addTrace(In.publishing_session_approve),await this.sendResult({id:f,topic:C,result:{relay:{protocol:h??"irn"},responderPublicKey:F},throwOnFailedPublish:!0}).catch(U=>{throw H?.setError(qo.session_approve_publish_failure),U}),H.addTrace(In.session_approve_publish_success)}catch(U){throw this.client.logger.error(U),this.client.session.delete(B,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(B),U}return this.client.core.eventClient.deleteEvent({eventId:H.eventId}),await this.client.core.pairing.updateMetadata({topic:C,metadata:O.metadata}),await this.client.proposal.delete(f,Gt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:C}),await this.setExpiry(B,Ir(Wa)),{topic:B,acknowledged:()=>Promise.resolve(this.client.session.get(B))}},this.reject=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(a){throw this.client.logger.error("reject() -> isValidReject() failed"),a}const{id:i,reason:n}=t;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(a){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),a}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:Br.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED")))},this.update=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(w){throw this.client.logger.error("update() -> isValidUpdate() failed"),w}const{topic:i,namespaces:n}=t,{done:s,resolve:a,reject:f}=To(),h=Es(),u=Fo().toString(),g=this.client.session.get(i).namespaces;return this.events.once(Dt("session_update",h),({error:w})=>{w?f(w):a()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:h,relayRpcId:u}).catch(w=>{this.client.logger.error(w),this.client.session.update(i,{namespaces:g}),f(w)}),{acknowledged:s}},this.extend=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(h){throw this.client.logger.error("extend() -> isValidExtend() failed"),h}const{topic:i}=t,n=Es(),{done:s,resolve:a,reject:f}=To();return this.events.once(Dt("session_extend",n),({error:h})=>{h?f(h):a()}),await this.setExpiry(i,Ir(Wa)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(h=>{f(h)}),{acknowledged:s}},this.request=async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(O){throw this.client.logger.error("request() -> isValidRequest() failed"),O}const{chainId:i,request:n,topic:s,expiry:a=Br.wc_sessionRequest.req.ttl}=t,f=this.client.session.get(s);f?.transportType===sr.relay&&await this.confirmOnlineStateOrThrow();const h=Es(),u=Fo().toString(),{done:g,resolve:w,reject:M}=To(a,"Request expired. Please try again.");this.events.once(Dt("session_request",h),({error:O,result:$})=>{O?M(O):w($)});const C=this.getAppLinkIfEnabled(f.peer.metadata,f.transportType);return C?(await this.sendRequest({clientRpcId:h,relayRpcId:u,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0,appLink:C}).catch(O=>M(O)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),await g()):await Promise.all([new Promise(async O=>{await this.sendRequest({clientRpcId:h,relayRpcId:u,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0}).catch($=>M($)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),O()}),new Promise(async O=>{var $;if(!(($=f.sessionConfig)!=null&&$.disableDeepLink)){const j=await oA(this.client.core.storage,V2);await nA({id:h,topic:s,wcDeepLink:j})}O()}),g()]).then(O=>O[2])},this.respond=async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:n}=t,{id:s}=n,a=this.client.session.get(i);a.transportType===sr.relay&&await this.confirmOnlineStateOrThrow();const f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);es(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:f}):rn(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:f}),this.cleanupAfterResponse(t)},this.ping=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=t;if(this.client.session.keys.includes(i)){const n=Es(),s=Fo().toString(),{done:a,resolve:f,reject:h}=To();this.events.once(Dt("session_ping",n),({error:u})=>{u?h(u):f()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),a()])}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:n,chainId:s}=t,a=Fo().toString(),f=Es();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:a,clientRpcId:f})},this.disconnect=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Gt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=xe("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}},this.find=t=>(this.isInitialized(),this.client.session.getAll().filter(i=>aE(i,t))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(t,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(t);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),a=s?sr.link_mode:sr.relay;a===sr.relay&&await this.confirmOnlineStateOrThrow();const{chains:f,statement:h="",uri:u,domain:g,nonce:w,type:M,exp:C,nbf:O,methods:$=[],expiry:j}=t,H=[...t.resources||[]],{topic:F,uri:G}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:a});this.client.logger.info({message:"Generated new pairing",pairing:{topic:F,uri:G}});const B=await this.client.core.crypto.generateKeyPair(),z=jl(B);if(await Promise.all([this.client.auth.authKeys.set(fh,{responseTopic:z,publicKey:B}),this.client.auth.pairingTopics.set(z,{topic:z,pairingTopic:F})]),await this.client.core.relayer.subscribe(z,{transportType:a}),this.client.logger.info(`sending request to new pairing topic: ${F}`),$.length>0){const{namespace:D}=Ua(f[0]);let S=CA(D,"request",$);kl(H)&&(S=DA(S,H.pop())),H.push(S)}const W=j&&j>Br.wc_sessionAuthenticate.req.ttl?j:Br.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:M??"caip122",chains:f,statement:h,aud:u,domain:g,version:"1",nonce:w,iat:new Date().toISOString(),exp:C,nbf:O,resources:H},requester:{publicKey:B,metadata:this.client.metadata},expiryTimestamp:Ir(W)},U={eip155:{chains:f,methods:[...new Set(["personal_sign",...$])],events:["chainChanged","accountsChanged"]}},ee={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:F,proposer:{publicKey:B,metadata:this.client.metadata},expiryTimestamp:Ir(Br.wc_sessionPropose.req.ttl)},{done:oe,resolve:L,reject:b}=To(W,"Request expired"),m=async({error:D,session:S})=>{if(this.events.off(Dt("session_request",d),l),D)b(D);else if(S){S.self.publicKey=B,await this.client.session.set(S.topic,S),await this.setExpiry(S.topic,S.expiry),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:S.peer.metadata});const v=this.client.session.get(S.topic);await this.deleteProposal(y),L({session:v})}},l=async D=>{var S,v,A;if(await this.deletePendingAuthRequest(d,{message:"fulfilled",code:0}),D.error){const J=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return D.error.code===J.code?void 0:(this.events.off(Dt("session_connect"),m),b(D.error.message))}await this.deleteProposal(y),this.events.off(Dt("session_connect"),m);const{cacaos:x,responder:N}=D.result,ae=[],R=[];for(const J of x){await Xm({cacao:J,projectId:this.client.core.projectId})||(this.client.logger.error(J,"Signature verification failed"),b(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:K}=J,E=kl(K.resources),Y=[Xd(K.iss)],re=Hl(K.iss);if(E){const le=rb(E),he=ib(E);ae.push(...le),Y.push(...he)}for(const le of Y)R.push(`${le}:${re}`)}const X=await this.client.core.crypto.generateSharedKey(B,N.publicKey);let V;ae.length>0&&(V={topic:X,acknowledged:!0,self:{publicKey:B,metadata:this.client.metadata},peer:N,controller:N.publicKey,expiry:Ir(Wa),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:F,namespaces:mb([...new Set(ae)],[...new Set(R)]),transportType:a},await this.client.core.relayer.subscribe(X,{transportType:a}),await this.client.session.set(X,V),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:N.metadata}),V=this.client.session.get(X)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(v=N.metadata.redirect)!=null&&v.linkMode&&(A=N.metadata.redirect)!=null&&A.universal&&i&&(this.client.core.addLinkModeSupportedApp(N.metadata.redirect.universal),this.client.session.update(X,{transportType:sr.link_mode})),L({auths:x,session:V})},d=Es(),y=Es();this.events.once(Dt("session_connect"),m),this.events.once(Dt("session_request",d),l);let P;try{if(s){const D=Js("wc_sessionAuthenticate",_,d);this.client.core.history.set(F,D);const S=await this.client.core.crypto.encode("",D,{type:Jc,encoding:Gc});P=Kl(i,F,S)}else await Promise.all([this.sendRequest({topic:F,method:"wc_sessionAuthenticate",params:_,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:d}),this.sendRequest({topic:F,method:"wc_sessionPropose",params:ee,expiry:Br.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:y})])}catch(D){throw this.events.off(Dt("session_connect"),m),this.events.off(Dt("session_request",d),l),D}return await this.setProposal(y,pr({id:y},ee)),await this.setAuthRequest(d,{request:Mn(pr({},_),{verifyContext:{}}),pairingTopic:F,transportType:a}),{uri:P??G,response:oe}},this.approveSessionAuthenticate=async t=>{const{id:i,auths:n}=t,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[zo.authenticated_session_approve_started]}});try{this.isInitialized()}catch(j){throw s.setError(uf.no_internet_connection),j}const a=this.getPendingAuthRequest(i);if(!a)throw s.setError(uf.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const f=a.transportType||sr.relay;f===sr.relay&&await this.confirmOnlineStateOrThrow();const h=a.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),g=jl(h),w={type:ws,receiverPublicKey:h,senderPublicKey:u},M=[],C=[];for(const j of n){if(!await Xm({cacao:j,projectId:this.client.core.projectId})){s.setError(uf.invalid_cacao);const z=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:g,error:z,encodeOpts:w}),new Error(z.message)}s.addTrace(zo.cacaos_verified);const{p:H}=j,F=kl(H.resources),G=[Xd(H.iss)],B=Hl(H.iss);if(F){const z=rb(F),W=ib(F);M.push(...z),G.push(...W)}for(const z of G)C.push(`${z}:${B}`)}const O=await this.client.core.crypto.generateSharedKey(u,h);s.addTrace(zo.create_authenticated_session_topic);let $;if(M?.length>0){$={topic:O,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:h,metadata:a.requester.metadata},controller:h,expiry:Ir(Wa),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:a.pairingTopic,namespaces:mb([...new Set(M)],[...new Set(C)]),transportType:f},s.addTrace(zo.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:f})}catch(j){throw s.setError(uf.subscribe_authenticated_session_topic_failure),j}s.addTrace(zo.subscribe_authenticated_session_topic_success),await this.client.session.set(O,$),s.addTrace(zo.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:a.pairingTopic,metadata:a.requester.metadata})}s.addTrace(zo.publishing_authenticated_session_approve);try{await this.sendResult({topic:g,id:i,result:{cacaos:n,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:w,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(a.requester.metadata,f)})}catch(j){throw s.setError(uf.authenticated_session_approve_publish_failure),j}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:a.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:$}},this.rejectSessionAuthenticate=async t=>{this.isInitialized();const{id:i,reason:n}=t,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===sr.relay&&await this.confirmOnlineStateOrThrow();const a=s.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),h=jl(a),u={type:ws,receiverPublicKey:a,senderPublicKey:f};await this.sendError({id:i,topic:h,error:n,encodeOpts:u,rpcOpts:Br.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED"))},this.formatAuthMessage=t=>{this.isInitialized();const{request:i,iss:n}=t;return eb(i,n)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)},this.cleanupDuplicatePairings=async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var a,f;return((a=s.peerMetadata)==null?void 0:a.url)&&((f=s.peerMetadata)==null?void 0:f.url)===t.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}},this.deleteSession=async t=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:a=!0,id:f=0}=t,{self:h}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(h.publicKey)&&await this.client.core.crypto.deleteKeyPair(h.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(V2).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===n&&this.deletePendingSessionRequest(u.id,Gt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=is.idle),a&&this.client.events.emit("session_delete",{id:f,topic:n})},this.deleteProposal=async(t,i)=>{if(i)try{const n=this.client.proposal.get(t),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s?.setError(qo.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Gt("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")},this.deletePendingSessionRequest=async(t,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),n?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==t),n&&(this.sessionRequestQueue.state=is.idle,this.client.events.emit("session_request_expire",{id:t}))},this.deletePendingAuthRequest=async(t,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),n?Promise.resolve():this.client.core.expirer.del(t)])},this.setExpiry=async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))},this.setProposal=async(t,i)=>{this.client.core.expirer.set(t,Ir(Br.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)},this.setAuthRequest=async(t,i)=>{const{request:n,pairingTopic:s,transportType:a=sr.relay}=i;this.client.core.expirer.set(t,n.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:t,pairingTopic:s,verifyContext:n.verifyContext,transportType:a})},this.setPendingSessionRequest=async t=>{const{id:i,topic:n,params:s,verifyContext:a}=t,f=s.request.expiryTimestamp||Ir(Br.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,f),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:a})},this.sendRequest=async t=>{const{topic:i,method:n,params:s,expiry:a,relayRpcId:f,clientRpcId:h,throwOnFailedPublish:u,appLink:g}=t,w=Js(n,s,h);let M;const C=!!g;try{const j=C?Gc:Ys;M=await this.client.core.crypto.encode(i,w,{encoding:j})}catch(j){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),j}let O;if(BP.includes(n)){const j=ys(JSON.stringify(w)),H=ys(M);O=await this.client.core.verify.register({id:H,decryptedId:j})}const $=Br[n].req;if($.attestation=O,a&&($.ttl=a),f&&($.id=f),this.client.core.history.set(i,w),C){const j=Kl(g,i,M);await global.Linking.openURL(j,this.client.name)}else{const j=Br[n].req;a&&(j.ttl=a),f&&(j.id=f),u?(j.internal=Mn(pr({},j.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,M,j)):this.client.core.relayer.publish(i,M,j).catch(H=>this.client.logger.error(H))}return w.id},this.sendResult=async t=>{const{id:i,topic:n,result:s,throwOnFailedPublish:a,encodeOpts:f,appLink:h}=t,u=ih(i,s);let g;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const C=w?Gc:Ys;g=await this.client.core.crypto.encode(n,u,Mn(pr({},f||{}),{encoding:C}))}catch(C){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),C}let M;try{M=await this.client.core.history.get(n,i)}catch(C){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),C}if(w){const C=Kl(h,n,g);await global.Linking.openURL(C,this.client.name)}else{const C=Br[M.request.method].res;a?(C.internal=Mn(pr({},C.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,g,C)):this.client.core.relayer.publish(n,g,C).catch(O=>this.client.logger.error(O))}await this.client.core.history.resolve(u)},this.sendError=async t=>{const{id:i,topic:n,error:s,encodeOpts:a,rpcOpts:f,appLink:h}=t,u=nh(i,s);let g;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const C=w?Gc:Ys;g=await this.client.core.crypto.encode(n,u,Mn(pr({},a||{}),{encoding:C}))}catch(C){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),C}let M;try{M=await this.client.core.history.get(n,i)}catch(C){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),C}if(w){const C=Kl(h,n,g);await global.Linking.openURL(C,this.client.name)}else{const C=f||Br[M.request.method].res;this.client.core.relayer.publish(n,g,C)}await this.client.core.history.resolve(u)},this.cleanup=async()=>{const t=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;Gs(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&t.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{Gs(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...t.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])},this.onRelayEventRequest=async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===is.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=is.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=is.idle},this.processRequest=async t=>{const{topic:i,payload:n,attestation:s,transportType:a,encryptedId:f}=t,h=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:h}))switch(h){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:f});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:f,transportType:a});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:f,transportType:a});default:return this.client.logger.info(`Unsupported request method ${h}`)}},this.onRelayEventResponse=async t=>{const{topic:i,payload:n,transportType:s}=t,a=(await this.client.core.history.get(i,n.id)).request.method;switch(a){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${a}`)}},this.onRelayEventUnknownPayload=t=>{const{topic:i}=t,{message:n}=xe("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},this.shouldIgnorePairingRequest=t=>{const{topic:i,requestMethod:n}=t,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async t=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=t,{params:f,id:h}=n;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Ss.proposal_listener_not_found)),this.isValidConnect(pr({},n.params));const g=f.expiryTimestamp||Ir(Br.wc_sessionPropose.req.ttl),w=pr({id:h,pairingTopic:i,expiryTimestamp:g},f);await this.setProposal(h,w);const M=await this.getVerifyContext({attestationId:s,hash:ys(JSON.stringify(n)),encryptedId:a,metadata:w.proposer.metadata});u?.addTrace(rs.emit_session_proposal),this.client.events.emit("session_proposal",{id:h,params:w,verifyContext:M})}catch(u){await this.sendError({id:h,topic:i,error:u,rpcOpts:Br.wc_sessionPropose.autoReject}),this.client.logger.error(u)}},this.onSessionProposeResponse=async(t,i,n)=>{const{id:s}=i;if(es(i)){const{result:a}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const f=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:f});const h=f.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:h});const u=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const g=await this.client.core.crypto.generateSharedKey(h,u);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:g});const w=await this.client.core.relayer.subscribe(g,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:t})}else if(rn(i)){await this.client.proposal.delete(s,Gt("USER_DISCONNECTED"));const a=Dt("session_connect");if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners, 954`);this.events.emit(Dt("session_connect"),{error:i.error})}},this.onSessionSettleRequest=async(t,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:a,controller:f,expiry:h,namespaces:u,sessionProperties:g,sessionConfig:w}=i.params,M=Mn(pr(pr({topic:t,relay:a,expiry:h,namespaces:u,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:f.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:f.publicKey,metadata:f.metadata}},g&&{sessionProperties:g}),w&&{sessionConfig:w}),{transportType:sr.relay}),C=Dt("session_connect");if(this.events.listenerCount(C)===0)throw new Error(`emitting ${C} without any listeners 997`);this.events.emit(Dt("session_connect"),{session:M}),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(a){await this.sendError({id:n,topic:t,error:a}),this.client.logger.error(a)}},this.onSessionSettleResponse=async(t,i)=>{const{id:n}=i;es(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Dt("session_approve",n),{})):rn(i)&&(await this.client.session.delete(t,Gt("USER_DISCONNECTED")),this.events.emit(Dt("session_approve",n),{error:i.error}))},this.onSessionUpdateRequest=async(t,i)=>{const{params:n,id:s}=i;try{const a=`${t}_session_update`,f=rf.get(a);if(f&&this.isRequestOutOfSync(f,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:t,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(pr({topic:t},n));try{rf.set(a,s),await this.client.session.update(t,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0})}catch(h){throw rf.delete(a),h}this.client.events.emit("session_update",{id:s,topic:t,params:n})}catch(a){await this.sendError({id:s,topic:t,error:a}),this.client.logger.error(a)}},this.isRequestOutOfSync=(t,i)=>i.toString().slice(0,-3){const{id:n}=i,s=Dt("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);es(i)?this.events.emit(Dt("session_update",n),{}):rn(i)&&this.events.emit(Dt("session_update",n),{error:i.error})},this.onSessionExtendRequest=async(t,i)=>{const{id:n}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,Ir(Wa)),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:n,topic:t})}catch(s){await this.sendError({id:n,topic:t,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(t,i)=>{const{id:n}=i,s=Dt("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);es(i)?this.events.emit(Dt("session_extend",n),{}):rn(i)&&this.events.emit(Dt("session_extend",n),{error:i.error})},this.onSessionPingRequest=async(t,i)=>{const{id:n}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:t})}catch(s){await this.sendError({id:n,topic:t,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(t,i)=>{const{id:n}=i,s=Dt("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{es(i)?this.events.emit(Dt("session_ping",n),{}):rn(i)&&this.events.emit(Dt("session_ping",n),{error:i.error})},500)},this.onSessionDeleteRequest=async(t,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Lr.publish,async()=>{s(await this.deleteSession({topic:t,id:n}))})}),this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Gt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async t=>{var i,n,s;const{topic:a,payload:f,attestation:h,encryptedId:u,transportType:g}=t,{id:w,params:M}=f;try{await this.isValidRequest(pr({topic:a},M));const C=this.client.session.get(a),O=await this.getVerifyContext({attestationId:h,hash:ys(JSON.stringify(Js("wc_sessionRequest",M,w))),encryptedId:u,metadata:C.peer.metadata,transportType:g}),$={id:w,topic:a,params:M,verifyContext:O};await this.setPendingSessionRequest($),g===sr.link_mode&&(i=C.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=C.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest($):(this.addSessionRequestToSessionRequestQueue($),this.processSessionRequestQueue())}catch(C){await this.sendError({id:w,topic:a,error:C}),this.client.logger.error(C)}},this.onSessionRequestResponse=(t,i)=>{const{id:n}=i,s=Dt("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);es(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionEventRequest=async(t,i)=>{const{id:n,params:s}=i;try{const a=`${t}_session_event_${s.event.name}`,f=rf.get(a);if(f&&this.isRequestOutOfSync(f,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(pr({topic:t},s)),this.client.events.emit("session_event",{id:n,topic:t,params:s}),rf.set(a,n)}catch(a){await this.sendError({id:n,topic:t,error:a}),this.client.logger.error(a)}},this.onSessionAuthenticateResponse=(t,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),es(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async t=>{var i;const{topic:n,payload:s,attestation:a,encryptedId:f,transportType:h}=t;try{const{requester:u,authPayload:g,expiryTimestamp:w}=s.params,M=await this.getVerifyContext({attestationId:a,hash:ys(JSON.stringify(s)),encryptedId:f,metadata:u.metadata,transportType:h}),C={requester:u,pairingTopic:n,id:s.id,authPayload:g,verifyContext:M,expiryTimestamp:w};await this.setAuthRequest(s.id,{request:C,pairingTopic:n,transportType:h}),h===sr.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:M})}catch(u){this.client.logger.error(u);const g=s.params.requester.publicKey,w=await this.client.core.crypto.generateKeyPair(),M=this.getAppLinkIfEnabled(s.params.requester.metadata,h),C={type:ws,receiverPublicKey:g,senderPublicKey:w};await this.sendError({id:s.id,topic:n,error:u,encodeOpts:C,rpcOpts:Br.wc_sessionAuthenticate.autoReject,appLink:M})}},this.addSessionRequestToSessionRequestQueue=t=>{this.sessionRequestQueue.queue.push(t)},this.cleanupAfterResponse=t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=is.idle,this.processSessionRequestQueue()},_e.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:t,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===t&&s.request.method==="wc_sessionRequest").forEach(s=>{const a=s.request.id,f=Dt("session_request",a);if(this.events.listenerCount(f)===0)throw new Error(`emitting ${f} without any listeners`);this.events.emit(Dt("session_request",s.request.id),{error:i})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===is.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=is.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}},this.emitSessionRequest=t=>{this.client.events.emit("session_request",t)},this.onPairingCreated=t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:Js("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async t=>{if(!bi(t)){const{message:h}=xe("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:a,relays:f}=t;if(ai(i)||await this.isValidPairingTopic(i),!wE(f,!0)){const{message:h}=xe("MISSING_OR_INVALID",`connect() relays: ${f}`);throw new Error(h)}!ai(n)&&tf(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!ai(s)&&tf(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ai(a)||this.validateSessionProps(a,"sessionProperties")},this.validateNamespaces=(t,i)=>{const n=bE(t,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async t=>{if(!bi(t))throw new Error(xe("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const f=this.client.proposal.get(i),h=n0(n,"approve()");if(h)throw new Error(h.message);const u=xb(f.requiredNamespaces,n,"approve()");if(u)throw new Error(u.message);if(!wr(s,!0)){const{message:g}=xe("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(g)}ai(a)||this.validateSessionProps(a,"sessionProperties")},this.isValidReject=async t=>{if(!bi(t)){const{message:s}=xe("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(s)}const{id:i,reason:n}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!_E(n)){const{message:s}=xe("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}},this.isValidSessionSettleRequest=t=>{if(!bi(t)){const{message:u}=xe("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(u)}const{relay:i,controller:n,namespaces:s,expiry:a}=t;if(!yb(i)){const{message:u}=xe("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const f=uE(n,"onSessionSettleRequest()");if(f)throw new Error(f.message);const h=n0(s,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(Gs(a)){const{message:u}=xe("EXPIRED","onSessionSettleRequest()");throw new Error(u)}},this.isValidUpdate=async t=>{if(!bi(t)){const{message:h}=xe("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(h)}const{topic:i,namespaces:n}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),a=n0(n,"update()");if(a)throw new Error(a.message);const f=xb(s.requiredNamespaces,n,"update()");if(f)throw new Error(f.message)},this.isValidExtend=async t=>{if(!bi(t)){const{message:n}=xe("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(n)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)},this.isValidRequest=async t=>{if(!bi(t)){const{message:h}=xe("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(h)}const{topic:i,request:n,chainId:s,expiry:a}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:f}=this.client.session.get(i);if(!_b(f,s)){const{message:h}=xe("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(h)}if(!xE(n)){const{message:h}=xe("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(h)}if(!SE(f,s,n.method)){const{message:h}=xe("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(h)}if(a&&!PE(a,C0)){const{message:h}=xe("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${C0.min} and ${C0.max}`);throw new Error(h)}},this.isValidRespond=async t=>{var i;if(!bi(t)){const{message:a}=xe("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(a)}const{topic:n,response:s}=t;try{await this.isValidSessionTopic(n)}catch(a){throw(i=t?.response)!=null&&i.id&&this.cleanupAfterResponse(t),a}if(!AE(s)){const{message:a}=xe("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidPing=async t=>{if(!bi(t)){const{message:n}=xe("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(n)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async t=>{if(!bi(t)){const{message:f}=xe("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(f)}const{topic:i,event:n,chainId:s}=t;await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!_b(a,s)){const{message:f}=xe("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(f)}if(!EE(n)){const{message:f}=xe("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(f)}if(!IE(a,s,n.name)){const{message:f}=xe("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(f)}},this.isValidDisconnect=async t=>{if(!bi(t)){const{message:n}=xe("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(n)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidAuthenticate=t=>{const{chains:i,uri:n,domain:s,nonce:a}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!wr(n,!1))throw new Error("uri is required parameter");if(!wr(s,!1))throw new Error("domain is required parameter");if(!wr(a,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(h=>Ua(h).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:f}=Ua(i[0]);if(f!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async t=>{const{attestationId:i,hash:n,encryptedId:s,metadata:a,transportType:f}=t,h={verified:{verifyUrl:a.verifyUrl||hf,validation:"UNKNOWN",origin:a.url||""}};try{if(f===sr.link_mode){const g=this.getAppLinkIfEnabled(a,f);return h.verified.validation=g&&new URL(g).origin===new URL(a.url).origin?"VALID":"INVALID",h}const u=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:a.verifyUrl});u&&(h.verified.origin=u.origin,h.verified.isScam=u.isScam,h.verified.validation=u.origin===new URL(a.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(h)}`),h},this.validateSessionProps=(t,i)=>{Object.values(t).forEach(n=>{if(!wr(n,!1)){const{message:s}=xe("MISSING_OR_INVALID",`${i} must be in Record format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})},this.getPendingAuthRequest=t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0},this.addToRecentlyDeleted=(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const a of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(a)}}},this.checkRecentlyDeleted=t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:n}=xe("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(n)}},this.isLinkModeEnabled=(t,i)=>{var n,s,a,f,h,u,g,w,M;return!t||i!==sr.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((f=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:f.universal)!==void 0&&((u=(h=this.client.metadata)==null?void 0:h.redirect)==null?void 0:u.universal)!==""&&((g=t?.redirect)==null?void 0:g.universal)!==void 0&&((w=t?.redirect)==null?void 0:w.universal)!==""&&((M=t?.redirect)==null?void 0:M.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(t,i)=>{var n;return this.isLinkModeEnabled(t,i)?(n=t?.redirect)==null?void 0:n.universal:void 0},this.handleLinkModeMessage=({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Gm(t,"topic")||"",n=decodeURIComponent(Gm(t,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:sr.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})},this.registerLinkModeListeners=async()=>{var t;if(Qd()||qa()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}}isInitialized(){if(!this.initialized){const{message:e}=xe("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Lr.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:n,transportType:s}=e,{publicKey:a}=this.client.auth.authKeys.keys.includes(fh)?this.client.auth.authKeys.get(fh):{responseTopic:void 0,publicKey:void 0},f=await this.client.core.crypto.decode(t,i,{receiverPublicKey:a,encoding:s===sr.link_mode?Gc:Ys});try{b0(f)?(this.client.core.history.set(t,f),this.onRelayEventRequest({topic:t,payload:f,attestation:n,transportType:s,encryptedId:ys(i)})):sh(f)?(await this.client.core.history.resolve(f),await this.onRelayEventResponse({topic:t,payload:f,transportType:s}),this.client.core.history.delete(t,f.id)):this.onRelayEventUnknownPayload({topic:t,payload:f,transportType:s})}catch(h){this.client.logger.error(h)}}registerExpirerEvents(){this.client.core.expirer.on(on.expired,async e=>{const{topic:t,id:i}=Vm(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,xe("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,xe("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Uo.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Uo.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!wr(e,!1)){const{message:t}=xe("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}=xe("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Gs(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=xe("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!wr(e,!1)){const{message:t}=xe("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=xe("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Gs(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=xe("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=xe("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(wr(e,!1)){const{message:t}=xe("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=xe("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!yE(e)){const{message:t}=xe("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=xe("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Gs(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=xe("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class YP extends Ho{constructor(e,t){super(e,t,TP,I0),this.core=e,this.logger=t}}class JP extends Ho{constructor(e,t){super(e,t,$P,I0),this.core=e,this.logger=t}}class QP extends Ho{constructor(e,t){super(e,t,LP,I0,i=>i.id),this.core=e,this.logger=t}}class ZP extends Ho{constructor(e,t){super(e,t,qP,ch,()=>fh),this.core=e,this.logger=t}}class XP extends Ho{constructor(e,t){super(e,t,zP,ch),this.core=e,this.logger=t}}class eD extends Ho{constructor(e,t){super(e,t,HP,ch,i=>i.id),this.core=e,this.logger=t}}class tD{constructor(e,t){this.core=e,this.logger=t,this.authKeys=new ZP(this.core,this.logger),this.pairingTopics=new XP(this.core,this.logger),this.requests=new eD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class P0 extends ZS{constructor(e){super(e),this.protocol=j2,this.version=W2,this.name=M0.name,this.events=new zr.exports.EventEmitter,this.on=(i,n)=>this.events.on(i,n),this.once=(i,n)=>this.events.once(i,n),this.off=(i,n)=>this.events.off(i,n),this.removeListener=(i,n)=>this.events.removeListener(i,n),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}},this.update=async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}},this.request=async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}},this.find=i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.authenticate=async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||M0.name,this.metadata=e?.metadata||Hm(),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Zn(rh({level:e?.logger||M0.logger}));this.core=e?.core||new RP(e),this.logger=ci(t,this.name),this.session=new JP(this.core,this.logger),this.proposal=new YP(this.core,this.logger),this.pendingRequest=new QP(this.core,this.logger),this.engine=new GP(this),this.auth=new tD(this.core,this.logger)}static async init(e){const t=new P0(e);return await t.initialize(),t}get context(){return yi(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.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},_e.toMiliseconds(_e.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var D0={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +- */(function(r,e){(function(){var t,i="4.17.21",n=200,s="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",a="Expected a function",f="Invalid `variable` option passed into `_.template`",h="__lodash_hash_undefined__",u=500,g="__lodash_placeholder__",w=1,P=2,M=4,O=1,$=2,W=1,H=2,F=4,Y=8,B=16,z=32,j=64,_=128,U=256,ee=512,oe=30,L="...",b=800,m=16,l=1,d=2,y=3,C=1/0,D=9007199254740991,S=17976931348623157e292,v=0/0,A=4294967295,x=A-1,N=A>>>1,ae=[["ary",_],["bind",W],["bindKey",H],["curry",Y],["curryRight",B],["flip",ee],["partial",z],["partialRight",j],["rearg",U]],R="[object Arguments]",X="[object Array]",V="[object AsyncFunction]",J="[object Boolean]",K="[object Date]",E="[object DOMException]",G="[object Error]",re="[object Function]",le="[object GeneratorFunction]",he="[object Map]",ge="[object Number]",He="[object Null]",Te="[object Object]",Ce="[object Promise]",Xe="[object Proxy]",$e="[object RegExp]",be="[object Set]",Pe="[object String]",De="[object Symbol]",ye="[object Undefined]",Ie="[object WeakMap]",Oe="[object WeakSet]",me="[object ArrayBuffer]",Me="[object DataView]",Be="[object Float32Array]",we="[object Float64Array]",ke="[object Int8Array]",We="[object Int16Array]",xe="[object Int32Array]",Ve="[object Uint8Array]",Ke="[object Uint8ClampedArray]",Ge="[object Uint16Array]",mt="[object Uint32Array]",It=/\b__p \+= '';/g,Ye=/\b(__p \+=) '' \+/g,Pt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Ot=/&(?:amp|lt|gt|quot|#39);/g,Ze=/[&<>"']/g,rt=RegExp(Ot.source),et=RegExp(Ze.source),Ne=/<%-([\s\S]+?)%>/g,it=/<%([\s\S]+?)%>/g,tt=/<%=([\s\S]+?)%>/g,Re=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,lt=/^\w*$/,ht=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Le=/[\\^$.*+?()[\]{}|]/g,ut=RegExp(Le.source),nt=/^\s+/,Fe=/\s/,st=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Qe=/\{\n\/\* \[wrapped with (.+)\] \*/,qe=/,? & /,dt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Ht=/[()=,{}\[\]\/\s]/,at=/\\(\\)?/g,kt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,_t=/\w*$/,qt=/^[-+]0x[0-9a-f]+$/i,Qr=/^0b[01]+$/i,Zr=/^\[object .+?Constructor\]$/,Xr=/^0o[0-7]+$/i,ei=/^(?:0|[1-9]\d*)$/,vr=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Ai=/($^)/,Mn=/['\n\r\u2028\u2029\\]/g,Ei="\\ud800-\\udfff",Cn="\\u0300-\\u036f",Pn="\\ufe20-\\ufe2f",Si="\\u20d0-\\u20ff",cn=Cn+Pn+Si,fn="\\u2700-\\u27bf",Cr="a-z\\xdf-\\xf6\\xf8-\\xff",Dn="\\xac\\xb1\\xd7\\xf7",On="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",Rn="\\u2000-\\u206f",ta=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",co="A-Z\\xc0-\\xd6\\xd8-\\xde",qh="\\ufe0e\\ufe0f",ra=Dn+On+Rn+ta,$f="['\u2019]",ia="["+Ei+"]",Nf="["+ra+"]",na="["+cn+"]",zh="\\d+",Kp="["+fn+"]",Hh="["+Cr+"]",kh="[^"+Ei+ra+zh+fn+Cr+co+"]",lc="\\ud83c[\\udffb-\\udfff]",Vp="(?:"+na+"|"+lc+")",jh="[^"+Ei+"]",hc="(?:\\ud83c[\\udde6-\\uddff]){2}",fo="[\\ud800-\\udbff][\\udc00-\\udfff]",zi="["+co+"]",Wh="\\u200d",Kh="(?:"+Hh+"|"+kh+")",cs="(?:"+zi+"|"+kh+")",Vh="(?:"+$f+"(?:d|ll|m|re|s|t|ve))?",Gh="(?:"+$f+"(?:D|LL|M|RE|S|T|VE))?",Yh=Vp+"?",Jh="["+qh+"]?",Gp="(?:"+Wh+"(?:"+[jh,hc,fo].join("|")+")"+Jh+Yh+")*",Cs="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Qh="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Zh=Jh+Yh+Gp,uc="(?:"+[Kp,hc,fo].join("|")+")"+Zh,Yp="(?:"+[jh+na+"?",na,hc,fo,ia].join("|")+")",Lf=RegExp($f,"g"),Jp=RegExp(na,"g"),dc=RegExp(lc+"(?="+lc+")|"+Yp+Zh,"g"),Xh=RegExp([zi+"?"+Hh+"+"+Vh+"(?="+[Nf,zi,"$"].join("|")+")",cs+"+"+Gh+"(?="+[Nf,zi+Kh,"$"].join("|")+")",zi+"?"+Kh+"+"+Vh,zi+"+"+Gh,Qh,Cs,zh,uc].join("|"),"g"),eu=RegExp("["+Wh+Ei+cn+qh+"]"),sa=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,tu=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Qp=-1,Zt={};Zt[Be]=Zt[we]=Zt[ke]=Zt[We]=Zt[xe]=Zt[Ve]=Zt[Ke]=Zt[Ge]=Zt[mt]=!0,Zt[R]=Zt[X]=Zt[me]=Zt[J]=Zt[Me]=Zt[K]=Zt[G]=Zt[re]=Zt[he]=Zt[ge]=Zt[Te]=Zt[$e]=Zt[be]=Zt[Pe]=Zt[Ie]=!1;var Qt={};Qt[R]=Qt[X]=Qt[me]=Qt[Me]=Qt[J]=Qt[K]=Qt[Be]=Qt[we]=Qt[ke]=Qt[We]=Qt[xe]=Qt[he]=Qt[ge]=Qt[Te]=Qt[$e]=Qt[be]=Qt[Pe]=Qt[De]=Qt[Ve]=Qt[Ke]=Qt[Ge]=Qt[mt]=!0,Qt[G]=Qt[re]=Qt[Ie]=!1;var Q={\u00C0:"A",\u00C1:"A",\u00C2:"A",\u00C3:"A",\u00C4:"A",\u00C5:"A",\u00E0:"a",\u00E1:"a",\u00E2:"a",\u00E3:"a",\u00E4:"a",\u00E5:"a",\u00C7:"C",\u00E7:"c",\u00D0:"D",\u00F0:"d",\u00C8:"E",\u00C9:"E",\u00CA:"E",\u00CB:"E",\u00E8:"e",\u00E9:"e",\u00EA:"e",\u00EB:"e",\u00CC:"I",\u00CD:"I",\u00CE:"I",\u00CF:"I",\u00EC:"i",\u00ED:"i",\u00EE:"i",\u00EF:"i",\u00D1:"N",\u00F1:"n",\u00D2:"O",\u00D3:"O",\u00D4:"O",\u00D5:"O",\u00D6:"O",\u00D8:"O",\u00F2:"o",\u00F3:"o",\u00F4:"o",\u00F5:"o",\u00F6:"o",\u00F8:"o",\u00D9:"U",\u00DA:"U",\u00DB:"U",\u00DC:"U",\u00F9:"u",\u00FA:"u",\u00FB:"u",\u00FC:"u",\u00DD:"Y",\u00FD:"y",\u00FF:"y",\u00C6:"Ae",\u00E6:"ae",\u00DE:"Th",\u00FE:"th",\u00DF:"ss",\u0100:"A",\u0102:"A",\u0104:"A",\u0101:"a",\u0103:"a",\u0105:"a",\u0106:"C",\u0108:"C",\u010A:"C",\u010C:"C",\u0107:"c",\u0109:"c",\u010B:"c",\u010D:"c",\u010E:"D",\u0110:"D",\u010F:"d",\u0111:"d",\u0112:"E",\u0114:"E",\u0116:"E",\u0118:"E",\u011A:"E",\u0113:"e",\u0115:"e",\u0117:"e",\u0119:"e",\u011B:"e",\u011C:"G",\u011E:"G",\u0120:"G",\u0122:"G",\u011D:"g",\u011F:"g",\u0121:"g",\u0123:"g",\u0124:"H",\u0126:"H",\u0125:"h",\u0127:"h",\u0128:"I",\u012A:"I",\u012C:"I",\u012E:"I",\u0130:"I",\u0129:"i",\u012B:"i",\u012D:"i",\u012F:"i",\u0131:"i",\u0134:"J",\u0135:"j",\u0136:"K",\u0137:"k",\u0138:"k",\u0139:"L",\u013B:"L",\u013D:"L",\u013F:"L",\u0141:"L",\u013A:"l",\u013C:"l",\u013E:"l",\u0140:"l",\u0142:"l",\u0143:"N",\u0145:"N",\u0147:"N",\u014A:"N",\u0144:"n",\u0146:"n",\u0148:"n",\u014B:"n",\u014C:"O",\u014E:"O",\u0150:"O",\u014D:"o",\u014F:"o",\u0151:"o",\u0154:"R",\u0156:"R",\u0158:"R",\u0155:"r",\u0157:"r",\u0159:"r",\u015A:"S",\u015C:"S",\u015E:"S",\u0160:"S",\u015B:"s",\u015D:"s",\u015F:"s",\u0161:"s",\u0162:"T",\u0164:"T",\u0166:"T",\u0163:"t",\u0165:"t",\u0167:"t",\u0168:"U",\u016A:"U",\u016C:"U",\u016E:"U",\u0170:"U",\u0172:"U",\u0169:"u",\u016B:"u",\u016D:"u",\u016F:"u",\u0171:"u",\u0173:"u",\u0174:"W",\u0175:"w",\u0176:"Y",\u0177:"y",\u0178:"Y",\u0179:"Z",\u017B:"Z",\u017D:"Z",\u017A:"z",\u017C:"z",\u017E:"z",\u0132:"IJ",\u0133:"ij",\u0152:"Oe",\u0153:"oe",\u0149:"'n",\u017F:"s"},ne={"&":"&","<":"<",">":">",'"':""","'":"'"},pe={"&":"&","<":"<",">":">",""":'"',"'":"'"},Ue={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Xt=parseFloat,bt=parseInt,or=typeof fr=="object"&&fr&&fr.Object===Object&&fr,Er=typeof self=="object"&&self&&self.Object===Object&&self,Bt=or||Er||Function("return this")(),er=e&&!e.nodeType&&e,_r=er&&!0&&r&&!r.nodeType&&r,Ii=_r&&_r.exports===er,Sr=Ii&&or.process,ar=function(){try{var ie=_r&&_r.require&&_r.require("util").types;return ie||Sr&&Sr.binding&&Sr.binding("util")}catch{}}(),hi=ar&&ar.isArrayBuffer,Tn=ar&&ar.isDate,ln=ar&&ar.isMap,fs=ar&&ar.isRegExp,Bf=ar&&ar.isSet,oa=ar&&ar.isTypedArray;function Fr(ie,fe,ce){switch(ce.length){case 0:return ie.call(fe);case 1:return ie.call(fe,ce[0]);case 2:return ie.call(fe,ce[0],ce[1]);case 3:return ie.call(fe,ce[0],ce[1],ce[2])}return ie.apply(fe,ce)}function _N(ie,fe,ce,ze){for(var gt=-1,Wt=ie==null?0:ie.length;++gt-1}function Zp(ie,fe,ce){for(var ze=-1,gt=ie==null?0:ie.length;++ze-1;);return ce}function Yw(ie,fe){for(var ce=ie.length;ce--&&pc(fe,ie[ce],0)>-1;);return ce}function DN(ie,fe){for(var ce=ie.length,ze=0;ce--;)ie[ce]===fe&&++ze;return ze}var ON=r1(Q),RN=r1(ne);function TN(ie){return"\\"+Ue[ie]}function $N(ie,fe){return ie==null?t:ie[fe]}function gc(ie){return eu.test(ie)}function NN(ie){return sa.test(ie)}function LN(ie){for(var fe,ce=[];!(fe=ie.next()).done;)ce.push(fe.value);return ce}function o1(ie){var fe=-1,ce=Array(ie.size);return ie.forEach(function(ze,gt){ce[++fe]=[gt,ze]}),ce}function Jw(ie,fe){return function(ce){return ie(fe(ce))}}function uo(ie,fe){for(var ce=-1,ze=ie.length,gt=0,Wt=[];++ce-1}function AL(o,c){var p=this.__data__,I=wu(p,o);return I<0?(++this.size,p.push([o,c])):p[I][1]=c,this}Ps.prototype.clear=wL,Ps.prototype.delete=yL,Ps.prototype.get=_L,Ps.prototype.has=xL,Ps.prototype.set=AL;function Ds(o){var c=-1,p=o==null?0:o.length;for(this.clear();++c=c?o:c)),o}function pn(o,c,p,I,T,k){var Z,te=c&w,se=c&P,ue=c&M;if(p&&(Z=T?p(o,I,T,k):p(o)),Z!==t)return Z;if(!hr(o))return o;var de=wt(o);if(de){if(Z=MB(o),!te)return Mi(o,Z)}else{var ve=ri(o),Se=ve==re||ve==le;if(wo(o))return Ry(o,te);if(ve==Te||ve==R||Se&&!T){if(Z=se||Se?{}:Qy(o),!te)return se?vB(o,UL(Z,o)):gB(o,cy(Z,o))}else{if(!Qt[ve])return T?o:{};Z=CB(o,ve,te)}}k||(k=new Nn);var Je=k.get(o);if(Je)return Je;k.set(o,Z),I6(o)?o.forEach(function(ft){Z.add(pn(ft,c,p,ft,o,k))}):E6(o)&&o.forEach(function(ft,Rt){Z.set(Rt,pn(ft,c,p,Rt,o,k))});var ct=ue?se?R1:O1:se?Pi:Ur,St=de?t:ct(o);return hn(St||o,function(ft,Rt){St&&(Rt=ft,ft=o[Rt]),jf(Z,Rt,pn(ft,c,p,Rt,o,k))}),Z}function qL(o){var c=Ur(o);return function(p){return fy(p,o,c)}}function fy(o,c,p){var I=p.length;if(o==null)return!I;for(o=tr(o);I--;){var T=p[I],k=c[T],Z=o[T];if(Z===t&&!(T in o)||!k(Z))return!1}return!0}function ly(o,c,p){if(typeof o!="function")throw new un(a);return Qf(function(){o.apply(t,p)},c)}function Wf(o,c,p,I){var T=-1,k=ru,Z=!0,te=o.length,se=[],ue=c.length;if(!te)return se;p&&(c=cr(c,Hi(p))),I?(k=Zp,Z=!1):c.length>=n&&(k=Ff,Z=!1,c=new fa(c));e:for(;++TT?0:T+p),I=I===t||I>T?T:Et(I),I<0&&(I+=T),I=p>I?0:C6(I);p0&&p(te)?c>1?Kr(te,c-1,p,I,T):ho(T,te):I||(T[T.length]=te)}return T}var d1=Fy(),dy=Fy(!0);function ls(o,c){return o&&d1(o,c,Ur)}function p1(o,c){return o&&dy(o,c,Ur)}function _u(o,c){return lo(c,function(p){return Ns(o[p])})}function ha(o,c){c=mo(c,o);for(var p=0,I=c.length;o!=null&&pc}function kL(o,c){return o!=null&&Yt.call(o,c)}function jL(o,c){return o!=null&&c in tr(o)}function WL(o,c,p){return o>=ti(c,p)&&o=120&&de.length>=120)?new fa(Z&&de):t}de=o[0];var ve=-1,Se=te[0];e:for(;++ve-1;)te!==o&&uu.call(te,se,1),uu.call(o,se,1);return o}function Ey(o,c){for(var p=o?c.length:0,I=p-1;p--;){var T=c[p];if(p==I||T!==k){var k=T;$s(T)?uu.call(o,T,1):E1(o,T)}}return o}function _1(o,c){return o+gu(ny()*(c-o+1))}function nB(o,c,p,I){for(var T=-1,k=Dr(pu((c-o)/(p||1)),0),Z=ce(k);k--;)Z[I?k:++T]=o,o+=p;return Z}function x1(o,c){var p="";if(!o||c<1||c>D)return p;do c%2&&(p+=o),c=gu(c/2),c&&(o+=o);while(c);return p}function Mt(o,c){return U1(e6(o,c,Di),o+"")}function sB(o){return ay(Ic(o))}function oB(o,c){var p=Ic(o);return Ru(p,la(c,0,p.length))}function Gf(o,c,p,I){if(!hr(o))return o;c=mo(c,o);for(var T=-1,k=c.length,Z=k-1,te=o;te!=null&&++TT?0:T+c),p=p>T?T:p,p<0&&(p+=T),T=c>p?0:p-c>>>0,c>>>=0;for(var k=ce(T);++I>>1,Z=o[k];Z!==null&&!ji(Z)&&(p?Z<=c:Z=n){var ue=c?null:yB(o);if(ue)return nu(ue);Z=!1,T=Ff,se=new fa}else se=c?[]:te;e:for(;++I=I?o:gn(o,c,p)}var Oy=QN||function(o){return Bt.clearTimeout(o)};function Ry(o,c){if(c)return o.slice();var p=o.length,I=Xw?Xw(p):new o.constructor(p);return o.copy(I),I}function C1(o){var c=new o.constructor(o.byteLength);return new lu(c).set(new lu(o)),c}function hB(o,c){var p=c?C1(o.buffer):o.buffer;return new o.constructor(p,o.byteOffset,o.byteLength)}function uB(o){var c=new o.constructor(o.source,_t.exec(o));return c.lastIndex=o.lastIndex,c}function dB(o){return kf?tr(kf.call(o)):{}}function Ty(o,c){var p=c?C1(o.buffer):o.buffer;return new o.constructor(p,o.byteOffset,o.length)}function $y(o,c){if(o!==c){var p=o!==t,I=o===null,T=o===o,k=ji(o),Z=c!==t,te=c===null,se=c===c,ue=ji(c);if(!te&&!ue&&!k&&o>c||k&&Z&&se&&!te&&!ue||I&&Z&&se||!p&&se||!T)return 1;if(!I&&!k&&!ue&&o=te)return se;var ue=p[I];return se*(ue=="desc"?-1:1)}}return o.index-c.index}function Ny(o,c,p,I){for(var T=-1,k=o.length,Z=p.length,te=-1,se=c.length,ue=Dr(k-Z,0),de=ce(se+ue),ve=!I;++te1?p[T-1]:t,Z=T>2?p[2]:t;for(k=o.length>3&&typeof k=="function"?(T--,k):t,Z&&di(p[0],p[1],Z)&&(k=T<3?t:k,T=1),c=tr(c);++I-1?T[k?c[Z]:Z]:t}}function zy(o){return Ts(function(c){var p=c.length,I=p,T=dn.prototype.thru;for(o&&c.reverse();I--;){var k=c[I];if(typeof k!="function")throw new un(a);if(T&&!Z&&Du(k)=="wrapper")var Z=new dn([],!0)}for(I=Z?I:p;++I1&&Ft.reverse(),de&&sete))return!1;var ue=k.get(o),de=k.get(c);if(ue&&de)return ue==c&&de==o;var ve=-1,Se=!0,Je=p&$?new fa:t;for(k.set(o,c),k.set(c,o);++ve1?"& ":"")+c[I],c=c.join(p>2?", ":" "),o.replace(st,`{ ++ */(function(r,e){(function(){var t,i="4.17.21",n=200,s="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",a="Expected a function",f="Invalid `variable` option passed into `_.template`",h="__lodash_hash_undefined__",u=500,g="__lodash_placeholder__",w=1,M=2,C=4,O=1,$=2,j=1,H=2,F=4,G=8,B=16,z=32,W=64,_=128,U=256,ee=512,oe=30,L="...",b=800,m=16,l=1,d=2,y=3,P=1/0,D=9007199254740991,S=17976931348623157e292,v=0/0,A=4294967295,x=A-1,N=A>>>1,ae=[["ary",_],["bind",j],["bindKey",H],["curry",G],["curryRight",B],["flip",ee],["partial",z],["partialRight",W],["rearg",U]],R="[object Arguments]",X="[object Array]",V="[object AsyncFunction]",J="[object Boolean]",K="[object Date]",E="[object DOMException]",Y="[object Error]",re="[object Function]",le="[object GeneratorFunction]",he="[object Map]",ge="[object Number]",He="[object Null]",Te="[object Object]",Ce="[object Promise]",Xe="[object Proxy]",$e="[object RegExp]",be="[object Set]",Pe="[object String]",De="[object Symbol]",ye="[object Undefined]",Ie="[object WeakMap]",Oe="[object WeakSet]",me="[object ArrayBuffer]",Me="[object DataView]",Be="[object Float32Array]",we="[object Float64Array]",ke="[object Int8Array]",We="[object Int16Array]",Ae="[object Int32Array]",Ve="[object Uint8Array]",Ke="[object Uint8ClampedArray]",Ge="[object Uint16Array]",mt="[object Uint32Array]",It=/\b__p \+= '';/g,Ye=/\b(__p \+=) '' \+/g,Pt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Ot=/&(?:amp|lt|gt|quot|#39);/g,Ze=/[&<>"']/g,rt=RegExp(Ot.source),et=RegExp(Ze.source),Ne=/<%-([\s\S]+?)%>/g,it=/<%([\s\S]+?)%>/g,tt=/<%=([\s\S]+?)%>/g,Re=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,lt=/^\w*$/,ht=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Le=/[\\^$.*+?()[\]{}|]/g,ut=RegExp(Le.source),nt=/^\s+/,Fe=/\s/,st=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Qe=/\{\n\/\* \[wrapped with (.+)\] \*/,qe=/,? & /,dt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Ht=/[()=,{}\[\]\/\s]/,at=/\\(\\)?/g,kt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,_t=/\w*$/,qt=/^[-+]0x[0-9a-f]+$/i,Zr=/^0b[01]+$/i,Xr=/^\[object .+?Constructor\]$/,ei=/^0o[0-7]+$/i,ti=/^(?:0|[1-9]\d*)$/,vr=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Ai=/($^)/,Pn=/['\n\r\u2028\u2029\\]/g,Ei="\\ud800-\\udfff",Dn="\\u0300-\\u036f",On="\\ufe20-\\ufe2f",Si="\\u20d0-\\u20ff",fn=Dn+On+Si,ln="\\u2700-\\u27bf",Cr="a-z\\xdf-\\xf6\\xf8-\\xff",Rn="\\xac\\xb1\\xd7\\xf7",Tn="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",$n="\\u2000-\\u206f",ia=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",fo="A-Z\\xc0-\\xd6\\xd8-\\xde",kh="\\ufe0e\\ufe0f",na=Rn+Tn+$n+ia,Nf="['\u2019]",sa="["+Ei+"]",Lf="["+na+"]",oa="["+fn+"]",jh="\\d+",Vp="["+ln+"]",Wh="["+Cr+"]",Kh="[^"+Ei+na+jh+ln+Cr+fo+"]",hc="\\ud83c[\\udffb-\\udfff]",Gp="(?:"+oa+"|"+hc+")",Vh="[^"+Ei+"]",uc="(?:\\ud83c[\\udde6-\\uddff]){2}",lo="[\\ud800-\\udbff][\\udc00-\\udfff]",Hi="["+fo+"]",Gh="\\u200d",Yh="(?:"+Wh+"|"+Kh+")",cs="(?:"+Hi+"|"+Kh+")",Jh="(?:"+Nf+"(?:d|ll|m|re|s|t|ve))?",Qh="(?:"+Nf+"(?:D|LL|M|RE|S|T|VE))?",Zh=Gp+"?",Xh="["+kh+"]?",Yp="(?:"+Gh+"(?:"+[Vh,uc,lo].join("|")+")"+Xh+Zh+")*",Ps="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",eu="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",tu=Xh+Zh+Yp,dc="(?:"+[Vp,uc,lo].join("|")+")"+tu,Jp="(?:"+[Vh+oa+"?",oa,uc,lo,sa].join("|")+")",Bf=RegExp(Nf,"g"),Qp=RegExp(oa,"g"),pc=RegExp(hc+"(?="+hc+")|"+Jp+tu,"g"),ru=RegExp([Hi+"?"+Wh+"+"+Jh+"(?="+[Lf,Hi,"$"].join("|")+")",cs+"+"+Qh+"(?="+[Lf,Hi+Yh,"$"].join("|")+")",Hi+"?"+Yh+"+"+Jh,Hi+"+"+Qh,eu,Ps,jh,dc].join("|"),"g"),iu=RegExp("["+Gh+Ei+fn+kh+"]"),aa=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,nu=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Zp=-1,Zt={};Zt[Be]=Zt[we]=Zt[ke]=Zt[We]=Zt[Ae]=Zt[Ve]=Zt[Ke]=Zt[Ge]=Zt[mt]=!0,Zt[R]=Zt[X]=Zt[me]=Zt[J]=Zt[Me]=Zt[K]=Zt[Y]=Zt[re]=Zt[he]=Zt[ge]=Zt[Te]=Zt[$e]=Zt[be]=Zt[Pe]=Zt[Ie]=!1;var Qt={};Qt[R]=Qt[X]=Qt[me]=Qt[Me]=Qt[J]=Qt[K]=Qt[Be]=Qt[we]=Qt[ke]=Qt[We]=Qt[Ae]=Qt[he]=Qt[ge]=Qt[Te]=Qt[$e]=Qt[be]=Qt[Pe]=Qt[De]=Qt[Ve]=Qt[Ke]=Qt[Ge]=Qt[mt]=!0,Qt[Y]=Qt[re]=Qt[Ie]=!1;var Q={\u00C0:"A",\u00C1:"A",\u00C2:"A",\u00C3:"A",\u00C4:"A",\u00C5:"A",\u00E0:"a",\u00E1:"a",\u00E2:"a",\u00E3:"a",\u00E4:"a",\u00E5:"a",\u00C7:"C",\u00E7:"c",\u00D0:"D",\u00F0:"d",\u00C8:"E",\u00C9:"E",\u00CA:"E",\u00CB:"E",\u00E8:"e",\u00E9:"e",\u00EA:"e",\u00EB:"e",\u00CC:"I",\u00CD:"I",\u00CE:"I",\u00CF:"I",\u00EC:"i",\u00ED:"i",\u00EE:"i",\u00EF:"i",\u00D1:"N",\u00F1:"n",\u00D2:"O",\u00D3:"O",\u00D4:"O",\u00D5:"O",\u00D6:"O",\u00D8:"O",\u00F2:"o",\u00F3:"o",\u00F4:"o",\u00F5:"o",\u00F6:"o",\u00F8:"o",\u00D9:"U",\u00DA:"U",\u00DB:"U",\u00DC:"U",\u00F9:"u",\u00FA:"u",\u00FB:"u",\u00FC:"u",\u00DD:"Y",\u00FD:"y",\u00FF:"y",\u00C6:"Ae",\u00E6:"ae",\u00DE:"Th",\u00FE:"th",\u00DF:"ss",\u0100:"A",\u0102:"A",\u0104:"A",\u0101:"a",\u0103:"a",\u0105:"a",\u0106:"C",\u0108:"C",\u010A:"C",\u010C:"C",\u0107:"c",\u0109:"c",\u010B:"c",\u010D:"c",\u010E:"D",\u0110:"D",\u010F:"d",\u0111:"d",\u0112:"E",\u0114:"E",\u0116:"E",\u0118:"E",\u011A:"E",\u0113:"e",\u0115:"e",\u0117:"e",\u0119:"e",\u011B:"e",\u011C:"G",\u011E:"G",\u0120:"G",\u0122:"G",\u011D:"g",\u011F:"g",\u0121:"g",\u0123:"g",\u0124:"H",\u0126:"H",\u0125:"h",\u0127:"h",\u0128:"I",\u012A:"I",\u012C:"I",\u012E:"I",\u0130:"I",\u0129:"i",\u012B:"i",\u012D:"i",\u012F:"i",\u0131:"i",\u0134:"J",\u0135:"j",\u0136:"K",\u0137:"k",\u0138:"k",\u0139:"L",\u013B:"L",\u013D:"L",\u013F:"L",\u0141:"L",\u013A:"l",\u013C:"l",\u013E:"l",\u0140:"l",\u0142:"l",\u0143:"N",\u0145:"N",\u0147:"N",\u014A:"N",\u0144:"n",\u0146:"n",\u0148:"n",\u014B:"n",\u014C:"O",\u014E:"O",\u0150:"O",\u014D:"o",\u014F:"o",\u0151:"o",\u0154:"R",\u0156:"R",\u0158:"R",\u0155:"r",\u0157:"r",\u0159:"r",\u015A:"S",\u015C:"S",\u015E:"S",\u0160:"S",\u015B:"s",\u015D:"s",\u015F:"s",\u0161:"s",\u0162:"T",\u0164:"T",\u0166:"T",\u0163:"t",\u0165:"t",\u0167:"t",\u0168:"U",\u016A:"U",\u016C:"U",\u016E:"U",\u0170:"U",\u0172:"U",\u0169:"u",\u016B:"u",\u016D:"u",\u016F:"u",\u0171:"u",\u0173:"u",\u0174:"W",\u0175:"w",\u0176:"Y",\u0177:"y",\u0178:"Y",\u0179:"Z",\u017B:"Z",\u017D:"Z",\u017A:"z",\u017C:"z",\u017E:"z",\u0132:"IJ",\u0133:"ij",\u0152:"Oe",\u0153:"oe",\u0149:"'n",\u017F:"s"},ne={"&":"&","<":"<",">":">",'"':""","'":"'"},pe={"&":"&","<":"<",">":">",""":'"',"'":"'"},Ue={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Xt=parseFloat,bt=parseInt,or=typeof fr=="object"&&fr&&fr.Object===Object&&fr,Er=typeof self=="object"&&self&&self.Object===Object&&self,Bt=or||Er||Function("return this")(),er=e&&!e.nodeType&&e,_r=er&&!0&&r&&!r.nodeType&&r,Ii=_r&&_r.exports===er,Sr=Ii&&or.process,ar=function(){try{var ie=_r&&_r.require&&_r.require("util").types;return ie||Sr&&Sr.binding&&Sr.binding("util")}catch{}}(),hi=ar&&ar.isArrayBuffer,Nn=ar&&ar.isDate,hn=ar&&ar.isMap,fs=ar&&ar.isRegExp,Ff=ar&&ar.isSet,ca=ar&&ar.isTypedArray;function Ur(ie,fe,ce){switch(ce.length){case 0:return ie.call(fe);case 1:return ie.call(fe,ce[0]);case 2:return ie.call(fe,ce[0],ce[1]);case 3:return ie.call(fe,ce[0],ce[1],ce[2])}return ie.apply(fe,ce)}function ON(ie,fe,ce,ze){for(var gt=-1,Wt=ie==null?0:ie.length;++gt-1}function Xp(ie,fe,ce){for(var ze=-1,gt=ie==null?0:ie.length;++ze-1;);return ce}function ey(ie,fe){for(var ce=ie.length;ce--&&gc(fe,ie[ce],0)>-1;);return ce}function qN(ie,fe){for(var ce=ie.length,ze=0;ce--;)ie[ce]===fe&&++ze;return ze}var zN=i1(Q),HN=i1(ne);function kN(ie){return"\\"+Ue[ie]}function jN(ie,fe){return ie==null?t:ie[fe]}function vc(ie){return iu.test(ie)}function WN(ie){return aa.test(ie)}function KN(ie){for(var fe,ce=[];!(fe=ie.next()).done;)ce.push(fe.value);return ce}function a1(ie){var fe=-1,ce=Array(ie.size);return ie.forEach(function(ze,gt){ce[++fe]=[gt,ze]}),ce}function ty(ie,fe){return function(ce){return ie(fe(ce))}}function po(ie,fe){for(var ce=-1,ze=ie.length,gt=0,Wt=[];++ce-1}function TL(o,c){var p=this.__data__,I=xu(p,o);return I<0?(++this.size,p.push([o,c])):p[I][1]=c,this}Ds.prototype.clear=PL,Ds.prototype.delete=DL,Ds.prototype.get=OL,Ds.prototype.has=RL,Ds.prototype.set=TL;function Os(o){var c=-1,p=o==null?0:o.length;for(this.clear();++c=c?o:c)),o}function gn(o,c,p,I,T,k){var Z,te=c&w,se=c&M,ue=c&C;if(p&&(Z=T?p(o,I,T,k):p(o)),Z!==t)return Z;if(!hr(o))return o;var de=wt(o);if(de){if(Z=BB(o),!te)return Mi(o,Z)}else{var ve=ii(o),Se=ve==re||ve==le;if(yo(o))return By(o,te);if(ve==Te||ve==R||Se&&!T){if(Z=se||Se?{}:r6(o),!te)return se?IB(o,YL(Z,o)):SB(o,dy(Z,o))}else{if(!Qt[ve])return T?o:{};Z=FB(o,ve,te)}}k||(k=new Bn);var Je=k.get(o);if(Je)return Je;k.set(o,Z),O6(o)?o.forEach(function(ft){Z.add(gn(ft,c,p,ft,o,k))}):P6(o)&&o.forEach(function(ft,Rt){Z.set(Rt,gn(ft,c,p,Rt,o,k))});var ct=ue?se?T1:R1:se?Pi:qr,St=de?t:ct(o);return un(St||o,function(ft,Rt){St&&(Rt=ft,ft=o[Rt]),Wf(Z,Rt,gn(ft,c,p,Rt,o,k))}),Z}function JL(o){var c=qr(o);return function(p){return py(p,o,c)}}function py(o,c,p){var I=p.length;if(o==null)return!I;for(o=tr(o);I--;){var T=p[I],k=c[T],Z=o[T];if(Z===t&&!(T in o)||!k(Z))return!1}return!0}function gy(o,c,p){if(typeof o!="function")throw new dn(a);return Zf(function(){o.apply(t,p)},c)}function Kf(o,c,p,I){var T=-1,k=su,Z=!0,te=o.length,se=[],ue=c.length;if(!te)return se;p&&(c=cr(c,ki(p))),I?(k=Xp,Z=!1):c.length>=n&&(k=Uf,Z=!1,c=new ha(c));e:for(;++TT?0:T+p),I=I===t||I>T?T:Et(I),I<0&&(I+=T),I=p>I?0:T6(I);p0&&p(te)?c>1?Vr(te,c-1,p,I,T):uo(T,te):I||(T[T.length]=te)}return T}var p1=ky(),by=ky(!0);function ls(o,c){return o&&p1(o,c,qr)}function g1(o,c){return o&&by(o,c,qr)}function Eu(o,c){return ho(c,function(p){return Ls(o[p])})}function da(o,c){c=bo(c,o);for(var p=0,I=c.length;o!=null&&pc}function XL(o,c){return o!=null&&Yt.call(o,c)}function eB(o,c){return o!=null&&c in tr(o)}function tB(o,c,p){return o>=ri(c,p)&&o=120&&de.length>=120)?new ha(Z&&de):t}de=o[0];var ve=-1,Se=te[0];e:for(;++ve-1;)te!==o&&gu.call(te,se,1),gu.call(o,se,1);return o}function Py(o,c){for(var p=o?c.length:0,I=p-1;p--;){var T=c[p];if(p==I||T!==k){var k=T;Ns(T)?gu.call(o,T,1):S1(o,T)}}return o}function x1(o,c){return o+bu(fy()*(c-o+1))}function pB(o,c,p,I){for(var T=-1,k=Dr(mu((c-o)/(p||1)),0),Z=ce(k);k--;)Z[I?k:++T]=o,o+=p;return Z}function A1(o,c){var p="";if(!o||c<1||c>D)return p;do c%2&&(p+=o),c=bu(c/2),c&&(o+=o);while(c);return p}function Mt(o,c){return q1(s6(o,c,Di),o+"")}function gB(o){return uy(Mc(o))}function vB(o,c){var p=Mc(o);return Nu(p,ua(c,0,p.length))}function Yf(o,c,p,I){if(!hr(o))return o;c=bo(c,o);for(var T=-1,k=c.length,Z=k-1,te=o;te!=null&&++TT?0:T+c),p=p>T?T:p,p<0&&(p+=T),T=c>p?0:p-c>>>0,c>>>=0;for(var k=ce(T);++I>>1,Z=o[k];Z!==null&&!Wi(Z)&&(p?Z<=c:Z=n){var ue=c?null:DB(o);if(ue)return au(ue);Z=!1,T=Uf,se=new ha}else se=c?[]:te;e:for(;++I=I?o:vn(o,c,p)}var Ly=aL||function(o){return Bt.clearTimeout(o)};function By(o,c){if(c)return o.slice();var p=o.length,I=ny?ny(p):new o.constructor(p);return o.copy(I),I}function P1(o){var c=new o.constructor(o.byteLength);return new du(c).set(new du(o)),c}function _B(o,c){var p=c?P1(o.buffer):o.buffer;return new o.constructor(p,o.byteOffset,o.byteLength)}function xB(o){var c=new o.constructor(o.source,_t.exec(o));return c.lastIndex=o.lastIndex,c}function AB(o){return jf?tr(jf.call(o)):{}}function Fy(o,c){var p=c?P1(o.buffer):o.buffer;return new o.constructor(p,o.byteOffset,o.length)}function Uy(o,c){if(o!==c){var p=o!==t,I=o===null,T=o===o,k=Wi(o),Z=c!==t,te=c===null,se=c===c,ue=Wi(c);if(!te&&!ue&&!k&&o>c||k&&Z&&se&&!te&&!ue||I&&Z&&se||!p&&se||!T)return 1;if(!I&&!k&&!ue&&o=te)return se;var ue=p[I];return se*(ue=="desc"?-1:1)}}return o.index-c.index}function qy(o,c,p,I){for(var T=-1,k=o.length,Z=p.length,te=-1,se=c.length,ue=Dr(k-Z,0),de=ce(se+ue),ve=!I;++te1?p[T-1]:t,Z=T>2?p[2]:t;for(k=o.length>3&&typeof k=="function"?(T--,k):t,Z&&di(p[0],p[1],Z)&&(k=T<3?t:k,T=1),c=tr(c);++I-1?T[k?c[Z]:Z]:t}}function Ky(o){return $s(function(c){var p=c.length,I=p,T=pn.prototype.thru;for(o&&c.reverse();I--;){var k=c[I];if(typeof k!="function")throw new dn(a);if(T&&!Z&&Tu(k)=="wrapper")var Z=new pn([],!0)}for(I=Z?I:p;++I1&&Ft.reverse(),de&&sete))return!1;var ue=k.get(o),de=k.get(c);if(ue&&de)return ue==c&&de==o;var ve=-1,Se=!0,Je=p&$?new ha:t;for(k.set(o,c),k.set(c,o);++ve1?"& ":"")+c[I],c=c.join(p>2?", ":" "),o.replace(st,`{ + /* [wrapped with `+c+`] */ +-`)}function DB(o){return wt(o)||pa(o)||!!(ry&&o&&o[ry])}function $s(o,c){var p=typeof o;return c=c??D,!!c&&(p=="number"||p!="symbol"&&ei.test(o))&&o>-1&&o%1==0&&o0){if(++c>=b)return arguments[0]}else c=0;return o.apply(t,arguments)}}function Ru(o,c){var p=-1,I=o.length,T=I-1;for(c=c===t?I:c;++p1?o[c-1]:t;return p=typeof p=="function"?(o.pop(),p):t,u6(o,p)});function d6(o){var c=q(o);return c.__chain__=!0,c}function zF(o,c){return c(o),o}function Tu(o,c){return c(o)}var HF=Ts(function(o){var c=o.length,p=c?o[0]:0,I=this.__wrapped__,T=function(k){return u1(k,o)};return c>1||this.__actions__.length||!(I instanceof Nt)||!$s(p)?this.thru(T):(I=I.slice(p,+p+(c?1:0)),I.__actions__.push({func:Tu,args:[T],thisArg:t}),new dn(I,this.__chain__).thru(function(k){return c&&!k.length&&k.push(t),k}))});function kF(){return d6(this)}function jF(){return new dn(this.value(),this.__chain__)}function WF(){this.__values__===t&&(this.__values__=M6(this.value()));var o=this.__index__>=this.__values__.length,c=o?t:this.__values__[this.__index__++];return{done:o,value:c}}function KF(){return this}function VF(o){for(var c,p=this;p instanceof bu;){var I=o6(p);I.__index__=0,I.__values__=t,c?T.__wrapped__=I:c=I;var T=I;p=p.__wrapped__}return T.__wrapped__=o,c}function GF(){var o=this.__wrapped__;if(o instanceof Nt){var c=o;return this.__actions__.length&&(c=new Nt(this)),c=c.reverse(),c.__actions__.push({func:Tu,args:[q1],thisArg:t}),new dn(c,this.__chain__)}return this.thru(q1)}function YF(){return Py(this.__wrapped__,this.__actions__)}var JF=Su(function(o,c,p){Yt.call(o,p)?++o[p]:Os(o,p,1)});function QF(o,c,p){var I=wt(o)?Hw:zL;return p&&di(o,c,p)&&(c=t),I(o,ot(c,3))}function ZF(o,c){var p=wt(o)?lo:uy;return p(o,ot(c,3))}var XF=qy(a6),eU=qy(c6);function tU(o,c){return Kr($u(o,c),1)}function rU(o,c){return Kr($u(o,c),C)}function iU(o,c,p){return p=p===t?1:Et(p),Kr($u(o,c),p)}function p6(o,c){var p=wt(o)?hn:go;return p(o,ot(c,3))}function g6(o,c){var p=wt(o)?xN:hy;return p(o,ot(c,3))}var nU=Su(function(o,c,p){Yt.call(o,p)?o[p].push(c):Os(o,p,[c])});function sU(o,c,p,I){o=Ci(o)?o:Ic(o),p=p&&!I?Et(p):0;var T=o.length;return p<0&&(p=Dr(T+p,0)),Uu(o)?p<=T&&o.indexOf(c,p)>-1:!!T&&pc(o,c,p)>-1}var oU=Mt(function(o,c,p){var I=-1,T=typeof c=="function",k=Ci(o)?ce(o.length):[];return go(o,function(Z){k[++I]=T?Fr(c,Z,p):Kf(Z,c,p)}),k}),aU=Su(function(o,c,p){Os(o,p,c)});function $u(o,c){var p=wt(o)?cr:by;return p(o,ot(c,3))}function cU(o,c,p,I){return o==null?[]:(wt(c)||(c=c==null?[]:[c]),p=I?t:p,wt(p)||(p=p==null?[]:[p]),xy(o,c,p))}var fU=Su(function(o,c,p){o[p?0:1].push(c)},function(){return[[],[]]});function lU(o,c,p){var I=wt(o)?Xp:Kw,T=arguments.length<3;return I(o,ot(c,4),p,T,go)}function hU(o,c,p){var I=wt(o)?AN:Kw,T=arguments.length<3;return I(o,ot(c,4),p,T,hy)}function uU(o,c){var p=wt(o)?lo:uy;return p(o,Bu(ot(c,3)))}function dU(o){var c=wt(o)?ay:sB;return c(o)}function pU(o,c,p){(p?di(o,c,p):c===t)?c=1:c=Et(c);var I=wt(o)?LL:oB;return I(o,c)}function gU(o){var c=wt(o)?BL:cB;return c(o)}function vU(o){if(o==null)return 0;if(Ci(o))return Uu(o)?vc(o):o.length;var c=ri(o);return c==he||c==be?o.size:b1(o).length}function mU(o,c,p){var I=wt(o)?e1:fB;return p&&di(o,c,p)&&(c=t),I(o,ot(c,3))}var bU=Mt(function(o,c){if(o==null)return[];var p=c.length;return p>1&&di(o,c[0],c[1])?c=[]:p>2&&di(c[0],c[1],c[2])&&(c=[c[0]]),xy(o,Kr(c,1),[])}),Nu=ZN||function(){return Bt.Date.now()};function wU(o,c){if(typeof c!="function")throw new un(a);return o=Et(o),function(){if(--o<1)return c.apply(this,arguments)}}function v6(o,c,p){return c=p?t:c,c=o&&c==null?o.length:c,Rs(o,_,t,t,t,t,c)}function m6(o,c){var p;if(typeof c!="function")throw new un(a);return o=Et(o),function(){return--o>0&&(p=c.apply(this,arguments)),o<=1&&(c=t),p}}var H1=Mt(function(o,c,p){var I=W;if(p.length){var T=uo(p,Ec(H1));I|=z}return Rs(o,I,c,p,T)}),b6=Mt(function(o,c,p){var I=W|H;if(p.length){var T=uo(p,Ec(b6));I|=z}return Rs(c,I,o,p,T)});function w6(o,c,p){c=p?t:c;var I=Rs(o,Y,t,t,t,t,t,c);return I.placeholder=w6.placeholder,I}function y6(o,c,p){c=p?t:c;var I=Rs(o,B,t,t,t,t,t,c);return I.placeholder=y6.placeholder,I}function _6(o,c,p){var I,T,k,Z,te,se,ue=0,de=!1,ve=!1,Se=!0;if(typeof o!="function")throw new un(a);c=mn(c)||0,hr(p)&&(de=!!p.leading,ve="maxWait"in p,k=ve?Dr(mn(p.maxWait)||0,c):k,Se="trailing"in p?!!p.trailing:Se);function Je(Ar){var Bn=I,Bs=T;return I=T=t,ue=Ar,Z=o.apply(Bs,Bn),Z}function ct(Ar){return ue=Ar,te=Qf(Rt,c),de?Je(Ar):Z}function St(Ar){var Bn=Ar-se,Bs=Ar-ue,q6=c-Bn;return ve?ti(q6,k-Bs):q6}function ft(Ar){var Bn=Ar-se,Bs=Ar-ue;return se===t||Bn>=c||Bn<0||ve&&Bs>=k}function Rt(){var Ar=Nu();if(ft(Ar))return Ft(Ar);te=Qf(Rt,St(Ar))}function Ft(Ar){return te=t,Se&&I?Je(Ar):(I=T=t,Z)}function Wi(){te!==t&&Oy(te),ue=0,I=se=T=te=t}function pi(){return te===t?Z:Ft(Nu())}function Ki(){var Ar=Nu(),Bn=ft(Ar);if(I=arguments,T=this,se=Ar,Bn){if(te===t)return ct(se);if(ve)return Oy(te),te=Qf(Rt,c),Je(se)}return te===t&&(te=Qf(Rt,c)),Z}return Ki.cancel=Wi,Ki.flush=pi,Ki}var yU=Mt(function(o,c){return ly(o,1,c)}),_U=Mt(function(o,c,p){return ly(o,mn(c)||0,p)});function xU(o){return Rs(o,ee)}function Lu(o,c){if(typeof o!="function"||c!=null&&typeof c!="function")throw new un(a);var p=function(){var I=arguments,T=c?c.apply(this,I):I[0],k=p.cache;if(k.has(T))return k.get(T);var Z=o.apply(this,I);return p.cache=k.set(T,Z)||k,Z};return p.cache=new(Lu.Cache||Ds),p}Lu.Cache=Ds;function Bu(o){if(typeof o!="function")throw new un(a);return function(){var c=arguments;switch(c.length){case 0:return!o.call(this);case 1:return!o.call(this,c[0]);case 2:return!o.call(this,c[0],c[1]);case 3:return!o.call(this,c[0],c[1],c[2])}return!o.apply(this,c)}}function AU(o){return m6(2,o)}var EU=lB(function(o,c){c=c.length==1&&wt(c[0])?cr(c[0],Hi(ot())):cr(Kr(c,1),Hi(ot()));var p=c.length;return Mt(function(I){for(var T=-1,k=ti(I.length,p);++T=c}),pa=gy(function(){return arguments}())?gy:function(o){return mr(o)&&Yt.call(o,"callee")&&!ty.call(o,"callee")},wt=ce.isArray,UU=hi?Hi(hi):VL;function Ci(o){return o!=null&&Fu(o.length)&&!Ns(o)}function xr(o){return mr(o)&&Ci(o)}function qU(o){return o===!0||o===!1||mr(o)&&ui(o)==J}var wo=eL||eg,zU=Tn?Hi(Tn):GL;function HU(o){return mr(o)&&o.nodeType===1&&!Zf(o)}function kU(o){if(o==null)return!0;if(Ci(o)&&(wt(o)||typeof o=="string"||typeof o.splice=="function"||wo(o)||Sc(o)||pa(o)))return!o.length;var c=ri(o);if(c==he||c==be)return!o.size;if(Jf(o))return!b1(o).length;for(var p in o)if(Yt.call(o,p))return!1;return!0}function jU(o,c){return Vf(o,c)}function WU(o,c,p){p=typeof p=="function"?p:t;var I=p?p(o,c):t;return I===t?Vf(o,c,t,p):!!I}function j1(o){if(!mr(o))return!1;var c=ui(o);return c==G||c==E||typeof o.message=="string"&&typeof o.name=="string"&&!Zf(o)}function KU(o){return typeof o=="number"&&iy(o)}function Ns(o){if(!hr(o))return!1;var c=ui(o);return c==re||c==le||c==V||c==Xe}function A6(o){return typeof o=="number"&&o==Et(o)}function Fu(o){return typeof o=="number"&&o>-1&&o%1==0&&o<=D}function hr(o){var c=typeof o;return o!=null&&(c=="object"||c=="function")}function mr(o){return o!=null&&typeof o=="object"}var E6=ln?Hi(ln):JL;function VU(o,c){return o===c||m1(o,c,$1(c))}function GU(o,c,p){return p=typeof p=="function"?p:t,m1(o,c,$1(c),p)}function YU(o){return S6(o)&&o!=+o}function JU(o){if(TB(o))throw new gt(s);return vy(o)}function QU(o){return o===null}function ZU(o){return o==null}function S6(o){return typeof o=="number"||mr(o)&&ui(o)==ge}function Zf(o){if(!mr(o)||ui(o)!=Te)return!1;var c=hu(o);if(c===null)return!0;var p=Yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&au.call(p)==GN}var W1=fs?Hi(fs):QL;function XU(o){return A6(o)&&o>=-D&&o<=D}var I6=Bf?Hi(Bf):ZL;function Uu(o){return typeof o=="string"||!wt(o)&&mr(o)&&ui(o)==Pe}function ji(o){return typeof o=="symbol"||mr(o)&&ui(o)==De}var Sc=oa?Hi(oa):XL;function eq(o){return o===t}function tq(o){return mr(o)&&ri(o)==Ie}function rq(o){return mr(o)&&ui(o)==Oe}var iq=Pu(w1),nq=Pu(function(o,c){return o<=c});function M6(o){if(!o)return[];if(Ci(o))return Uu(o)?$n(o):Mi(o);if(Uf&&o[Uf])return LN(o[Uf]());var c=ri(o),p=c==he?o1:c==be?nu:Ic;return p(o)}function Ls(o){if(!o)return o===0?o:0;if(o=mn(o),o===C||o===-C){var c=o<0?-1:1;return c*S}return o===o?o:0}function Et(o){var c=Ls(o),p=c%1;return c===c?p?c-p:c:0}function C6(o){return o?la(Et(o),0,A):0}function mn(o){if(typeof o=="number")return o;if(ji(o))return v;if(hr(o)){var c=typeof o.valueOf=="function"?o.valueOf():o;o=hr(c)?c+"":c}if(typeof o!="string")return o===0?o:+o;o=Vw(o);var p=Qr.test(o);return p||Xr.test(o)?bt(o.slice(2),p?2:8):qt.test(o)?v:+o}function P6(o){return hs(o,Pi(o))}function sq(o){return o?la(Et(o),-D,D):o===0?o:0}function Vt(o){return o==null?"":ki(o)}var oq=xc(function(o,c){if(Jf(c)||Ci(c)){hs(c,Ur(c),o);return}for(var p in c)Yt.call(c,p)&&jf(o,p,c[p])}),D6=xc(function(o,c){hs(c,Pi(c),o)}),qu=xc(function(o,c,p,I){hs(c,Pi(c),o,I)}),aq=xc(function(o,c,p,I){hs(c,Ur(c),o,I)}),cq=Ts(u1);function fq(o,c){var p=_c(o);return c==null?p:cy(p,c)}var lq=Mt(function(o,c){o=tr(o);var p=-1,I=c.length,T=I>2?c[2]:t;for(T&&di(c[0],c[1],T)&&(I=1);++p1),k}),hs(o,R1(o),p),I&&(p=pn(p,w|P|M,_B));for(var T=c.length;T--;)E1(p,c[T]);return p});function Cq(o,c){return R6(o,Bu(ot(c)))}var Pq=Ts(function(o,c){return o==null?{}:rB(o,c)});function R6(o,c){if(o==null)return{};var p=cr(R1(o),function(I){return[I]});return c=ot(c),Ay(o,p,function(I,T){return c(I,T[0])})}function Dq(o,c,p){c=mo(c,o);var I=-1,T=c.length;for(T||(T=1,o=t);++Ic){var I=o;o=c,c=I}if(p||o%1||c%1){var T=ny();return ti(o+T*(c-o+Xt("1e-"+((T+"").length-1))),c)}return _1(o,c)}var zq=Ac(function(o,c,p){return c=c.toLowerCase(),o+(p?N6(c):c)});function N6(o){return G1(Vt(o).toLowerCase())}function L6(o){return o=Vt(o),o&&o.replace(vr,ON).replace(Jp,"")}function Hq(o,c,p){o=Vt(o),c=ki(c);var I=o.length;p=p===t?I:la(Et(p),0,I);var T=p;return p-=c.length,p>=0&&o.slice(p,T)==c}function kq(o){return o=Vt(o),o&&et.test(o)?o.replace(Ze,RN):o}function jq(o){return o=Vt(o),o&&ut.test(o)?o.replace(Le,"\\$&"):o}var Wq=Ac(function(o,c,p){return o+(p?"-":"")+c.toLowerCase()}),Kq=Ac(function(o,c,p){return o+(p?" ":"")+c.toLowerCase()}),Vq=Uy("toLowerCase");function Gq(o,c,p){o=Vt(o),c=Et(c);var I=c?vc(o):0;if(!c||I>=c)return o;var T=(c-I)/2;return Cu(gu(T),p)+o+Cu(pu(T),p)}function Yq(o,c,p){o=Vt(o),c=Et(c);var I=c?vc(o):0;return c&&I>>0,p?(o=Vt(o),o&&(typeof c=="string"||c!=null&&!W1(c))&&(c=ki(c),!c&&gc(o))?bo($n(o),0,p):o.split(c,p)):[]}var rz=Ac(function(o,c,p){return o+(p?" ":"")+G1(c)});function iz(o,c,p){return o=Vt(o),p=p==null?0:la(Et(p),0,o.length),c=ki(c),o.slice(p,p+c.length)==c}function nz(o,c,p){var I=q.templateSettings;p&&di(o,c,p)&&(c=t),o=Vt(o),c=qu({},c,I,Ky);var T=qu({},c.imports,I.imports,Ky),k=Ur(T),Z=s1(T,k),te,se,ue=0,de=c.interpolate||Ai,ve="__p += '",Se=a1((c.escape||Ai).source+"|"+de.source+"|"+(de===tt?kt:Ai).source+"|"+(c.evaluate||Ai).source+"|$","g"),Je="//# sourceURL="+(Yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Qp+"]")+` +-`;o.replace(Se,function(ft,Rt,Ft,Wi,pi,Ki){return Ft||(Ft=Wi),ve+=o.slice(ue,Ki).replace(Mn,TN),Rt&&(te=!0,ve+=`' + ++`)}function qB(o){return wt(o)||va(o)||!!(ay&&o&&o[ay])}function Ns(o,c){var p=typeof o;return c=c??D,!!c&&(p=="number"||p!="symbol"&&ti.test(o))&&o>-1&&o%1==0&&o0){if(++c>=b)return arguments[0]}else c=0;return o.apply(t,arguments)}}function Nu(o,c){var p=-1,I=o.length,T=I-1;for(c=c===t?I:c;++p1?o[c-1]:t;return p=typeof p=="function"?(o.pop(),p):t,m6(o,p)});function b6(o){var c=q(o);return c.__chain__=!0,c}function QF(o,c){return c(o),o}function Lu(o,c){return c(o)}var ZF=$s(function(o){var c=o.length,p=c?o[0]:0,I=this.__wrapped__,T=function(k){return d1(k,o)};return c>1||this.__actions__.length||!(I instanceof Nt)||!Ns(p)?this.thru(T):(I=I.slice(p,+p+(c?1:0)),I.__actions__.push({func:Lu,args:[T],thisArg:t}),new pn(I,this.__chain__).thru(function(k){return c&&!k.length&&k.push(t),k}))});function XF(){return b6(this)}function eU(){return new pn(this.value(),this.__chain__)}function tU(){this.__values__===t&&(this.__values__=R6(this.value()));var o=this.__index__>=this.__values__.length,c=o?t:this.__values__[this.__index__++];return{done:o,value:c}}function rU(){return this}function iU(o){for(var c,p=this;p instanceof _u;){var I=h6(p);I.__index__=0,I.__values__=t,c?T.__wrapped__=I:c=I;var T=I;p=p.__wrapped__}return T.__wrapped__=o,c}function nU(){var o=this.__wrapped__;if(o instanceof Nt){var c=o;return this.__actions__.length&&(c=new Nt(this)),c=c.reverse(),c.__actions__.push({func:Lu,args:[z1],thisArg:t}),new pn(c,this.__chain__)}return this.thru(z1)}function sU(){return $y(this.__wrapped__,this.__actions__)}var oU=Cu(function(o,c,p){Yt.call(o,p)?++o[p]:Rs(o,p,1)});function aU(o,c,p){var I=wt(o)?Vw:QL;return p&&di(o,c,p)&&(c=t),I(o,ot(c,3))}function cU(o,c){var p=wt(o)?ho:my;return p(o,ot(c,3))}var fU=Wy(u6),lU=Wy(d6);function hU(o,c){return Vr(Bu(o,c),1)}function uU(o,c){return Vr(Bu(o,c),P)}function dU(o,c,p){return p=p===t?1:Et(p),Vr(Bu(o,c),p)}function w6(o,c){var p=wt(o)?un:vo;return p(o,ot(c,3))}function y6(o,c){var p=wt(o)?RN:vy;return p(o,ot(c,3))}var pU=Cu(function(o,c,p){Yt.call(o,p)?o[p].push(c):Rs(o,p,[c])});function gU(o,c,p,I){o=Ci(o)?o:Mc(o),p=p&&!I?Et(p):0;var T=o.length;return p<0&&(p=Dr(T+p,0)),Hu(o)?p<=T&&o.indexOf(c,p)>-1:!!T&&gc(o,c,p)>-1}var vU=Mt(function(o,c,p){var I=-1,T=typeof c=="function",k=Ci(o)?ce(o.length):[];return vo(o,function(Z){k[++I]=T?Ur(c,Z,p):Vf(Z,c,p)}),k}),mU=Cu(function(o,c,p){Rs(o,p,c)});function Bu(o,c){var p=wt(o)?cr:Ay;return p(o,ot(c,3))}function bU(o,c,p,I){return o==null?[]:(wt(c)||(c=c==null?[]:[c]),p=I?t:p,wt(p)||(p=p==null?[]:[p]),My(o,c,p))}var wU=Cu(function(o,c,p){o[p?0:1].push(c)},function(){return[[],[]]});function yU(o,c,p){var I=wt(o)?e1:Qw,T=arguments.length<3;return I(o,ot(c,4),p,T,vo)}function _U(o,c,p){var I=wt(o)?TN:Qw,T=arguments.length<3;return I(o,ot(c,4),p,T,vy)}function xU(o,c){var p=wt(o)?ho:my;return p(o,qu(ot(c,3)))}function AU(o){var c=wt(o)?uy:gB;return c(o)}function EU(o,c,p){(p?di(o,c,p):c===t)?c=1:c=Et(c);var I=wt(o)?KL:vB;return I(o,c)}function SU(o){var c=wt(o)?VL:bB;return c(o)}function IU(o){if(o==null)return 0;if(Ci(o))return Hu(o)?mc(o):o.length;var c=ii(o);return c==he||c==be?o.size:w1(o).length}function MU(o,c,p){var I=wt(o)?t1:wB;return p&&di(o,c,p)&&(c=t),I(o,ot(c,3))}var CU=Mt(function(o,c){if(o==null)return[];var p=c.length;return p>1&&di(o,c[0],c[1])?c=[]:p>2&&di(c[0],c[1],c[2])&&(c=[c[0]]),My(o,Vr(c,1),[])}),Fu=cL||function(){return Bt.Date.now()};function PU(o,c){if(typeof c!="function")throw new dn(a);return o=Et(o),function(){if(--o<1)return c.apply(this,arguments)}}function _6(o,c,p){return c=p?t:c,c=o&&c==null?o.length:c,Ts(o,_,t,t,t,t,c)}function x6(o,c){var p;if(typeof c!="function")throw new dn(a);return o=Et(o),function(){return--o>0&&(p=c.apply(this,arguments)),o<=1&&(c=t),p}}var k1=Mt(function(o,c,p){var I=j;if(p.length){var T=po(p,Sc(k1));I|=z}return Ts(o,I,c,p,T)}),A6=Mt(function(o,c,p){var I=j|H;if(p.length){var T=po(p,Sc(A6));I|=z}return Ts(c,I,o,p,T)});function E6(o,c,p){c=p?t:c;var I=Ts(o,G,t,t,t,t,t,c);return I.placeholder=E6.placeholder,I}function S6(o,c,p){c=p?t:c;var I=Ts(o,B,t,t,t,t,t,c);return I.placeholder=S6.placeholder,I}function I6(o,c,p){var I,T,k,Z,te,se,ue=0,de=!1,ve=!1,Se=!0;if(typeof o!="function")throw new dn(a);c=bn(c)||0,hr(p)&&(de=!!p.leading,ve="maxWait"in p,k=ve?Dr(bn(p.maxWait)||0,c):k,Se="trailing"in p?!!p.trailing:Se);function Je(Ar){var Un=I,Fs=T;return I=T=t,ue=Ar,Z=o.apply(Fs,Un),Z}function ct(Ar){return ue=Ar,te=Zf(Rt,c),de?Je(Ar):Z}function St(Ar){var Un=Ar-se,Fs=Ar-ue,W6=c-Un;return ve?ri(W6,k-Fs):W6}function ft(Ar){var Un=Ar-se,Fs=Ar-ue;return se===t||Un>=c||Un<0||ve&&Fs>=k}function Rt(){var Ar=Fu();if(ft(Ar))return Ft(Ar);te=Zf(Rt,St(Ar))}function Ft(Ar){return te=t,Se&&I?Je(Ar):(I=T=t,Z)}function Ki(){te!==t&&Ly(te),ue=0,I=se=T=te=t}function pi(){return te===t?Z:Ft(Fu())}function Vi(){var Ar=Fu(),Un=ft(Ar);if(I=arguments,T=this,se=Ar,Un){if(te===t)return ct(se);if(ve)return Ly(te),te=Zf(Rt,c),Je(se)}return te===t&&(te=Zf(Rt,c)),Z}return Vi.cancel=Ki,Vi.flush=pi,Vi}var DU=Mt(function(o,c){return gy(o,1,c)}),OU=Mt(function(o,c,p){return gy(o,bn(c)||0,p)});function RU(o){return Ts(o,ee)}function Uu(o,c){if(typeof o!="function"||c!=null&&typeof c!="function")throw new dn(a);var p=function(){var I=arguments,T=c?c.apply(this,I):I[0],k=p.cache;if(k.has(T))return k.get(T);var Z=o.apply(this,I);return p.cache=k.set(T,Z)||k,Z};return p.cache=new(Uu.Cache||Os),p}Uu.Cache=Os;function qu(o){if(typeof o!="function")throw new dn(a);return function(){var c=arguments;switch(c.length){case 0:return!o.call(this);case 1:return!o.call(this,c[0]);case 2:return!o.call(this,c[0],c[1]);case 3:return!o.call(this,c[0],c[1],c[2])}return!o.apply(this,c)}}function TU(o){return x6(2,o)}var $U=yB(function(o,c){c=c.length==1&&wt(c[0])?cr(c[0],ki(ot())):cr(Vr(c,1),ki(ot()));var p=c.length;return Mt(function(I){for(var T=-1,k=ri(I.length,p);++T=c}),va=yy(function(){return arguments}())?yy:function(o){return mr(o)&&Yt.call(o,"callee")&&!oy.call(o,"callee")},wt=ce.isArray,YU=hi?ki(hi):iB;function Ci(o){return o!=null&&zu(o.length)&&!Ls(o)}function xr(o){return mr(o)&&Ci(o)}function JU(o){return o===!0||o===!1||mr(o)&&ui(o)==J}var yo=lL||tg,QU=Nn?ki(Nn):nB;function ZU(o){return mr(o)&&o.nodeType===1&&!Xf(o)}function XU(o){if(o==null)return!0;if(Ci(o)&&(wt(o)||typeof o=="string"||typeof o.splice=="function"||yo(o)||Ic(o)||va(o)))return!o.length;var c=ii(o);if(c==he||c==be)return!o.size;if(Qf(o))return!w1(o).length;for(var p in o)if(Yt.call(o,p))return!1;return!0}function eq(o,c){return Gf(o,c)}function tq(o,c,p){p=typeof p=="function"?p:t;var I=p?p(o,c):t;return I===t?Gf(o,c,t,p):!!I}function W1(o){if(!mr(o))return!1;var c=ui(o);return c==Y||c==E||typeof o.message=="string"&&typeof o.name=="string"&&!Xf(o)}function rq(o){return typeof o=="number"&&cy(o)}function Ls(o){if(!hr(o))return!1;var c=ui(o);return c==re||c==le||c==V||c==Xe}function C6(o){return typeof o=="number"&&o==Et(o)}function zu(o){return typeof o=="number"&&o>-1&&o%1==0&&o<=D}function hr(o){var c=typeof o;return o!=null&&(c=="object"||c=="function")}function mr(o){return o!=null&&typeof o=="object"}var P6=hn?ki(hn):oB;function iq(o,c){return o===c||b1(o,c,N1(c))}function nq(o,c,p){return p=typeof p=="function"?p:t,b1(o,c,N1(c),p)}function sq(o){return D6(o)&&o!=+o}function oq(o){if(kB(o))throw new gt(s);return _y(o)}function aq(o){return o===null}function cq(o){return o==null}function D6(o){return typeof o=="number"||mr(o)&&ui(o)==ge}function Xf(o){if(!mr(o)||ui(o)!=Te)return!1;var c=pu(o);if(c===null)return!0;var p=Yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&lu.call(p)==nL}var K1=fs?ki(fs):aB;function fq(o){return C6(o)&&o>=-D&&o<=D}var O6=Ff?ki(Ff):cB;function Hu(o){return typeof o=="string"||!wt(o)&&mr(o)&&ui(o)==Pe}function Wi(o){return typeof o=="symbol"||mr(o)&&ui(o)==De}var Ic=ca?ki(ca):fB;function lq(o){return o===t}function hq(o){return mr(o)&&ii(o)==Ie}function uq(o){return mr(o)&&ui(o)==Oe}var dq=Ru(y1),pq=Ru(function(o,c){return o<=c});function R6(o){if(!o)return[];if(Ci(o))return Hu(o)?Ln(o):Mi(o);if(qf&&o[qf])return KN(o[qf]());var c=ii(o),p=c==he?a1:c==be?au:Mc;return p(o)}function Bs(o){if(!o)return o===0?o:0;if(o=bn(o),o===P||o===-P){var c=o<0?-1:1;return c*S}return o===o?o:0}function Et(o){var c=Bs(o),p=c%1;return c===c?p?c-p:c:0}function T6(o){return o?ua(Et(o),0,A):0}function bn(o){if(typeof o=="number")return o;if(Wi(o))return v;if(hr(o)){var c=typeof o.valueOf=="function"?o.valueOf():o;o=hr(c)?c+"":c}if(typeof o!="string")return o===0?o:+o;o=Zw(o);var p=Zr.test(o);return p||ei.test(o)?bt(o.slice(2),p?2:8):qt.test(o)?v:+o}function $6(o){return hs(o,Pi(o))}function gq(o){return o?ua(Et(o),-D,D):o===0?o:0}function Vt(o){return o==null?"":ji(o)}var vq=Ac(function(o,c){if(Qf(c)||Ci(c)){hs(c,qr(c),o);return}for(var p in c)Yt.call(c,p)&&Wf(o,p,c[p])}),N6=Ac(function(o,c){hs(c,Pi(c),o)}),ku=Ac(function(o,c,p,I){hs(c,Pi(c),o,I)}),mq=Ac(function(o,c,p,I){hs(c,qr(c),o,I)}),bq=$s(d1);function wq(o,c){var p=xc(o);return c==null?p:dy(p,c)}var yq=Mt(function(o,c){o=tr(o);var p=-1,I=c.length,T=I>2?c[2]:t;for(T&&di(c[0],c[1],T)&&(I=1);++p1),k}),hs(o,T1(o),p),I&&(p=gn(p,w|M|C,OB));for(var T=c.length;T--;)S1(p,c[T]);return p});function Fq(o,c){return B6(o,qu(ot(c)))}var Uq=$s(function(o,c){return o==null?{}:uB(o,c)});function B6(o,c){if(o==null)return{};var p=cr(T1(o),function(I){return[I]});return c=ot(c),Cy(o,p,function(I,T){return c(I,T[0])})}function qq(o,c,p){c=bo(c,o);var I=-1,T=c.length;for(T||(T=1,o=t);++Ic){var I=o;o=c,c=I}if(p||o%1||c%1){var T=fy();return ri(o+T*(c-o+Xt("1e-"+((T+"").length-1))),c)}return x1(o,c)}var Qq=Ec(function(o,c,p){return c=c.toLowerCase(),o+(p?q6(c):c)});function q6(o){return Y1(Vt(o).toLowerCase())}function z6(o){return o=Vt(o),o&&o.replace(vr,zN).replace(Qp,"")}function Zq(o,c,p){o=Vt(o),c=ji(c);var I=o.length;p=p===t?I:ua(Et(p),0,I);var T=p;return p-=c.length,p>=0&&o.slice(p,T)==c}function Xq(o){return o=Vt(o),o&&et.test(o)?o.replace(Ze,HN):o}function ez(o){return o=Vt(o),o&&ut.test(o)?o.replace(Le,"\\$&"):o}var tz=Ec(function(o,c,p){return o+(p?"-":"")+c.toLowerCase()}),rz=Ec(function(o,c,p){return o+(p?" ":"")+c.toLowerCase()}),iz=jy("toLowerCase");function nz(o,c,p){o=Vt(o),c=Et(c);var I=c?mc(o):0;if(!c||I>=c)return o;var T=(c-I)/2;return Ou(bu(T),p)+o+Ou(mu(T),p)}function sz(o,c,p){o=Vt(o),c=Et(c);var I=c?mc(o):0;return c&&I>>0,p?(o=Vt(o),o&&(typeof c=="string"||c!=null&&!K1(c))&&(c=ji(c),!c&&vc(o))?wo(Ln(o),0,p):o.split(c,p)):[]}var uz=Ec(function(o,c,p){return o+(p?" ":"")+Y1(c)});function dz(o,c,p){return o=Vt(o),p=p==null?0:ua(Et(p),0,o.length),c=ji(c),o.slice(p,p+c.length)==c}function pz(o,c,p){var I=q.templateSettings;p&&di(o,c,p)&&(c=t),o=Vt(o),c=ku({},c,I,Qy);var T=ku({},c.imports,I.imports,Qy),k=qr(T),Z=o1(T,k),te,se,ue=0,de=c.interpolate||Ai,ve="__p += '",Se=c1((c.escape||Ai).source+"|"+de.source+"|"+(de===tt?kt:Ai).source+"|"+(c.evaluate||Ai).source+"|$","g"),Je="//# sourceURL="+(Yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Zp+"]")+` ++`;o.replace(Se,function(ft,Rt,Ft,Ki,pi,Vi){return Ft||(Ft=Ki),ve+=o.slice(ue,Vi).replace(Pn,kN),Rt&&(te=!0,ve+=`' + + __e(`+Rt+`) + + '`),pi&&(se=!0,ve+=`'; + `+pi+`; + __p += '`),Ft&&(ve+=`' + + ((__t = (`+Ft+`)) == null ? '' : __t) + +-'`),ue=Ki+ft.length,ft}),ve+=`'; ++'`),ue=Vi+ft.length,ft}),ve+=`'; + `;var ct=Yt.call(c,"variable")&&c.variable;if(!ct)ve=`with (obj) { + `+ve+` + } +@@ -66,25 +66,25 @@ __p += '`),Ft&&(ve+=`' + + function print() { __p += __j.call(arguments, '') } + `:`; + `)+ve+`return __p +-}`;var St=F6(function(){return Wt(k,Je+"return "+ve).apply(t,Z)});if(St.source=ve,j1(St))throw St;return St}function sz(o){return Vt(o).toLowerCase()}function oz(o){return Vt(o).toUpperCase()}function az(o,c,p){if(o=Vt(o),o&&(p||c===t))return Vw(o);if(!o||!(c=ki(c)))return o;var I=$n(o),T=$n(c),k=Gw(I,T),Z=Yw(I,T)+1;return bo(I,k,Z).join("")}function cz(o,c,p){if(o=Vt(o),o&&(p||c===t))return o.slice(0,Qw(o)+1);if(!o||!(c=ki(c)))return o;var I=$n(o),T=Yw(I,$n(c))+1;return bo(I,0,T).join("")}function fz(o,c,p){if(o=Vt(o),o&&(p||c===t))return o.replace(nt,"");if(!o||!(c=ki(c)))return o;var I=$n(o),T=Gw(I,$n(c));return bo(I,T).join("")}function lz(o,c){var p=oe,I=L;if(hr(c)){var T="separator"in c?c.separator:T;p="length"in c?Et(c.length):p,I="omission"in c?ki(c.omission):I}o=Vt(o);var k=o.length;if(gc(o)){var Z=$n(o);k=Z.length}if(p>=k)return o;var te=p-vc(I);if(te<1)return I;var se=Z?bo(Z,0,te).join(""):o.slice(0,te);if(T===t)return se+I;if(Z&&(te+=se.length-te),W1(T)){if(o.slice(te).search(T)){var ue,de=se;for(T.global||(T=a1(T.source,Vt(_t.exec(T))+"g")),T.lastIndex=0;ue=T.exec(de);)var ve=ue.index;se=se.slice(0,ve===t?te:ve)}}else if(o.indexOf(ki(T),te)!=te){var Se=se.lastIndexOf(T);Se>-1&&(se=se.slice(0,Se))}return se+I}function hz(o){return o=Vt(o),o&&rt.test(o)?o.replace(Ot,qN):o}var uz=Ac(function(o,c,p){return o+(p?" ":"")+c.toUpperCase()}),G1=Uy("toUpperCase");function B6(o,c,p){return o=Vt(o),c=p?t:c,c===t?NN(o)?kN(o):IN(o):o.match(c)||[]}var F6=Mt(function(o,c){try{return Fr(o,t,c)}catch(p){return j1(p)?p:new gt(p)}}),dz=Ts(function(o,c){return hn(c,function(p){p=us(p),Os(o,p,H1(o[p],o))}),o});function pz(o){var c=o==null?0:o.length,p=ot();return o=c?cr(o,function(I){if(typeof I[1]!="function")throw new un(a);return[p(I[0]),I[1]]}):[],Mt(function(I){for(var T=-1;++TD)return[];var p=A,I=ti(o,A);c=ot(c),o-=A;for(var T=n1(I,c);++p0||c<0)?new Nt(p):(o<0?p=p.takeRight(-o):o&&(p=p.drop(o)),c!==t&&(c=Et(c),p=c<0?p.dropRight(-c):p.take(c-o)),p)},Nt.prototype.takeRightWhile=function(o){return this.reverse().takeWhile(o).reverse()},Nt.prototype.toArray=function(){return this.take(A)},ls(Nt.prototype,function(o,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),I=/^(?:head|last)$/.test(c),T=q[I?"take"+(c=="last"?"Right":""):c],k=I||/^find/.test(c);T&&(q.prototype[c]=function(){var Z=this.__wrapped__,te=I?[1]:arguments,se=Z instanceof Nt,ue=te[0],de=se||wt(Z),ve=function(Rt){var Ft=T.apply(q,ho([Rt],te));return I&&Se?Ft[0]:Ft};de&&p&&typeof ue=="function"&&ue.length!=1&&(se=de=!1);var Se=this.__chain__,Je=!!this.__actions__.length,ct=k&&!Se,St=se&&!Je;if(!k&&de){Z=St?Z:new Nt(this);var ft=o.apply(Z,te);return ft.__actions__.push({func:Tu,args:[ve],thisArg:t}),new dn(ft,Se)}return ct&&St?o.apply(this,te):(ft=this.thru(ve),ct?I?ft.value()[0]:ft.value():ft)})}),hn(["pop","push","shift","sort","splice","unshift"],function(o){var c=su[o],p=/^(?:push|sort|unshift)$/.test(o)?"tap":"thru",I=/^(?:pop|shift)$/.test(o);q.prototype[o]=function(){var T=arguments;if(I&&!this.__chain__){var k=this.value();return c.apply(wt(k)?k:[],T)}return this[p](function(Z){return c.apply(wt(Z)?Z:[],T)})}}),ls(Nt.prototype,function(o,c){var p=q[c];if(p){var I=p.name+"";Yt.call(yc,I)||(yc[I]=[]),yc[I].push({name:c,func:p})}}),yc[Iu(t,H).name]=[{name:"wrapper",func:t}],Nt.prototype.clone=hL,Nt.prototype.reverse=uL,Nt.prototype.value=dL,q.prototype.at=HF,q.prototype.chain=kF,q.prototype.commit=jF,q.prototype.next=WF,q.prototype.plant=VF,q.prototype.reverse=GF,q.prototype.toJSON=q.prototype.valueOf=q.prototype.value=YF,q.prototype.first=q.prototype.head,Uf&&(q.prototype[Uf]=KF),q},mc=jN();_r?((_r.exports=mc)._=mc,er._=mc):Bt._=mc}).call(fr)})(P0,P0.exports);var D0={exports:{}};(function(r,e){var t=typeof self<"u"?self:fr,i=function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s}();(function(s){(function(a){var f={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function h(l){return l&&DataView.prototype.isPrototypeOf(l)}if(f.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(l){return l&&u.indexOf(Object.prototype.toString.call(l))>-1};function w(l){if(typeof l!="string"&&(l=String(l)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(l))throw new TypeError("Invalid character in header field name");return l.toLowerCase()}function P(l){return typeof l!="string"&&(l=String(l)),l}function M(l){var d={next:function(){var y=l.shift();return{done:y===void 0,value:y}}};return f.iterable&&(d[Symbol.iterator]=function(){return d}),d}function O(l){this.map={},l instanceof O?l.forEach(function(d,y){this.append(y,d)},this):Array.isArray(l)?l.forEach(function(d){this.append(d[0],d[1])},this):l&&Object.getOwnPropertyNames(l).forEach(function(d){this.append(d,l[d])},this)}O.prototype.append=function(l,d){l=w(l),d=P(d);var y=this.map[l];this.map[l]=y?y+", "+d:d},O.prototype.delete=function(l){delete this.map[w(l)]},O.prototype.get=function(l){return l=w(l),this.has(l)?this.map[l]:null},O.prototype.has=function(l){return this.map.hasOwnProperty(w(l))},O.prototype.set=function(l,d){this.map[w(l)]=P(d)},O.prototype.forEach=function(l,d){for(var y in this.map)this.map.hasOwnProperty(y)&&l.call(d,this.map[y],y,this)},O.prototype.keys=function(){var l=[];return this.forEach(function(d,y){l.push(y)}),M(l)},O.prototype.values=function(){var l=[];return this.forEach(function(d){l.push(d)}),M(l)},O.prototype.entries=function(){var l=[];return this.forEach(function(d,y){l.push([y,d])}),M(l)},f.iterable&&(O.prototype[Symbol.iterator]=O.prototype.entries);function $(l){if(l.bodyUsed)return Promise.reject(new TypeError("Already read"));l.bodyUsed=!0}function W(l){return new Promise(function(d,y){l.onload=function(){d(l.result)},l.onerror=function(){y(l.error)}})}function H(l){var d=new FileReader,y=W(d);return d.readAsArrayBuffer(l),y}function F(l){var d=new FileReader,y=W(d);return d.readAsText(l),y}function Y(l){for(var d=new Uint8Array(l),y=new Array(d.length),C=0;C-1?d:l}function U(l,d){d=d||{};var y=d.body;if(l instanceof U){if(l.bodyUsed)throw new TypeError("Already read");this.url=l.url,this.credentials=l.credentials,d.headers||(this.headers=new O(l.headers)),this.method=l.method,this.mode=l.mode,this.signal=l.signal,!y&&l._bodyInit!=null&&(y=l._bodyInit,l.bodyUsed=!0)}else this.url=String(l);if(this.credentials=d.credentials||this.credentials||"same-origin",(d.headers||!this.headers)&&(this.headers=new O(d.headers)),this.method=_(d.method||this.method||"GET"),this.mode=d.mode||this.mode||null,this.signal=d.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&y)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(y)}U.prototype.clone=function(){return new U(this,{body:this._bodyInit})};function ee(l){var d=new FormData;return l.trim().split("&").forEach(function(y){if(y){var C=y.split("="),D=C.shift().replace(/\+/g," "),S=C.join("=").replace(/\+/g," ");d.append(decodeURIComponent(D),decodeURIComponent(S))}}),d}function oe(l){var d=new O,y=l.replace(/\r?\n[\t ]+/g," ");return y.split(/\r?\n/).forEach(function(C){var D=C.split(":"),S=D.shift().trim();if(S){var v=D.join(":").trim();d.append(S,v)}}),d}z.call(U.prototype);function L(l,d){d||(d={}),this.type="default",this.status=d.status===void 0?200:d.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in d?d.statusText:"OK",this.headers=new O(d.headers),this.url=d.url||"",this._initBody(l)}z.call(L.prototype),L.prototype.clone=function(){return new L(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new O(this.headers),url:this.url})},L.error=function(){var l=new L(null,{status:0,statusText:""});return l.type="error",l};var b=[301,302,303,307,308];L.redirect=function(l,d){if(b.indexOf(d)===-1)throw new RangeError("Invalid status code");return new L(null,{status:d,headers:{location:l}})},a.DOMException=s.DOMException;try{new a.DOMException}catch{a.DOMException=function(d,y){this.message=d,this.name=y;var C=Error(d);this.stack=C.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function m(l,d){return new Promise(function(y,C){var D=new U(l,d);if(D.signal&&D.signal.aborted)return C(new a.DOMException("Aborted","AbortError"));var S=new XMLHttpRequest;function v(){S.abort()}S.onload=function(){var A={status:S.status,statusText:S.statusText,headers:oe(S.getAllResponseHeaders()||"")};A.url="responseURL"in S?S.responseURL:A.headers.get("X-Request-URL");var x="response"in S?S.response:S.responseText;y(new L(x,A))},S.onerror=function(){C(new TypeError("Network request failed"))},S.ontimeout=function(){C(new TypeError("Network request failed"))},S.onabort=function(){C(new a.DOMException("Aborted","AbortError"))},S.open(D.method,D.url,!0),D.credentials==="include"?S.withCredentials=!0:D.credentials==="omit"&&(S.withCredentials=!1),"responseType"in S&&f.blob&&(S.responseType="blob"),D.headers.forEach(function(A,x){S.setRequestHeader(x,A)}),D.signal&&(D.signal.addEventListener("abort",v),S.onreadystatechange=function(){S.readyState===4&&D.signal.removeEventListener("abort",v)}),S.send(typeof D._bodyInit>"u"?null:D._bodyInit)})}return m.polyfill=!0,s.fetch||(s.fetch=m,s.Headers=O,s.Request=U,s.Response=L),a.Headers=O,a.Request=U,a.Response=L,a.fetch=m,Object.defineProperty(a,"__esModule",{value:!0}),a})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,r.exports=e})(D0,D0.exports);var K2=z6(D0.exports),KP=Object.defineProperty,VP=Object.defineProperties,GP=Object.getOwnPropertyDescriptors,V2=Object.getOwnPropertySymbols,YP=Object.prototype.hasOwnProperty,JP=Object.prototype.propertyIsEnumerable,G2=(r,e,t)=>e in r?KP(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Y2=(r,e)=>{for(var t in e||(e={}))YP.call(e,t)&&G2(r,t,e[t]);if(V2)for(var t of V2(e))JP.call(e,t)&&G2(r,t,e[t]);return r},J2=(r,e)=>VP(r,GP(e));const QP={Accept:"application/json","Content-Type":"application/json"},ZP="POST",Q2={headers:QP,method:ZP},Z2=10;class In{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new qr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Jb(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}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(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const t=ws(e),i=await(await K2(this.url,J2(Y2({},Q2),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!Jb(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=ws({id:1,jsonrpc:"2.0",method:"test",params:[]});await K2(e,J2(Y2({},Q2),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?Po(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),n=i.message||i.toString(),s=rh(e,n);this.events.emit("payload",s)}parseError(e,t=this.url){return jb(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Z2&&this.events.setMaxListeners(Z2)}}const X2="error",XP="wss://relay.walletconnect.org",eD="wc",tD="universal_provider",e3=`${eD}@2:${tD}:`,t3="https://rpc.walletconnect.org/v1/",Wa="generic",rD=`${t3}bundler`,on={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var iD=Object.defineProperty,nD=Object.defineProperties,sD=Object.getOwnPropertyDescriptors,r3=Object.getOwnPropertySymbols,oD=Object.prototype.hasOwnProperty,aD=Object.prototype.propertyIsEnumerable,i3=(r,e,t)=>e in r?iD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ah=(r,e)=>{for(var t in e||(e={}))oD.call(e,t)&&i3(r,t,e[t]);if(r3)for(var t of r3(e))aD.call(e,t)&&i3(r,t,e[t]);return r},cD=(r,e)=>nD(r,sD(e));function Fi(r,e,t){var i;const n=Ba(r);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${t3}?chainId=${n.namespace}:${n.reference}&projectId=${t}`}function zo(r){return r.includes(":")?r.split(":")[1]:r}function n3(r){return r.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function fD(r,e){const t=Object.keys(e.namespaces).filter(n=>n.includes(r));if(!t.length)return[];const i=[];return t.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function O0(r={},e={}){const t=s3(r),i=s3(e);return P0.exports.merge(t,i)}function s3(r){var e,t,i,n;const s={};if(!ef(r))return s;for(const[a,f]of Object.entries(r)){const h=e0(a)?[a]:f.chains,u=f.methods||[],g=f.events||[],w=f.rpcMap||{},P=Xc(a);s[P]=cD(ah(ah({},s[P]),f),{chains:ql(h,(e=s[P])==null?void 0:e.chains),methods:ql(u,(t=s[P])==null?void 0:t.methods),events:ql(g,(i=s[P])==null?void 0:i.events),rpcMap:ah(ah({},w),(n=s[P])==null?void 0:n.rpcMap)})}return s}function lD(r){return r.includes(":")?r.split(":")[2]:r}function o3(r){const e={};for(const[t,i]of Object.entries(r)){const n=i.methods||[],s=i.events||[],a=i.accounts||[],f=e0(t)?[t]:i.chains?i.chains:n3(i.accounts);e[t]={chains:f,methods:n,events:s,accounts:a}}return e}function R0(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const a3={},zt=r=>a3[r],T0=(r,e)=>{a3[r]=e};class hD{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=zo(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new rn(new In(i,zt("disableProviderPing")))}}var uD=Object.defineProperty,dD=Object.defineProperties,pD=Object.getOwnPropertyDescriptors,c3=Object.getOwnPropertySymbols,gD=Object.prototype.hasOwnProperty,vD=Object.prototype.propertyIsEnumerable,f3=(r,e,t)=>e in r?uD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,l3=(r,e)=>{for(var t in e||(e={}))gD.call(e,t)&&f3(r,t,e[t]);if(c3)for(var t of c3(e))vD.call(e,t)&&f3(r,t,e[t]);return r},h3=(r,e)=>dD(r,pD(e));class mD{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||Fi(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new rn(new In(i,zt("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=parseInt(zo(t));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let n=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,n;const s=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!s)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const a=this.client.session.get(e.topic),f=((n=a?.sessionProperties)==null?void 0:n.capabilities)||{};if(f!=null&&f[s])return f?.[s];const h=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:h3(l3({},a.sessionProperties||{}),{capabilities:h3(l3({},f||{}),{[s]:h})})})}catch(u){console.warn("Failed to update session with capabilities",u)}return h}async getCallStatus(e){var t,i;const n=this.client.session.get(e.topic),s=(t=n.sessionProperties)==null?void 0:t.bundler_name;if(s){const f=this.getBundlerUrl(e.chainId,s);try{return await this.getUserOperationReceipt(f,e)}catch(h){console.warn("Failed to fetch call status from bundler",h,f)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(f){console.warn("Failed to fetch call status from custom bundler",f,a)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ys("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,t){return`${rD}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}class bD{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=zo(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new rn(new In(i,zt("disableProviderPing")))}}class wD{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=zo(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new rn(new In(i,zt("disableProviderPing")))}}class yD{constructor(e){this.name="algorand",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||Fi(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new rn(new In(i,zt("disableProviderPing")))}}class _D{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),n=zo(t);e[n]=this.createHttpProvider(n,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new rn(new In(i,zt("disableProviderPing")))}}class xD{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=zo(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new rn(new In(i,zt("disableProviderPing")))}}class AD{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=zo(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new rn(new In(i,zt("disableProviderPing")))}}class ED{constructor(e){this.name="near",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Fi(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace);return typeof i>"u"?void 0:new rn(new In(i,zt("disableProviderPing")))}}class SD{constructor(e){this.name="tezos",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Fi(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace);return typeof i>"u"?void 0:new rn(new In(i))}}class ID{constructor(e){this.name=Wa,this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(on.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(n=>{const s=Ba(n);i[`${s.namespace}:${s.reference}`]=this.createHttpProvider(n)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Fi(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new rn(new In(i,zt("disableProviderPing")))}}var MD=Object.defineProperty,CD=Object.defineProperties,PD=Object.getOwnPropertyDescriptors,u3=Object.getOwnPropertySymbols,DD=Object.prototype.hasOwnProperty,OD=Object.prototype.propertyIsEnumerable,d3=(r,e,t)=>e in r?MD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ch=(r,e)=>{for(var t in e||(e={}))DD.call(e,t)&&d3(r,t,e[t]);if(u3)for(var t of u3(e))OD.call(e,t)&&d3(r,t,e[t]);return r},$0=(r,e)=>CD(r,PD(e));class N0{constructor(e){this.events=new qr.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Qn(eh({level:e?.logger||X2})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new N0(e);return await t.initialize(),t}async request(e,t,i){const[n,s]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ch({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,n){const s=new Date().getTime();this.request(e,i,n).then(a=>t(null,th(s,a))).catch(a=>t(a,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Gt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const a=o3(this.session.namespaces);this.namespaces=O0(this.namespaces,a),this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let t=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(t>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:i,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});i&&(this.uri=i,this.events.emit("display_uri",i)),await n().then(s=>{this.session=s;const a=o3(s.namespaces);this.namespaces=O0(this.namespaces,a),this.persist("namespaces",this.namespaces)}).catch(s=>{if(s.message!==k2)throw s;t++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,n]=this.validateChain(e),s=this.getProvider(i);s.name===Wa?s.setDefaultChain(`${i}:${n}`,t):s.setDefaultChain(n,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(Jn(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await C0.init({core:this.providerOpts.core,logger:this.providerOpts.logger||X2,relayUrl:this.providerOpts.relayUrl||XP,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>Xc(t)))];T0("client",this.client),T0("events",this.events),T0("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=fD(t,this.session),n=n3(i),s=O0(this.namespaces,this.optionalNamespaces),a=$0(ch({},s[t]),{accounts:i,chains:n});switch(t){case"eip155":this.rpcProviders[t]=new mD({namespace:a});break;case"algorand":this.rpcProviders[t]=new yD({namespace:a});break;case"solana":this.rpcProviders[t]=new bD({namespace:a});break;case"cosmos":this.rpcProviders[t]=new wD({namespace:a});break;case"polkadot":this.rpcProviders[t]=new hD({namespace:a});break;case"cip34":this.rpcProviders[t]=new _D({namespace:a});break;case"elrond":this.rpcProviders[t]=new xD({namespace:a});break;case"multiversx":this.rpcProviders[t]=new AD({namespace:a});break;case"near":this.rpcProviders[t]=new ED({namespace:a});break;case"tezos":this.rpcProviders[t]=new SD({namespace:a});break;default:this.rpcProviders[Wa]?this.rpcProviders[Wa].updateNamespace(a):this.rpcProviders[Wa]=new ID({namespace:a})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t}=e,{event:i}=t;if(i.name==="accountsChanged"){const n=i.data;n&&Jn(n)&&this.events.emit("accountsChanged",n.map(lD))}else if(i.name==="chainChanged"){const n=t.chainId,s=t.event.data,a=Xc(n),f=R0(n)!==R0(s)?`${a}:${R0(s)}`:n;this.onChainChanged(f)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i;const{namespaces:n}=t,s=(i=this.client)==null?void 0:i.session.get(e);this.session=$0(ch({},s),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",$0(ch({},Gt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(on.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Wa]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:n}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=n,this.persist("namespaces",t),this.persist("optionalNamespaces",i)}validateChain(e){const[t,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(a=>Xc(a)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const n=Xc(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);n&&(t||this.getProvider(i).setDefaultChain(n),this.namespaces[i]?this.namespaces[i].defaultChain=n:this.namespaces[`${i}:${n}`]?this.namespaces[`${i}:${n}`].defaultChain=n:this.namespaces[`${i}:${n}`]={defaultChain:n},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",n))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,t){this.client.core.storage.setItem(`${e3}/${e}`,t)}async getFromStore(e){return await this.client.core.storage.getItem(`${e3}/${e}`)}}const RD=N0,TD="wc",$D="ethereum_provider",ND=`${TD}@2:${$D}:`,LD="https://rpc.walletconnect.org/v1/",fh=["eth_sendTransaction","personal_sign"],p3=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],lh=["chainChanged","accountsChanged"],g3=["chainChanged","accountsChanged","message","disconnect","connect"];var BD=Object.defineProperty,FD=Object.defineProperties,UD=Object.getOwnPropertyDescriptors,v3=Object.getOwnPropertySymbols,qD=Object.prototype.hasOwnProperty,zD=Object.prototype.propertyIsEnumerable,m3=(r,e,t)=>e in r?BD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ka=(r,e)=>{for(var t in e||(e={}))qD.call(e,t)&&m3(r,t,e[t]);if(v3)for(var t of v3(e))zD.call(e,t)&&m3(r,t,e[t]);return r},L0=(r,e)=>FD(r,UD(e));function hh(r){return Number(r[0].split(":")[1])}function uh(r){return`0x${r.toString(16)}`}function HD(r){const{chains:e,optionalChains:t,methods:i,optionalMethods:n,events:s,optionalEvents:a,rpcMap:f}=r;if(!Jn(e))throw new Error("Invalid chains");const h={chains:e,methods:i||fh,events:s||lh,rpcMap:Ka({},e.length?{[hh(e)]:f[hh(e)]}:{})},u=s?.filter(M=>!lh.includes(M)),g=i?.filter(M=>!fh.includes(M));if(!t&&!a&&!n&&!(u!=null&&u.length)&&!(g!=null&&g.length))return{required:e.length?h:void 0};const w=u?.length&&g?.length||!t,P={chains:[...new Set(w?h.chains.concat(t||[]):t)],methods:[...new Set(h.methods.concat(n!=null&&n.length?n:p3))],events:[...new Set(h.events.concat(a!=null&&a.length?a:g3))],rpcMap:f};return{required:e.length?h:void 0,optional:t.length?P:void 0}}class dh{constructor(){this.events=new qr.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=ND,this.on=(e,t)=>(this.events.on(e,t),this),this.once=(e,t)=>(this.events.once(e,t),this),this.removeListener=(e,t)=>(this.events.removeListener(e,t),this),this.off=(e,t)=>(this.events.off(e,t),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const t=new dh;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:i}=HD(this.rpc);try{const n=await new Promise(async(a,f)=>{var h;this.rpc.showQrModal&&((h=this.modal)==null||h.subscribeModal(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),f(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(L0(Ka({namespaces:Ka({},t&&{[this.namespace]:t})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic})).then(u=>{a(u)}).catch(u=>{f(new Error(u.message))})});if(!n)return;const s=Bm(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:uh(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async authenticate(e,t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(s,a)=>{var f;this.rpc.showQrModal&&((f=this.modal)==null||f.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(L0(Ka({},e),{chains:this.rpc.chains}),t).then(h=>{s(h)}).catch(h=>{a(new Error(h.message))})}),n=i.session;if(n){const s=Bm(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:uh(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:i}=t;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",uh(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",L0(Ka({},Gt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var t,i;this.rpc.showQrModal&&((t=this.modal)==null||t.closeModal(),(i=this.modal)==null||i.openModal({uri:e})),this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",uh(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,n]=e.split(":");return{chainId:`${t}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;const n=(t=e?.chains)!=null?t:[],s=(i=e?.optionalChains)!=null?i:[],a=n.concat(s);if(!a.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const f=n.length?e?.methods||fh:[],h=n.length?e?.events||lh:[],u=e?.optionalMethods||[],g=e?.optionalEvents||[],w=e?.rpcMap||this.buildRpcMap(a,e.projectId),P=e?.qrModalOptions||void 0;return{chains:n?.map(M=>this.formatChainId(M)),optionalChains:s.map(M=>this.formatChainId(M)),methods:f,events:h,optionalMethods:u,optionalEvents:g,rpcMap:w,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:P,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,t)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?hh(this.rpc.chains):hh(this.rpc.optionalChains),this.signer=await RD.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const{WalletConnectModal:i}=await Promise.resolve().then(function(){return hO});t=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(t)try{this.modal=new t(Ka({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:n}=e;t&&Jn(t)&&(this.rpc.chains=t.map(s=>this.formatChainId(s)),t.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)})),i&&Jn(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${LD}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const kD=dh,jD=Symbol(),b3=Object.getPrototypeOf,B0=new WeakMap,WD=r=>r&&(B0.has(r)?B0.get(r):b3(r)===Object.prototype||b3(r)===Array.prototype),KD=r=>WD(r)&&r[jD]||null,w3=(r,e=!0)=>{B0.set(r,e)},F0=r=>typeof r=="object"&&r!==null,Js=new WeakMap,ph=new WeakSet,VD=(r=Object.is,e=(u,g)=>new Proxy(u,g),t=u=>F0(u)&&!ph.has(u)&&(Array.isArray(u)||!(Symbol.iterator in u))&&!(u instanceof WeakMap)&&!(u instanceof WeakSet)&&!(u instanceof Error)&&!(u instanceof Number)&&!(u instanceof Date)&&!(u instanceof String)&&!(u instanceof RegExp)&&!(u instanceof ArrayBuffer),i=u=>{switch(u.status){case"fulfilled":return u.value;case"rejected":throw u.reason;default:throw u}},n=new WeakMap,s=(u,g,w=i)=>{const P=n.get(u);if(P?.[0]===g)return P[1];const M=Array.isArray(u)?[]:Object.create(Object.getPrototypeOf(u));return w3(M,!0),n.set(u,[g,M]),Reflect.ownKeys(u).forEach(O=>{if(Object.getOwnPropertyDescriptor(M,O))return;const $=Reflect.get(u,O),W={value:$,enumerable:!0,configurable:!0};if(ph.has($))w3($,!1);else if($ instanceof Promise)delete W.value,W.get=()=>w($);else if(Js.has($)){const[H,F]=Js.get($);W.value=s(H,F(),w)}Object.defineProperty(M,O,W)}),Object.preventExtensions(M)},a=new WeakMap,f=[1,1],h=u=>{if(!F0(u))throw new Error("object required");const g=a.get(u);if(g)return g;let w=f[0];const P=new Set,M=(ee,oe=++f[0])=>{w!==oe&&(w=oe,P.forEach(L=>L(ee,oe)))};let O=f[1];const $=(ee=++f[1])=>(O!==ee&&!P.size&&(O=ee,H.forEach(([oe])=>{const L=oe[1](ee);L>w&&(w=L)})),w),W=ee=>(oe,L)=>{const b=[...oe];b[1]=[ee,...b[1]],M(b,L)},H=new Map,F=(ee,oe)=>{if(H.has(ee))throw new Error("prop listener already exists");if(P.size){const L=oe[3](W(ee));H.set(ee,[oe,L])}else H.set(ee,[oe])},Y=ee=>{var oe;const L=H.get(ee);L&&(H.delete(ee),(oe=L[1])==null||oe.call(L))},B=ee=>(P.add(ee),P.size===1&&H.forEach(([L,b],m)=>{if(b)throw new Error("remove already exists");const l=L[3](W(m));H.set(m,[L,l])}),()=>{P.delete(ee),P.size===0&&H.forEach(([L,b],m)=>{b&&(b(),H.set(m,[L]))})}),z=Array.isArray(u)?[]:Object.create(Object.getPrototypeOf(u)),_=e(z,{deleteProperty(ee,oe){const L=Reflect.get(ee,oe);Y(oe);const b=Reflect.deleteProperty(ee,oe);return b&&M(["delete",[oe],L]),b},set(ee,oe,L,b){const m=Reflect.has(ee,oe),l=Reflect.get(ee,oe,b);if(m&&(r(l,L)||a.has(L)&&r(l,a.get(L))))return!0;Y(oe),F0(L)&&(L=KD(L)||L);let d=L;if(L instanceof Promise)L.then(y=>{L.status="fulfilled",L.value=y,M(["resolve",[oe],y])}).catch(y=>{L.status="rejected",L.reason=y,M(["reject",[oe],y])});else{!Js.has(L)&&t(L)&&(d=h(L));const y=!ph.has(d)&&Js.get(d);y&&F(oe,y)}return Reflect.set(ee,oe,d,b),M(["set",[oe],L,l]),!0}});a.set(u,_);const U=[z,$,s,B];return Js.set(_,U),Reflect.ownKeys(u).forEach(ee=>{const oe=Object.getOwnPropertyDescriptor(u,ee);"value"in oe&&(_[ee]=u[ee],delete oe.value,delete oe.writable),Object.defineProperty(z,ee,oe)}),_})=>[h,Js,ph,r,e,t,i,n,s,a,f],[GD]=VD();function Qs(r={}){return GD(r)}function Ho(r,e,t){const i=Js.get(r);i||console.warn("Please use proxy object");let n;const s=[],a=i[3];let f=!1;const u=a(g=>{if(s.push(g),t){e(s.splice(0));return}n||(n=Promise.resolve().then(()=>{n=void 0,f&&e(s.splice(0))}))});return f=!0,()=>{f=!1,u()}}function YD(r,e){const t=Js.get(r);t||console.warn("Please use proxy object");const[i,n,s]=t;return s(i,n(),e)}const Br=Qs({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),lr={state:Br,subscribe(r){return Ho(Br,()=>r(Br))},push(r,e){r!==Br.view&&(Br.view=r,e&&(Br.data=e),Br.history.push(r))},reset(r){Br.view=r,Br.history=[r]},replace(r){Br.history.length>1&&(Br.history[Br.history.length-1]=r,Br.view=r)},goBack(){if(Br.history.length>1){Br.history.pop();const[r]=Br.history.slice(-1);Br.view=r}},setData(r){Br.data=r}},je={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return je.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const r=navigator.userAgent.toLowerCase();return je.isMobile()&&(r.includes("iphone")||r.includes("ipad"))},isHttpUrl(r){return r.startsWith("http://")||r.startsWith("https://")},isArray(r){return Array.isArray(r)&&r.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(r,e,t){if(je.isHttpUrl(r))return this.formatUniversalUrl(r,e,t);let i=r;i.includes("://")||(i=r.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,t);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},formatUniversalUrl(r,e,t){if(!je.isHttpUrl(r))return this.formatNativeUrl(r,e,t);let i=r;if(i.startsWith("https://t.me")){const s=Buffer.from(e).toString("base64").replace(/[=]/g,"");i.endsWith("/")&&(i=i.slice(0,-1)),this.setWalletConnectDeepLink(i,t);const a=new URL(i);return a.searchParams.set("startapp",s),a.toString()}i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,t);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},async wait(r){return new Promise(e=>{setTimeout(e,r)})},openHref(r,e){const t=this.isTelegram()?"_blank":e;window.open(r,t,"noreferrer noopener")},setWalletConnectDeepLink(r,e){try{localStorage.setItem(je.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:r,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(r){try{const[e]=r.split("?");localStorage.setItem(je.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(je.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(je.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var r;const e=(r=lr.state.data)==null?void 0:r.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},JD=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),Jr=Qs({enabled:JD,userSessionId:"",events:[],connectedWalletId:void 0}),y3={state:Jr,subscribe(r){return Ho(Jr.events,()=>r(YD(Jr.events[Jr.events.length-1])))},initialize(){Jr.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(Jr.userSessionId=crypto.randomUUID())},setConnectedWalletId(r){Jr.connectedWalletId=r},click(r){if(Jr.enabled){const e={type:"CLICK",name:r.name,userSessionId:Jr.userSessionId,timestamp:Date.now(),data:r};Jr.events.push(e)}},track(r){if(Jr.enabled){const e={type:"TRACK",name:r.name,userSessionId:Jr.userSessionId,timestamp:Date.now(),data:r};Jr.events.push(e)}},view(r){if(Jr.enabled){const e={type:"VIEW",name:r.name,userSessionId:Jr.userSessionId,timestamp:Date.now(),data:r};Jr.events.push(e)}}},ns=Qs({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),yr={state:ns,subscribe(r){return Ho(ns,()=>r(ns))},setChains(r){ns.chains=r},setWalletConnectUri(r){ns.walletConnectUri=r},setIsCustomDesktop(r){ns.isCustomDesktop=r},setIsCustomMobile(r){ns.isCustomMobile=r},setIsDataLoaded(r){ns.isDataLoaded=r},setIsUiLoaded(r){ns.isUiLoaded=r},setIsAuth(r){ns.isAuth=r}},gh=Qs({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),Ui={state:gh,subscribe(r){return Ho(gh,()=>r(gh))},setConfig(r){var e,t;y3.initialize(),yr.setChains(r.chains),yr.setIsAuth(!!r.enableAuthMode),yr.setIsCustomMobile(!!((e=r.mobileWallets)!=null&&e.length)),yr.setIsCustomDesktop(!!((t=r.desktopWallets)!=null&&t.length)),je.setModalVersionInStorage(),Object.assign(gh,r)}};var QD=Object.defineProperty,_3=Object.getOwnPropertySymbols,ZD=Object.prototype.hasOwnProperty,XD=Object.prototype.propertyIsEnumerable,x3=(r,e,t)=>e in r?QD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,eO=(r,e)=>{for(var t in e||(e={}))ZD.call(e,t)&&x3(r,t,e[t]);if(_3)for(var t of _3(e))XD.call(e,t)&&x3(r,t,e[t]);return r};const U0="https://explorer-api.walletconnect.com",q0="wcm",z0="js-2.7.0";async function vh(r,e){const t=eO({sdkType:q0,sdkVersion:z0},e),i=new URL(r,U0);return i.searchParams.append("projectId",Ui.state.projectId),Object.entries(t).forEach(([s,a])=>{a&&i.searchParams.append(s,String(a))}),(await fetch(i)).json()}const ko={async getDesktopListings(r){return vh("/w3m/v1/getDesktopListings",r)},async getMobileListings(r){return vh("/w3m/v1/getMobileListings",r)},async getInjectedListings(r){return vh("/w3m/v1/getInjectedListings",r)},async getAllListings(r){return vh("/w3m/v1/getAllListings",r)},getWalletImageUrl(r){return`${U0}/w3m/v1/getWalletImage/${r}?projectId=${Ui.state.projectId}&sdkType=${q0}&sdkVersion=${z0}`},getAssetImageUrl(r){return`${U0}/w3m/v1/getAssetImage/${r}?projectId=${Ui.state.projectId}&sdkType=${q0}&sdkVersion=${z0}`}};var tO=Object.defineProperty,A3=Object.getOwnPropertySymbols,rO=Object.prototype.hasOwnProperty,iO=Object.prototype.propertyIsEnumerable,E3=(r,e,t)=>e in r?tO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,nO=(r,e)=>{for(var t in e||(e={}))rO.call(e,t)&&E3(r,t,e[t]);if(A3)for(var t of A3(e))iO.call(e,t)&&E3(r,t,e[t]);return r};const S3=je.isMobile(),ss=Qs({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),_i={state:ss,async getRecomendedWallets(){const{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:e}=Ui.state;if(r==="NONE"||e==="ALL"&&!r)return ss.recomendedWallets;if(je.isArray(r)){const i={recommendedIds:r.join(",")},{listings:n}=await ko.getAllListings(i),s=Object.values(n);s.sort((a,f)=>{const h=r.indexOf(a.id),u=r.indexOf(f.id);return h-u}),ss.recomendedWallets=s}else{const{chains:t,isAuth:i}=yr.state,n=t?.join(","),s=je.isArray(e),a={page:1,sdks:i?"auth_v1":void 0,entries:je.RECOMMENDED_WALLET_AMOUNT,chains:n,version:2,excludedIds:s?e.join(","):void 0},{listings:f}=S3?await ko.getMobileListings(a):await ko.getDesktopListings(a);ss.recomendedWallets=Object.values(f)}return ss.recomendedWallets},async getWallets(r){const e=nO({},r),{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:i}=Ui.state,{recomendedWallets:n}=ss;if(i==="ALL")return ss.wallets;n.length?e.excludedIds=n.map(w=>w.id).join(","):je.isArray(t)&&(e.excludedIds=t.join(",")),je.isArray(i)&&(e.excludedIds=[e.excludedIds,i].filter(Boolean).join(",")),yr.state.isAuth&&(e.sdks="auth_v1");const{page:s,search:a}=r,{listings:f,total:h}=S3?await ko.getMobileListings(e):await ko.getDesktopListings(e),u=Object.values(f),g=a?"search":"wallets";return ss[g]={listings:[...ss[g].listings,...u],total:h,page:s??1},{listings:u,total:h}},getWalletImageUrl(r){return ko.getWalletImageUrl(r)},getAssetImageUrl(r){return ko.getAssetImageUrl(r)},resetSearch(){ss.search={listings:[],total:0,page:1}}},Va=Qs({open:!1}),jo={state:Va,subscribe(r){return Ho(Va,()=>r(Va))},async open(r){return new Promise(e=>{const{isUiLoaded:t,isDataLoaded:i}=yr.state;if(je.removeWalletConnectDeepLink(),yr.setWalletConnectUri(r?.uri),yr.setChains(r?.chains),lr.reset("ConnectWallet"),t&&i)Va.open=!0,e();else{const n=setInterval(()=>{const s=yr.state;s.isUiLoaded&&s.isDataLoaded&&(clearInterval(n),Va.open=!0,e())},200)}})},close(){Va.open=!1}};var sO=Object.defineProperty,I3=Object.getOwnPropertySymbols,oO=Object.prototype.hasOwnProperty,aO=Object.prototype.propertyIsEnumerable,M3=(r,e,t)=>e in r?sO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,cO=(r,e)=>{for(var t in e||(e={}))oO.call(e,t)&&M3(r,t,e[t]);if(I3)for(var t of I3(e))aO.call(e,t)&&M3(r,t,e[t]);return r};function fO(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const gf=Qs({themeMode:fO()?"dark":"light"}),Zs={state:gf,subscribe(r){return Ho(gf,()=>r(gf))},setThemeConfig(r){const{themeMode:e,themeVariables:t}=r;e&&(gf.themeMode=e),t&&(gf.themeVariables=cO({},t))}},Wo=Qs({open:!1,message:"",variant:"success"}),Xs={state:Wo,subscribe(r){return Ho(Wo,()=>r(Wo))},openToast(r,e){Wo.open=!0,Wo.message=r,Wo.variant=e},closeToast(){Wo.open=!1}};class lO{constructor(e){this.openModal=jo.open,this.closeModal=jo.close,this.subscribeModal=jo.subscribe,this.setTheme=Zs.setThemeConfig,Zs.setThemeConfig(e),Ui.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return yN});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),yr.setIsUiLoaded(!0)}}}var hO=Object.freeze({__proto__:null,WalletConnectModal:lO});/** ++}`;var St=k6(function(){return Wt(k,Je+"return "+ve).apply(t,Z)});if(St.source=ve,W1(St))throw St;return St}function gz(o){return Vt(o).toLowerCase()}function vz(o){return Vt(o).toUpperCase()}function mz(o,c,p){if(o=Vt(o),o&&(p||c===t))return Zw(o);if(!o||!(c=ji(c)))return o;var I=Ln(o),T=Ln(c),k=Xw(I,T),Z=ey(I,T)+1;return wo(I,k,Z).join("")}function bz(o,c,p){if(o=Vt(o),o&&(p||c===t))return o.slice(0,ry(o)+1);if(!o||!(c=ji(c)))return o;var I=Ln(o),T=ey(I,Ln(c))+1;return wo(I,0,T).join("")}function wz(o,c,p){if(o=Vt(o),o&&(p||c===t))return o.replace(nt,"");if(!o||!(c=ji(c)))return o;var I=Ln(o),T=Xw(I,Ln(c));return wo(I,T).join("")}function yz(o,c){var p=oe,I=L;if(hr(c)){var T="separator"in c?c.separator:T;p="length"in c?Et(c.length):p,I="omission"in c?ji(c.omission):I}o=Vt(o);var k=o.length;if(vc(o)){var Z=Ln(o);k=Z.length}if(p>=k)return o;var te=p-mc(I);if(te<1)return I;var se=Z?wo(Z,0,te).join(""):o.slice(0,te);if(T===t)return se+I;if(Z&&(te+=se.length-te),K1(T)){if(o.slice(te).search(T)){var ue,de=se;for(T.global||(T=c1(T.source,Vt(_t.exec(T))+"g")),T.lastIndex=0;ue=T.exec(de);)var ve=ue.index;se=se.slice(0,ve===t?te:ve)}}else if(o.indexOf(ji(T),te)!=te){var Se=se.lastIndexOf(T);Se>-1&&(se=se.slice(0,Se))}return se+I}function _z(o){return o=Vt(o),o&&rt.test(o)?o.replace(Ot,JN):o}var xz=Ec(function(o,c,p){return o+(p?" ":"")+c.toUpperCase()}),Y1=jy("toUpperCase");function H6(o,c,p){return o=Vt(o),c=p?t:c,c===t?WN(o)?XN(o):LN(o):o.match(c)||[]}var k6=Mt(function(o,c){try{return Ur(o,t,c)}catch(p){return W1(p)?p:new gt(p)}}),Az=$s(function(o,c){return un(c,function(p){p=us(p),Rs(o,p,k1(o[p],o))}),o});function Ez(o){var c=o==null?0:o.length,p=ot();return o=c?cr(o,function(I){if(typeof I[1]!="function")throw new dn(a);return[p(I[0]),I[1]]}):[],Mt(function(I){for(var T=-1;++TD)return[];var p=A,I=ri(o,A);c=ot(c),o-=A;for(var T=s1(I,c);++p0||c<0)?new Nt(p):(o<0?p=p.takeRight(-o):o&&(p=p.drop(o)),c!==t&&(c=Et(c),p=c<0?p.dropRight(-c):p.take(c-o)),p)},Nt.prototype.takeRightWhile=function(o){return this.reverse().takeWhile(o).reverse()},Nt.prototype.toArray=function(){return this.take(A)},ls(Nt.prototype,function(o,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),I=/^(?:head|last)$/.test(c),T=q[I?"take"+(c=="last"?"Right":""):c],k=I||/^find/.test(c);T&&(q.prototype[c]=function(){var Z=this.__wrapped__,te=I?[1]:arguments,se=Z instanceof Nt,ue=te[0],de=se||wt(Z),ve=function(Rt){var Ft=T.apply(q,uo([Rt],te));return I&&Se?Ft[0]:Ft};de&&p&&typeof ue=="function"&&ue.length!=1&&(se=de=!1);var Se=this.__chain__,Je=!!this.__actions__.length,ct=k&&!Se,St=se&&!Je;if(!k&&de){Z=St?Z:new Nt(this);var ft=o.apply(Z,te);return ft.__actions__.push({func:Lu,args:[ve],thisArg:t}),new pn(ft,Se)}return ct&&St?o.apply(this,te):(ft=this.thru(ve),ct?I?ft.value()[0]:ft.value():ft)})}),un(["pop","push","shift","sort","splice","unshift"],function(o){var c=cu[o],p=/^(?:push|sort|unshift)$/.test(o)?"tap":"thru",I=/^(?:pop|shift)$/.test(o);q.prototype[o]=function(){var T=arguments;if(I&&!this.__chain__){var k=this.value();return c.apply(wt(k)?k:[],T)}return this[p](function(Z){return c.apply(wt(Z)?Z:[],T)})}}),ls(Nt.prototype,function(o,c){var p=q[c];if(p){var I=p.name+"";Yt.call(_c,I)||(_c[I]=[]),_c[I].push({name:c,func:p})}}),_c[Pu(t,H).name]=[{name:"wrapper",func:t}],Nt.prototype.clone=_L,Nt.prototype.reverse=xL,Nt.prototype.value=AL,q.prototype.at=ZF,q.prototype.chain=XF,q.prototype.commit=eU,q.prototype.next=tU,q.prototype.plant=iU,q.prototype.reverse=nU,q.prototype.toJSON=q.prototype.valueOf=q.prototype.value=sU,q.prototype.first=q.prototype.head,qf&&(q.prototype[qf]=rU),q},bc=eL();_r?((_r.exports=bc)._=bc,er._=bc):Bt._=bc}).call(fr)})(D0,D0.exports);var O0={exports:{}};(function(r,e){var t=typeof self<"u"?self:fr,i=function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s}();(function(s){(function(a){var f={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function h(l){return l&&DataView.prototype.isPrototypeOf(l)}if(f.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(l){return l&&u.indexOf(Object.prototype.toString.call(l))>-1};function w(l){if(typeof l!="string"&&(l=String(l)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(l))throw new TypeError("Invalid character in header field name");return l.toLowerCase()}function M(l){return typeof l!="string"&&(l=String(l)),l}function C(l){var d={next:function(){var y=l.shift();return{done:y===void 0,value:y}}};return f.iterable&&(d[Symbol.iterator]=function(){return d}),d}function O(l){this.map={},l instanceof O?l.forEach(function(d,y){this.append(y,d)},this):Array.isArray(l)?l.forEach(function(d){this.append(d[0],d[1])},this):l&&Object.getOwnPropertyNames(l).forEach(function(d){this.append(d,l[d])},this)}O.prototype.append=function(l,d){l=w(l),d=M(d);var y=this.map[l];this.map[l]=y?y+", "+d:d},O.prototype.delete=function(l){delete this.map[w(l)]},O.prototype.get=function(l){return l=w(l),this.has(l)?this.map[l]:null},O.prototype.has=function(l){return this.map.hasOwnProperty(w(l))},O.prototype.set=function(l,d){this.map[w(l)]=M(d)},O.prototype.forEach=function(l,d){for(var y in this.map)this.map.hasOwnProperty(y)&&l.call(d,this.map[y],y,this)},O.prototype.keys=function(){var l=[];return this.forEach(function(d,y){l.push(y)}),C(l)},O.prototype.values=function(){var l=[];return this.forEach(function(d){l.push(d)}),C(l)},O.prototype.entries=function(){var l=[];return this.forEach(function(d,y){l.push([y,d])}),C(l)},f.iterable&&(O.prototype[Symbol.iterator]=O.prototype.entries);function $(l){if(l.bodyUsed)return Promise.reject(new TypeError("Already read"));l.bodyUsed=!0}function j(l){return new Promise(function(d,y){l.onload=function(){d(l.result)},l.onerror=function(){y(l.error)}})}function H(l){var d=new FileReader,y=j(d);return d.readAsArrayBuffer(l),y}function F(l){var d=new FileReader,y=j(d);return d.readAsText(l),y}function G(l){for(var d=new Uint8Array(l),y=new Array(d.length),P=0;P-1?d:l}function U(l,d){d=d||{};var y=d.body;if(l instanceof U){if(l.bodyUsed)throw new TypeError("Already read");this.url=l.url,this.credentials=l.credentials,d.headers||(this.headers=new O(l.headers)),this.method=l.method,this.mode=l.mode,this.signal=l.signal,!y&&l._bodyInit!=null&&(y=l._bodyInit,l.bodyUsed=!0)}else this.url=String(l);if(this.credentials=d.credentials||this.credentials||"same-origin",(d.headers||!this.headers)&&(this.headers=new O(d.headers)),this.method=_(d.method||this.method||"GET"),this.mode=d.mode||this.mode||null,this.signal=d.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&y)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(y)}U.prototype.clone=function(){return new U(this,{body:this._bodyInit})};function ee(l){var d=new FormData;return l.trim().split("&").forEach(function(y){if(y){var P=y.split("="),D=P.shift().replace(/\+/g," "),S=P.join("=").replace(/\+/g," ");d.append(decodeURIComponent(D),decodeURIComponent(S))}}),d}function oe(l){var d=new O,y=l.replace(/\r?\n[\t ]+/g," ");return y.split(/\r?\n/).forEach(function(P){var D=P.split(":"),S=D.shift().trim();if(S){var v=D.join(":").trim();d.append(S,v)}}),d}z.call(U.prototype);function L(l,d){d||(d={}),this.type="default",this.status=d.status===void 0?200:d.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in d?d.statusText:"OK",this.headers=new O(d.headers),this.url=d.url||"",this._initBody(l)}z.call(L.prototype),L.prototype.clone=function(){return new L(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new O(this.headers),url:this.url})},L.error=function(){var l=new L(null,{status:0,statusText:""});return l.type="error",l};var b=[301,302,303,307,308];L.redirect=function(l,d){if(b.indexOf(d)===-1)throw new RangeError("Invalid status code");return new L(null,{status:d,headers:{location:l}})},a.DOMException=s.DOMException;try{new a.DOMException}catch{a.DOMException=function(d,y){this.message=d,this.name=y;var P=Error(d);this.stack=P.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function m(l,d){return new Promise(function(y,P){var D=new U(l,d);if(D.signal&&D.signal.aborted)return P(new a.DOMException("Aborted","AbortError"));var S=new XMLHttpRequest;function v(){S.abort()}S.onload=function(){var A={status:S.status,statusText:S.statusText,headers:oe(S.getAllResponseHeaders()||"")};A.url="responseURL"in S?S.responseURL:A.headers.get("X-Request-URL");var x="response"in S?S.response:S.responseText;y(new L(x,A))},S.onerror=function(){P(new TypeError("Network request failed"))},S.ontimeout=function(){P(new TypeError("Network request failed"))},S.onabort=function(){P(new a.DOMException("Aborted","AbortError"))},S.open(D.method,D.url,!0),D.credentials==="include"?S.withCredentials=!0:D.credentials==="omit"&&(S.withCredentials=!1),"responseType"in S&&f.blob&&(S.responseType="blob"),D.headers.forEach(function(A,x){S.setRequestHeader(x,A)}),D.signal&&(D.signal.addEventListener("abort",v),S.onreadystatechange=function(){S.readyState===4&&D.signal.removeEventListener("abort",v)}),S.send(typeof D._bodyInit>"u"?null:D._bodyInit)})}return m.polyfill=!0,s.fetch||(s.fetch=m,s.Headers=O,s.Request=U,s.Response=L),a.Headers=O,a.Request=U,a.Response=L,a.fetch=m,Object.defineProperty(a,"__esModule",{value:!0}),a})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,r.exports=e})(O0,O0.exports);var Q2=K6(O0.exports),rD=Object.defineProperty,iD=Object.defineProperties,nD=Object.getOwnPropertyDescriptors,Z2=Object.getOwnPropertySymbols,sD=Object.prototype.hasOwnProperty,oD=Object.prototype.propertyIsEnumerable,X2=(r,e,t)=>e in r?rD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,e3=(r,e)=>{for(var t in e||(e={}))sD.call(e,t)&&X2(r,t,e[t]);if(Z2)for(var t of Z2(e))oD.call(e,t)&&X2(r,t,e[t]);return r},t3=(r,e)=>iD(r,nD(e));const aD={Accept:"application/json","Content-Type":"application/json"},cD="POST",r3={headers:aD,method:cD},i3=10;class Cn{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new zr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Jb(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}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(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const t=bs(e),i=await(await Q2(this.url,t3(e3({},r3),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!Jb(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=bs({id:1,jsonrpc:"2.0",method:"test",params:[]});await Q2(e,t3(e3({},r3),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?Oo(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),n=i.message||i.toString(),s=nh(e,n);this.events.emit("payload",s)}parseError(e,t=this.url){return jb(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>i3&&this.events.setMaxListeners(i3)}}const n3="error",fD="wss://relay.walletconnect.org",lD="wc",hD="universal_provider",s3=`${lD}@2:${hD}:`,o3="https://rpc.walletconnect.org/v1/",Ka="generic",uD=`${o3}bundler`,an={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var dD=Object.defineProperty,pD=Object.defineProperties,gD=Object.getOwnPropertyDescriptors,a3=Object.getOwnPropertySymbols,vD=Object.prototype.hasOwnProperty,mD=Object.prototype.propertyIsEnumerable,c3=(r,e,t)=>e in r?dD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,lh=(r,e)=>{for(var t in e||(e={}))vD.call(e,t)&&c3(r,t,e[t]);if(a3)for(var t of a3(e))mD.call(e,t)&&c3(r,t,e[t]);return r},bD=(r,e)=>pD(r,gD(e));function Ui(r,e,t){var i;const n=Ua(r);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${o3}?chainId=${n.namespace}:${n.reference}&projectId=${t}`}function ko(r){return r.includes(":")?r.split(":")[1]:r}function f3(r){return r.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function wD(r,e){const t=Object.keys(e.namespaces).filter(n=>n.includes(r));if(!t.length)return[];const i=[];return t.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function R0(r={},e={}){const t=l3(r),i=l3(e);return D0.exports.merge(t,i)}function l3(r){var e,t,i,n;const s={};if(!tf(r))return s;for(const[a,f]of Object.entries(r)){const h=r0(a)?[a]:f.chains,u=f.methods||[],g=f.events||[],w=f.rpcMap||{},M=ef(a);s[M]=bD(lh(lh({},s[M]),f),{chains:zl(h,(e=s[M])==null?void 0:e.chains),methods:zl(u,(t=s[M])==null?void 0:t.methods),events:zl(g,(i=s[M])==null?void 0:i.events),rpcMap:lh(lh({},w),(n=s[M])==null?void 0:n.rpcMap)})}return s}function yD(r){return r.includes(":")?r.split(":")[2]:r}function h3(r){const e={};for(const[t,i]of Object.entries(r)){const n=i.methods||[],s=i.events||[],a=i.accounts||[],f=r0(t)?[t]:i.chains?i.chains:f3(i.accounts);e[t]={chains:f,methods:n,events:s,accounts:a}}return e}function T0(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const u3={},zt=r=>u3[r],$0=(r,e)=>{u3[r]=e};class _D{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=ko(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new nn(new Cn(i,zt("disableProviderPing")))}}var xD=Object.defineProperty,AD=Object.defineProperties,ED=Object.getOwnPropertyDescriptors,d3=Object.getOwnPropertySymbols,SD=Object.prototype.hasOwnProperty,ID=Object.prototype.propertyIsEnumerable,p3=(r,e,t)=>e in r?xD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g3=(r,e)=>{for(var t in e||(e={}))SD.call(e,t)&&p3(r,t,e[t]);if(d3)for(var t of d3(e))ID.call(e,t)&&p3(r,t,e[t]);return r},v3=(r,e)=>AD(r,ED(e));class MD{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||Ui(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new nn(new Cn(i,zt("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=parseInt(ko(t));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let n=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,n;const s=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!s)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const a=this.client.session.get(e.topic),f=((n=a?.sessionProperties)==null?void 0:n.capabilities)||{};if(f!=null&&f[s])return f?.[s];const h=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:v3(g3({},a.sessionProperties||{}),{capabilities:v3(g3({},f||{}),{[s]:h})})})}catch(u){console.warn("Failed to update session with capabilities",u)}return h}async getCallStatus(e){var t,i;const n=this.client.session.get(e.topic),s=(t=n.sessionProperties)==null?void 0:t.bundler_name;if(s){const f=this.getBundlerUrl(e.chainId,s);try{return await this.getUserOperationReceipt(f,e)}catch(h){console.warn("Failed to fetch call status from bundler",h,f)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(f){console.warn("Failed to fetch call status from custom bundler",f,a)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Js("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,t){return`${uD}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}class CD{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=ko(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new nn(new Cn(i,zt("disableProviderPing")))}}class PD{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=ko(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new nn(new Cn(i,zt("disableProviderPing")))}}class DD{constructor(e){this.name="algorand",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||Ui(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new nn(new Cn(i,zt("disableProviderPing")))}}class OD{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),n=ko(t);e[n]=this.createHttpProvider(n,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new nn(new Cn(i,zt("disableProviderPing")))}}class RD{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=ko(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new nn(new Cn(i,zt("disableProviderPing")))}}class TD{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const n=ko(t);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new nn(new Cn(i,zt("disableProviderPing")))}}class $D{constructor(e){this.name="near",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ui(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace);return typeof i>"u"?void 0:new nn(new Cn(i,zt("disableProviderPing")))}}class ND{constructor(e){this.name="tezos",this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ui(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace);return typeof i>"u"?void 0:new nn(new Cn(i))}}class LD{constructor(e){this.name=Ka,this.namespace=e.namespace,this.events=zt("events"),this.client=zt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(an.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(n=>{const s=Ua(n);i[`${s.namespace}:${s.reference}`]=this.createHttpProvider(n)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ui(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new nn(new Cn(i,zt("disableProviderPing")))}}var BD=Object.defineProperty,FD=Object.defineProperties,UD=Object.getOwnPropertyDescriptors,m3=Object.getOwnPropertySymbols,qD=Object.prototype.hasOwnProperty,zD=Object.prototype.propertyIsEnumerable,b3=(r,e,t)=>e in r?BD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,hh=(r,e)=>{for(var t in e||(e={}))qD.call(e,t)&&b3(r,t,e[t]);if(m3)for(var t of m3(e))zD.call(e,t)&&b3(r,t,e[t]);return r},N0=(r,e)=>FD(r,UD(e));class L0{constructor(e){this.events=new zr.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Zn(rh({level:e?.logger||n3})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new L0(e);return await t.initialize(),t}async request(e,t,i){const[n,s]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:hh({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,n){const s=new Date().getTime();this.request(e,i,n).then(a=>t(null,ih(s,a))).catch(a=>t(a,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Gt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const a=h3(this.session.namespaces);this.namespaces=R0(this.namespaces,a),this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let t=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(t>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:i,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});i&&(this.uri=i,this.events.emit("display_uri",i)),await n().then(s=>{this.session=s;const a=h3(s.namespaces);this.namespaces=R0(this.namespaces,a),this.persist("namespaces",this.namespaces)}).catch(s=>{if(s.message!==G2)throw s;t++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,n]=this.validateChain(e),s=this.getProvider(i);s.name===Ka?s.setDefaultChain(`${i}:${n}`,t):s.setDefaultChain(n,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(_s(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await P0.init({core:this.providerOpts.core,logger:this.providerOpts.logger||n3,relayUrl:this.providerOpts.relayUrl||fD,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>ef(t)))];$0("client",this.client),$0("events",this.events),$0("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=wD(t,this.session),n=f3(i),s=R0(this.namespaces,this.optionalNamespaces),a=N0(hh({},s[t]),{accounts:i,chains:n});switch(t){case"eip155":this.rpcProviders[t]=new MD({namespace:a});break;case"algorand":this.rpcProviders[t]=new DD({namespace:a});break;case"solana":this.rpcProviders[t]=new CD({namespace:a});break;case"cosmos":this.rpcProviders[t]=new PD({namespace:a});break;case"polkadot":this.rpcProviders[t]=new _D({namespace:a});break;case"cip34":this.rpcProviders[t]=new OD({namespace:a});break;case"elrond":this.rpcProviders[t]=new RD({namespace:a});break;case"multiversx":this.rpcProviders[t]=new TD({namespace:a});break;case"near":this.rpcProviders[t]=new $D({namespace:a});break;case"tezos":this.rpcProviders[t]=new ND({namespace:a});break;default:this.rpcProviders[Ka]?this.rpcProviders[Ka].updateNamespace(a):this.rpcProviders[Ka]=new LD({namespace:a})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t}=e,{event:i}=t;if(i.name==="accountsChanged"){const n=i.data;n&&_s(n)&&this.events.emit("accountsChanged",n.map(yD))}else if(i.name==="chainChanged"){const n=t.chainId,s=t.event.data,a=ef(n),f=T0(n)!==T0(s)?`${a}:${T0(s)}`:n;this.onChainChanged(f)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i;const{namespaces:n}=t,s=(i=this.client)==null?void 0:i.session.get(e);this.session=N0(hh({},s),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",N0(hh({},Gt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(an.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Ka]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:n}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=n,this.persist("namespaces",t),this.persist("optionalNamespaces",i)}validateChain(e){const[t,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(a=>ef(a)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const n=ef(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);n&&(t||this.getProvider(i).setDefaultChain(n),this.namespaces[i]?this.namespaces[i].defaultChain=n:this.namespaces[`${i}:${n}`]?this.namespaces[`${i}:${n}`].defaultChain=n:this.namespaces[`${i}:${n}`]={defaultChain:n},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",n))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,t){this.client.core.storage.setItem(`${s3}/${e}`,t)}async getFromStore(e){return await this.client.core.storage.getItem(`${s3}/${e}`)}}const HD=L0,kD="wc",jD="ethereum_provider",WD=`${kD}@2:${jD}:`,KD="https://rpc.walletconnect.org/v1/",uh=["eth_sendTransaction","personal_sign"],w3=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],dh=["chainChanged","accountsChanged"],y3=["chainChanged","accountsChanged","message","disconnect","connect"];var VD=Object.defineProperty,GD=Object.defineProperties,YD=Object.getOwnPropertyDescriptors,_3=Object.getOwnPropertySymbols,JD=Object.prototype.hasOwnProperty,QD=Object.prototype.propertyIsEnumerable,x3=(r,e,t)=>e in r?VD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Va=(r,e)=>{for(var t in e||(e={}))JD.call(e,t)&&x3(r,t,e[t]);if(_3)for(var t of _3(e))QD.call(e,t)&&x3(r,t,e[t]);return r},B0=(r,e)=>GD(r,YD(e));function ph(r){return Number(r[0].split(":")[1])}function gh(r){return`0x${r.toString(16)}`}function ZD(r){const{chains:e,optionalChains:t,methods:i,optionalMethods:n,events:s,optionalEvents:a,rpcMap:f}=r;if(!_s(e))throw new Error("Invalid chains");const h={chains:e,methods:i||uh,events:s||dh,rpcMap:Va({},e.length?{[ph(e)]:f[ph(e)]}:{})},u=s?.filter(C=>!dh.includes(C)),g=i?.filter(C=>!uh.includes(C));if(!t&&!a&&!n&&!(u!=null&&u.length)&&!(g!=null&&g.length))return{required:e.length?h:void 0};const w=u?.length&&g?.length||!t,M={chains:[...new Set(w?h.chains.concat(t||[]):t)],methods:[...new Set(h.methods.concat(n!=null&&n.length?n:w3))],events:[...new Set(h.events.concat(a!=null&&a.length?a:y3))],rpcMap:f};return{required:e.length?h:void 0,optional:t.length?M:void 0}}class vh{constructor(){this.events=new zr.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=WD,this.on=(e,t)=>(this.events.on(e,t),this),this.once=(e,t)=>(this.events.once(e,t),this),this.removeListener=(e,t)=>(this.events.removeListener(e,t),this),this.off=(e,t)=>(this.events.off(e,t),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const t=new vh;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:i}=ZD(this.rpc);try{const n=await new Promise(async(a,f)=>{var h;this.rpc.showQrModal&&((h=this.modal)==null||h.subscribeModal(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),f(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(B0(Va({namespaces:Va({},t&&{[this.namespace]:t})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic})).then(u=>{a(u)}).catch(u=>{f(new Error(u.message))})});if(!n)return;const s=Bm(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:gh(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async authenticate(e,t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(s,a)=>{var f;this.rpc.showQrModal&&((f=this.modal)==null||f.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(B0(Va({},e),{chains:this.rpc.chains}),t).then(h=>{s(h)}).catch(h=>{a(new Error(h.message))})}),n=i.session;if(n){const s=Bm(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:gh(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:i}=t;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",gh(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",B0(Va({},Gt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var t,i;this.rpc.showQrModal&&((t=this.modal)==null||t.closeModal(),(i=this.modal)==null||i.openModal({uri:e})),this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",gh(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,n]=e.split(":");return{chainId:`${t}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;const n=(t=e?.chains)!=null?t:[],s=(i=e?.optionalChains)!=null?i:[],a=n.concat(s);if(!a.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const f=n.length?e?.methods||uh:[],h=n.length?e?.events||dh:[],u=e?.optionalMethods||[],g=e?.optionalEvents||[],w=e?.rpcMap||this.buildRpcMap(a,e.projectId),M=e?.qrModalOptions||void 0;return{chains:n?.map(C=>this.formatChainId(C)),optionalChains:s.map(C=>this.formatChainId(C)),methods:f,events:h,optionalMethods:u,optionalEvents:g,rpcMap:w,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:M,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,t)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?ph(this.rpc.chains):ph(this.rpc.optionalChains),this.signer=await HD.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const{WalletConnectModal:i}=await Promise.resolve().then(function(){return _O});t=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(t)try{this.modal=new t(Va({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:n}=e;t&&_s(t)&&(this.rpc.chains=t.map(s=>this.formatChainId(s)),t.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)})),i&&_s(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${KD}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const XD=vh,eO=Symbol(),A3=Object.getPrototypeOf,F0=new WeakMap,tO=r=>r&&(F0.has(r)?F0.get(r):A3(r)===Object.prototype||A3(r)===Array.prototype),rO=r=>tO(r)&&r[eO]||null,E3=(r,e=!0)=>{F0.set(r,e)},U0=r=>typeof r=="object"&&r!==null,Qs=new WeakMap,mh=new WeakSet,iO=(r=Object.is,e=(u,g)=>new Proxy(u,g),t=u=>U0(u)&&!mh.has(u)&&(Array.isArray(u)||!(Symbol.iterator in u))&&!(u instanceof WeakMap)&&!(u instanceof WeakSet)&&!(u instanceof Error)&&!(u instanceof Number)&&!(u instanceof Date)&&!(u instanceof String)&&!(u instanceof RegExp)&&!(u instanceof ArrayBuffer),i=u=>{switch(u.status){case"fulfilled":return u.value;case"rejected":throw u.reason;default:throw u}},n=new WeakMap,s=(u,g,w=i)=>{const M=n.get(u);if(M?.[0]===g)return M[1];const C=Array.isArray(u)?[]:Object.create(Object.getPrototypeOf(u));return E3(C,!0),n.set(u,[g,C]),Reflect.ownKeys(u).forEach(O=>{if(Object.getOwnPropertyDescriptor(C,O))return;const $=Reflect.get(u,O),j={value:$,enumerable:!0,configurable:!0};if(mh.has($))E3($,!1);else if($ instanceof Promise)delete j.value,j.get=()=>w($);else if(Qs.has($)){const[H,F]=Qs.get($);j.value=s(H,F(),w)}Object.defineProperty(C,O,j)}),Object.preventExtensions(C)},a=new WeakMap,f=[1,1],h=u=>{if(!U0(u))throw new Error("object required");const g=a.get(u);if(g)return g;let w=f[0];const M=new Set,C=(ee,oe=++f[0])=>{w!==oe&&(w=oe,M.forEach(L=>L(ee,oe)))};let O=f[1];const $=(ee=++f[1])=>(O!==ee&&!M.size&&(O=ee,H.forEach(([oe])=>{const L=oe[1](ee);L>w&&(w=L)})),w),j=ee=>(oe,L)=>{const b=[...oe];b[1]=[ee,...b[1]],C(b,L)},H=new Map,F=(ee,oe)=>{if(H.has(ee))throw new Error("prop listener already exists");if(M.size){const L=oe[3](j(ee));H.set(ee,[oe,L])}else H.set(ee,[oe])},G=ee=>{var oe;const L=H.get(ee);L&&(H.delete(ee),(oe=L[1])==null||oe.call(L))},B=ee=>(M.add(ee),M.size===1&&H.forEach(([L,b],m)=>{if(b)throw new Error("remove already exists");const l=L[3](j(m));H.set(m,[L,l])}),()=>{M.delete(ee),M.size===0&&H.forEach(([L,b],m)=>{b&&(b(),H.set(m,[L]))})}),z=Array.isArray(u)?[]:Object.create(Object.getPrototypeOf(u)),_=e(z,{deleteProperty(ee,oe){const L=Reflect.get(ee,oe);G(oe);const b=Reflect.deleteProperty(ee,oe);return b&&C(["delete",[oe],L]),b},set(ee,oe,L,b){const m=Reflect.has(ee,oe),l=Reflect.get(ee,oe,b);if(m&&(r(l,L)||a.has(L)&&r(l,a.get(L))))return!0;G(oe),U0(L)&&(L=rO(L)||L);let d=L;if(L instanceof Promise)L.then(y=>{L.status="fulfilled",L.value=y,C(["resolve",[oe],y])}).catch(y=>{L.status="rejected",L.reason=y,C(["reject",[oe],y])});else{!Qs.has(L)&&t(L)&&(d=h(L));const y=!mh.has(d)&&Qs.get(d);y&&F(oe,y)}return Reflect.set(ee,oe,d,b),C(["set",[oe],L,l]),!0}});a.set(u,_);const U=[z,$,s,B];return Qs.set(_,U),Reflect.ownKeys(u).forEach(ee=>{const oe=Object.getOwnPropertyDescriptor(u,ee);"value"in oe&&(_[ee]=u[ee],delete oe.value,delete oe.writable),Object.defineProperty(z,ee,oe)}),_})=>[h,Qs,mh,r,e,t,i,n,s,a,f],[nO]=iO();function Zs(r={}){return nO(r)}function jo(r,e,t){const i=Qs.get(r);i||console.warn("Please use proxy object");let n;const s=[],a=i[3];let f=!1;const u=a(g=>{if(s.push(g),t){e(s.splice(0));return}n||(n=Promise.resolve().then(()=>{n=void 0,f&&e(s.splice(0))}))});return f=!0,()=>{f=!1,u()}}function sO(r,e){const t=Qs.get(r);t||console.warn("Please use proxy object");const[i,n,s]=t;return s(i,n(),e)}const Fr=Zs({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),lr={state:Fr,subscribe(r){return jo(Fr,()=>r(Fr))},push(r,e){r!==Fr.view&&(Fr.view=r,e&&(Fr.data=e),Fr.history.push(r))},reset(r){Fr.view=r,Fr.history=[r]},replace(r){Fr.history.length>1&&(Fr.history[Fr.history.length-1]=r,Fr.view=r)},goBack(){if(Fr.history.length>1){Fr.history.pop();const[r]=Fr.history.slice(-1);Fr.view=r}},setData(r){Fr.data=r}},je={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return je.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const r=navigator.userAgent.toLowerCase();return je.isMobile()&&(r.includes("iphone")||r.includes("ipad"))},isHttpUrl(r){return r.startsWith("http://")||r.startsWith("https://")},isArray(r){return Array.isArray(r)&&r.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(r,e,t){if(je.isHttpUrl(r))return this.formatUniversalUrl(r,e,t);let i=r;i.includes("://")||(i=r.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,t);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},formatUniversalUrl(r,e,t){if(!je.isHttpUrl(r))return this.formatNativeUrl(r,e,t);let i=r;if(i.startsWith("https://t.me")){const s=Buffer.from(e).toString("base64").replace(/[=]/g,"");i.endsWith("/")&&(i=i.slice(0,-1)),this.setWalletConnectDeepLink(i,t);const a=new URL(i);return a.searchParams.set("startapp",s),a.toString()}i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,t);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},async wait(r){return new Promise(e=>{setTimeout(e,r)})},openHref(r,e){const t=this.isTelegram()?"_blank":e;window.open(r,t,"noreferrer noopener")},setWalletConnectDeepLink(r,e){try{localStorage.setItem(je.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:r,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(r){try{const[e]=r.split("?");localStorage.setItem(je.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(je.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(je.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var r;const e=(r=lr.state.data)==null?void 0:r.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},oO=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),Qr=Zs({enabled:oO,userSessionId:"",events:[],connectedWalletId:void 0}),S3={state:Qr,subscribe(r){return jo(Qr.events,()=>r(sO(Qr.events[Qr.events.length-1])))},initialize(){Qr.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(Qr.userSessionId=crypto.randomUUID())},setConnectedWalletId(r){Qr.connectedWalletId=r},click(r){if(Qr.enabled){const e={type:"CLICK",name:r.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:r};Qr.events.push(e)}},track(r){if(Qr.enabled){const e={type:"TRACK",name:r.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:r};Qr.events.push(e)}},view(r){if(Qr.enabled){const e={type:"VIEW",name:r.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:r};Qr.events.push(e)}}},ns=Zs({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),yr={state:ns,subscribe(r){return jo(ns,()=>r(ns))},setChains(r){ns.chains=r},setWalletConnectUri(r){ns.walletConnectUri=r},setIsCustomDesktop(r){ns.isCustomDesktop=r},setIsCustomMobile(r){ns.isCustomMobile=r},setIsDataLoaded(r){ns.isDataLoaded=r},setIsUiLoaded(r){ns.isUiLoaded=r},setIsAuth(r){ns.isAuth=r}},bh=Zs({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),qi={state:bh,subscribe(r){return jo(bh,()=>r(bh))},setConfig(r){var e,t;S3.initialize(),yr.setChains(r.chains),yr.setIsAuth(!!r.enableAuthMode),yr.setIsCustomMobile(!!((e=r.mobileWallets)!=null&&e.length)),yr.setIsCustomDesktop(!!((t=r.desktopWallets)!=null&&t.length)),je.setModalVersionInStorage(),Object.assign(bh,r)}};var aO=Object.defineProperty,I3=Object.getOwnPropertySymbols,cO=Object.prototype.hasOwnProperty,fO=Object.prototype.propertyIsEnumerable,M3=(r,e,t)=>e in r?aO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,lO=(r,e)=>{for(var t in e||(e={}))cO.call(e,t)&&M3(r,t,e[t]);if(I3)for(var t of I3(e))fO.call(e,t)&&M3(r,t,e[t]);return r};const q0="https://explorer-api.walletconnect.com",z0="wcm",H0="js-2.7.0";async function wh(r,e){const t=lO({sdkType:z0,sdkVersion:H0},e),i=new URL(r,q0);return i.searchParams.append("projectId",qi.state.projectId),Object.entries(t).forEach(([s,a])=>{a&&i.searchParams.append(s,String(a))}),(await fetch(i)).json()}const Wo={async getDesktopListings(r){return wh("/w3m/v1/getDesktopListings",r)},async getMobileListings(r){return wh("/w3m/v1/getMobileListings",r)},async getInjectedListings(r){return wh("/w3m/v1/getInjectedListings",r)},async getAllListings(r){return wh("/w3m/v1/getAllListings",r)},getWalletImageUrl(r){return`${q0}/w3m/v1/getWalletImage/${r}?projectId=${qi.state.projectId}&sdkType=${z0}&sdkVersion=${H0}`},getAssetImageUrl(r){return`${q0}/w3m/v1/getAssetImage/${r}?projectId=${qi.state.projectId}&sdkType=${z0}&sdkVersion=${H0}`}};var hO=Object.defineProperty,C3=Object.getOwnPropertySymbols,uO=Object.prototype.hasOwnProperty,dO=Object.prototype.propertyIsEnumerable,P3=(r,e,t)=>e in r?hO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pO=(r,e)=>{for(var t in e||(e={}))uO.call(e,t)&&P3(r,t,e[t]);if(C3)for(var t of C3(e))dO.call(e,t)&&P3(r,t,e[t]);return r};const D3=je.isMobile(),ss=Zs({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),_i={state:ss,async getRecomendedWallets(){const{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:e}=qi.state;if(r==="NONE"||e==="ALL"&&!r)return ss.recomendedWallets;if(je.isArray(r)){const i={recommendedIds:r.join(",")},{listings:n}=await Wo.getAllListings(i),s=Object.values(n);s.sort((a,f)=>{const h=r.indexOf(a.id),u=r.indexOf(f.id);return h-u}),ss.recomendedWallets=s}else{const{chains:t,isAuth:i}=yr.state,n=t?.join(","),s=je.isArray(e),a={page:1,sdks:i?"auth_v1":void 0,entries:je.RECOMMENDED_WALLET_AMOUNT,chains:n,version:2,excludedIds:s?e.join(","):void 0},{listings:f}=D3?await Wo.getMobileListings(a):await Wo.getDesktopListings(a);ss.recomendedWallets=Object.values(f)}return ss.recomendedWallets},async getWallets(r){const e=pO({},r),{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:i}=qi.state,{recomendedWallets:n}=ss;if(i==="ALL")return ss.wallets;n.length?e.excludedIds=n.map(w=>w.id).join(","):je.isArray(t)&&(e.excludedIds=t.join(",")),je.isArray(i)&&(e.excludedIds=[e.excludedIds,i].filter(Boolean).join(",")),yr.state.isAuth&&(e.sdks="auth_v1");const{page:s,search:a}=r,{listings:f,total:h}=D3?await Wo.getMobileListings(e):await Wo.getDesktopListings(e),u=Object.values(f),g=a?"search":"wallets";return ss[g]={listings:[...ss[g].listings,...u],total:h,page:s??1},{listings:u,total:h}},getWalletImageUrl(r){return Wo.getWalletImageUrl(r)},getAssetImageUrl(r){return Wo.getAssetImageUrl(r)},resetSearch(){ss.search={listings:[],total:0,page:1}}},Ga=Zs({open:!1}),Ko={state:Ga,subscribe(r){return jo(Ga,()=>r(Ga))},async open(r){return new Promise(e=>{const{isUiLoaded:t,isDataLoaded:i}=yr.state;if(je.removeWalletConnectDeepLink(),yr.setWalletConnectUri(r?.uri),yr.setChains(r?.chains),lr.reset("ConnectWallet"),t&&i)Ga.open=!0,e();else{const n=setInterval(()=>{const s=yr.state;s.isUiLoaded&&s.isDataLoaded&&(clearInterval(n),Ga.open=!0,e())},200)}})},close(){Ga.open=!1}};var gO=Object.defineProperty,O3=Object.getOwnPropertySymbols,vO=Object.prototype.hasOwnProperty,mO=Object.prototype.propertyIsEnumerable,R3=(r,e,t)=>e in r?gO(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,bO=(r,e)=>{for(var t in e||(e={}))vO.call(e,t)&&R3(r,t,e[t]);if(O3)for(var t of O3(e))mO.call(e,t)&&R3(r,t,e[t]);return r};function wO(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const vf=Zs({themeMode:wO()?"dark":"light"}),Xs={state:vf,subscribe(r){return jo(vf,()=>r(vf))},setThemeConfig(r){const{themeMode:e,themeVariables:t}=r;e&&(vf.themeMode=e),t&&(vf.themeVariables=bO({},t))}},Vo=Zs({open:!1,message:"",variant:"success"}),eo={state:Vo,subscribe(r){return jo(Vo,()=>r(Vo))},openToast(r,e){Vo.open=!0,Vo.message=r,Vo.variant=e},closeToast(){Vo.open=!1}};class yO{constructor(e){this.openModal=Ko.open,this.closeModal=Ko.close,this.subscribeModal=Ko.subscribe,this.setTheme=Xs.setThemeConfig,Xs.setThemeConfig(e),qi.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return DN});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),yr.setIsUiLoaded(!0)}}}var _O=Object.freeze({__proto__:null,WalletConnectModal:yO});/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */const mh=window,H0=mh.ShadowRoot&&(mh.ShadyCSS===void 0||mh.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,k0=Symbol(),C3=new WeakMap;class P3{constructor(e,t,i){if(this._$cssResult$=!0,i!==k0)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(H0&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=C3.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&C3.set(t,e))}return e}toString(){return this.cssText}}const uO=r=>new P3(typeof r=="string"?r:r+"",void 0,k0),jt=(r,...e)=>{const t=r.length===1?r[0]:e.reduce((i,n,s)=>i+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+r[s+1],r[0]);return new P3(t,r,k0)},dO=(r,e)=>{H0?r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet):e.forEach(t=>{const i=document.createElement("style"),n=mh.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=t.cssText,r.appendChild(i)})},D3=H0?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return uO(t)})(r):r;/** ++ */const yh=window,k0=yh.ShadowRoot&&(yh.ShadyCSS===void 0||yh.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,j0=Symbol(),T3=new WeakMap;class $3{constructor(e,t,i){if(this._$cssResult$=!0,i!==j0)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(k0&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=T3.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&T3.set(t,e))}return e}toString(){return this.cssText}}const xO=r=>new $3(typeof r=="string"?r:r+"",void 0,j0),jt=(r,...e)=>{const t=r.length===1?r[0]:e.reduce((i,n,s)=>i+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+r[s+1],r[0]);return new $3(t,r,j0)},AO=(r,e)=>{k0?r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet):e.forEach(t=>{const i=document.createElement("style"),n=yh.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=t.cssText,r.appendChild(i)})},N3=k0?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return xO(t)})(r):r;/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */var j0;const bh=window,O3=bh.trustedTypes,pO=O3?O3.emptyScript:"",R3=bh.reactiveElementPolyfillSupport,W0={toAttribute(r,e){switch(e){case Boolean:r=r?pO:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},T3=(r,e)=>e!==r&&(e==e||r==r),K0={attribute:!0,type:String,converter:W0,reflect:!1,hasChanged:T3},V0="finalized";class Ga extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this._$Eu()}static addInitializer(e){var t;this.finalize(),((t=this.h)!==null&&t!==void 0?t:this.h=[]).push(e)}static get observedAttributes(){this.finalize();const e=[];return this.elementProperties.forEach((t,i)=>{const n=this._$Ep(i,t);n!==void 0&&(this._$Ev.set(n,i),e.push(n))}),e}static createProperty(e,t=K0){if(t.state&&(t.attribute=!1),this.finalize(),this.elementProperties.set(e,t),!t.noAccessor&&!this.prototype.hasOwnProperty(e)){const i=typeof e=="symbol"?Symbol():"__"+e,n=this.getPropertyDescriptor(e,i,t);n!==void 0&&Object.defineProperty(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){return{get(){return this[t]},set(n){const s=this[e];this[t]=n,this.requestUpdate(e,s,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)||K0}static finalize(){if(this.hasOwnProperty(V0))return!1;this[V0]=!0;const e=Object.getPrototypeOf(this);if(e.finalize(),e.h!==void 0&&(this.h=[...e.h]),this.elementProperties=new Map(e.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const t=this.properties,i=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const n of i)this.createProperty(n,t[n])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const n of i)t.unshift(D3(n))}else e!==void 0&&t.push(D3(e));return t}static _$Ep(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}_$Eu(){var e;this._$E_=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$Eg(),this.requestUpdate(),(e=this.constructor.h)===null||e===void 0||e.forEach(t=>t(this))}addController(e){var t,i;((t=this._$ES)!==null&&t!==void 0?t:this._$ES=[]).push(e),this.renderRoot!==void 0&&this.isConnected&&((i=e.hostConnected)===null||i===void 0||i.call(e))}removeController(e){var t;(t=this._$ES)===null||t===void 0||t.splice(this._$ES.indexOf(e)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach((e,t)=>{this.hasOwnProperty(t)&&(this._$Ei.set(t,this[t]),delete this[t])})}createRenderRoot(){var e;const t=(e=this.shadowRoot)!==null&&e!==void 0?e:this.attachShadow(this.constructor.shadowRootOptions);return dO(t,this.constructor.elementStyles),t}connectedCallback(){var e;this.renderRoot===void 0&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$ES)===null||e===void 0||e.forEach(t=>{var i;return(i=t.hostConnected)===null||i===void 0?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$ES)===null||e===void 0||e.forEach(t=>{var i;return(i=t.hostDisconnected)===null||i===void 0?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$EO(e,t,i=K0){var n;const s=this.constructor._$Ep(e,i);if(s!==void 0&&i.reflect===!0){const a=(((n=i.converter)===null||n===void 0?void 0:n.toAttribute)!==void 0?i.converter:W0).toAttribute(t,i.type);this._$El=e,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$El=null}}_$AK(e,t){var i;const n=this.constructor,s=n._$Ev.get(e);if(s!==void 0&&this._$El!==s){const a=n.getPropertyOptions(s),f=typeof a.converter=="function"?{fromAttribute:a.converter}:((i=a.converter)===null||i===void 0?void 0:i.fromAttribute)!==void 0?a.converter:W0;this._$El=s,this[s]=f.fromAttribute(t,a.type),this._$El=null}}requestUpdate(e,t,i){let n=!0;e!==void 0&&(((i=i||this.constructor.getPropertyOptions(e)).hasChanged||T3)(this[e],t)?(this._$AL.has(e)||this._$AL.set(e,t),i.reflect===!0&&this._$El!==e&&(this._$EC===void 0&&(this._$EC=new Map),this._$EC.set(e,i))):n=!1),!this.isUpdatePending&&n&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var e;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach((n,s)=>this[s]=n),this._$Ei=void 0);let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),(e=this._$ES)===null||e===void 0||e.forEach(n=>{var s;return(s=n.hostUpdate)===null||s===void 0?void 0:s.call(n)}),this.update(i)):this._$Ek()}catch(n){throw t=!1,this._$Ek(),n}t&&this._$AE(i)}willUpdate(e){}_$AE(e){var t;(t=this._$ES)===null||t===void 0||t.forEach(i=>{var n;return(n=i.hostUpdated)===null||n===void 0?void 0:n.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(e){return!0}update(e){this._$EC!==void 0&&(this._$EC.forEach((t,i)=>this._$EO(i,this[i],t)),this._$EC=void 0),this._$Ek()}updated(e){}firstUpdated(e){}}Ga[V0]=!0,Ga.elementProperties=new Map,Ga.elementStyles=[],Ga.shadowRootOptions={mode:"open"},R3?.({ReactiveElement:Ga}),((j0=bh.reactiveElementVersions)!==null&&j0!==void 0?j0:bh.reactiveElementVersions=[]).push("1.6.3");/** ++ */var W0;const _h=window,L3=_h.trustedTypes,EO=L3?L3.emptyScript:"",B3=_h.reactiveElementPolyfillSupport,K0={toAttribute(r,e){switch(e){case Boolean:r=r?EO:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},F3=(r,e)=>e!==r&&(e==e||r==r),V0={attribute:!0,type:String,converter:K0,reflect:!1,hasChanged:F3},G0="finalized";class Ya extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this._$Eu()}static addInitializer(e){var t;this.finalize(),((t=this.h)!==null&&t!==void 0?t:this.h=[]).push(e)}static get observedAttributes(){this.finalize();const e=[];return this.elementProperties.forEach((t,i)=>{const n=this._$Ep(i,t);n!==void 0&&(this._$Ev.set(n,i),e.push(n))}),e}static createProperty(e,t=V0){if(t.state&&(t.attribute=!1),this.finalize(),this.elementProperties.set(e,t),!t.noAccessor&&!this.prototype.hasOwnProperty(e)){const i=typeof e=="symbol"?Symbol():"__"+e,n=this.getPropertyDescriptor(e,i,t);n!==void 0&&Object.defineProperty(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){return{get(){return this[t]},set(n){const s=this[e];this[t]=n,this.requestUpdate(e,s,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)||V0}static finalize(){if(this.hasOwnProperty(G0))return!1;this[G0]=!0;const e=Object.getPrototypeOf(this);if(e.finalize(),e.h!==void 0&&(this.h=[...e.h]),this.elementProperties=new Map(e.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const t=this.properties,i=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const n of i)this.createProperty(n,t[n])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const n of i)t.unshift(N3(n))}else e!==void 0&&t.push(N3(e));return t}static _$Ep(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}_$Eu(){var e;this._$E_=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$Eg(),this.requestUpdate(),(e=this.constructor.h)===null||e===void 0||e.forEach(t=>t(this))}addController(e){var t,i;((t=this._$ES)!==null&&t!==void 0?t:this._$ES=[]).push(e),this.renderRoot!==void 0&&this.isConnected&&((i=e.hostConnected)===null||i===void 0||i.call(e))}removeController(e){var t;(t=this._$ES)===null||t===void 0||t.splice(this._$ES.indexOf(e)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach((e,t)=>{this.hasOwnProperty(t)&&(this._$Ei.set(t,this[t]),delete this[t])})}createRenderRoot(){var e;const t=(e=this.shadowRoot)!==null&&e!==void 0?e:this.attachShadow(this.constructor.shadowRootOptions);return AO(t,this.constructor.elementStyles),t}connectedCallback(){var e;this.renderRoot===void 0&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$ES)===null||e===void 0||e.forEach(t=>{var i;return(i=t.hostConnected)===null||i===void 0?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$ES)===null||e===void 0||e.forEach(t=>{var i;return(i=t.hostDisconnected)===null||i===void 0?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$EO(e,t,i=V0){var n;const s=this.constructor._$Ep(e,i);if(s!==void 0&&i.reflect===!0){const a=(((n=i.converter)===null||n===void 0?void 0:n.toAttribute)!==void 0?i.converter:K0).toAttribute(t,i.type);this._$El=e,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$El=null}}_$AK(e,t){var i;const n=this.constructor,s=n._$Ev.get(e);if(s!==void 0&&this._$El!==s){const a=n.getPropertyOptions(s),f=typeof a.converter=="function"?{fromAttribute:a.converter}:((i=a.converter)===null||i===void 0?void 0:i.fromAttribute)!==void 0?a.converter:K0;this._$El=s,this[s]=f.fromAttribute(t,a.type),this._$El=null}}requestUpdate(e,t,i){let n=!0;e!==void 0&&(((i=i||this.constructor.getPropertyOptions(e)).hasChanged||F3)(this[e],t)?(this._$AL.has(e)||this._$AL.set(e,t),i.reflect===!0&&this._$El!==e&&(this._$EC===void 0&&(this._$EC=new Map),this._$EC.set(e,i))):n=!1),!this.isUpdatePending&&n&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var e;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach((n,s)=>this[s]=n),this._$Ei=void 0);let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),(e=this._$ES)===null||e===void 0||e.forEach(n=>{var s;return(s=n.hostUpdate)===null||s===void 0?void 0:s.call(n)}),this.update(i)):this._$Ek()}catch(n){throw t=!1,this._$Ek(),n}t&&this._$AE(i)}willUpdate(e){}_$AE(e){var t;(t=this._$ES)===null||t===void 0||t.forEach(i=>{var n;return(n=i.hostUpdated)===null||n===void 0?void 0:n.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(e){return!0}update(e){this._$EC!==void 0&&(this._$EC.forEach((t,i)=>this._$EO(i,this[i],t)),this._$EC=void 0),this._$Ek()}updated(e){}firstUpdated(e){}}Ya[G0]=!0,Ya.elementProperties=new Map,Ya.elementStyles=[],Ya.shadowRootOptions={mode:"open"},B3?.({ReactiveElement:Ya}),((W0=_h.reactiveElementVersions)!==null&&W0!==void 0?W0:_h.reactiveElementVersions=[]).push("1.6.3");/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */var G0;const wh=window,Ya=wh.trustedTypes,$3=Ya?Ya.createPolicy("lit-html",{createHTML:r=>r}):void 0,Y0="$lit$",eo=`lit$${(Math.random()+"").slice(9)}$`,N3="?"+eo,gO=`<${N3}>`,Ko=document,vf=()=>Ko.createComment(""),mf=r=>r===null||typeof r!="object"&&typeof r!="function",L3=Array.isArray,vO=r=>L3(r)||typeof r?.[Symbol.iterator]=="function",J0=`[ +-\f\r]`,bf=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,B3=/-->/g,F3=/>/g,Vo=RegExp(`>|${J0}(?:([^\\s"'>=/]+)(${J0}*=${J0}*(?:[^ +-\f\r"'\`<>=]|("|')|))|$)`,"g"),U3=/'/g,q3=/"/g,z3=/^(?:script|style|textarea|title)$/i,H3=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),Ee=H3(1),gr=H3(2),Go=Symbol.for("lit-noChange"),Mr=Symbol.for("lit-nothing"),k3=new WeakMap,Yo=Ko.createTreeWalker(Ko,129,null,!1);function j3(r,e){if(!Array.isArray(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return $3!==void 0?$3.createHTML(e):e}const mO=(r,e)=>{const t=r.length-1,i=[];let n,s=e===2?"":"",a=bf;for(let f=0;f"?(a=n??bf,w=-1):g[1]===void 0?w=-2:(w=a.lastIndex-g[2].length,u=g[1],a=g[3]===void 0?Vo:g[3]==='"'?q3:U3):a===q3||a===U3?a=Vo:a===B3||a===F3?a=bf:(a=Vo,n=void 0);const M=a===Vo&&r[f+1].startsWith("/>")?" ":"";s+=a===bf?h+gO:w>=0?(i.push(u),h.slice(0,w)+Y0+h.slice(w)+eo+M):h+eo+(w===-2?(i.push(void 0),f):M)}return[j3(r,s+(r[t]||"")+(e===2?"":"")),i]};class wf{constructor({strings:e,_$litType$:t},i){let n;this.parts=[];let s=0,a=0;const f=e.length-1,h=this.parts,[u,g]=mO(e,t);if(this.el=wf.createElement(u,i),Yo.currentNode=this.el.content,t===2){const w=this.el.content,P=w.firstChild;P.remove(),w.append(...P.childNodes)}for(;(n=Yo.nextNode())!==null&&h.length0){n.textContent=Ya?Ya.emptyScript:"";for(let M=0;M2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Mr}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(e,t=this,i,n){const s=this.strings;let a=!1;if(s===void 0)e=Ja(this,e,t,0),a=!mf(e)||e!==this._$AH&&e!==Go,a&&(this._$AH=e);else{const f=e;let h,u;for(e=s[0],h=0;h{var i,n;const s=(i=t?.renderBefore)!==null&&i!==void 0?i:e;let a=s._$litPart$;if(a===void 0){const f=(n=t?.renderBefore)!==null&&n!==void 0?n:null;s._$litPart$=a=new yf(e.insertBefore(vf(),f),f,void 0,t??{})}return a._$AI(r),a};/** ++ */var Y0;const xh=window,Ja=xh.trustedTypes,U3=Ja?Ja.createPolicy("lit-html",{createHTML:r=>r}):void 0,J0="$lit$",to=`lit$${(Math.random()+"").slice(9)}$`,q3="?"+to,SO=`<${q3}>`,Go=document,mf=()=>Go.createComment(""),bf=r=>r===null||typeof r!="object"&&typeof r!="function",z3=Array.isArray,IO=r=>z3(r)||typeof r?.[Symbol.iterator]=="function",Q0=`[ ++\f\r]`,wf=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,H3=/-->/g,k3=/>/g,Yo=RegExp(`>|${Q0}(?:([^\\s"'>=/]+)(${Q0}*=${Q0}*(?:[^ ++\f\r"'\`<>=]|("|')|))|$)`,"g"),j3=/'/g,W3=/"/g,K3=/^(?:script|style|textarea|title)$/i,V3=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),Ee=V3(1),gr=V3(2),Jo=Symbol.for("lit-noChange"),Mr=Symbol.for("lit-nothing"),G3=new WeakMap,Qo=Go.createTreeWalker(Go,129,null,!1);function Y3(r,e){if(!Array.isArray(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return U3!==void 0?U3.createHTML(e):e}const MO=(r,e)=>{const t=r.length-1,i=[];let n,s=e===2?"":"",a=wf;for(let f=0;f"?(a=n??wf,w=-1):g[1]===void 0?w=-2:(w=a.lastIndex-g[2].length,u=g[1],a=g[3]===void 0?Yo:g[3]==='"'?W3:j3):a===W3||a===j3?a=Yo:a===H3||a===k3?a=wf:(a=Yo,n=void 0);const C=a===Yo&&r[f+1].startsWith("/>")?" ":"";s+=a===wf?h+SO:w>=0?(i.push(u),h.slice(0,w)+J0+h.slice(w)+to+C):h+to+(w===-2?(i.push(void 0),f):C)}return[Y3(r,s+(r[t]||"")+(e===2?"":"")),i]};class yf{constructor({strings:e,_$litType$:t},i){let n;this.parts=[];let s=0,a=0;const f=e.length-1,h=this.parts,[u,g]=MO(e,t);if(this.el=yf.createElement(u,i),Qo.currentNode=this.el.content,t===2){const w=this.el.content,M=w.firstChild;M.remove(),w.append(...M.childNodes)}for(;(n=Qo.nextNode())!==null&&h.length0){n.textContent=Ja?Ja.emptyScript:"";for(let C=0;C2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Mr}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(e,t=this,i,n){const s=this.strings;let a=!1;if(s===void 0)e=Qa(this,e,t,0),a=!bf(e)||e!==this._$AH&&e!==Jo,a&&(this._$AH=e);else{const f=e;let h,u;for(e=s[0],h=0;h{var i,n;const s=(i=t?.renderBefore)!==null&&i!==void 0?i:e;let a=s._$litPart$;if(a===void 0){const f=(n=t?.renderBefore)!==null&&n!==void 0?n:null;s._$litPart$=a=new _f(e.insertBefore(mf(),f),f,void 0,t??{})}return a._$AI(r),a};/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */var Q0,Z0;class Ct extends Ga{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e,t;const i=super.createRenderRoot();return(e=(t=this.renderOptions).renderBefore)!==null&&e!==void 0||(t.renderBefore=i.firstChild),i}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=EO(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)===null||e===void 0||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)===null||e===void 0||e.setConnected(!1)}render(){return Go}}Ct.finalized=!0,Ct._$litElement$=!0,(Q0=globalThis.litElementHydrateSupport)===null||Q0===void 0||Q0.call(globalThis,{LitElement:Ct});const K3=globalThis.litElementPolyfillSupport;K3?.({LitElement:Ct}),((Z0=globalThis.litElementVersions)!==null&&Z0!==void 0?Z0:globalThis.litElementVersions=[]).push("3.3.3");/** ++ */var Z0,X0;class Ct extends Ya{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e,t;const i=super.createRenderRoot();return(e=(t=this.renderOptions).renderBefore)!==null&&e!==void 0||(t.renderBefore=i.firstChild),i}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=$O(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)===null||e===void 0||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)===null||e===void 0||e.setConnected(!1)}render(){return Jo}}Ct.finalized=!0,Ct._$litElement$=!0,(Z0=globalThis.litElementHydrateSupport)===null||Z0===void 0||Z0.call(globalThis,{LitElement:Ct});const Q3=globalThis.litElementPolyfillSupport;Q3?.({LitElement:Ct}),((X0=globalThis.litElementVersions)!==null&&X0!==void 0?X0:globalThis.litElementVersions=[]).push("3.3.3");/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +@@ -92,7 +92,7 @@ function print() { __p += __j.call(arguments, '') } + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */const SO=(r,e)=>e.kind==="method"&&e.descriptor&&!("value"in e.descriptor)?{...e,finisher(t){t.createProperty(e.key,r)}}:{kind:"field",key:Symbol(),placement:"own",descriptor:{},originalKey:e.key,initializer(){typeof e.initializer=="function"&&(this[e.key]=e.initializer.call(this))},finisher(t){t.createProperty(e.key,r)}},IO=(r,e,t)=>{e.constructor.createProperty(t,r)};function At(r){return(e,t)=>t!==void 0?IO(r,e,t):SO(r,e)}/** ++ */const NO=(r,e)=>e.kind==="method"&&e.descriptor&&!("value"in e.descriptor)?{...e,finisher(t){t.createProperty(e.key,r)}}:{kind:"field",key:Symbol(),placement:"own",descriptor:{},originalKey:e.key,initializer(){typeof e.initializer=="function"&&(this[e.key]=e.initializer.call(this))},finisher(t){t.createProperty(e.key,r)}},LO=(r,e,t)=>{e.constructor.createProperty(t,r)};function At(r){return(e,t)=>t!==void 0?LO(r,e,t):NO(r,e)}/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +@@ -100,24 +100,24 @@ function print() { __p += __j.call(arguments, '') } + * @license + * Copyright 2021 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */var X0;((X0=window.HTMLSlotElement)===null||X0===void 0?void 0:X0.prototype.assignedElements)!=null;/** ++ */var ep;((ep=window.HTMLSlotElement)===null||ep===void 0?void 0:ep.prototype.assignedElements)!=null;/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */const MO={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},CO=r=>(...e)=>({_$litDirective$:r,values:e});class PO{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/** ++ */const BO={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},FO=r=>(...e)=>({_$litDirective$:r,values:e});class UO{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */const Ss=CO(class extends PO{constructor(r){var e;if(super(r),r.type!==MO.ATTRIBUTE||r.name!=="class"||((e=r.strings)===null||e===void 0?void 0:e.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(r){return" "+Object.keys(r).filter(e=>r[e]).join(" ")+" "}update(r,[e]){var t,i;if(this.it===void 0){this.it=new Set,r.strings!==void 0&&(this.nt=new Set(r.strings.join(" ").split(/\s/).filter(s=>s!=="")));for(const s in e)e[s]&&!(!((t=this.nt)===null||t===void 0)&&t.has(s))&&this.it.add(s);return this.render(e)}const n=r.element.classList;this.it.forEach(s=>{s in e||(n.remove(s),this.it.delete(s))});for(const s in e){const a=!!e[s];a===this.it.has(s)||!((i=this.nt)===null||i===void 0)&&i.has(s)||(a?(n.add(s),this.it.add(s)):(n.remove(s),this.it.delete(s)))}return Go}});function DO(r,e){r.indexOf(e)===-1&&r.push(e)}const V3=(r,e,t)=>Math.min(Math.max(t,r),e),an={duration:.3,delay:0,endDelay:0,repeat:0,easing:"ease"},_h=r=>typeof r=="number",Qa=r=>Array.isArray(r)&&!_h(r[0]),OO=(r,e,t)=>{const i=e-r;return((t-r)%i+i)%i+r};function RO(r,e){return Qa(r)?r[OO(0,r.length,e)]:r}const G3=(r,e,t)=>-t*r+t*e+r,Y3=()=>{},to=r=>r,ep=(r,e,t)=>e-r===0?1:(t-r)/(e-r);function J3(r,e){const t=r[r.length-1];for(let i=1;i<=e;i++){const n=ep(0,e,i);r.push(G3(t,1,n))}}function TO(r){const e=[0];return J3(e,r-1),e}function $O(r,e=TO(r.length),t=to){const i=r.length,n=i-e.length;return n>0&&J3(e,n),s=>{let a=0;for(;aArray.isArray(r)&&_h(r[0]),tp=r=>typeof r=="object"&&!!r.createAnimation,Jo=r=>typeof r=="function",NO=r=>typeof r=="string",_f={ms:r=>r*1e3,s:r=>r/1e3},Z3=(r,e,t)=>(((1-3*t+3*e)*r+(3*t-6*e))*r+3*e)*r,LO=1e-7,BO=12;function FO(r,e,t,i,n){let s,a,f=0;do a=e+(t-e)/2,s=Z3(a,i,n)-r,s>0?t=a:e=a;while(Math.abs(s)>LO&&++fFO(s,0,1,r,t);return s=>s===0||s===1?s:Z3(n(s),e,i)}const UO=(r,e="end")=>t=>{t=e==="end"?Math.min(t,.999):Math.max(t,.001);const i=t*r,n=e==="end"?Math.floor(i):Math.ceil(i);return V3(0,1,n/r)},qO={ease:xf(.25,.1,.25,1),"ease-in":xf(.42,0,1,1),"ease-in-out":xf(.42,0,.58,1),"ease-out":xf(0,0,.58,1)},zO=/\((.*?)\)/;function X3(r){if(Jo(r))return r;if(Q3(r))return xf(...r);const e=qO[r];if(e)return e;if(r.startsWith("steps")){const t=zO.exec(r);if(t){const i=t[1].split(",");return UO(parseFloat(i[0]),i[1].trim())}}return to}class ew{constructor(e,t=[0,1],{easing:i,duration:n=an.duration,delay:s=an.delay,endDelay:a=an.endDelay,repeat:f=an.repeat,offset:h,direction:u="normal",autoplay:g=!0}={}){if(this.startTime=null,this.rate=1,this.t=0,this.cancelTimestamp=null,this.easing=to,this.duration=0,this.totalDuration=0,this.repeat=0,this.playState="idle",this.finished=new Promise((P,M)=>{this.resolve=P,this.reject=M}),i=i||an.easing,tp(i)){const P=i.createAnimation(t);i=P.easing,t=P.keyframes||t,n=P.duration||n}this.repeat=f,this.easing=Qa(i)?to:X3(i),this.updateDuration(n);const w=$O(t,h,Qa(i)?i.map(X3):to);this.tick=P=>{var M;s=s;let O=0;this.pauseTime!==void 0?O=this.pauseTime:O=(P-this.startTime)*this.rate,this.t=O,O/=1e3,O=Math.max(O-s,0),this.playState==="finished"&&this.pauseTime===void 0&&(O=this.totalDuration);const $=O/this.duration;let W=Math.floor($),H=$%1;!H&&$>=1&&(H=1),H===1&&W--;const F=W%2;(u==="reverse"||u==="alternate"&&F||u==="alternate-reverse"&&!F)&&(H=1-H);const Y=O>=this.totalDuration?1:Math.min(H,1),B=w(this.easing(Y));e(B),this.pauseTime===void 0&&(this.playState==="finished"||O>=this.totalDuration+a)?(this.playState="finished",(M=this.resolve)===null||M===void 0||M.call(this,B)):this.playState!=="idle"&&(this.frameRequestId=requestAnimationFrame(this.tick))},g&&this.play()}play(){const e=performance.now();this.playState="running",this.pauseTime!==void 0?this.startTime=e-this.pauseTime:this.startTime||(this.startTime=e),this.cancelTimestamp=this.startTime,this.pauseTime=void 0,this.frameRequestId=requestAnimationFrame(this.tick)}pause(){this.playState="paused",this.pauseTime=this.t}finish(){this.playState="finished",this.tick(0)}stop(){var e;this.playState="idle",this.frameRequestId!==void 0&&cancelAnimationFrame(this.frameRequestId),(e=this.reject)===null||e===void 0||e.call(this,!1)}cancel(){this.stop(),this.tick(this.cancelTimestamp)}reverse(){this.rate*=-1}commitStyles(){}updateDuration(e){this.duration=e,this.totalDuration=e*(this.repeat+1)}get currentTime(){return this.t}set currentTime(e){this.pauseTime!==void 0||this.rate===0?this.pauseTime=e:this.startTime=performance.now()-e/this.rate}get playbackRate(){return this.rate}set playbackRate(e){this.rate=e}}var rp=function(){};process.env.NODE_ENV!=="production"&&(rp=function(r,e){if(!r)throw new Error(e)});class HO{setAnimation(e){this.animation=e,e?.finished.then(()=>this.clearAnimation()).catch(()=>{})}clearAnimation(){this.animation=this.generator=void 0}}const ip=new WeakMap;function tw(r){return ip.has(r)||ip.set(r,{transforms:[],values:new Map}),ip.get(r)}function kO(r,e){return r.has(e)||r.set(e,new HO),r.get(e)}const jO=["","X","Y","Z"],WO=["translate","scale","rotate","skew"],xh={x:"translateX",y:"translateY",z:"translateZ"},rw={syntax:"",initialValue:"0deg",toDefaultUnit:r=>r+"deg"},KO={translate:{syntax:"",initialValue:"0px",toDefaultUnit:r=>r+"px"},rotate:rw,scale:{syntax:"",initialValue:1,toDefaultUnit:to},skew:rw},Af=new Map,np=r=>`--motion-${r}`,Ah=["x","y","z"];WO.forEach(r=>{jO.forEach(e=>{Ah.push(r+e),Af.set(np(r+e),KO[r])})});const VO=(r,e)=>Ah.indexOf(r)-Ah.indexOf(e),GO=new Set(Ah),iw=r=>GO.has(r),YO=(r,e)=>{xh[e]&&(e=xh[e]);const{transforms:t}=tw(r);DO(t,e),r.style.transform=JO(t)},JO=r=>r.sort(VO).reduce(QO,"").trim(),QO=(r,e)=>`${r} ${e}(var(${np(e)}))`,sp=r=>r.startsWith("--"),nw=new Set;function ZO(r){if(!nw.has(r)){nw.add(r);try{const{syntax:e,initialValue:t}=Af.has(r)?Af.get(r):{};CSS.registerProperty({name:r,inherits:!1,syntax:e,initialValue:t})}catch{}}}const op=(r,e)=>document.createElement("div").animate(r,e),sw={cssRegisterProperty:()=>typeof CSS<"u"&&Object.hasOwnProperty.call(CSS,"registerProperty"),waapi:()=>Object.hasOwnProperty.call(Element.prototype,"animate"),partialKeyframes:()=>{try{op({opacity:[1]})}catch{return!1}return!0},finished:()=>!!op({opacity:[0,1]},{duration:.001}).finished,linearEasing:()=>{try{op({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0}},ap={},Za={};for(const r in sw)Za[r]=()=>(ap[r]===void 0&&(ap[r]=sw[r]()),ap[r]);const XO=.015,eR=(r,e)=>{let t="";const i=Math.round(e/XO);for(let n=0;nJo(r)?Za.linearEasing()?`linear(${eR(r,e)})`:an.easing:Q3(r)?tR(r):r,tR=([r,e,t,i])=>`cubic-bezier(${r}, ${e}, ${t}, ${i})`;function rR(r,e){for(let t=0;tArray.isArray(r)?r:[r];function cp(r){return xh[r]&&(r=xh[r]),iw(r)?np(r):r}const Eh={get:(r,e)=>{e=cp(e);let t=sp(e)?r.style.getPropertyValue(e):getComputedStyle(r)[e];if(!t&&t!==0){const i=Af.get(e);i&&(t=i.initialValue)}return t},set:(r,e,t)=>{e=cp(e),sp(e)?r.style.setProperty(e,t):r.style[e]=t}};function aw(r,e=!0){if(!(!r||r.playState==="finished"))try{r.stop?r.stop():(e&&r.commitStyles(),r.cancel())}catch{}}function nR(r,e){var t;let i=e?.toDefaultUnit||to;const n=r[r.length-1];if(NO(n)){const s=((t=n.match(/(-?[\d.]+)([a-z%]*)/))===null||t===void 0?void 0:t[2])||"";s&&(i=a=>a+s)}return i}function sR(){return window.__MOTION_DEV_TOOLS_RECORD}function oR(r,e,t,i={},n){const s=sR(),a=i.record!==!1&&s;let f,{duration:h=an.duration,delay:u=an.delay,endDelay:g=an.endDelay,repeat:w=an.repeat,easing:P=an.easing,persist:M=!1,direction:O,offset:$,allowWebkitAcceleration:W=!1,autoplay:H=!0}=i;const F=tw(r),Y=iw(e);let B=Za.waapi();Y&&YO(r,e);const z=cp(e),j=kO(F.values,z),_=Af.get(z);return aw(j.animation,!(tp(P)&&j.generator)&&i.record!==!1),()=>{const U=()=>{var L,b;return(b=(L=Eh.get(r,z))!==null&&L!==void 0?L:_?.initialValue)!==null&&b!==void 0?b:0};let ee=rR(iR(t),U);const oe=nR(ee,_);if(tp(P)){const L=P.createAnimation(ee,e!=="opacity",U,z,j);P=L.easing,ee=L.keyframes||ee,h=L.duration||h}if(sp(z)&&(Za.cssRegisterProperty()?ZO(z):B=!1),Y&&!Za.linearEasing()&&(Jo(P)||Qa(P)&&P.some(Jo))&&(B=!1),B){_&&(ee=ee.map(m=>_h(m)?_.toDefaultUnit(m):m)),ee.length===1&&(!Za.partialKeyframes()||a)&&ee.unshift(U());const L={delay:_f.ms(u),duration:_f.ms(h),endDelay:_f.ms(g),easing:Qa(P)?void 0:ow(P,h),direction:O,iterations:w+1,fill:"both"};f=r.animate({[z]:ee,offset:$,easing:Qa(P)?P.map(m=>ow(m,h)):void 0},L),f.finished||(f.finished=new Promise((m,l)=>{f.onfinish=m,f.oncancel=l}));const b=ee[ee.length-1];f.finished.then(()=>{M||(Eh.set(r,z,b),f.cancel())}).catch(Y3),W||(f.playbackRate=1.000001)}else if(n&&Y)ee=ee.map(L=>typeof L=="string"?parseFloat(L):L),ee.length===1&&ee.unshift(parseFloat(U())),f=new n(L=>{Eh.set(r,z,oe?oe(L):L)},ee,Object.assign(Object.assign({},i),{duration:h,easing:P}));else{const L=ee[ee.length-1];Eh.set(r,z,_&&_h(L)?_.toDefaultUnit(L):L)}return a&&s(r,e,ee,{duration:h,delay:u,easing:P,repeat:w,offset:$},"motion-one"),j.setAnimation(f),f&&!H&&f.pause(),f}}const aR=(r,e)=>r[e]?Object.assign(Object.assign({},r),r[e]):Object.assign({},r);function cw(r,e){var t;return typeof r=="string"?e?((t=e[r])!==null&&t!==void 0||(e[r]=document.querySelectorAll(r)),r=e[r]):r=document.querySelectorAll(r):r instanceof Element&&(r=[r]),Array.from(r||[])}const cR=r=>r(),fw=(r,e,t=an.duration)=>new Proxy({animations:r.map(cR).filter(Boolean),duration:t,options:e},lR),fR=r=>r.animations[0],lR={get:(r,e)=>{const t=fR(r);switch(e){case"duration":return r.duration;case"currentTime":return _f.s(t?.[e]||0);case"playbackRate":case"playState":return t?.[e];case"finished":return r.finished||(r.finished=Promise.all(r.animations.map(hR)).catch(Y3)),r.finished;case"stop":return()=>{r.animations.forEach(i=>aw(i))};case"forEachNative":return i=>{r.animations.forEach(n=>i(n,r))};default:return typeof t?.[e]>"u"?void 0:()=>r.animations.forEach(i=>i[e]())}},set:(r,e,t)=>{switch(e){case"currentTime":t=_f.ms(t);case"playbackRate":for(let i=0;ir.finished;function uR(r,e,t){return Jo(r)?r(e,t):r}function dR(r){return function(t,i,n={}){t=cw(t);const s=t.length;rp(!!s,"No valid element provided."),rp(!!i,"No keyframes defined.");const a=[];for(let f=0;f"u")return()=>{};const s=cw(r),a=new WeakMap,f=u=>{u.forEach(g=>{const w=a.get(g.target);if(g.isIntersecting!==!!w)if(g.isIntersecting){const P=e(g);Jo(P)?a.set(g.target,P):h.unobserve(g.target)}else w&&(w(g),a.delete(g.target))})},h=new IntersectionObserver(f,{root:t,rootMargin:i,threshold:typeof n=="number"?n:vR[n]});return s.forEach(u=>h.observe(u)),()=>h.disconnect()}function fp(r,e,t){r.dispatchEvent(new CustomEvent(e,{detail:{originalEvent:t}}))}function lw(r,e,t){r.dispatchEvent(new CustomEvent(e,{detail:{originalEntry:t}}))}const bR={isActive:r=>!!r.inView,subscribe:(r,{enable:e,disable:t},{inViewOptions:i={}})=>{const{once:n}=i,s=gR(i,["once"]);return mR(r,a=>{if(e(),lw(r,"viewenter",a),!n)return f=>{t(),lw(r,"viewleave",f)}},s)}},hw=(r,e,t)=>i=>{i.pointerType&&i.pointerType!=="mouse"||(t(),fp(r,e,i))};[...Object.keys({inView:bR,hover:{isActive:r=>!!r.hover,subscribe:(r,{enable:e,disable:t})=>{const i=hw(r,"hoverstart",e),n=hw(r,"hoverend",t);return r.addEventListener("pointerenter",i),r.addEventListener("pointerleave",n),()=>{r.removeEventListener("pointerenter",i),r.removeEventListener("pointerleave",n)}}},press:{isActive:r=>!!r.press,subscribe:(r,{enable:e,disable:t})=>{const i=s=>{t(),fp(r,"pressend",s),window.removeEventListener("pointerup",i)},n=s=>{e(),fp(r,"pressstart",s),window.addEventListener("pointerup",i)};return r.addEventListener("pointerdown",n),()=>{r.removeEventListener("pointerdown",n),window.removeEventListener("pointerup",i)}}}})];function wR(r,e={}){return fw([()=>{const t=new ew(r,[0,1],e);return t.finished.catch(()=>{}),t}],e,e.duration)}function Qo(r,e,t){return(Jo(r)?wR:pR)(r,e,t)}/** ++ */const Is=FO(class extends UO{constructor(r){var e;if(super(r),r.type!==BO.ATTRIBUTE||r.name!=="class"||((e=r.strings)===null||e===void 0?void 0:e.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(r){return" "+Object.keys(r).filter(e=>r[e]).join(" ")+" "}update(r,[e]){var t,i;if(this.it===void 0){this.it=new Set,r.strings!==void 0&&(this.nt=new Set(r.strings.join(" ").split(/\s/).filter(s=>s!=="")));for(const s in e)e[s]&&!(!((t=this.nt)===null||t===void 0)&&t.has(s))&&this.it.add(s);return this.render(e)}const n=r.element.classList;this.it.forEach(s=>{s in e||(n.remove(s),this.it.delete(s))});for(const s in e){const a=!!e[s];a===this.it.has(s)||!((i=this.nt)===null||i===void 0)&&i.has(s)||(a?(n.add(s),this.it.add(s)):(n.remove(s),this.it.delete(s)))}return Jo}});function qO(r,e){r.indexOf(e)===-1&&r.push(e)}const Z3=(r,e,t)=>Math.min(Math.max(t,r),e),cn={duration:.3,delay:0,endDelay:0,repeat:0,easing:"ease"},Eh=r=>typeof r=="number",Za=r=>Array.isArray(r)&&!Eh(r[0]),zO=(r,e,t)=>{const i=e-r;return((t-r)%i+i)%i+r};function HO(r,e){return Za(r)?r[zO(0,r.length,e)]:r}const X3=(r,e,t)=>-t*r+t*e+r,ew=()=>{},ro=r=>r,tp=(r,e,t)=>e-r===0?1:(t-r)/(e-r);function tw(r,e){const t=r[r.length-1];for(let i=1;i<=e;i++){const n=tp(0,e,i);r.push(X3(t,1,n))}}function kO(r){const e=[0];return tw(e,r-1),e}function jO(r,e=kO(r.length),t=ro){const i=r.length,n=i-e.length;return n>0&&tw(e,n),s=>{let a=0;for(;aArray.isArray(r)&&Eh(r[0]),rp=r=>typeof r=="object"&&!!r.createAnimation,Zo=r=>typeof r=="function",WO=r=>typeof r=="string",xf={ms:r=>r*1e3,s:r=>r/1e3},iw=(r,e,t)=>(((1-3*t+3*e)*r+(3*t-6*e))*r+3*e)*r,KO=1e-7,VO=12;function GO(r,e,t,i,n){let s,a,f=0;do a=e+(t-e)/2,s=iw(a,i,n)-r,s>0?t=a:e=a;while(Math.abs(s)>KO&&++fGO(s,0,1,r,t);return s=>s===0||s===1?s:iw(n(s),e,i)}const YO=(r,e="end")=>t=>{t=e==="end"?Math.min(t,.999):Math.max(t,.001);const i=t*r,n=e==="end"?Math.floor(i):Math.ceil(i);return Z3(0,1,n/r)},JO={ease:Af(.25,.1,.25,1),"ease-in":Af(.42,0,1,1),"ease-in-out":Af(.42,0,.58,1),"ease-out":Af(0,0,.58,1)},QO=/\((.*?)\)/;function nw(r){if(Zo(r))return r;if(rw(r))return Af(...r);const e=JO[r];if(e)return e;if(r.startsWith("steps")){const t=QO.exec(r);if(t){const i=t[1].split(",");return YO(parseFloat(i[0]),i[1].trim())}}return ro}class sw{constructor(e,t=[0,1],{easing:i,duration:n=cn.duration,delay:s=cn.delay,endDelay:a=cn.endDelay,repeat:f=cn.repeat,offset:h,direction:u="normal",autoplay:g=!0}={}){if(this.startTime=null,this.rate=1,this.t=0,this.cancelTimestamp=null,this.easing=ro,this.duration=0,this.totalDuration=0,this.repeat=0,this.playState="idle",this.finished=new Promise((M,C)=>{this.resolve=M,this.reject=C}),i=i||cn.easing,rp(i)){const M=i.createAnimation(t);i=M.easing,t=M.keyframes||t,n=M.duration||n}this.repeat=f,this.easing=Za(i)?ro:nw(i),this.updateDuration(n);const w=jO(t,h,Za(i)?i.map(nw):ro);this.tick=M=>{var C;s=s;let O=0;this.pauseTime!==void 0?O=this.pauseTime:O=(M-this.startTime)*this.rate,this.t=O,O/=1e3,O=Math.max(O-s,0),this.playState==="finished"&&this.pauseTime===void 0&&(O=this.totalDuration);const $=O/this.duration;let j=Math.floor($),H=$%1;!H&&$>=1&&(H=1),H===1&&j--;const F=j%2;(u==="reverse"||u==="alternate"&&F||u==="alternate-reverse"&&!F)&&(H=1-H);const G=O>=this.totalDuration?1:Math.min(H,1),B=w(this.easing(G));e(B),this.pauseTime===void 0&&(this.playState==="finished"||O>=this.totalDuration+a)?(this.playState="finished",(C=this.resolve)===null||C===void 0||C.call(this,B)):this.playState!=="idle"&&(this.frameRequestId=requestAnimationFrame(this.tick))},g&&this.play()}play(){const e=performance.now();this.playState="running",this.pauseTime!==void 0?this.startTime=e-this.pauseTime:this.startTime||(this.startTime=e),this.cancelTimestamp=this.startTime,this.pauseTime=void 0,this.frameRequestId=requestAnimationFrame(this.tick)}pause(){this.playState="paused",this.pauseTime=this.t}finish(){this.playState="finished",this.tick(0)}stop(){var e;this.playState="idle",this.frameRequestId!==void 0&&cancelAnimationFrame(this.frameRequestId),(e=this.reject)===null||e===void 0||e.call(this,!1)}cancel(){this.stop(),this.tick(this.cancelTimestamp)}reverse(){this.rate*=-1}commitStyles(){}updateDuration(e){this.duration=e,this.totalDuration=e*(this.repeat+1)}get currentTime(){return this.t}set currentTime(e){this.pauseTime!==void 0||this.rate===0?this.pauseTime=e:this.startTime=performance.now()-e/this.rate}get playbackRate(){return this.rate}set playbackRate(e){this.rate=e}}var ip=function(){};process.env.NODE_ENV!=="production"&&(ip=function(r,e){if(!r)throw new Error(e)});class ZO{setAnimation(e){this.animation=e,e?.finished.then(()=>this.clearAnimation()).catch(()=>{})}clearAnimation(){this.animation=this.generator=void 0}}const np=new WeakMap;function ow(r){return np.has(r)||np.set(r,{transforms:[],values:new Map}),np.get(r)}function XO(r,e){return r.has(e)||r.set(e,new ZO),r.get(e)}const eR=["","X","Y","Z"],tR=["translate","scale","rotate","skew"],Sh={x:"translateX",y:"translateY",z:"translateZ"},aw={syntax:"",initialValue:"0deg",toDefaultUnit:r=>r+"deg"},rR={translate:{syntax:"",initialValue:"0px",toDefaultUnit:r=>r+"px"},rotate:aw,scale:{syntax:"",initialValue:1,toDefaultUnit:ro},skew:aw},Ef=new Map,sp=r=>`--motion-${r}`,Ih=["x","y","z"];tR.forEach(r=>{eR.forEach(e=>{Ih.push(r+e),Ef.set(sp(r+e),rR[r])})});const iR=(r,e)=>Ih.indexOf(r)-Ih.indexOf(e),nR=new Set(Ih),cw=r=>nR.has(r),sR=(r,e)=>{Sh[e]&&(e=Sh[e]);const{transforms:t}=ow(r);qO(t,e),r.style.transform=oR(t)},oR=r=>r.sort(iR).reduce(aR,"").trim(),aR=(r,e)=>`${r} ${e}(var(${sp(e)}))`,op=r=>r.startsWith("--"),fw=new Set;function cR(r){if(!fw.has(r)){fw.add(r);try{const{syntax:e,initialValue:t}=Ef.has(r)?Ef.get(r):{};CSS.registerProperty({name:r,inherits:!1,syntax:e,initialValue:t})}catch{}}}const ap=(r,e)=>document.createElement("div").animate(r,e),lw={cssRegisterProperty:()=>typeof CSS<"u"&&Object.hasOwnProperty.call(CSS,"registerProperty"),waapi:()=>Object.hasOwnProperty.call(Element.prototype,"animate"),partialKeyframes:()=>{try{ap({opacity:[1]})}catch{return!1}return!0},finished:()=>!!ap({opacity:[0,1]},{duration:.001}).finished,linearEasing:()=>{try{ap({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0}},cp={},Xa={};for(const r in lw)Xa[r]=()=>(cp[r]===void 0&&(cp[r]=lw[r]()),cp[r]);const fR=.015,lR=(r,e)=>{let t="";const i=Math.round(e/fR);for(let n=0;nZo(r)?Xa.linearEasing()?`linear(${lR(r,e)})`:cn.easing:rw(r)?hR(r):r,hR=([r,e,t,i])=>`cubic-bezier(${r}, ${e}, ${t}, ${i})`;function uR(r,e){for(let t=0;tArray.isArray(r)?r:[r];function fp(r){return Sh[r]&&(r=Sh[r]),cw(r)?sp(r):r}const Mh={get:(r,e)=>{e=fp(e);let t=op(e)?r.style.getPropertyValue(e):getComputedStyle(r)[e];if(!t&&t!==0){const i=Ef.get(e);i&&(t=i.initialValue)}return t},set:(r,e,t)=>{e=fp(e),op(e)?r.style.setProperty(e,t):r.style[e]=t}};function uw(r,e=!0){if(!(!r||r.playState==="finished"))try{r.stop?r.stop():(e&&r.commitStyles(),r.cancel())}catch{}}function pR(r,e){var t;let i=e?.toDefaultUnit||ro;const n=r[r.length-1];if(WO(n)){const s=((t=n.match(/(-?[\d.]+)([a-z%]*)/))===null||t===void 0?void 0:t[2])||"";s&&(i=a=>a+s)}return i}function gR(){return window.__MOTION_DEV_TOOLS_RECORD}function vR(r,e,t,i={},n){const s=gR(),a=i.record!==!1&&s;let f,{duration:h=cn.duration,delay:u=cn.delay,endDelay:g=cn.endDelay,repeat:w=cn.repeat,easing:M=cn.easing,persist:C=!1,direction:O,offset:$,allowWebkitAcceleration:j=!1,autoplay:H=!0}=i;const F=ow(r),G=cw(e);let B=Xa.waapi();G&&sR(r,e);const z=fp(e),W=XO(F.values,z),_=Ef.get(z);return uw(W.animation,!(rp(M)&&W.generator)&&i.record!==!1),()=>{const U=()=>{var L,b;return(b=(L=Mh.get(r,z))!==null&&L!==void 0?L:_?.initialValue)!==null&&b!==void 0?b:0};let ee=uR(dR(t),U);const oe=pR(ee,_);if(rp(M)){const L=M.createAnimation(ee,e!=="opacity",U,z,W);M=L.easing,ee=L.keyframes||ee,h=L.duration||h}if(op(z)&&(Xa.cssRegisterProperty()?cR(z):B=!1),G&&!Xa.linearEasing()&&(Zo(M)||Za(M)&&M.some(Zo))&&(B=!1),B){_&&(ee=ee.map(m=>Eh(m)?_.toDefaultUnit(m):m)),ee.length===1&&(!Xa.partialKeyframes()||a)&&ee.unshift(U());const L={delay:xf.ms(u),duration:xf.ms(h),endDelay:xf.ms(g),easing:Za(M)?void 0:hw(M,h),direction:O,iterations:w+1,fill:"both"};f=r.animate({[z]:ee,offset:$,easing:Za(M)?M.map(m=>hw(m,h)):void 0},L),f.finished||(f.finished=new Promise((m,l)=>{f.onfinish=m,f.oncancel=l}));const b=ee[ee.length-1];f.finished.then(()=>{C||(Mh.set(r,z,b),f.cancel())}).catch(ew),j||(f.playbackRate=1.000001)}else if(n&&G)ee=ee.map(L=>typeof L=="string"?parseFloat(L):L),ee.length===1&&ee.unshift(parseFloat(U())),f=new n(L=>{Mh.set(r,z,oe?oe(L):L)},ee,Object.assign(Object.assign({},i),{duration:h,easing:M}));else{const L=ee[ee.length-1];Mh.set(r,z,_&&Eh(L)?_.toDefaultUnit(L):L)}return a&&s(r,e,ee,{duration:h,delay:u,easing:M,repeat:w,offset:$},"motion-one"),W.setAnimation(f),f&&!H&&f.pause(),f}}const mR=(r,e)=>r[e]?Object.assign(Object.assign({},r),r[e]):Object.assign({},r);function dw(r,e){var t;return typeof r=="string"?e?((t=e[r])!==null&&t!==void 0||(e[r]=document.querySelectorAll(r)),r=e[r]):r=document.querySelectorAll(r):r instanceof Element&&(r=[r]),Array.from(r||[])}const bR=r=>r(),pw=(r,e,t=cn.duration)=>new Proxy({animations:r.map(bR).filter(Boolean),duration:t,options:e},yR),wR=r=>r.animations[0],yR={get:(r,e)=>{const t=wR(r);switch(e){case"duration":return r.duration;case"currentTime":return xf.s(t?.[e]||0);case"playbackRate":case"playState":return t?.[e];case"finished":return r.finished||(r.finished=Promise.all(r.animations.map(_R)).catch(ew)),r.finished;case"stop":return()=>{r.animations.forEach(i=>uw(i))};case"forEachNative":return i=>{r.animations.forEach(n=>i(n,r))};default:return typeof t?.[e]>"u"?void 0:()=>r.animations.forEach(i=>i[e]())}},set:(r,e,t)=>{switch(e){case"currentTime":t=xf.ms(t);case"playbackRate":for(let i=0;ir.finished;function xR(r,e,t){return Zo(r)?r(e,t):r}function AR(r){return function(t,i,n={}){t=dw(t);const s=t.length;ip(!!s,"No valid element provided."),ip(!!i,"No keyframes defined.");const a=[];for(let f=0;f"u")return()=>{};const s=dw(r),a=new WeakMap,f=u=>{u.forEach(g=>{const w=a.get(g.target);if(g.isIntersecting!==!!w)if(g.isIntersecting){const M=e(g);Zo(M)?a.set(g.target,M):h.unobserve(g.target)}else w&&(w(g),a.delete(g.target))})},h=new IntersectionObserver(f,{root:t,rootMargin:i,threshold:typeof n=="number"?n:IR[n]});return s.forEach(u=>h.observe(u)),()=>h.disconnect()}function lp(r,e,t){r.dispatchEvent(new CustomEvent(e,{detail:{originalEvent:t}}))}function gw(r,e,t){r.dispatchEvent(new CustomEvent(e,{detail:{originalEntry:t}}))}const CR={isActive:r=>!!r.inView,subscribe:(r,{enable:e,disable:t},{inViewOptions:i={}})=>{const{once:n}=i,s=SR(i,["once"]);return MR(r,a=>{if(e(),gw(r,"viewenter",a),!n)return f=>{t(),gw(r,"viewleave",f)}},s)}},vw=(r,e,t)=>i=>{i.pointerType&&i.pointerType!=="mouse"||(t(),lp(r,e,i))};[...Object.keys({inView:CR,hover:{isActive:r=>!!r.hover,subscribe:(r,{enable:e,disable:t})=>{const i=vw(r,"hoverstart",e),n=vw(r,"hoverend",t);return r.addEventListener("pointerenter",i),r.addEventListener("pointerleave",n),()=>{r.removeEventListener("pointerenter",i),r.removeEventListener("pointerleave",n)}}},press:{isActive:r=>!!r.press,subscribe:(r,{enable:e,disable:t})=>{const i=s=>{t(),lp(r,"pressend",s),window.removeEventListener("pointerup",i)},n=s=>{e(),lp(r,"pressstart",s),window.addEventListener("pointerup",i)};return r.addEventListener("pointerdown",n),()=>{r.removeEventListener("pointerdown",n),window.removeEventListener("pointerup",i)}}}})];function PR(r,e={}){return pw([()=>{const t=new sw(r,[0,1],e);return t.finished.catch(()=>{}),t}],e,e.duration)}function Xo(r,e,t){return(Zo(r)?PR:ER)(r,e,t)}/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause +- */const li=r=>r??Mr;var Ef={},yR=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},uw={},qi={};let lp;const _R=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];qi.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},qi.getSymbolTotalCodewords=function(e){return _R[e]},qi.getBCHDigit=function(r){let e=0;for(;r!==0;)e++,r>>>=1;return e},qi.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');lp=e},qi.isKanjiModeEnabled=function(){return typeof lp<"u"},qi.toSJIS=function(e){return lp(e)};var Sh={};(function(r){r.L={bit:1},r.M={bit:0},r.Q={bit:3},r.H={bit:2};function e(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return r.L;case"m":case"medium":return r.M;case"q":case"quartile":return r.Q;case"h":case"high":return r.H;default:throw new Error("Unknown EC Level: "+t)}}r.isValid=function(i){return i&&typeof i.bit<"u"&&i.bit>=0&&i.bit<4},r.from=function(i,n){if(r.isValid(i))return i;try{return e(i)}catch{return n}}})(Sh);function dw(){this.buffer=[],this.length=0}dw.prototype={get:function(r){const e=Math.floor(r/8);return(this.buffer[e]>>>7-r%8&1)===1},put:function(r,e){for(let t=0;t>>e-t-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),r&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var xR=dw;function Sf(r){if(!r||r<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=r,this.data=new Uint8Array(r*r),this.reservedBit=new Uint8Array(r*r)}Sf.prototype.set=function(r,e,t,i){const n=r*this.size+e;this.data[n]=t,i&&(this.reservedBit[n]=!0)},Sf.prototype.get=function(r,e){return this.data[r*this.size+e]},Sf.prototype.xor=function(r,e,t){this.data[r*this.size+e]^=t},Sf.prototype.isReserved=function(r,e){return this.reservedBit[r*this.size+e]};var AR=Sf,pw={};(function(r){const e=qi.getSymbolSize;r.getRowColCoords=function(i){if(i===1)return[];const n=Math.floor(i/7)+2,s=e(i),a=s===145?26:Math.ceil((s-13)/(2*n-2))*2,f=[s-7];for(let h=1;h=0&&n<=7},r.from=function(n){return r.isValid(n)?parseInt(n,10):void 0},r.getPenaltyN1=function(n){const s=n.size;let a=0,f=0,h=0,u=null,g=null;for(let w=0;w=5&&(a+=e.N1+(f-5)),u=M,f=1),M=n.get(P,w),M===g?h++:(h>=5&&(a+=e.N1+(h-5)),g=M,h=1)}f>=5&&(a+=e.N1+(f-5)),h>=5&&(a+=e.N1+(h-5))}return a},r.getPenaltyN2=function(n){const s=n.size;let a=0;for(let f=0;f=10&&(f===1488||f===93)&&a++,h=h<<1&2047|n.get(g,u),g>=10&&(h===1488||h===93)&&a++}return a*e.N3},r.getPenaltyN4=function(n){let s=0;const a=n.data.length;for(let h=0;h=0;){const a=s[0];for(let h=0;h0){const s=new Uint8Array(this.degree);return s.set(i,n),s}return i};var SR=hp,yw={},io={},up={};up.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var os={};const _w="[0-9]+",IR="[A-Z $%*+\\-./:]+";let Mf="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Mf=Mf.replace(/u/g,"\\u");const MR="(?:(?![A-Z0-9 $%*+\\-./:]|"+Mf+`)(?:.|[\r +-]))+`;os.KANJI=new RegExp(Mf,"g"),os.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),os.BYTE=new RegExp(MR,"g"),os.NUMERIC=new RegExp(_w,"g"),os.ALPHANUMERIC=new RegExp(IR,"g");const CR=new RegExp("^"+Mf+"$"),PR=new RegExp("^"+_w+"$"),DR=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");os.testKanji=function(e){return CR.test(e)},os.testNumeric=function(e){return PR.test(e)},os.testAlphanumeric=function(e){return DR.test(e)},function(r){const e=up,t=os;r.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},r.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},r.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},r.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},r.MIXED={bit:-1},r.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},r.getBestModeForData=function(s){return t.testNumeric(s)?r.NUMERIC:t.testAlphanumeric(s)?r.ALPHANUMERIC:t.testKanji(s)?r.KANJI:r.BYTE},r.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},r.isValid=function(s){return s&&s.bit&&s.ccBits};function i(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return r.NUMERIC;case"alphanumeric":return r.ALPHANUMERIC;case"kanji":return r.KANJI;case"byte":return r.BYTE;default:throw new Error("Unknown mode: "+n)}}r.from=function(s,a){if(r.isValid(s))return s;try{return i(s)}catch{return a}}}(io),function(r){const e=qi,t=Ih,i=Sh,n=io,s=up,a=7973,f=e.getBCHDigit(a);function h(P,M,O){for(let $=1;$<=40;$++)if(M<=r.getCapacity($,O,P))return $}function u(P,M){return n.getCharCountIndicator(P,M)+4}function g(P,M){let O=0;return P.forEach(function($){const W=u($.mode,M);O+=W+$.getBitsLength()}),O}function w(P,M){for(let O=1;O<=40;O++)if(g(P,O)<=r.getCapacity(O,M,n.MIXED))return O}r.from=function(M,O){return s.isValid(M)?parseInt(M,10):O},r.getCapacity=function(M,O,$){if(!s.isValid(M))throw new Error("Invalid QR Code version");typeof $>"u"&&($=n.BYTE);const W=e.getSymbolTotalCodewords(M),H=t.getTotalCodewordsCount(M,O),F=(W-H)*8;if($===n.MIXED)return F;const Y=F-u($,M);switch($){case n.NUMERIC:return Math.floor(Y/10*3);case n.ALPHANUMERIC:return Math.floor(Y/11*2);case n.KANJI:return Math.floor(Y/13);case n.BYTE:default:return Math.floor(Y/8)}},r.getBestVersionForData=function(M,O){let $;const W=i.from(O,i.M);if(Array.isArray(M)){if(M.length>1)return w(M,W);if(M.length===0)return 1;$=M[0]}else $=M;return h($.mode,$.getLength(),W)},r.getEncodedBits=function(M){if(!s.isValid(M)||M<7)throw new Error("Invalid QR Code version");let O=M<<12;for(;e.getBCHDigit(O)-f>=0;)O^=a<=0;)n^=Aw<0&&(i=this.data.substr(t),n=parseInt(i,10),e.put(n,s*3+1))};var TR=Xa;const $R=io,pp=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function ec(r){this.mode=$R.ALPHANUMERIC,this.data=r}ec.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)},ec.prototype.getLength=function(){return this.data.length},ec.prototype.getBitsLength=function(){return ec.getBitsLength(this.data.length)},ec.prototype.write=function(e){let t;for(t=0;t+2<=this.data.length;t+=2){let i=pp.indexOf(this.data[t])*45;i+=pp.indexOf(this.data[t+1]),e.put(i,11)}this.data.length%2&&e.put(pp.indexOf(this.data[t]),6)};var NR=ec,LR=function(e){for(var t=[],i=e.length,n=0;n=55296&&s<=56319&&i>n+1){var a=e.charCodeAt(n+1);a>=56320&&a<=57343&&(s=(s-55296)*1024+a-56320+65536,n+=1)}if(s<128){t.push(s);continue}if(s<2048){t.push(s>>6|192),t.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){t.push(s>>12|224),t.push(s>>6&63|128),t.push(s&63|128);continue}if(s>=65536&&s<=1114111){t.push(s>>18|240),t.push(s>>12&63|128),t.push(s>>6&63|128),t.push(s&63|128);continue}t.push(239,191,189)}return new Uint8Array(t).buffer};const BR=LR,FR=io;function tc(r){this.mode=FR.BYTE,typeof r=="string"&&(r=BR(r)),this.data=new Uint8Array(r)}tc.getBitsLength=function(e){return e*8},tc.prototype.getLength=function(){return this.data.length},tc.prototype.getBitsLength=function(){return tc.getBitsLength(this.data.length)},tc.prototype.write=function(r){for(let e=0,t=this.data.length;e=33088&&t<=40956)t-=33088;else if(t>=57408&&t<=60351)t-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` +-Make sure your charset is UTF-8`);t=(t>>>8&255)*192+(t&255),r.put(t,13)}};var HR=rc,Iw={exports:{}};(function(r){var e={single_source_shortest_paths:function(t,i,n){var s={},a={};a[i]=0;var f=e.PriorityQueue.make();f.push(i,0);for(var h,u,g,w,P,M,O,$,W;!f.empty();){h=f.pop(),u=h.value,w=h.cost,P=t[u]||{};for(g in P)P.hasOwnProperty(g)&&(M=P[g],O=w+M,$=a[g],W=typeof a[g]>"u",(W||$>O)&&(a[g]=O,f.push(g,O),s[g]=u))}if(typeof n<"u"&&typeof a[n]>"u"){var H=["Could not find a path from ",i," to ",n,"."].join("");throw new Error(H)}return s},extract_shortest_path_from_predecessor_list:function(t,i){for(var n=[],s=i;s;)n.push(s),t[s],s=t[s];return n.reverse(),n},find_path:function(t,i,n){var s=e.single_source_shortest_paths(t,i,n);return e.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(t){var i=e.PriorityQueue,n={},s;t=t||{};for(s in i)i.hasOwnProperty(s)&&(n[s]=i[s]);return n.queue=[],n.sorter=t.sorter||i.default_sorter,n},default_sorter:function(t,i){return t.cost-i.cost},push:function(t,i){var n={value:t,cost:i};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};r.exports=e})(Iw),function(r){const e=io,t=TR,i=NR,n=UR,s=HR,a=os,f=qi,h=Iw.exports;function u(H){return unescape(encodeURIComponent(H)).length}function g(H,F,Y){const B=[];let z;for(;(z=H.exec(Y))!==null;)B.push({data:z[0],index:z.index,mode:F,length:z[0].length});return B}function w(H){const F=g(a.NUMERIC,e.NUMERIC,H),Y=g(a.ALPHANUMERIC,e.ALPHANUMERIC,H);let B,z;return f.isKanjiModeEnabled()?(B=g(a.BYTE,e.BYTE,H),z=g(a.KANJI,e.KANJI,H)):(B=g(a.BYTE_KANJI,e.BYTE,H),z=[]),F.concat(Y,B,z).sort(function(_,U){return _.index-U.index}).map(function(_){return{data:_.data,mode:_.mode,length:_.length}})}function P(H,F){switch(F){case e.NUMERIC:return t.getBitsLength(H);case e.ALPHANUMERIC:return i.getBitsLength(H);case e.KANJI:return s.getBitsLength(H);case e.BYTE:return n.getBitsLength(H)}}function M(H){return H.reduce(function(F,Y){const B=F.length-1>=0?F[F.length-1]:null;return B&&B.mode===Y.mode?(F[F.length-1].data+=Y.data,F):(F.push(Y),F)},[])}function O(H){const F=[];for(let Y=0;Y=0&&f<=6&&(h===0||h===6)||h>=0&&h<=6&&(f===0||f===6)||f>=2&&f<=4&&h>=2&&h<=4?r.set(s+f,a+h,!0,!0):r.set(s+f,a+h,!1,!0))}}function QR(r){const e=r.size;for(let t=8;t>f&1)===1,r.set(n,s,a,!0),r.set(s,n,a,!0)}function wp(r,e,t){const i=r.size,n=GR.getEncodedBits(e,t);let s,a;for(s=0;s<15;s++)a=(n>>s&1)===1,s<6?r.set(s,8,a,!0):s<8?r.set(s+1,8,a,!0):r.set(i-15+s,8,a,!0),s<8?r.set(8,i-s-1,a,!0):s<9?r.set(8,15-s-1+1,a,!0):r.set(8,15-s-1,a,!0);r.set(i-8,8,1,!0)}function eT(r,e){const t=r.size;let i=-1,n=t-1,s=7,a=0;for(let f=t-1;f>0;f-=2)for(f===6&&f--;;){for(let h=0;h<2;h++)if(!r.isReserved(n,f-h)){let u=!1;a>>s&1)===1),r.set(n,f-h,u),s--,s===-1&&(a++,s=7)}if(n+=i,n<0||t<=n){n-=i,i=-i;break}}}function tT(r,e,t){const i=new kR;t.forEach(function(h){i.put(h.mode.bit,4),i.put(h.getLength(),YR.getCharCountIndicator(h.mode,r)),h.write(i)});const n=Oh.getSymbolTotalCodewords(r),s=mp.getTotalCodewordsCount(r,e),a=(n-s)*8;for(i.getLengthInBits()+4<=a&&i.put(0,4);i.getLengthInBits()%8!==0;)i.putBit(0);const f=(a-i.getLengthInBits())/8;for(let h=0;hr??Mr;var Sf={},DR=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},mw={},zi={};let hp;const OR=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];zi.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},zi.getSymbolTotalCodewords=function(e){return OR[e]},zi.getBCHDigit=function(r){let e=0;for(;r!==0;)e++,r>>>=1;return e},zi.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');hp=e},zi.isKanjiModeEnabled=function(){return typeof hp<"u"},zi.toSJIS=function(e){return hp(e)};var Ch={};(function(r){r.L={bit:1},r.M={bit:0},r.Q={bit:3},r.H={bit:2};function e(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return r.L;case"m":case"medium":return r.M;case"q":case"quartile":return r.Q;case"h":case"high":return r.H;default:throw new Error("Unknown EC Level: "+t)}}r.isValid=function(i){return i&&typeof i.bit<"u"&&i.bit>=0&&i.bit<4},r.from=function(i,n){if(r.isValid(i))return i;try{return e(i)}catch{return n}}})(Ch);function bw(){this.buffer=[],this.length=0}bw.prototype={get:function(r){const e=Math.floor(r/8);return(this.buffer[e]>>>7-r%8&1)===1},put:function(r,e){for(let t=0;t>>e-t-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),r&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var RR=bw;function If(r){if(!r||r<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=r,this.data=new Uint8Array(r*r),this.reservedBit=new Uint8Array(r*r)}If.prototype.set=function(r,e,t,i){const n=r*this.size+e;this.data[n]=t,i&&(this.reservedBit[n]=!0)},If.prototype.get=function(r,e){return this.data[r*this.size+e]},If.prototype.xor=function(r,e,t){this.data[r*this.size+e]^=t},If.prototype.isReserved=function(r,e){return this.reservedBit[r*this.size+e]};var TR=If,ww={};(function(r){const e=zi.getSymbolSize;r.getRowColCoords=function(i){if(i===1)return[];const n=Math.floor(i/7)+2,s=e(i),a=s===145?26:Math.ceil((s-13)/(2*n-2))*2,f=[s-7];for(let h=1;h=0&&n<=7},r.from=function(n){return r.isValid(n)?parseInt(n,10):void 0},r.getPenaltyN1=function(n){const s=n.size;let a=0,f=0,h=0,u=null,g=null;for(let w=0;w=5&&(a+=e.N1+(f-5)),u=C,f=1),C=n.get(M,w),C===g?h++:(h>=5&&(a+=e.N1+(h-5)),g=C,h=1)}f>=5&&(a+=e.N1+(f-5)),h>=5&&(a+=e.N1+(h-5))}return a},r.getPenaltyN2=function(n){const s=n.size;let a=0;for(let f=0;f=10&&(f===1488||f===93)&&a++,h=h<<1&2047|n.get(g,u),g>=10&&(h===1488||h===93)&&a++}return a*e.N3},r.getPenaltyN4=function(n){let s=0;const a=n.data.length;for(let h=0;h=0;){const a=s[0];for(let h=0;h0){const s=new Uint8Array(this.degree);return s.set(i,n),s}return i};var NR=up,Sw={},no={},dp={};dp.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var os={};const Iw="[0-9]+",LR="[A-Z $%*+\\-./:]+";let Cf="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Cf=Cf.replace(/u/g,"\\u");const BR="(?:(?![A-Z0-9 $%*+\\-./:]|"+Cf+`)(?:.|[\r ++]))+`;os.KANJI=new RegExp(Cf,"g"),os.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),os.BYTE=new RegExp(BR,"g"),os.NUMERIC=new RegExp(Iw,"g"),os.ALPHANUMERIC=new RegExp(LR,"g");const FR=new RegExp("^"+Cf+"$"),UR=new RegExp("^"+Iw+"$"),qR=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");os.testKanji=function(e){return FR.test(e)},os.testNumeric=function(e){return UR.test(e)},os.testAlphanumeric=function(e){return qR.test(e)},function(r){const e=dp,t=os;r.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},r.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},r.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},r.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},r.MIXED={bit:-1},r.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},r.getBestModeForData=function(s){return t.testNumeric(s)?r.NUMERIC:t.testAlphanumeric(s)?r.ALPHANUMERIC:t.testKanji(s)?r.KANJI:r.BYTE},r.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},r.isValid=function(s){return s&&s.bit&&s.ccBits};function i(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return r.NUMERIC;case"alphanumeric":return r.ALPHANUMERIC;case"kanji":return r.KANJI;case"byte":return r.BYTE;default:throw new Error("Unknown mode: "+n)}}r.from=function(s,a){if(r.isValid(s))return s;try{return i(s)}catch{return a}}}(no),function(r){const e=zi,t=Ph,i=Ch,n=no,s=dp,a=7973,f=e.getBCHDigit(a);function h(M,C,O){for(let $=1;$<=40;$++)if(C<=r.getCapacity($,O,M))return $}function u(M,C){return n.getCharCountIndicator(M,C)+4}function g(M,C){let O=0;return M.forEach(function($){const j=u($.mode,C);O+=j+$.getBitsLength()}),O}function w(M,C){for(let O=1;O<=40;O++)if(g(M,O)<=r.getCapacity(O,C,n.MIXED))return O}r.from=function(C,O){return s.isValid(C)?parseInt(C,10):O},r.getCapacity=function(C,O,$){if(!s.isValid(C))throw new Error("Invalid QR Code version");typeof $>"u"&&($=n.BYTE);const j=e.getSymbolTotalCodewords(C),H=t.getTotalCodewordsCount(C,O),F=(j-H)*8;if($===n.MIXED)return F;const G=F-u($,C);switch($){case n.NUMERIC:return Math.floor(G/10*3);case n.ALPHANUMERIC:return Math.floor(G/11*2);case n.KANJI:return Math.floor(G/13);case n.BYTE:default:return Math.floor(G/8)}},r.getBestVersionForData=function(C,O){let $;const j=i.from(O,i.M);if(Array.isArray(C)){if(C.length>1)return w(C,j);if(C.length===0)return 1;$=C[0]}else $=C;return h($.mode,$.getLength(),j)},r.getEncodedBits=function(C){if(!s.isValid(C)||C<7)throw new Error("Invalid QR Code version");let O=C<<12;for(;e.getBCHDigit(O)-f>=0;)O^=a<=0;)n^=Cw<0&&(i=this.data.substr(t),n=parseInt(i,10),e.put(n,s*3+1))};var kR=ec;const jR=no,gp=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function tc(r){this.mode=jR.ALPHANUMERIC,this.data=r}tc.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)},tc.prototype.getLength=function(){return this.data.length},tc.prototype.getBitsLength=function(){return tc.getBitsLength(this.data.length)},tc.prototype.write=function(e){let t;for(t=0;t+2<=this.data.length;t+=2){let i=gp.indexOf(this.data[t])*45;i+=gp.indexOf(this.data[t+1]),e.put(i,11)}this.data.length%2&&e.put(gp.indexOf(this.data[t]),6)};var WR=tc,KR=function(e){for(var t=[],i=e.length,n=0;n=55296&&s<=56319&&i>n+1){var a=e.charCodeAt(n+1);a>=56320&&a<=57343&&(s=(s-55296)*1024+a-56320+65536,n+=1)}if(s<128){t.push(s);continue}if(s<2048){t.push(s>>6|192),t.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){t.push(s>>12|224),t.push(s>>6&63|128),t.push(s&63|128);continue}if(s>=65536&&s<=1114111){t.push(s>>18|240),t.push(s>>12&63|128),t.push(s>>6&63|128),t.push(s&63|128);continue}t.push(239,191,189)}return new Uint8Array(t).buffer};const VR=KR,GR=no;function rc(r){this.mode=GR.BYTE,typeof r=="string"&&(r=VR(r)),this.data=new Uint8Array(r)}rc.getBitsLength=function(e){return e*8},rc.prototype.getLength=function(){return this.data.length},rc.prototype.getBitsLength=function(){return rc.getBitsLength(this.data.length)},rc.prototype.write=function(r){for(let e=0,t=this.data.length;e=33088&&t<=40956)t-=33088;else if(t>=57408&&t<=60351)t-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` ++Make sure your charset is UTF-8`);t=(t>>>8&255)*192+(t&255),r.put(t,13)}};var ZR=ic,Ow={exports:{}};(function(r){var e={single_source_shortest_paths:function(t,i,n){var s={},a={};a[i]=0;var f=e.PriorityQueue.make();f.push(i,0);for(var h,u,g,w,M,C,O,$,j;!f.empty();){h=f.pop(),u=h.value,w=h.cost,M=t[u]||{};for(g in M)M.hasOwnProperty(g)&&(C=M[g],O=w+C,$=a[g],j=typeof a[g]>"u",(j||$>O)&&(a[g]=O,f.push(g,O),s[g]=u))}if(typeof n<"u"&&typeof a[n]>"u"){var H=["Could not find a path from ",i," to ",n,"."].join("");throw new Error(H)}return s},extract_shortest_path_from_predecessor_list:function(t,i){for(var n=[],s=i;s;)n.push(s),t[s],s=t[s];return n.reverse(),n},find_path:function(t,i,n){var s=e.single_source_shortest_paths(t,i,n);return e.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(t){var i=e.PriorityQueue,n={},s;t=t||{};for(s in i)i.hasOwnProperty(s)&&(n[s]=i[s]);return n.queue=[],n.sorter=t.sorter||i.default_sorter,n},default_sorter:function(t,i){return t.cost-i.cost},push:function(t,i){var n={value:t,cost:i};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};r.exports=e})(Ow),function(r){const e=no,t=kR,i=WR,n=YR,s=ZR,a=os,f=zi,h=Ow.exports;function u(H){return unescape(encodeURIComponent(H)).length}function g(H,F,G){const B=[];let z;for(;(z=H.exec(G))!==null;)B.push({data:z[0],index:z.index,mode:F,length:z[0].length});return B}function w(H){const F=g(a.NUMERIC,e.NUMERIC,H),G=g(a.ALPHANUMERIC,e.ALPHANUMERIC,H);let B,z;return f.isKanjiModeEnabled()?(B=g(a.BYTE,e.BYTE,H),z=g(a.KANJI,e.KANJI,H)):(B=g(a.BYTE_KANJI,e.BYTE,H),z=[]),F.concat(G,B,z).sort(function(_,U){return _.index-U.index}).map(function(_){return{data:_.data,mode:_.mode,length:_.length}})}function M(H,F){switch(F){case e.NUMERIC:return t.getBitsLength(H);case e.ALPHANUMERIC:return i.getBitsLength(H);case e.KANJI:return s.getBitsLength(H);case e.BYTE:return n.getBitsLength(H)}}function C(H){return H.reduce(function(F,G){const B=F.length-1>=0?F[F.length-1]:null;return B&&B.mode===G.mode?(F[F.length-1].data+=G.data,F):(F.push(G),F)},[])}function O(H){const F=[];for(let G=0;G=0&&f<=6&&(h===0||h===6)||h>=0&&h<=6&&(f===0||f===6)||f>=2&&f<=4&&h>=2&&h<=4?r.set(s+f,a+h,!0,!0):r.set(s+f,a+h,!1,!0))}}function aT(r){const e=r.size;for(let t=8;t>f&1)===1,r.set(n,s,a,!0),r.set(s,n,a,!0)}function yp(r,e,t){const i=r.size,n=nT.getEncodedBits(e,t);let s,a;for(s=0;s<15;s++)a=(n>>s&1)===1,s<6?r.set(s,8,a,!0):s<8?r.set(s+1,8,a,!0):r.set(i-15+s,8,a,!0),s<8?r.set(8,i-s-1,a,!0):s<9?r.set(8,15-s-1+1,a,!0):r.set(8,15-s-1,a,!0);r.set(i-8,8,1,!0)}function lT(r,e){const t=r.size;let i=-1,n=t-1,s=7,a=0;for(let f=t-1;f>0;f-=2)for(f===6&&f--;;){for(let h=0;h<2;h++)if(!r.isReserved(n,f-h)){let u=!1;a>>s&1)===1),r.set(n,f-h,u),s--,s===-1&&(a++,s=7)}if(n+=i,n<0||t<=n){n-=i,i=-i;break}}}function hT(r,e,t){const i=new XR;t.forEach(function(h){i.put(h.mode.bit,4),i.put(h.getLength(),sT.getCharCountIndicator(h.mode,r)),h.write(i)});const n=$h.getSymbolTotalCodewords(r),s=bp.getTotalCodewordsCount(r,e),a=(n-s)*8;for(i.getLengthInBits()+4<=a&&i.put(0,4);i.getLengthInBits()%8!==0;)i.putBit(0);const f=(a-i.getLengthInBits())/8;for(let h=0;h=7&&XR(h,e),eT(h,a),isNaN(i)&&(i=vp.getBestMask(h,wp.bind(null,h,t))),vp.applyMask(i,h),wp(h,t,i),{modules:h,version:e,errorCorrectionLevel:t,maskPattern:i,segments:n}}uw.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let i=gp.M,n,s;return typeof t<"u"&&(i=gp.from(t.errorCorrectionLevel,gp.M),n=Rh.from(t.version),s=vp.from(t.maskPattern),t.toSJISFunc&&Oh.setToSJISFunction(t.toSJISFunc)),iT(e,n,i,s)};var Mw={},yp={};(function(r){function e(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let i=t.slice().replace("#","").split("");if(i.length<3||i.length===5||i.length>8)throw new Error("Invalid hex color: "+t);(i.length===3||i.length===4)&&(i=Array.prototype.concat.apply([],i.map(function(s){return[s,s]}))),i.length===6&&i.push("F","F");const n=parseInt(i.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+i.slice(0,6).join("")}}r.getOptions=function(i){i||(i={}),i.color||(i.color={});const n=typeof i.margin>"u"||i.margin===null||i.margin<0?4:i.margin,s=i.width&&i.width>=21?i.width:void 0,a=i.scale||4;return{width:s,scale:s?4:a,margin:n,color:{dark:e(i.color.dark||"#000000ff"),light:e(i.color.light||"#ffffffff")},type:i.type,rendererOpts:i.rendererOpts||{}}},r.getScale=function(i,n){return n.width&&n.width>=i+n.margin*2?n.width/(i+n.margin*2):n.scale},r.getImageWidth=function(i,n){const s=r.getScale(i,n);return Math.floor((i+n.margin*2)*s)},r.qrToImageData=function(i,n,s){const a=n.modules.size,f=n.modules.data,h=r.getScale(a,s),u=Math.floor((a+s.margin*2)*h),g=s.margin*h,w=[s.color.light,s.color.dark];for(let P=0;P=g&&M>=g&&P"u"&&(!a||!a.getContext)&&(h=a,a=void 0),a||(u=i()),h=e.getOptions(h);const g=e.getImageWidth(s.modules.size,h),w=u.getContext("2d"),P=w.createImageData(g,g);return e.qrToImageData(P.data,s,h),t(w,u,g),w.putImageData(P,0,0),u},r.renderToDataURL=function(s,a,f){let h=f;typeof h>"u"&&(!a||!a.getContext)&&(h=a,a=void 0),h||(h={});const u=r.render(s,a,h),g=h.type||"image/png",w=h.rendererOpts||{};return u.toDataURL(g,w.quality)}}(Mw);var Cw={};const nT=yp;function Pw(r,e){const t=r.a/255,i=e+'="'+r.hex+'"';return t<1?i+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':i}function _p(r,e,t){let i=r+e;return typeof t<"u"&&(i+=" "+t),i}function sT(r,e,t){let i="",n=0,s=!1,a=0;for(let f=0;f0&&h>0&&r[f-1]||(i+=s?_p("M",h+t,.5+u+t):_p("m",n,0),n=0,s=!1),h+1':"",u="',g='viewBox="0 0 '+f+" "+f+'"',P=''+h+u+` +-`;return typeof i=="function"&&i(null,P),P};const oT=yR,xp=uw,Dw=Mw,aT=Cw;function Ap(r,e,t,i,n){const s=[].slice.call(arguments,1),a=s.length,f=typeof s[a-1]=="function";if(!f&&!oT())throw new Error("Callback required as last argument");if(f){if(a<2)throw new Error("Too few arguments provided");a===2?(n=t,t=e,e=i=void 0):a===3&&(e.getContext&&typeof n>"u"?(n=i,i=void 0):(n=i,i=t,t=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(t=e,e=i=void 0):a===2&&!e.getContext&&(i=t,t=e,e=void 0),new Promise(function(h,u){try{const g=xp.create(t,i);h(r(g,e,i))}catch(g){u(g)}})}try{const h=xp.create(t,i);n(null,r(h,e,i))}catch(h){n(h)}}Ef.create=xp.create,Ef.toCanvas=Ap.bind(null,Dw.render),Ef.toDataURL=Ap.bind(null,Dw.renderToDataURL),Ef.toString=Ap.bind(null,function(r,e,t){return aT.render(r,t)});var cT=Object.defineProperty,Ow=Object.getOwnPropertySymbols,fT=Object.prototype.hasOwnProperty,lT=Object.prototype.propertyIsEnumerable,Rw=(r,e,t)=>e in r?cT(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ep=(r,e)=>{for(var t in e||(e={}))fT.call(e,t)&&Rw(r,t,e[t]);if(Ow)for(var t of Ow(e))lT.call(e,t)&&Rw(r,t,e[t]);return r};function hT(){var r;const e=(r=Zs.state.themeMode)!=null?r:"dark",i={light:{foreground:{1:"rgb(20,20,20)",2:"rgb(121,134,134)",3:"rgb(158,169,169)"},background:{1:"rgb(255,255,255)",2:"rgb(241,243,243)",3:"rgb(228,231,231)"},overlay:"rgba(0,0,0,0.1)"},dark:{foreground:{1:"rgb(228,231,231)",2:"rgb(148,158,158)",3:"rgb(110,119,119)"},background:{1:"rgb(20,20,20)",2:"rgb(39,42,42)",3:"rgb(59,64,64)"},overlay:"rgba(255,255,255,0.1)"}}[e];return{"--wcm-color-fg-1":i.foreground[1],"--wcm-color-fg-2":i.foreground[2],"--wcm-color-fg-3":i.foreground[3],"--wcm-color-bg-1":i.background[1],"--wcm-color-bg-2":i.background[2],"--wcm-color-bg-3":i.background[3],"--wcm-color-overlay":i.overlay}}function Tw(){return{"--wcm-accent-color":"#3396FF","--wcm-accent-fill-color":"#FFFFFF","--wcm-z-index":"89","--wcm-background-color":"#3396FF","--wcm-background-border-radius":"8px","--wcm-container-border-radius":"30px","--wcm-wallet-icon-border-radius":"15px","--wcm-wallet-icon-large-border-radius":"30px","--wcm-wallet-icon-small-border-radius":"7px","--wcm-input-border-radius":"28px","--wcm-button-border-radius":"10px","--wcm-notification-border-radius":"36px","--wcm-secondary-button-border-radius":"28px","--wcm-icon-button-border-radius":"50%","--wcm-button-hover-highlight-border-radius":"10px","--wcm-text-big-bold-size":"20px","--wcm-text-big-bold-weight":"600","--wcm-text-big-bold-line-height":"24px","--wcm-text-big-bold-letter-spacing":"-0.03em","--wcm-text-big-bold-text-transform":"none","--wcm-text-xsmall-bold-size":"10px","--wcm-text-xsmall-bold-weight":"700","--wcm-text-xsmall-bold-line-height":"12px","--wcm-text-xsmall-bold-letter-spacing":"0.02em","--wcm-text-xsmall-bold-text-transform":"uppercase","--wcm-text-xsmall-regular-size":"12px","--wcm-text-xsmall-regular-weight":"600","--wcm-text-xsmall-regular-line-height":"14px","--wcm-text-xsmall-regular-letter-spacing":"-0.03em","--wcm-text-xsmall-regular-text-transform":"none","--wcm-text-small-thin-size":"14px","--wcm-text-small-thin-weight":"500","--wcm-text-small-thin-line-height":"16px","--wcm-text-small-thin-letter-spacing":"-0.03em","--wcm-text-small-thin-text-transform":"none","--wcm-text-small-regular-size":"14px","--wcm-text-small-regular-weight":"600","--wcm-text-small-regular-line-height":"16px","--wcm-text-small-regular-letter-spacing":"-0.03em","--wcm-text-small-regular-text-transform":"none","--wcm-text-medium-regular-size":"16px","--wcm-text-medium-regular-weight":"600","--wcm-text-medium-regular-line-height":"20px","--wcm-text-medium-regular-letter-spacing":"-0.03em","--wcm-text-medium-regular-text-transform":"none","--wcm-font-family":"-apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, 'Helvetica Neue', sans-serif","--wcm-font-feature-settings":"'tnum' on, 'lnum' on, 'case' on","--wcm-success-color":"rgb(38,181,98)","--wcm-error-color":"rgb(242, 90, 103)","--wcm-overlay-background-color":"rgba(0, 0, 0, 0.3)","--wcm-overlay-backdrop-filter":"none"}}const Lt={getPreset(r){return Tw()[r]},setTheme(){const r=document.querySelector(":root"),{themeVariables:e}=Zs.state;if(r){const t=Ep(Ep(Ep({},hT()),Tw()),e);Object.entries(t).forEach(([i,n])=>r.style.setProperty(i,n))}},globalCss:jt`*,::after,::before{margin:0;padding:0;box-sizing:border-box;font-style:normal;text-rendering:optimizeSpeed;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-tap-highlight-color:transparent;backface-visibility:hidden}button{cursor:pointer;display:flex;justify-content:center;align-items:center;position:relative;border:none;background-color:transparent;transition:all .2s ease}@media (hover:hover) and (pointer:fine){button:active{transition:all .1s ease;transform:scale(.93)}}button::after{content:'';position:absolute;top:0;bottom:0;left:0;right:0;transition:background-color,.2s ease}button:disabled{cursor:not-allowed}button svg,button wcm-text{position:relative;z-index:1}input{border:none;outline:0;appearance:none}img{display:block}::selection{color:var(--wcm-accent-fill-color);background:var(--wcm-accent-color)}`},uT=jt`button{border-radius:var(--wcm-secondary-button-border-radius);height:28px;padding:0 10px;background-color:var(--wcm-accent-color)}button path{fill:var(--wcm-accent-fill-color)}button::after{border-radius:inherit;border:1px solid var(--wcm-color-overlay)}button:disabled::after{background-color:transparent}.wcm-icon-left svg{margin-right:5px}.wcm-icon-right svg{margin-left:5px}button:active::after{background-color:var(--wcm-color-overlay)}.wcm-ghost,.wcm-ghost:active::after,.wcm-outline{background-color:transparent}.wcm-ghost:active{opacity:.5}@media(hover:hover){button:hover::after{background-color:var(--wcm-color-overlay)}.wcm-ghost:hover::after{background-color:transparent}.wcm-ghost:hover{opacity:.5}}button:disabled{background-color:var(--wcm-color-bg-3);pointer-events:none}.wcm-ghost::after{border-color:transparent}.wcm-ghost path{fill:var(--wcm-color-fg-2)}.wcm-outline path{fill:var(--wcm-accent-color)}.wcm-outline:disabled{background-color:transparent;opacity:.5}`;var dT=Object.defineProperty,pT=Object.getOwnPropertyDescriptor,ic=(r,e,t,i)=>{for(var n=i>1?void 0:i?pT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&dT(e,t,n),n};let no=class extends Ct{constructor(){super(...arguments),this.disabled=!1,this.iconLeft=void 0,this.iconRight=void 0,this.onClick=()=>null,this.variant="default"}render(){const r={"wcm-icon-left":this.iconLeft!==void 0,"wcm-icon-right":this.iconRight!==void 0,"wcm-ghost":this.variant==="ghost","wcm-outline":this.variant==="outline"};let e="inverse";return this.variant==="ghost"&&(e="secondary"),this.variant==="outline"&&(e="accent"),Ee``}};no.styles=[Lt.globalCss,uT],ic([At({type:Boolean})],no.prototype,"disabled",2),ic([At()],no.prototype,"iconLeft",2),ic([At()],no.prototype,"iconRight",2),ic([At()],no.prototype,"onClick",2),ic([At()],no.prototype,"variant",2),no=ic([Ut("wcm-button")],no);const gT=jt`:host{display:inline-block}button{padding:0 15px 1px;height:40px;border-radius:var(--wcm-button-border-radius);color:var(--wcm-accent-fill-color);background-color:var(--wcm-accent-color)}button::after{content:'';top:0;bottom:0;left:0;right:0;position:absolute;background-color:transparent;border-radius:inherit;transition:background-color .2s ease;border:1px solid var(--wcm-color-overlay)}button:active::after{background-color:var(--wcm-color-overlay)}button:disabled{padding-bottom:0;background-color:var(--wcm-color-bg-3);color:var(--wcm-color-fg-3)}.wcm-secondary{color:var(--wcm-accent-color);background-color:transparent}.wcm-secondary::after{display:none}@media(hover:hover){button:hover::after{background-color:var(--wcm-color-overlay)}}`;var vT=Object.defineProperty,mT=Object.getOwnPropertyDescriptor,Sp=(r,e,t,i)=>{for(var n=i>1?void 0:i?mT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&vT(e,t,n),n};let Cf=class extends Ct{constructor(){super(...arguments),this.disabled=!1,this.variant="primary"}render(){const r={"wcm-secondary":this.variant==="secondary"};return Ee``}};Cf.styles=[Lt.globalCss,gT],Sp([At({type:Boolean})],Cf.prototype,"disabled",2),Sp([At()],Cf.prototype,"variant",2),Cf=Sp([Ut("wcm-button-big")],Cf);const bT=jt`:host{background-color:var(--wcm-color-bg-2);border-top:1px solid var(--wcm-color-bg-3)}div{padding:10px 20px;display:inherit;flex-direction:inherit;align-items:inherit;width:inherit;justify-content:inherit}`;var wT=Object.defineProperty,yT=Object.getOwnPropertyDescriptor,_T=(r,e,t,i)=>{for(var n=i>1?void 0:i?yT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&wT(e,t,n),n};let Ip=class extends Ct{render(){return Ee`
`}};Ip.styles=[Lt.globalCss,bT],Ip=_T([Ut("wcm-info-footer")],Ip);const Kt={CROSS_ICON:gr``,WALLET_CONNECT_LOGO:gr``,WALLET_CONNECT_ICON:gr``,WALLET_CONNECT_ICON_COLORED:gr``,BACK_ICON:gr``,COPY_ICON:gr``,RETRY_ICON:gr``,DESKTOP_ICON:gr``,MOBILE_ICON:gr``,ARROW_DOWN_ICON:gr``,ARROW_UP_RIGHT_ICON:gr``,ARROW_RIGHT_ICON:gr``,QRCODE_ICON:gr``,SCAN_ICON:gr``,CHECKMARK_ICON:gr``,SEARCH_ICON:gr``,WALLET_PLACEHOLDER:gr``,GLOBE_ICON:gr``},xT=jt`.wcm-toolbar-placeholder{top:0;bottom:0;left:0;right:0;width:100%;position:absolute;display:block;pointer-events:none;height:100px;border-radius:calc(var(--wcm-background-border-radius) * .9);background-color:var(--wcm-background-color);background-position:center;background-size:cover}.wcm-toolbar{height:38px;display:flex;position:relative;margin:5px 15px 5px 5px;justify-content:space-between;align-items:center}.wcm-toolbar img,.wcm-toolbar svg{height:28px;object-position:left center;object-fit:contain}#wcm-wc-logo path{fill:var(--wcm-accent-fill-color)}button{width:28px;height:28px;border-radius:var(--wcm-icon-button-border-radius);border:0;display:flex;justify-content:center;align-items:center;cursor:pointer;background-color:var(--wcm-color-bg-1);box-shadow:0 0 0 1px var(--wcm-color-overlay)}button:active{background-color:var(--wcm-color-bg-2)}button svg{display:block;object-position:center}button path{fill:var(--wcm-color-fg-1)}.wcm-toolbar div{display:flex}@media(hover:hover){button:hover{background-color:var(--wcm-color-bg-2)}}`;var AT=Object.defineProperty,ET=Object.getOwnPropertyDescriptor,ST=(r,e,t,i)=>{for(var n=i>1?void 0:i?ET(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&AT(e,t,n),n};let Mp=class extends Ct{render(){return Ee`
${Kt.WALLET_CONNECT_LOGO}
`}};Mp.styles=[Lt.globalCss,xT],Mp=ST([Ut("wcm-modal-backcard")],Mp);const IT=jt`main{padding:20px;padding-top:0;width:100%}`;var MT=Object.defineProperty,CT=Object.getOwnPropertyDescriptor,PT=(r,e,t,i)=>{for(var n=i>1?void 0:i?CT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&MT(e,t,n),n};let Cp=class extends Ct{render(){return Ee`
`}};Cp.styles=[Lt.globalCss,IT],Cp=PT([Ut("wcm-modal-content")],Cp);const DT=jt`footer{padding:10px;display:flex;flex-direction:column;align-items:inherit;justify-content:inherit;border-top:1px solid var(--wcm-color-bg-2)}`;var OT=Object.defineProperty,RT=Object.getOwnPropertyDescriptor,TT=(r,e,t,i)=>{for(var n=i>1?void 0:i?RT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&OT(e,t,n),n};let Pp=class extends Ct{render(){return Ee`
`}};Pp.styles=[Lt.globalCss,DT],Pp=TT([Ut("wcm-modal-footer")],Pp);const $T=jt`header{display:flex;justify-content:center;align-items:center;padding:20px;position:relative}.wcm-border{border-bottom:1px solid var(--wcm-color-bg-2);margin-bottom:20px}header button{padding:15px 20px}header button:active{opacity:.5}@media(hover:hover){header button:hover{opacity:.5}}.wcm-back-btn{position:absolute;left:0}.wcm-action-btn{position:absolute;right:0}path{fill:var(--wcm-accent-color)}`;var NT=Object.defineProperty,LT=Object.getOwnPropertyDescriptor,Pf=(r,e,t,i)=>{for(var n=i>1?void 0:i?LT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&NT(e,t,n),n};let Zo=class extends Ct{constructor(){super(...arguments),this.title="",this.onAction=void 0,this.actionIcon=void 0,this.border=!1}backBtnTemplate(){return Ee``}actionBtnTemplate(){return Ee``}render(){const r={"wcm-border":this.border},e=lr.state.history.length>1,t=this.title?Ee`${this.title}`:Ee``;return Ee`
${e?this.backBtnTemplate():null} ${t} ${this.onAction?this.actionBtnTemplate():null}
`}};Zo.styles=[Lt.globalCss,$T],Pf([At()],Zo.prototype,"title",2),Pf([At()],Zo.prototype,"onAction",2),Pf([At()],Zo.prototype,"actionIcon",2),Pf([At({type:Boolean})],Zo.prototype,"border",2),Zo=Pf([Ut("wcm-modal-header")],Zo);const pt={MOBILE_BREAKPOINT:600,WCM_RECENT_WALLET_DATA:"WCM_RECENT_WALLET_DATA",EXPLORER_WALLET_URL:"https://explorer.walletconnect.com/?type=wallet",getShadowRootElement(r,e){const t=r.renderRoot.querySelector(e);if(!t)throw new Error(`${e} not found`);return t},getWalletIcon({id:r,image_id:e}){const{walletImages:t}=Ui.state;return t?.[r]?t[r]:e?_i.getWalletImageUrl(e):""},getWalletName(r,e=!1){return e&&r.length>8?`${r.substring(0,8)}..`:r},isMobileAnimation(){return window.innerWidth<=pt.MOBILE_BREAKPOINT},async preloadImage(r){const e=new Promise((t,i)=>{const n=new Image;n.onload=t,n.onerror=i,n.crossOrigin="anonymous",n.src=r});return Promise.race([e,je.wait(3e3)])},getErrorMessage(r){return r instanceof Error?r.message:"Unknown Error"},debounce(r,e=500){let t;return(...i)=>{function n(){r(...i)}t&&clearTimeout(t),t=setTimeout(n,e)}},handleMobileLinking(r,e="_self"){const{walletConnectUri:t}=yr.state,{mobile:i,name:n}=r,s=i?.native,a=i?.universal;pt.setRecentWallet(r);function f(h){if(s){const u=je.formatNativeUrl(s,h,n);je.openHref(u,e)}else if(a){const u=je.formatUniversalUrl(a,h,n);je.openHref(u,e)}}t&&f(t)},handleAndroidLinking(){const{walletConnectUri:r}=yr.state;r&&(je.setWalletConnectAndroidDeepLink(r),je.openHref(r,je.isTelegram()?"_blank":"_self"))},async handleUriCopy(){const{walletConnectUri:r}=yr.state;if(r)try{await navigator.clipboard.writeText(r),Xs.openToast("Link copied","success")}catch{Xs.openToast("Failed to copy","error")}},getCustomImageUrls(){const{walletImages:r}=Ui.state,e=Object.values(r??{});return Object.values(e)},truncate(r,e=8){return r.length<=e?r:`${r.substring(0,4)}...${r.substring(r.length-4)}`},setRecentWallet(r){try{localStorage.setItem(pt.WCM_RECENT_WALLET_DATA,JSON.stringify(r))}catch{console.info("Unable to set recent wallet")}},getRecentWallet(){try{const r=localStorage.getItem(pt.WCM_RECENT_WALLET_DATA);return r?JSON.parse(r):void 0}catch{console.info("Unable to get recent wallet")}},caseSafeIncludes(r,e){return r.toUpperCase().includes(e.toUpperCase())},openWalletExplorerUrl(){je.openHref(pt.EXPLORER_WALLET_URL,"_blank")},getCachedRouterWalletPlatforms(){const{desktop:r,mobile:e}=je.getWalletRouterData(),t=!!r?.native,i=!!r?.universal,n=!!e?.native||!!e?.universal;return{isDesktop:t,isMobile:n,isWeb:i}},goToConnectingView(r){lr.setData({Wallet:r});const e=je.isMobile(),{isDesktop:t,isWeb:i,isMobile:n}=pt.getCachedRouterWalletPlatforms();e?n?(lr.push("MobileConnecting"),!je.isAndroid()&&je.isTelegram()&&this.handleMobileLinking(r,"_blank")):i?lr.push("WebConnecting"):lr.push("InstallWallet"):t?lr.push("DesktopConnecting"):i?lr.push("WebConnecting"):n?lr.push("MobileQrcodeConnecting"):lr.push("InstallWallet")}},BT=jt`.wcm-router{overflow:hidden;will-change:transform}.wcm-content{display:flex;flex-direction:column}`;var FT=Object.defineProperty,UT=Object.getOwnPropertyDescriptor,Dp=(r,e,t,i)=>{for(var n=i>1?void 0:i?UT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&FT(e,t,n),n};let Df=class extends Ct{constructor(){super(),this.view=lr.state.view,this.prevView=lr.state.view,this.unsubscribe=void 0,this.oldHeight="0px",this.resizeObserver=void 0,this.unsubscribe=lr.subscribe(r=>{this.view!==r.view&&this.onChangeRoute()})}firstUpdated(){this.resizeObserver=new ResizeObserver(([r])=>{const e=`${r.contentRect.height}px`;this.oldHeight!=="0px"&&Qo(this.routerEl,{height:[this.oldHeight,e]},{duration:.2}),this.oldHeight=e}),this.resizeObserver.observe(this.contentEl)}disconnectedCallback(){var r,e;(r=this.unsubscribe)==null||r.call(this),(e=this.resizeObserver)==null||e.disconnect()}get routerEl(){return pt.getShadowRootElement(this,".wcm-router")}get contentEl(){return pt.getShadowRootElement(this,".wcm-content")}viewTemplate(){switch(this.view){case"ConnectWallet":return Ee``;case"DesktopConnecting":return Ee``;case"MobileConnecting":return Ee``;case"WebConnecting":return Ee``;case"MobileQrcodeConnecting":return Ee``;case"WalletExplorer":return Ee``;case"Qrcode":return Ee``;case"InstallWallet":return Ee``;default:return Ee`
Not Found
`}}async onChangeRoute(){await Qo(this.routerEl,{opacity:[1,0],scale:[1,1.02]},{duration:.15,delay:.1}).finished,this.view=lr.state.view,Qo(this.routerEl,{opacity:[0,1],scale:[.99,1]},{duration:.37,delay:.05})}render(){return Ee`
${this.viewTemplate()}
`}};Df.styles=[Lt.globalCss,BT],Dp([xi()],Df.prototype,"view",2),Dp([xi()],Df.prototype,"prevView",2),Df=Dp([Ut("wcm-modal-router")],Df);const qT=jt`div{height:36px;width:max-content;display:flex;justify-content:center;align-items:center;padding:9px 15px 11px;position:absolute;top:12px;box-shadow:0 6px 14px -6px rgba(10,16,31,.3),0 10px 32px -4px rgba(10,16,31,.15);z-index:2;left:50%;transform:translateX(-50%);pointer-events:none;backdrop-filter:blur(20px) saturate(1.8);-webkit-backdrop-filter:blur(20px) saturate(1.8);border-radius:var(--wcm-notification-border-radius);border:1px solid var(--wcm-color-overlay);background-color:var(--wcm-color-overlay)}svg{margin-right:5px}@-moz-document url-prefix(){div{background-color:var(--wcm-color-bg-3)}}.wcm-success path{fill:var(--wcm-accent-color)}.wcm-error path{fill:var(--wcm-error-color)}`;var zT=Object.defineProperty,HT=Object.getOwnPropertyDescriptor,$w=(r,e,t,i)=>{for(var n=i>1?void 0:i?HT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&zT(e,t,n),n};let Th=class extends Ct{constructor(){super(),this.open=!1,this.unsubscribe=void 0,this.timeout=void 0,this.unsubscribe=Xs.subscribe(r=>{r.open?(this.open=!0,this.timeout=setTimeout(()=>Xs.closeToast(),2200)):(this.open=!1,clearTimeout(this.timeout))})}disconnectedCallback(){var r;(r=this.unsubscribe)==null||r.call(this),clearTimeout(this.timeout),Xs.closeToast()}render(){const{message:r,variant:e}=Xs.state,t={"wcm-success":e==="success","wcm-error":e==="error"};return this.open?Ee`
${e==="success"?Kt.CHECKMARK_ICON:null} ${e==="error"?Kt.CROSS_ICON:null}${r}
`:null}};Th.styles=[Lt.globalCss,qT],$w([xi()],Th.prototype,"open",2),Th=$w([Ut("wcm-modal-toast")],Th);const kT=.1,Nw=2.5,Is=7;function Op(r,e,t){return r===e?!1:(r-e<0?e-r:r-e)<=t+kT}function jT(r,e){const t=Array.prototype.slice.call(Ef.create(r,{errorCorrectionLevel:e}).modules.data,0),i=Math.sqrt(t.length);return t.reduce((n,s,a)=>(a%i===0?n.push([s]):n[n.length-1].push(s))&&n,[])}const WT={generate(r,e,t){const i="#141414",n="#ffffff",s=[],a=jT(r,"Q"),f=e/a.length,h=[{x:0,y:0},{x:1,y:0},{x:0,y:1}];h.forEach(({x:O,y:$})=>{const W=(a.length-Is)*f*O,H=(a.length-Is)*f*$,F=.45;for(let Y=0;Y`)}});const u=Math.floor((t+25)/f),g=a.length/2-u/2,w=a.length/2+u/2-1,P=[];a.forEach((O,$)=>{O.forEach((W,H)=>{if(a[$][H]&&!($a.length-(Is+1)&&Ha.length-(Is+1))&&!($>g&&$g&&H{M[O]?M[O].push($):M[O]=[$]}),Object.entries(M).map(([O,$])=>{const W=$.filter(H=>$.every(F=>!Op(H,F,f)));return[Number(O),W]}).forEach(([O,$])=>{$.forEach(W=>{s.push(gr``)})}),Object.entries(M).filter(([O,$])=>$.length>1).map(([O,$])=>{const W=$.filter(H=>$.some(F=>Op(H,F,f)));return[Number(O),W]}).map(([O,$])=>{$.sort((H,F)=>HY.some(B=>Op(H,B,f)));F?F.push(H):W.push([H])}return[O,W.map(H=>[H[0],H[H.length-1]])]}).forEach(([O,$])=>{$.forEach(([W,H])=>{s.push(gr``)})}),s}},KT=jt`@keyframes fadeIn{0%{opacity:0}100%{opacity:1}}div{position:relative;user-select:none;display:block;overflow:hidden;aspect-ratio:1/1;animation:fadeIn ease .2s}.wcm-dark{background-color:#fff;border-radius:var(--wcm-container-border-radius);padding:18px;box-shadow:0 2px 5px #000}svg:first-child,wcm-wallet-image{position:absolute;top:50%;left:50%;transform:translateY(-50%) translateX(-50%)}wcm-wallet-image{transform:translateY(-50%) translateX(-50%)}wcm-wallet-image{width:25%;height:25%;border-radius:var(--wcm-wallet-icon-border-radius)}svg:first-child{transform:translateY(-50%) translateX(-50%) scale(.9)}svg:first-child path:first-child{fill:var(--wcm-accent-color)}svg:first-child path:last-child{stroke:var(--wcm-color-overlay)}`;var VT=Object.defineProperty,GT=Object.getOwnPropertyDescriptor,nc=(r,e,t,i)=>{for(var n=i>1?void 0:i?GT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&VT(e,t,n),n};let Ms=class extends Ct{constructor(){super(...arguments),this.uri="",this.size=0,this.imageId=void 0,this.walletId=void 0,this.imageUrl=void 0}svgTemplate(){const e=Zs.state.themeMode==="light"?this.size:this.size-18*2;return gr`${WT.generate(this.uri,e,e/4)}`}render(){const r={"wcm-dark":Zs.state.themeMode==="dark"};return Ee`
${this.walletId||this.imageUrl?Ee``:Kt.WALLET_CONNECT_ICON_COLORED} ${this.svgTemplate()}
`}};Ms.styles=[Lt.globalCss,KT],nc([At()],Ms.prototype,"uri",2),nc([At({type:Number})],Ms.prototype,"size",2),nc([At()],Ms.prototype,"imageId",2),nc([At()],Ms.prototype,"walletId",2),nc([At()],Ms.prototype,"imageUrl",2),Ms=nc([Ut("wcm-qrcode")],Ms);const YT=jt`:host{position:relative;height:28px;width:80%}input{width:100%;height:100%;line-height:28px!important;border-radius:var(--wcm-input-border-radius);font-style:normal;font-family:-apple-system,system-ui,BlinkMacSystemFont,'Segoe UI',Roboto,Ubuntu,'Helvetica Neue',sans-serif;font-feature-settings:'case' on;font-weight:500;font-size:16px;letter-spacing:-.03em;padding:0 10px 0 34px;transition:.2s all ease;color:var(--wcm-color-fg-1);background-color:var(--wcm-color-bg-3);box-shadow:inset 0 0 0 1px var(--wcm-color-overlay);caret-color:var(--wcm-accent-color)}input::placeholder{color:var(--wcm-color-fg-2)}svg{left:10px;top:4px;pointer-events:none;position:absolute;width:20px;height:20px}input:focus-within{box-shadow:inset 0 0 0 1px var(--wcm-accent-color)}path{fill:var(--wcm-color-fg-2)}`;var JT=Object.defineProperty,QT=Object.getOwnPropertyDescriptor,Lw=(r,e,t,i)=>{for(var n=i>1?void 0:i?QT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&JT(e,t,n),n};let $h=class extends Ct{constructor(){super(...arguments),this.onChange=()=>null}render(){return Ee` ${Kt.SEARCH_ICON}`}};$h.styles=[Lt.globalCss,YT],Lw([At()],$h.prototype,"onChange",2),$h=Lw([Ut("wcm-search-input")],$h);const ZT=jt`@keyframes rotate{100%{transform:rotate(360deg)}}@keyframes dash{0%{stroke-dasharray:1,150;stroke-dashoffset:0}50%{stroke-dasharray:90,150;stroke-dashoffset:-35}100%{stroke-dasharray:90,150;stroke-dashoffset:-124}}svg{animation:rotate 2s linear infinite;display:flex;justify-content:center;align-items:center}svg circle{stroke-linecap:round;animation:dash 1.5s ease infinite;stroke:var(--wcm-accent-color)}`;var XT=Object.defineProperty,e$=Object.getOwnPropertyDescriptor,t$=(r,e,t,i)=>{for(var n=i>1?void 0:i?e$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&XT(e,t,n),n};let Rp=class extends Ct{render(){return Ee``}};Rp.styles=[Lt.globalCss,ZT],Rp=t$([Ut("wcm-spinner")],Rp);const r$=jt`span{font-style:normal;font-family:var(--wcm-font-family);font-feature-settings:var(--wcm-font-feature-settings)}.wcm-xsmall-bold{font-family:var(--wcm-text-xsmall-bold-font-family);font-weight:var(--wcm-text-xsmall-bold-weight);font-size:var(--wcm-text-xsmall-bold-size);line-height:var(--wcm-text-xsmall-bold-line-height);letter-spacing:var(--wcm-text-xsmall-bold-letter-spacing);text-transform:var(--wcm-text-xsmall-bold-text-transform)}.wcm-xsmall-regular{font-family:var(--wcm-text-xsmall-regular-font-family);font-weight:var(--wcm-text-xsmall-regular-weight);font-size:var(--wcm-text-xsmall-regular-size);line-height:var(--wcm-text-xsmall-regular-line-height);letter-spacing:var(--wcm-text-xsmall-regular-letter-spacing);text-transform:var(--wcm-text-xsmall-regular-text-transform)}.wcm-small-thin{font-family:var(--wcm-text-small-thin-font-family);font-weight:var(--wcm-text-small-thin-weight);font-size:var(--wcm-text-small-thin-size);line-height:var(--wcm-text-small-thin-line-height);letter-spacing:var(--wcm-text-small-thin-letter-spacing);text-transform:var(--wcm-text-small-thin-text-transform)}.wcm-small-regular{font-family:var(--wcm-text-small-regular-font-family);font-weight:var(--wcm-text-small-regular-weight);font-size:var(--wcm-text-small-regular-size);line-height:var(--wcm-text-small-regular-line-height);letter-spacing:var(--wcm-text-small-regular-letter-spacing);text-transform:var(--wcm-text-small-regular-text-transform)}.wcm-medium-regular{font-family:var(--wcm-text-medium-regular-font-family);font-weight:var(--wcm-text-medium-regular-weight);font-size:var(--wcm-text-medium-regular-size);line-height:var(--wcm-text-medium-regular-line-height);letter-spacing:var(--wcm-text-medium-regular-letter-spacing);text-transform:var(--wcm-text-medium-regular-text-transform)}.wcm-big-bold{font-family:var(--wcm-text-big-bold-font-family);font-weight:var(--wcm-text-big-bold-weight);font-size:var(--wcm-text-big-bold-size);line-height:var(--wcm-text-big-bold-line-height);letter-spacing:var(--wcm-text-big-bold-letter-spacing);text-transform:var(--wcm-text-big-bold-text-transform)}:host(*){color:var(--wcm-color-fg-1)}.wcm-color-primary{color:var(--wcm-color-fg-1)}.wcm-color-secondary{color:var(--wcm-color-fg-2)}.wcm-color-tertiary{color:var(--wcm-color-fg-3)}.wcm-color-inverse{color:var(--wcm-accent-fill-color)}.wcm-color-accnt{color:var(--wcm-accent-color)}.wcm-color-error{color:var(--wcm-error-color)}`;var i$=Object.defineProperty,n$=Object.getOwnPropertyDescriptor,Tp=(r,e,t,i)=>{for(var n=i>1?void 0:i?n$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&i$(e,t,n),n};let Of=class extends Ct{constructor(){super(...arguments),this.variant="medium-regular",this.color="primary"}render(){const r={"wcm-big-bold":this.variant==="big-bold","wcm-medium-regular":this.variant==="medium-regular","wcm-small-regular":this.variant==="small-regular","wcm-small-thin":this.variant==="small-thin","wcm-xsmall-regular":this.variant==="xsmall-regular","wcm-xsmall-bold":this.variant==="xsmall-bold","wcm-color-primary":this.color==="primary","wcm-color-secondary":this.color==="secondary","wcm-color-tertiary":this.color==="tertiary","wcm-color-inverse":this.color==="inverse","wcm-color-accnt":this.color==="accent","wcm-color-error":this.color==="error"};return Ee``}};Of.styles=[Lt.globalCss,r$],Tp([At()],Of.prototype,"variant",2),Tp([At()],Of.prototype,"color",2),Of=Tp([Ut("wcm-text")],Of);const s$=jt`button{width:100%;height:100%;border-radius:var(--wcm-button-hover-highlight-border-radius);display:flex;align-items:flex-start}button:active{background-color:var(--wcm-color-overlay)}@media(hover:hover){button:hover{background-color:var(--wcm-color-overlay)}}button>div{width:80px;padding:5px 0;display:flex;flex-direction:column;align-items:center}wcm-text{width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:center}wcm-wallet-image{height:60px;width:60px;transition:all .2s ease;border-radius:var(--wcm-wallet-icon-border-radius);margin-bottom:5px}.wcm-sublabel{margin-top:2px}`;var o$=Object.defineProperty,a$=Object.getOwnPropertyDescriptor,so=(r,e,t,i)=>{for(var n=i>1?void 0:i?a$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&o$(e,t,n),n};let as=class extends Ct{constructor(){super(...arguments),this.onClick=()=>null,this.name="",this.walletId="",this.label=void 0,this.imageId=void 0,this.installed=!1,this.recent=!1}sublabelTemplate(){return this.recent?Ee`RECENT`:this.installed?Ee`INSTALLED`:null}handleClick(){y3.click({name:"WALLET_BUTTON",walletId:this.walletId}),this.onClick()}render(){var r;return Ee``}};as.styles=[Lt.globalCss,s$],so([At()],as.prototype,"onClick",2),so([At()],as.prototype,"name",2),so([At()],as.prototype,"walletId",2),so([At()],as.prototype,"label",2),so([At()],as.prototype,"imageId",2),so([At({type:Boolean})],as.prototype,"installed",2),so([At({type:Boolean})],as.prototype,"recent",2),as=so([Ut("wcm-wallet-button")],as);const c$=jt`:host{display:block}div{overflow:hidden;position:relative;border-radius:inherit;width:100%;height:100%;background-color:var(--wcm-color-overlay)}svg{position:relative;width:100%;height:100%}div::after{content:'';position:absolute;top:0;bottom:0;left:0;right:0;border-radius:inherit;border:1px solid var(--wcm-color-overlay)}div img{width:100%;height:100%;object-fit:cover;object-position:center}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var f$=Object.defineProperty,l$=Object.getOwnPropertyDescriptor,Nh=(r,e,t,i)=>{for(var n=i>1?void 0:i?l$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&f$(e,t,n),n};let sc=class extends Ct{constructor(){super(...arguments),this.walletId="",this.imageId=void 0,this.imageUrl=void 0}render(){var r;const e=(r=this.imageUrl)!=null&&r.length?this.imageUrl:pt.getWalletIcon({id:this.walletId,image_id:this.imageId});return Ee`${e.length?Ee`
${this.id}
`:Kt.WALLET_PLACEHOLDER}`}};sc.styles=[Lt.globalCss,c$],Nh([At()],sc.prototype,"walletId",2),Nh([At()],sc.prototype,"imageId",2),Nh([At()],sc.prototype,"imageUrl",2),sc=Nh([Ut("wcm-wallet-image")],sc);var h$=Object.defineProperty,u$=Object.getOwnPropertyDescriptor,Bw=(r,e,t,i)=>{for(var n=i>1?void 0:i?u$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&h$(e,t,n),n};let $p=class extends Ct{constructor(){super(),this.preload=!0,this.preloadData()}async loadImages(r){try{r?.length&&await Promise.all(r.map(async e=>pt.preloadImage(e)))}catch{console.info("Unsuccessful attempt at preloading some images",r)}}async preloadListings(){if(Ui.state.enableExplorer){await _i.getRecomendedWallets(),yr.setIsDataLoaded(!0);const{recomendedWallets:r}=_i.state,e=r.map(t=>pt.getWalletIcon(t));await this.loadImages(e)}else yr.setIsDataLoaded(!0)}async preloadCustomImages(){const r=pt.getCustomImageUrls();await this.loadImages(r)}async preloadData(){try{this.preload&&(this.preload=!1,await Promise.all([this.preloadListings(),this.preloadCustomImages()]))}catch(r){console.error(r),Xs.openToast("Failed preloading","error")}}};Bw([xi()],$p.prototype,"preload",2),$p=Bw([Ut("wcm-explorer-context")],$p);var d$=Object.defineProperty,p$=Object.getOwnPropertyDescriptor,g$=(r,e,t,i)=>{for(var n=i>1?void 0:i?p$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&d$(e,t,n),n};let Fw=class extends Ct{constructor(){super(),this.unsubscribeTheme=void 0,Lt.setTheme(),this.unsubscribeTheme=Zs.subscribe(Lt.setTheme)}disconnectedCallback(){var r;(r=this.unsubscribeTheme)==null||r.call(this)}};Fw=g$([Ut("wcm-theme-context")],Fw);const v$=jt`@keyframes scroll{0%{transform:translate3d(0,0,0)}100%{transform:translate3d(calc(-70px * 9),0,0)}}.wcm-slider{position:relative;overflow-x:hidden;padding:10px 0;margin:0 -20px;width:calc(100% + 40px)}.wcm-track{display:flex;width:calc(70px * 18);animation:scroll 20s linear infinite;opacity:.7}.wcm-track svg{margin:0 5px}wcm-wallet-image{width:60px;height:60px;margin:0 5px;border-radius:var(--wcm-wallet-icon-border-radius)}.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between}.wcm-title{display:flex;align-items:center;margin-bottom:10px}.wcm-title svg{margin-right:6px}.wcm-title path{fill:var(--wcm-accent-color)}wcm-modal-footer .wcm-title{padding:0 10px}wcm-button-big{position:absolute;top:50%;left:50%;transform:translateY(-50%) translateX(-50%);filter:drop-shadow(0 0 17px var(--wcm-color-bg-1))}wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-info-footer wcm-text{text-align:center;margin-bottom:15px}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var m$=Object.defineProperty,b$=Object.getOwnPropertyDescriptor,w$=(r,e,t,i)=>{for(var n=i>1?void 0:i?b$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&m$(e,t,n),n};let Np=class extends Ct{onGoToQrcode(){lr.push("Qrcode")}render(){const{recomendedWallets:r}=_i.state,e=[...r,...r],t=je.RECOMMENDED_WALLET_AMOUNT*2;return Ee`
${Kt.MOBILE_ICON}WalletConnect
${[...Array(t)].map((i,n)=>{const s=e[n%e.length];return s?Ee``:Kt.WALLET_PLACEHOLDER})}
Select Wallet
Choose WalletConnect to see supported apps on your device`}};Np.styles=[Lt.globalCss,v$],Np=w$([Ut("wcm-android-wallet-selection")],Np);const y$=jt`@keyframes loading{to{stroke-dashoffset:0}}@keyframes shake{10%,90%{transform:translate3d(-1px,0,0)}20%,80%{transform:translate3d(1px,0,0)}30%,50%,70%{transform:translate3d(-2px,0,0)}40%,60%{transform:translate3d(2px,0,0)}}:host{display:flex;flex-direction:column;align-items:center}div{position:relative;width:110px;height:110px;display:flex;justify-content:center;align-items:center;margin:40px 0 20px 0;transform:translate3d(0,0,0)}svg{position:absolute;width:110px;height:110px;fill:none;stroke:transparent;stroke-linecap:round;stroke-width:2px;top:0;left:0}use{stroke:var(--wcm-accent-color);animation:loading 1s linear infinite}wcm-wallet-image{border-radius:var(--wcm-wallet-icon-large-border-radius);width:90px;height:90px}wcm-text{margin-bottom:40px}.wcm-error svg{stroke:var(--wcm-error-color)}.wcm-error use{display:none}.wcm-error{animation:shake .4s cubic-bezier(.36,.07,.19,.97) both}.wcm-stale svg,.wcm-stale use{display:none}`;var _$=Object.defineProperty,x$=Object.getOwnPropertyDescriptor,oc=(r,e,t,i)=>{for(var n=i>1?void 0:i?x$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&_$(e,t,n),n};let oo=class extends Ct{constructor(){super(...arguments),this.walletId=void 0,this.imageId=void 0,this.isError=!1,this.isStale=!1,this.label=""}svgLoaderTemplate(){var r,e;const s=(e=(r=Zs.state.themeVariables)==null?void 0:r["--wcm-wallet-icon-large-border-radius"])!=null?e:Lt.getPreset("--wcm-wallet-icon-large-border-radius");let a=0;s.includes("%")?a=88/100*parseInt(s,10):a=parseInt(s,10),a*=1.17;const f=317-a*1.57,h=425-a*1.8;return Ee``}render(){const r={"wcm-error":this.isError,"wcm-stale":this.isStale};return Ee`
${this.svgLoaderTemplate()}
${this.isError?"Connection declined":this.label}`}};oo.styles=[Lt.globalCss,y$],oc([At()],oo.prototype,"walletId",2),oc([At()],oo.prototype,"imageId",2),oc([At({type:Boolean})],oo.prototype,"isError",2),oc([At({type:Boolean})],oo.prototype,"isStale",2),oc([At()],oo.prototype,"label",2),oo=oc([Ut("wcm-connector-waiting")],oo);const ac={manualWallets(){var r,e;const{mobileWallets:t,desktopWallets:i}=Ui.state,n=(r=ac.recentWallet())==null?void 0:r.id,s=je.isMobile()?t:i,a=s?.filter(f=>n!==f.id);return(e=je.isMobile()?a?.map(({id:f,name:h,links:u})=>({id:f,name:h,mobile:u,links:u})):a?.map(({id:f,name:h,links:u})=>({id:f,name:h,desktop:u,links:u})))!=null?e:[]},recentWallet(){return pt.getRecentWallet()},recomendedWallets(r=!1){var e;const t=r||(e=ac.recentWallet())==null?void 0:e.id,{recomendedWallets:i}=_i.state;return i.filter(s=>t!==s.id)}},ao={onConnecting(r){pt.goToConnectingView(r)},manualWalletsTemplate(){return ac.manualWallets().map(e=>Ee``)},recomendedWalletsTemplate(r=!1){return ac.recomendedWallets(r).map(t=>Ee``)},recentWalletTemplate(){const r=ac.recentWallet();if(r)return Ee``}},A$=jt`.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between}.wcm-desktop-title,.wcm-mobile-title{display:flex;align-items:center}.wcm-mobile-title{justify-content:space-between;margin-bottom:20px;margin-top:-10px}.wcm-desktop-title{margin-bottom:10px;padding:0 10px}.wcm-subtitle{display:flex;align-items:center}.wcm-subtitle:last-child path{fill:var(--wcm-color-fg-3)}.wcm-desktop-title svg,.wcm-mobile-title svg{margin-right:6px}.wcm-desktop-title path,.wcm-mobile-title path{fill:var(--wcm-accent-color)}`;var E$=Object.defineProperty,S$=Object.getOwnPropertyDescriptor,I$=(r,e,t,i)=>{for(var n=i>1?void 0:i?S$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&E$(e,t,n),n};let Lp=class extends Ct{render(){const{explorerExcludedWalletIds:r,enableExplorer:e}=Ui.state,t=r!=="ALL"&&e,i=ao.manualWalletsTemplate(),n=ao.recomendedWalletsTemplate();let a=[ao.recentWalletTemplate(),...i,...n];a=a.filter(Boolean);const f=a.length>4||t;let h=[];f?h=a.slice(0,3):h=a;const u=!!h.length;return Ee`
${Kt.MOBILE_ICON}Mobile
${Kt.SCAN_ICON}Scan with your wallet
${u?Ee`
${Kt.DESKTOP_ICON}Desktop
${h} ${f?Ee``:null}
`:null}`}};Lp.styles=[Lt.globalCss,A$],Lp=I$([Ut("wcm-desktop-wallet-selection")],Lp);const M$=jt`div{background-color:var(--wcm-color-bg-2);padding:10px 20px 15px 20px;border-top:1px solid var(--wcm-color-bg-3);text-align:center}a{color:var(--wcm-accent-color);text-decoration:none;transition:opacity .2s ease-in-out;display:inline}a:active{opacity:.8}@media(hover:hover){a:hover{opacity:.8}}`;var C$=Object.defineProperty,P$=Object.getOwnPropertyDescriptor,D$=(r,e,t,i)=>{for(var n=i>1?void 0:i?P$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&C$(e,t,n),n};let Bp=class extends Ct{render(){const{termsOfServiceUrl:r,privacyPolicyUrl:e}=Ui.state;return r??e?Ee`
`:null}};Bp.styles=[Lt.globalCss,M$],Bp=D$([Ut("wcm-legal-notice")],Bp);const O$=jt`div{display:grid;grid-template-columns:repeat(4,80px);margin:0 -10px;justify-content:space-between;row-gap:10px}`;var R$=Object.defineProperty,T$=Object.getOwnPropertyDescriptor,$$=(r,e,t,i)=>{for(var n=i>1?void 0:i?T$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&R$(e,t,n),n};let Fp=class extends Ct{onQrcode(){lr.push("Qrcode")}render(){const{explorerExcludedWalletIds:r,enableExplorer:e}=Ui.state,t=r!=="ALL"&&e,i=ao.manualWalletsTemplate(),n=ao.recomendedWalletsTemplate();let a=[ao.recentWalletTemplate(),...i,...n];a=a.filter(Boolean);const f=a.length>8||t;let h=[];f?h=a.slice(0,7):h=a;const u=!!h.length;return Ee`${u?Ee`
${h} ${f?Ee``:null}
`:null}`}};Fp.styles=[Lt.globalCss,O$],Fp=$$([Ut("wcm-mobile-wallet-selection")],Fp);const N$=jt`:host{all:initial}.wcm-overlay{top:0;bottom:0;left:0;right:0;position:fixed;z-index:var(--wcm-z-index);overflow:hidden;display:flex;justify-content:center;align-items:center;opacity:0;pointer-events:none;background-color:var(--wcm-overlay-background-color);backdrop-filter:var(--wcm-overlay-backdrop-filter)}@media(max-height:720px) and (orientation:landscape){.wcm-overlay{overflow:scroll;align-items:flex-start;padding:20px 0}}.wcm-active{pointer-events:auto}.wcm-container{position:relative;max-width:360px;width:100%;outline:0;border-radius:var(--wcm-background-border-radius) var(--wcm-background-border-radius) var(--wcm-container-border-radius) var(--wcm-container-border-radius);border:1px solid var(--wcm-color-overlay);overflow:hidden}.wcm-card{width:100%;position:relative;border-radius:var(--wcm-container-border-radius);overflow:hidden;box-shadow:0 6px 14px -6px rgba(10,16,31,.12),0 10px 32px -4px rgba(10,16,31,.1),0 0 0 1px var(--wcm-color-overlay);background-color:var(--wcm-color-bg-1);color:var(--wcm-color-fg-1)}@media(max-width:600px){.wcm-container{max-width:440px;border-radius:var(--wcm-background-border-radius) var(--wcm-background-border-radius) 0 0}.wcm-card{border-radius:var(--wcm-container-border-radius) var(--wcm-container-border-radius) 0 0}.wcm-overlay{align-items:flex-end}}@media(max-width:440px){.wcm-container{border:0}}`;var L$=Object.defineProperty,B$=Object.getOwnPropertyDescriptor,Up=(r,e,t,i)=>{for(var n=i>1?void 0:i?B$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&L$(e,t,n),n};let cc=class extends Ct{constructor(){super(),this.open=!1,this.active=!1,this.unsubscribeModal=void 0,this.abortController=void 0,this.unsubscribeModal=jo.subscribe(r=>{r.open?this.onOpenModalEvent():this.onCloseModalEvent()})}disconnectedCallback(){var r;(r=this.unsubscribeModal)==null||r.call(this)}get overlayEl(){return pt.getShadowRootElement(this,".wcm-overlay")}get containerEl(){return pt.getShadowRootElement(this,".wcm-container")}toggleBodyScroll(r){if(document.querySelector("body"))if(r){const t=document.getElementById("wcm-styles");t?.remove()}else document.head.insertAdjacentHTML("beforeend",'')}onCloseModal(r){r.target===r.currentTarget&&jo.close()}onOpenModalEvent(){this.toggleBodyScroll(!1),this.addKeyboardEvents(),this.open=!0,setTimeout(async()=>{const r=pt.isMobileAnimation()?{y:["50vh","0vh"]}:{scale:[.98,1]},e=.1,t=.2;await Promise.all([Qo(this.overlayEl,{opacity:[0,1]},{delay:e,duration:t}).finished,Qo(this.containerEl,r,{delay:e,duration:t}).finished]),this.active=!0},0)}async onCloseModalEvent(){this.toggleBodyScroll(!0),this.removeKeyboardEvents();const r=pt.isMobileAnimation()?{y:["0vh","50vh"]}:{scale:[1,.98]},e=.2;await Promise.all([Qo(this.overlayEl,{opacity:[1,0]},{duration:e}).finished,Qo(this.containerEl,r,{duration:e}).finished]),this.containerEl.removeAttribute("style"),this.active=!1,this.open=!1}addKeyboardEvents(){this.abortController=new AbortController,window.addEventListener("keydown",r=>{var e;r.key==="Escape"?jo.close():r.key==="Tab"&&((e=r.target)!=null&&e.tagName.includes("wcm-")||this.containerEl.focus())},this.abortController),this.containerEl.focus()}removeKeyboardEvents(){var r;(r=this.abortController)==null||r.abort(),this.abortController=void 0}render(){const r={"wcm-overlay":!0,"wcm-active":this.active};return Ee`
${this.open?Ee`
`:null}
`}};cc.styles=[Lt.globalCss,N$],Up([xi()],cc.prototype,"open",2),Up([xi()],cc.prototype,"active",2),cc=Up([Ut("wcm-modal")],cc);const F$=jt`div{display:flex;margin-top:15px}slot{display:inline-block;margin:0 5px}wcm-button{margin:0 5px}`;var U$=Object.defineProperty,q$=Object.getOwnPropertyDescriptor,Rf=(r,e,t,i)=>{for(var n=i>1?void 0:i?q$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&U$(e,t,n),n};let Xo=class extends Ct{constructor(){super(...arguments),this.isMobile=!1,this.isDesktop=!1,this.isWeb=!1,this.isRetry=!1}onMobile(){je.isMobile()?lr.replace("MobileConnecting"):lr.replace("MobileQrcodeConnecting")}onDesktop(){lr.replace("DesktopConnecting")}onWeb(){lr.replace("WebConnecting")}render(){return Ee`
${this.isRetry?Ee``:null} ${this.isMobile?Ee`Mobile`:null} ${this.isDesktop?Ee`Desktop`:null} ${this.isWeb?Ee`Web`:null}
`}};Xo.styles=[Lt.globalCss,F$],Rf([At({type:Boolean})],Xo.prototype,"isMobile",2),Rf([At({type:Boolean})],Xo.prototype,"isDesktop",2),Rf([At({type:Boolean})],Xo.prototype,"isWeb",2),Rf([At({type:Boolean})],Xo.prototype,"isRetry",2),Xo=Rf([Ut("wcm-platform-selection")],Xo);const z$=jt`button{display:flex;flex-direction:column;padding:5px 10px;border-radius:var(--wcm-button-hover-highlight-border-radius);height:100%;justify-content:flex-start}.wcm-icons{width:60px;height:60px;display:flex;flex-wrap:wrap;padding:7px;border-radius:var(--wcm-wallet-icon-border-radius);justify-content:space-between;align-items:center;margin-bottom:5px;background-color:var(--wcm-color-bg-2);box-shadow:inset 0 0 0 1px var(--wcm-color-overlay)}button:active{background-color:var(--wcm-color-overlay)}@media(hover:hover){button:hover{background-color:var(--wcm-color-overlay)}}.wcm-icons img{width:21px;height:21px;object-fit:cover;object-position:center;border-radius:calc(var(--wcm-wallet-icon-border-radius)/ 2);border:1px solid var(--wcm-color-overlay)}.wcm-icons svg{width:21px;height:21px}.wcm-icons img:nth-child(1),.wcm-icons img:nth-child(2),.wcm-icons svg:nth-child(1),.wcm-icons svg:nth-child(2){margin-bottom:4px}wcm-text{width:100%;text-align:center}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var H$=Object.defineProperty,k$=Object.getOwnPropertyDescriptor,j$=(r,e,t,i)=>{for(var n=i>1?void 0:i?k$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&H$(e,t,n),n};let qp=class extends Ct{onClick(){lr.push("WalletExplorer")}render(){const{recomendedWallets:r}=_i.state,e=ac.manualWallets(),t=[...r,...e].reverse().slice(0,4);return Ee``}};qp.styles=[Lt.globalCss,z$],qp=j$([Ut("wcm-view-all-wallets-button")],qp);const W$=jt`.wcm-qr-container{width:100%;display:flex;justify-content:center;align-items:center;aspect-ratio:1/1}`;var K$=Object.defineProperty,V$=Object.getOwnPropertyDescriptor,Lh=(r,e,t,i)=>{for(var n=i>1?void 0:i?V$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&K$(e,t,n),n};let fc=class extends Ct{constructor(){super(),this.walletId="",this.imageId="",this.uri="",setTimeout(()=>{const{walletConnectUri:r}=yr.state;this.uri=r},0)}get overlayEl(){return pt.getShadowRootElement(this,".wcm-qr-container")}render(){return Ee`
${this.uri?Ee``:Ee``}
`}};fc.styles=[Lt.globalCss,W$],Lh([At()],fc.prototype,"walletId",2),Lh([At()],fc.prototype,"imageId",2),Lh([xi()],fc.prototype,"uri",2),fc=Lh([Ut("wcm-walletconnect-qr")],fc);var G$=Object.defineProperty,Y$=Object.getOwnPropertyDescriptor,J$=(r,e,t,i)=>{for(var n=i>1?void 0:i?Y$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&G$(e,t,n),n};let zp=class extends Ct{viewTemplate(){return je.isAndroid()&&!je.isTelegram()?Ee``:je.isMobile()?Ee``:Ee``}render(){return Ee`${this.viewTemplate()}`}};zp.styles=[Lt.globalCss],zp=J$([Ut("wcm-connect-wallet-view")],zp);const Q$=jt`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var Z$=Object.defineProperty,X$=Object.getOwnPropertyDescriptor,Uw=(r,e,t,i)=>{for(var n=i>1?void 0:i?X$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Z$(e,t,n),n};let Bh=class extends Ct{constructor(){super(),this.isError=!1,this.openDesktopApp()}onFormatAndRedirect(r){const{desktop:e,name:t}=je.getWalletRouterData(),i=e?.native,n=e?.universal;if(i){const s=je.formatNativeUrl(i,r,t);je.openHref(s,"_self")}else if(n){const s=je.formatUniversalUrl(n,r,t);je.openHref(s,"_blank")}}openDesktopApp(){const{walletConnectUri:r}=yr.state,e=je.getWalletRouterData();pt.setRecentWallet(e),r&&this.onFormatAndRedirect(r)}render(){const{name:r,id:e,image_id:t}=je.getWalletRouterData(),{isMobile:i,isWeb:n}=pt.getCachedRouterWalletPlatforms();return Ee`${`Connection can continue loading if ${r} is not installed on your device`}Retry`}};Bh.styles=[Lt.globalCss,Q$],Uw([xi()],Bh.prototype,"isError",2),Bh=Uw([Ut("wcm-desktop-connecting-view")],Bh);const eN=jt`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}wcm-button{margin-top:15px}`;var tN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,iN=(r,e,t,i)=>{for(var n=i>1?void 0:i?rN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&tN(e,t,n),n};let Hp=class extends Ct{onInstall(r){r&&je.openHref(r,"_blank")}render(){const{name:r,id:e,image_id:t,homepage:i}=je.getWalletRouterData();return Ee`${`Download ${r} to continue. If multiple browser extensions are installed, disable non ${r} ones and try again`}Download`}};Hp.styles=[Lt.globalCss,eN],Hp=iN([Ut("wcm-install-wallet-view")],Hp);const nN=jt`wcm-wallet-image{border-radius:var(--wcm-wallet-icon-large-border-radius);width:96px;height:96px;margin-bottom:20px}wcm-info-footer{display:flex;width:100%}.wcm-app-store{justify-content:space-between}.wcm-app-store wcm-wallet-image{margin-right:10px;margin-bottom:0;width:28px;height:28px;border-radius:var(--wcm-wallet-icon-small-border-radius)}.wcm-app-store div{display:flex;align-items:center}.wcm-app-store wcm-button{margin-right:-10px}.wcm-note{flex-direction:column;align-items:center;padding:5px 0}.wcm-note wcm-text{text-align:center}wcm-platform-selection{margin-top:-15px}.wcm-note wcm-text{margin-top:15px}.wcm-note wcm-text span{color:var(--wcm-accent-color)}`;var sN=Object.defineProperty,oN=Object.getOwnPropertyDescriptor,qw=(r,e,t,i)=>{for(var n=i>1?void 0:i?oN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&sN(e,t,n),n};let Fh=class extends Ct{constructor(){super(),this.isError=!1,this.openMobileApp()}onFormatAndRedirect(r,e=!1){const{mobile:t,name:i}=je.getWalletRouterData(),n=t?.native,s=t?.universal,a=je.isTelegram()?"_blank":"_self";if(r=je.isTelegram()&&je.isAndroid()?encodeURIComponent(r):r,n&&!e){const f=je.formatNativeUrl(n,r,i);je.openHref(f,a)}else if(s){const f=je.formatUniversalUrl(s,r,i);je.openHref(f,a)}}openMobileApp(r=!1){const{walletConnectUri:e}=yr.state,t=je.getWalletRouterData();e&&this.onFormatAndRedirect(e,r),pt.setRecentWallet(t)}onGoToAppStore(r){r&&je.openHref(r,"_blank")}render(){const{name:r,id:e,image_id:t,app:i,mobile:n}=je.getWalletRouterData(),{isWeb:s}=pt.getCachedRouterWalletPlatforms(),a=i?.ios,f=n?.universal;return Ee`Retry${f?Ee`Still doesn't work? Try this alternate link`:null}
${`Get ${r}`}
App Store
`}};Fh.styles=[Lt.globalCss,nN],qw([xi()],Fh.prototype,"isError",2),Fh=qw([Ut("wcm-mobile-connecting-view")],Fh);const aN=jt`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var cN=Object.defineProperty,fN=Object.getOwnPropertyDescriptor,lN=(r,e,t,i)=>{for(var n=i>1?void 0:i?fN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&cN(e,t,n),n};let kp=class extends Ct{render(){const{name:r,id:e,image_id:t}=je.getWalletRouterData(),{isDesktop:i,isWeb:n}=pt.getCachedRouterWalletPlatforms();return Ee`${`Scan this QR Code with your phone's camera or inside ${r} app`}`}};kp.styles=[Lt.globalCss,aN],kp=lN([Ut("wcm-mobile-qr-connecting-view")],kp);var hN=Object.defineProperty,uN=Object.getOwnPropertyDescriptor,dN=(r,e,t,i)=>{for(var n=i>1?void 0:i?uN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&hN(e,t,n),n};let jp=class extends Ct{render(){return Ee``}};jp.styles=[Lt.globalCss],jp=dN([Ut("wcm-qrcode-view")],jp);const pN=jt`wcm-modal-content{height:clamp(200px,60vh,600px);display:block;overflow:scroll;scrollbar-width:none;position:relative;margin-top:1px}.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between;margin:-15px -10px;padding-top:20px}wcm-modal-content::after,wcm-modal-content::before{content:'';position:fixed;pointer-events:none;z-index:1;width:100%;height:20px;opacity:1}wcm-modal-content::before{box-shadow:0 -1px 0 0 var(--wcm-color-bg-1);background:linear-gradient(var(--wcm-color-bg-1),rgba(255,255,255,0))}wcm-modal-content::after{box-shadow:0 1px 0 0 var(--wcm-color-bg-1);background:linear-gradient(rgba(255,255,255,0),var(--wcm-color-bg-1));top:calc(100% - 20px)}wcm-modal-content::-webkit-scrollbar{display:none}.wcm-placeholder-block{display:flex;justify-content:center;align-items:center;height:100px;overflow:hidden}.wcm-empty,.wcm-loading{display:flex}.wcm-loading .wcm-placeholder-block{height:100%}.wcm-end-reached .wcm-placeholder-block{height:0;opacity:0}.wcm-empty .wcm-placeholder-block{opacity:1;height:100%}wcm-wallet-button{margin:calc((100% - 60px)/ 3) 0}`;var gN=Object.defineProperty,vN=Object.getOwnPropertyDescriptor,Tf=(r,e,t,i)=>{for(var n=i>1?void 0:i?vN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&gN(e,t,n),n};const Wp=40;let ea=class extends Ct{constructor(){super(...arguments),this.loading=!_i.state.wallets.listings.length,this.firstFetch=!_i.state.wallets.listings.length,this.search="",this.endReached=!1,this.intersectionObserver=void 0,this.searchDebounce=pt.debounce(r=>{r.length>=1?(this.firstFetch=!0,this.endReached=!1,this.search=r,_i.resetSearch(),this.fetchWallets()):this.search&&(this.search="",this.endReached=this.isLastPage(),_i.resetSearch())})}firstUpdated(){this.createPaginationObserver()}disconnectedCallback(){var r;(r=this.intersectionObserver)==null||r.disconnect()}get placeholderEl(){return pt.getShadowRootElement(this,".wcm-placeholder-block")}createPaginationObserver(){this.intersectionObserver=new IntersectionObserver(([r])=>{r.isIntersecting&&!(this.search&&this.firstFetch)&&this.fetchWallets()}),this.intersectionObserver.observe(this.placeholderEl)}isLastPage(){const{wallets:r,search:e}=_i.state,{listings:t,total:i}=this.search?e:r;return i<=Wp||t.length>=i}async fetchWallets(){var r;const{wallets:e,search:t}=_i.state,{listings:i,total:n,page:s}=this.search?t:e;if(!this.endReached&&(this.firstFetch||n>Wp&&i.lengthpt.getWalletIcon(u));await Promise.all([...h.map(async u=>pt.preloadImage(u)),je.wait(300)]),this.endReached=this.isLastPage()}catch(a){console.error(a),Xs.openToast(pt.getErrorMessage(a),"error")}finally{this.loading=!1,this.firstFetch=!1}}onConnect(r){je.isAndroid()?pt.handleMobileLinking(r):pt.goToConnectingView(r)}onSearchChange(r){const{value:e}=r.target;this.searchDebounce(e)}render(){const{wallets:r,search:e}=_i.state,{listings:t}=this.search?e:r,i=this.loading&&!t.length,n=this.search.length>=3;let s=ao.manualWalletsTemplate(),a=ao.recomendedWalletsTemplate(!0);n&&(s=s.filter(({values:u})=>pt.caseSafeIncludes(u[0],this.search)),a=a.filter(({values:u})=>pt.caseSafeIncludes(u[0],this.search)));const f=!this.loading&&!t.length&&!a.length,h={"wcm-loading":i,"wcm-end-reached":this.endReached||!this.loading,"wcm-empty":f};return Ee`
${i?null:s} ${i?null:a} ${i?null:t.map(u=>Ee`${u?Ee``:null}`)}
${f?Ee`No results found`:null} ${!f&&this.loading?Ee``:null}
`}};ea.styles=[Lt.globalCss,pN],Tf([xi()],ea.prototype,"loading",2),Tf([xi()],ea.prototype,"firstFetch",2),Tf([xi()],ea.prototype,"search",2),Tf([xi()],ea.prototype,"endReached",2),ea=Tf([Ut("wcm-wallet-explorer-view")],ea);const mN=jt`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var bN=Object.defineProperty,wN=Object.getOwnPropertyDescriptor,zw=(r,e,t,i)=>{for(var n=i>1?void 0:i?wN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&bN(e,t,n),n};let Uh=class extends Ct{constructor(){super(),this.isError=!1,this.openWebWallet()}onFormatAndRedirect(r){const{desktop:e,name:t}=je.getWalletRouterData(),i=e?.universal;if(i){const n=je.formatUniversalUrl(i,r,t);je.openHref(n,"_blank")}}openWebWallet(){const{walletConnectUri:r}=yr.state,e=je.getWalletRouterData();pt.setRecentWallet(e),r&&this.onFormatAndRedirect(r)}render(){const{name:r,id:e,image_id:t}=je.getWalletRouterData(),{isMobile:i,isDesktop:n}=pt.getCachedRouterWalletPlatforms(),s=je.isMobile();return Ee`${`${r} web app has opened in a new tab. Go there, accept the connection, and come back`}Retry`}};Uh.styles=[Lt.globalCss,mN],zw([xi()],Uh.prototype,"isError",2),Uh=zw([Ut("wcm-web-connecting-view")],Uh);var yN=Object.freeze({__proto__:null,get WcmModal(){return cc},get WcmQrCode(){return Ms}});bn.EthereumProvider=kD,bn.OPTIONAL_EVENTS=g3,bn.OPTIONAL_METHODS=p3,bn.REQUIRED_EVENTS=lh,bn.REQUIRED_METHODS=fh,bn.default=dh,Object.defineProperty(bn,"__esModule",{value:!0})}); ++`);const a=hT(e,t,n),f=$h.getSymbolSize(e),h=new eT(f);return oT(h,e),aT(h),cT(h,e),yp(h,t,0),e>=7&&fT(h,e),lT(h,a),isNaN(i)&&(i=mp.getBestMask(h,yp.bind(null,h,t))),mp.applyMask(i,h),yp(h,t,i),{modules:h,version:e,errorCorrectionLevel:t,maskPattern:i,segments:n}}mw.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let i=vp.M,n,s;return typeof t<"u"&&(i=vp.from(t.errorCorrectionLevel,vp.M),n=Nh.from(t.version),s=mp.from(t.maskPattern),t.toSJISFunc&&$h.setToSJISFunction(t.toSJISFunc)),dT(e,n,i,s)};var Rw={},_p={};(function(r){function e(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let i=t.slice().replace("#","").split("");if(i.length<3||i.length===5||i.length>8)throw new Error("Invalid hex color: "+t);(i.length===3||i.length===4)&&(i=Array.prototype.concat.apply([],i.map(function(s){return[s,s]}))),i.length===6&&i.push("F","F");const n=parseInt(i.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+i.slice(0,6).join("")}}r.getOptions=function(i){i||(i={}),i.color||(i.color={});const n=typeof i.margin>"u"||i.margin===null||i.margin<0?4:i.margin,s=i.width&&i.width>=21?i.width:void 0,a=i.scale||4;return{width:s,scale:s?4:a,margin:n,color:{dark:e(i.color.dark||"#000000ff"),light:e(i.color.light||"#ffffffff")},type:i.type,rendererOpts:i.rendererOpts||{}}},r.getScale=function(i,n){return n.width&&n.width>=i+n.margin*2?n.width/(i+n.margin*2):n.scale},r.getImageWidth=function(i,n){const s=r.getScale(i,n);return Math.floor((i+n.margin*2)*s)},r.qrToImageData=function(i,n,s){const a=n.modules.size,f=n.modules.data,h=r.getScale(a,s),u=Math.floor((a+s.margin*2)*h),g=s.margin*h,w=[s.color.light,s.color.dark];for(let M=0;M=g&&C>=g&&M"u"&&(!a||!a.getContext)&&(h=a,a=void 0),a||(u=i()),h=e.getOptions(h);const g=e.getImageWidth(s.modules.size,h),w=u.getContext("2d"),M=w.createImageData(g,g);return e.qrToImageData(M.data,s,h),t(w,u,g),w.putImageData(M,0,0),u},r.renderToDataURL=function(s,a,f){let h=f;typeof h>"u"&&(!a||!a.getContext)&&(h=a,a=void 0),h||(h={});const u=r.render(s,a,h),g=h.type||"image/png",w=h.rendererOpts||{};return u.toDataURL(g,w.quality)}}(Rw);var Tw={};const pT=_p;function $w(r,e){const t=r.a/255,i=e+'="'+r.hex+'"';return t<1?i+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':i}function xp(r,e,t){let i=r+e;return typeof t<"u"&&(i+=" "+t),i}function gT(r,e,t){let i="",n=0,s=!1,a=0;for(let f=0;f0&&h>0&&r[f-1]||(i+=s?xp("M",h+t,.5+u+t):xp("m",n,0),n=0,s=!1),h+1':"",u="',g='viewBox="0 0 '+f+" "+f+'"',M=''+h+u+` ++`;return typeof i=="function"&&i(null,M),M};const vT=DR,Ap=mw,Nw=Rw,mT=Tw;function Ep(r,e,t,i,n){const s=[].slice.call(arguments,1),a=s.length,f=typeof s[a-1]=="function";if(!f&&!vT())throw new Error("Callback required as last argument");if(f){if(a<2)throw new Error("Too few arguments provided");a===2?(n=t,t=e,e=i=void 0):a===3&&(e.getContext&&typeof n>"u"?(n=i,i=void 0):(n=i,i=t,t=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(t=e,e=i=void 0):a===2&&!e.getContext&&(i=t,t=e,e=void 0),new Promise(function(h,u){try{const g=Ap.create(t,i);h(r(g,e,i))}catch(g){u(g)}})}try{const h=Ap.create(t,i);n(null,r(h,e,i))}catch(h){n(h)}}Sf.create=Ap.create,Sf.toCanvas=Ep.bind(null,Nw.render),Sf.toDataURL=Ep.bind(null,Nw.renderToDataURL),Sf.toString=Ep.bind(null,function(r,e,t){return mT.render(r,t)});var bT=Object.defineProperty,Lw=Object.getOwnPropertySymbols,wT=Object.prototype.hasOwnProperty,yT=Object.prototype.propertyIsEnumerable,Bw=(r,e,t)=>e in r?bT(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Sp=(r,e)=>{for(var t in e||(e={}))wT.call(e,t)&&Bw(r,t,e[t]);if(Lw)for(var t of Lw(e))yT.call(e,t)&&Bw(r,t,e[t]);return r};function _T(){var r;const e=(r=Xs.state.themeMode)!=null?r:"dark",i={light:{foreground:{1:"rgb(20,20,20)",2:"rgb(121,134,134)",3:"rgb(158,169,169)"},background:{1:"rgb(255,255,255)",2:"rgb(241,243,243)",3:"rgb(228,231,231)"},overlay:"rgba(0,0,0,0.1)"},dark:{foreground:{1:"rgb(228,231,231)",2:"rgb(148,158,158)",3:"rgb(110,119,119)"},background:{1:"rgb(20,20,20)",2:"rgb(39,42,42)",3:"rgb(59,64,64)"},overlay:"rgba(255,255,255,0.1)"}}[e];return{"--wcm-color-fg-1":i.foreground[1],"--wcm-color-fg-2":i.foreground[2],"--wcm-color-fg-3":i.foreground[3],"--wcm-color-bg-1":i.background[1],"--wcm-color-bg-2":i.background[2],"--wcm-color-bg-3":i.background[3],"--wcm-color-overlay":i.overlay}}function Fw(){return{"--wcm-accent-color":"#3396FF","--wcm-accent-fill-color":"#FFFFFF","--wcm-z-index":"89","--wcm-background-color":"#3396FF","--wcm-background-border-radius":"8px","--wcm-container-border-radius":"30px","--wcm-wallet-icon-border-radius":"15px","--wcm-wallet-icon-large-border-radius":"30px","--wcm-wallet-icon-small-border-radius":"7px","--wcm-input-border-radius":"28px","--wcm-button-border-radius":"10px","--wcm-notification-border-radius":"36px","--wcm-secondary-button-border-radius":"28px","--wcm-icon-button-border-radius":"50%","--wcm-button-hover-highlight-border-radius":"10px","--wcm-text-big-bold-size":"20px","--wcm-text-big-bold-weight":"600","--wcm-text-big-bold-line-height":"24px","--wcm-text-big-bold-letter-spacing":"-0.03em","--wcm-text-big-bold-text-transform":"none","--wcm-text-xsmall-bold-size":"10px","--wcm-text-xsmall-bold-weight":"700","--wcm-text-xsmall-bold-line-height":"12px","--wcm-text-xsmall-bold-letter-spacing":"0.02em","--wcm-text-xsmall-bold-text-transform":"uppercase","--wcm-text-xsmall-regular-size":"12px","--wcm-text-xsmall-regular-weight":"600","--wcm-text-xsmall-regular-line-height":"14px","--wcm-text-xsmall-regular-letter-spacing":"-0.03em","--wcm-text-xsmall-regular-text-transform":"none","--wcm-text-small-thin-size":"14px","--wcm-text-small-thin-weight":"500","--wcm-text-small-thin-line-height":"16px","--wcm-text-small-thin-letter-spacing":"-0.03em","--wcm-text-small-thin-text-transform":"none","--wcm-text-small-regular-size":"14px","--wcm-text-small-regular-weight":"600","--wcm-text-small-regular-line-height":"16px","--wcm-text-small-regular-letter-spacing":"-0.03em","--wcm-text-small-regular-text-transform":"none","--wcm-text-medium-regular-size":"16px","--wcm-text-medium-regular-weight":"600","--wcm-text-medium-regular-line-height":"20px","--wcm-text-medium-regular-letter-spacing":"-0.03em","--wcm-text-medium-regular-text-transform":"none","--wcm-font-family":"-apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, 'Helvetica Neue', sans-serif","--wcm-font-feature-settings":"'tnum' on, 'lnum' on, 'case' on","--wcm-success-color":"rgb(38,181,98)","--wcm-error-color":"rgb(242, 90, 103)","--wcm-overlay-background-color":"rgba(0, 0, 0, 0.3)","--wcm-overlay-backdrop-filter":"none"}}const Lt={getPreset(r){return Fw()[r]},setTheme(){const r=document.querySelector(":root"),{themeVariables:e}=Xs.state;if(r){const t=Sp(Sp(Sp({},_T()),Fw()),e);Object.entries(t).forEach(([i,n])=>r.style.setProperty(i,n))}},globalCss:jt`*,::after,::before{margin:0;padding:0;box-sizing:border-box;font-style:normal;text-rendering:optimizeSpeed;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-tap-highlight-color:transparent;backface-visibility:hidden}button{cursor:pointer;display:flex;justify-content:center;align-items:center;position:relative;border:none;background-color:transparent;transition:all .2s ease}@media (hover:hover) and (pointer:fine){button:active{transition:all .1s ease;transform:scale(.93)}}button::after{content:'';position:absolute;top:0;bottom:0;left:0;right:0;transition:background-color,.2s ease}button:disabled{cursor:not-allowed}button svg,button wcm-text{position:relative;z-index:1}input{border:none;outline:0;appearance:none}img{display:block}::selection{color:var(--wcm-accent-fill-color);background:var(--wcm-accent-color)}`},xT=jt`button{border-radius:var(--wcm-secondary-button-border-radius);height:28px;padding:0 10px;background-color:var(--wcm-accent-color)}button path{fill:var(--wcm-accent-fill-color)}button::after{border-radius:inherit;border:1px solid var(--wcm-color-overlay)}button:disabled::after{background-color:transparent}.wcm-icon-left svg{margin-right:5px}.wcm-icon-right svg{margin-left:5px}button:active::after{background-color:var(--wcm-color-overlay)}.wcm-ghost,.wcm-ghost:active::after,.wcm-outline{background-color:transparent}.wcm-ghost:active{opacity:.5}@media(hover:hover){button:hover::after{background-color:var(--wcm-color-overlay)}.wcm-ghost:hover::after{background-color:transparent}.wcm-ghost:hover{opacity:.5}}button:disabled{background-color:var(--wcm-color-bg-3);pointer-events:none}.wcm-ghost::after{border-color:transparent}.wcm-ghost path{fill:var(--wcm-color-fg-2)}.wcm-outline path{fill:var(--wcm-accent-color)}.wcm-outline:disabled{background-color:transparent;opacity:.5}`;var AT=Object.defineProperty,ET=Object.getOwnPropertyDescriptor,nc=(r,e,t,i)=>{for(var n=i>1?void 0:i?ET(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&AT(e,t,n),n};let so=class extends Ct{constructor(){super(...arguments),this.disabled=!1,this.iconLeft=void 0,this.iconRight=void 0,this.onClick=()=>null,this.variant="default"}render(){const r={"wcm-icon-left":this.iconLeft!==void 0,"wcm-icon-right":this.iconRight!==void 0,"wcm-ghost":this.variant==="ghost","wcm-outline":this.variant==="outline"};let e="inverse";return this.variant==="ghost"&&(e="secondary"),this.variant==="outline"&&(e="accent"),Ee``}};so.styles=[Lt.globalCss,xT],nc([At({type:Boolean})],so.prototype,"disabled",2),nc([At()],so.prototype,"iconLeft",2),nc([At()],so.prototype,"iconRight",2),nc([At()],so.prototype,"onClick",2),nc([At()],so.prototype,"variant",2),so=nc([Ut("wcm-button")],so);const ST=jt`:host{display:inline-block}button{padding:0 15px 1px;height:40px;border-radius:var(--wcm-button-border-radius);color:var(--wcm-accent-fill-color);background-color:var(--wcm-accent-color)}button::after{content:'';top:0;bottom:0;left:0;right:0;position:absolute;background-color:transparent;border-radius:inherit;transition:background-color .2s ease;border:1px solid var(--wcm-color-overlay)}button:active::after{background-color:var(--wcm-color-overlay)}button:disabled{padding-bottom:0;background-color:var(--wcm-color-bg-3);color:var(--wcm-color-fg-3)}.wcm-secondary{color:var(--wcm-accent-color);background-color:transparent}.wcm-secondary::after{display:none}@media(hover:hover){button:hover::after{background-color:var(--wcm-color-overlay)}}`;var IT=Object.defineProperty,MT=Object.getOwnPropertyDescriptor,Ip=(r,e,t,i)=>{for(var n=i>1?void 0:i?MT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&IT(e,t,n),n};let Pf=class extends Ct{constructor(){super(...arguments),this.disabled=!1,this.variant="primary"}render(){const r={"wcm-secondary":this.variant==="secondary"};return Ee``}};Pf.styles=[Lt.globalCss,ST],Ip([At({type:Boolean})],Pf.prototype,"disabled",2),Ip([At()],Pf.prototype,"variant",2),Pf=Ip([Ut("wcm-button-big")],Pf);const CT=jt`:host{background-color:var(--wcm-color-bg-2);border-top:1px solid var(--wcm-color-bg-3)}div{padding:10px 20px;display:inherit;flex-direction:inherit;align-items:inherit;width:inherit;justify-content:inherit}`;var PT=Object.defineProperty,DT=Object.getOwnPropertyDescriptor,OT=(r,e,t,i)=>{for(var n=i>1?void 0:i?DT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&PT(e,t,n),n};let Mp=class extends Ct{render(){return Ee`
`}};Mp.styles=[Lt.globalCss,CT],Mp=OT([Ut("wcm-info-footer")],Mp);const Kt={CROSS_ICON:gr``,WALLET_CONNECT_LOGO:gr``,WALLET_CONNECT_ICON:gr``,WALLET_CONNECT_ICON_COLORED:gr``,BACK_ICON:gr``,COPY_ICON:gr``,RETRY_ICON:gr``,DESKTOP_ICON:gr``,MOBILE_ICON:gr``,ARROW_DOWN_ICON:gr``,ARROW_UP_RIGHT_ICON:gr``,ARROW_RIGHT_ICON:gr``,QRCODE_ICON:gr``,SCAN_ICON:gr``,CHECKMARK_ICON:gr``,SEARCH_ICON:gr``,WALLET_PLACEHOLDER:gr``,GLOBE_ICON:gr``},RT=jt`.wcm-toolbar-placeholder{top:0;bottom:0;left:0;right:0;width:100%;position:absolute;display:block;pointer-events:none;height:100px;border-radius:calc(var(--wcm-background-border-radius) * .9);background-color:var(--wcm-background-color);background-position:center;background-size:cover}.wcm-toolbar{height:38px;display:flex;position:relative;margin:5px 15px 5px 5px;justify-content:space-between;align-items:center}.wcm-toolbar img,.wcm-toolbar svg{height:28px;object-position:left center;object-fit:contain}#wcm-wc-logo path{fill:var(--wcm-accent-fill-color)}button{width:28px;height:28px;border-radius:var(--wcm-icon-button-border-radius);border:0;display:flex;justify-content:center;align-items:center;cursor:pointer;background-color:var(--wcm-color-bg-1);box-shadow:0 0 0 1px var(--wcm-color-overlay)}button:active{background-color:var(--wcm-color-bg-2)}button svg{display:block;object-position:center}button path{fill:var(--wcm-color-fg-1)}.wcm-toolbar div{display:flex}@media(hover:hover){button:hover{background-color:var(--wcm-color-bg-2)}}`;var TT=Object.defineProperty,$T=Object.getOwnPropertyDescriptor,NT=(r,e,t,i)=>{for(var n=i>1?void 0:i?$T(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&TT(e,t,n),n};let Cp=class extends Ct{render(){return Ee`
${Kt.WALLET_CONNECT_LOGO}
`}};Cp.styles=[Lt.globalCss,RT],Cp=NT([Ut("wcm-modal-backcard")],Cp);const LT=jt`main{padding:20px;padding-top:0;width:100%}`;var BT=Object.defineProperty,FT=Object.getOwnPropertyDescriptor,UT=(r,e,t,i)=>{for(var n=i>1?void 0:i?FT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&BT(e,t,n),n};let Pp=class extends Ct{render(){return Ee`
`}};Pp.styles=[Lt.globalCss,LT],Pp=UT([Ut("wcm-modal-content")],Pp);const qT=jt`footer{padding:10px;display:flex;flex-direction:column;align-items:inherit;justify-content:inherit;border-top:1px solid var(--wcm-color-bg-2)}`;var zT=Object.defineProperty,HT=Object.getOwnPropertyDescriptor,kT=(r,e,t,i)=>{for(var n=i>1?void 0:i?HT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&zT(e,t,n),n};let Dp=class extends Ct{render(){return Ee`
`}};Dp.styles=[Lt.globalCss,qT],Dp=kT([Ut("wcm-modal-footer")],Dp);const jT=jt`header{display:flex;justify-content:center;align-items:center;padding:20px;position:relative}.wcm-border{border-bottom:1px solid var(--wcm-color-bg-2);margin-bottom:20px}header button{padding:15px 20px}header button:active{opacity:.5}@media(hover:hover){header button:hover{opacity:.5}}.wcm-back-btn{position:absolute;left:0}.wcm-action-btn{position:absolute;right:0}path{fill:var(--wcm-accent-color)}`;var WT=Object.defineProperty,KT=Object.getOwnPropertyDescriptor,Df=(r,e,t,i)=>{for(var n=i>1?void 0:i?KT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&WT(e,t,n),n};let ea=class extends Ct{constructor(){super(...arguments),this.title="",this.onAction=void 0,this.actionIcon=void 0,this.border=!1}backBtnTemplate(){return Ee``}actionBtnTemplate(){return Ee``}render(){const r={"wcm-border":this.border},e=lr.state.history.length>1,t=this.title?Ee`${this.title}`:Ee``;return Ee`
${e?this.backBtnTemplate():null} ${t} ${this.onAction?this.actionBtnTemplate():null}
`}};ea.styles=[Lt.globalCss,jT],Df([At()],ea.prototype,"title",2),Df([At()],ea.prototype,"onAction",2),Df([At()],ea.prototype,"actionIcon",2),Df([At({type:Boolean})],ea.prototype,"border",2),ea=Df([Ut("wcm-modal-header")],ea);const pt={MOBILE_BREAKPOINT:600,WCM_RECENT_WALLET_DATA:"WCM_RECENT_WALLET_DATA",EXPLORER_WALLET_URL:"https://explorer.walletconnect.com/?type=wallet",getShadowRootElement(r,e){const t=r.renderRoot.querySelector(e);if(!t)throw new Error(`${e} not found`);return t},getWalletIcon({id:r,image_id:e}){const{walletImages:t}=qi.state;return t?.[r]?t[r]:e?_i.getWalletImageUrl(e):""},getWalletName(r,e=!1){return e&&r.length>8?`${r.substring(0,8)}..`:r},isMobileAnimation(){return window.innerWidth<=pt.MOBILE_BREAKPOINT},async preloadImage(r){const e=new Promise((t,i)=>{const n=new Image;n.onload=t,n.onerror=i,n.crossOrigin="anonymous",n.src=r});return Promise.race([e,je.wait(3e3)])},getErrorMessage(r){return r instanceof Error?r.message:"Unknown Error"},debounce(r,e=500){let t;return(...i)=>{function n(){r(...i)}t&&clearTimeout(t),t=setTimeout(n,e)}},handleMobileLinking(r,e="_self"){const{walletConnectUri:t}=yr.state,{mobile:i,name:n}=r,s=i?.native,a=i?.universal;pt.setRecentWallet(r);function f(h){if(s){const u=je.formatNativeUrl(s,h,n);je.openHref(u,e)}else if(a){const u=je.formatUniversalUrl(a,h,n);je.openHref(u,e)}}t&&f(t)},handleAndroidLinking(){const{walletConnectUri:r}=yr.state;r&&(je.setWalletConnectAndroidDeepLink(r),je.openHref(r,je.isTelegram()?"_blank":"_self"))},async handleUriCopy(){const{walletConnectUri:r}=yr.state;if(r)try{await navigator.clipboard.writeText(r),eo.openToast("Link copied","success")}catch{eo.openToast("Failed to copy","error")}},getCustomImageUrls(){const{walletImages:r}=qi.state,e=Object.values(r??{});return Object.values(e)},truncate(r,e=8){return r.length<=e?r:`${r.substring(0,4)}...${r.substring(r.length-4)}`},setRecentWallet(r){try{localStorage.setItem(pt.WCM_RECENT_WALLET_DATA,JSON.stringify(r))}catch{console.info("Unable to set recent wallet")}},getRecentWallet(){try{const r=localStorage.getItem(pt.WCM_RECENT_WALLET_DATA);return r?JSON.parse(r):void 0}catch{console.info("Unable to get recent wallet")}},caseSafeIncludes(r,e){return r.toUpperCase().includes(e.toUpperCase())},openWalletExplorerUrl(){je.openHref(pt.EXPLORER_WALLET_URL,"_blank")},getCachedRouterWalletPlatforms(){const{desktop:r,mobile:e}=je.getWalletRouterData(),t=!!r?.native,i=!!r?.universal,n=!!e?.native||!!e?.universal;return{isDesktop:t,isMobile:n,isWeb:i}},goToConnectingView(r){lr.setData({Wallet:r});const e=je.isMobile(),{isDesktop:t,isWeb:i,isMobile:n}=pt.getCachedRouterWalletPlatforms();e?n?(lr.push("MobileConnecting"),!je.isAndroid()&&je.isTelegram()&&this.handleMobileLinking(r,"_blank")):i?lr.push("WebConnecting"):lr.push("InstallWallet"):t?lr.push("DesktopConnecting"):i?lr.push("WebConnecting"):n?lr.push("MobileQrcodeConnecting"):lr.push("InstallWallet")}},VT=jt`.wcm-router{overflow:hidden;will-change:transform}.wcm-content{display:flex;flex-direction:column}`;var GT=Object.defineProperty,YT=Object.getOwnPropertyDescriptor,Op=(r,e,t,i)=>{for(var n=i>1?void 0:i?YT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&>(e,t,n),n};let Of=class extends Ct{constructor(){super(),this.view=lr.state.view,this.prevView=lr.state.view,this.unsubscribe=void 0,this.oldHeight="0px",this.resizeObserver=void 0,this.unsubscribe=lr.subscribe(r=>{this.view!==r.view&&this.onChangeRoute()})}firstUpdated(){this.resizeObserver=new ResizeObserver(([r])=>{const e=`${r.contentRect.height}px`;this.oldHeight!=="0px"&&Xo(this.routerEl,{height:[this.oldHeight,e]},{duration:.2}),this.oldHeight=e}),this.resizeObserver.observe(this.contentEl)}disconnectedCallback(){var r,e;(r=this.unsubscribe)==null||r.call(this),(e=this.resizeObserver)==null||e.disconnect()}get routerEl(){return pt.getShadowRootElement(this,".wcm-router")}get contentEl(){return pt.getShadowRootElement(this,".wcm-content")}viewTemplate(){switch(this.view){case"ConnectWallet":return Ee``;case"DesktopConnecting":return Ee``;case"MobileConnecting":return Ee``;case"WebConnecting":return Ee``;case"MobileQrcodeConnecting":return Ee``;case"WalletExplorer":return Ee``;case"Qrcode":return Ee``;case"InstallWallet":return Ee``;default:return Ee`
Not Found
`}}async onChangeRoute(){await Xo(this.routerEl,{opacity:[1,0],scale:[1,1.02]},{duration:.15,delay:.1}).finished,this.view=lr.state.view,Xo(this.routerEl,{opacity:[0,1],scale:[.99,1]},{duration:.37,delay:.05})}render(){return Ee`
${this.viewTemplate()}
`}};Of.styles=[Lt.globalCss,VT],Op([xi()],Of.prototype,"view",2),Op([xi()],Of.prototype,"prevView",2),Of=Op([Ut("wcm-modal-router")],Of);const JT=jt`div{height:36px;width:max-content;display:flex;justify-content:center;align-items:center;padding:9px 15px 11px;position:absolute;top:12px;box-shadow:0 6px 14px -6px rgba(10,16,31,.3),0 10px 32px -4px rgba(10,16,31,.15);z-index:2;left:50%;transform:translateX(-50%);pointer-events:none;backdrop-filter:blur(20px) saturate(1.8);-webkit-backdrop-filter:blur(20px) saturate(1.8);border-radius:var(--wcm-notification-border-radius);border:1px solid var(--wcm-color-overlay);background-color:var(--wcm-color-overlay)}svg{margin-right:5px}@-moz-document url-prefix(){div{background-color:var(--wcm-color-bg-3)}}.wcm-success path{fill:var(--wcm-accent-color)}.wcm-error path{fill:var(--wcm-error-color)}`;var QT=Object.defineProperty,ZT=Object.getOwnPropertyDescriptor,Uw=(r,e,t,i)=>{for(var n=i>1?void 0:i?ZT(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&QT(e,t,n),n};let Lh=class extends Ct{constructor(){super(),this.open=!1,this.unsubscribe=void 0,this.timeout=void 0,this.unsubscribe=eo.subscribe(r=>{r.open?(this.open=!0,this.timeout=setTimeout(()=>eo.closeToast(),2200)):(this.open=!1,clearTimeout(this.timeout))})}disconnectedCallback(){var r;(r=this.unsubscribe)==null||r.call(this),clearTimeout(this.timeout),eo.closeToast()}render(){const{message:r,variant:e}=eo.state,t={"wcm-success":e==="success","wcm-error":e==="error"};return this.open?Ee`
${e==="success"?Kt.CHECKMARK_ICON:null} ${e==="error"?Kt.CROSS_ICON:null}${r}
`:null}};Lh.styles=[Lt.globalCss,JT],Uw([xi()],Lh.prototype,"open",2),Lh=Uw([Ut("wcm-modal-toast")],Lh);const XT=.1,qw=2.5,Ms=7;function Rp(r,e,t){return r===e?!1:(r-e<0?e-r:r-e)<=t+XT}function e$(r,e){const t=Array.prototype.slice.call(Sf.create(r,{errorCorrectionLevel:e}).modules.data,0),i=Math.sqrt(t.length);return t.reduce((n,s,a)=>(a%i===0?n.push([s]):n[n.length-1].push(s))&&n,[])}const t$={generate(r,e,t){const i="#141414",n="#ffffff",s=[],a=e$(r,"Q"),f=e/a.length,h=[{x:0,y:0},{x:1,y:0},{x:0,y:1}];h.forEach(({x:O,y:$})=>{const j=(a.length-Ms)*f*O,H=(a.length-Ms)*f*$,F=.45;for(let G=0;G`)}});const u=Math.floor((t+25)/f),g=a.length/2-u/2,w=a.length/2+u/2-1,M=[];a.forEach((O,$)=>{O.forEach((j,H)=>{if(a[$][H]&&!($a.length-(Ms+1)&&Ha.length-(Ms+1))&&!($>g&&$g&&H{C[O]?C[O].push($):C[O]=[$]}),Object.entries(C).map(([O,$])=>{const j=$.filter(H=>$.every(F=>!Rp(H,F,f)));return[Number(O),j]}).forEach(([O,$])=>{$.forEach(j=>{s.push(gr``)})}),Object.entries(C).filter(([O,$])=>$.length>1).map(([O,$])=>{const j=$.filter(H=>$.some(F=>Rp(H,F,f)));return[Number(O),j]}).map(([O,$])=>{$.sort((H,F)=>HG.some(B=>Rp(H,B,f)));F?F.push(H):j.push([H])}return[O,j.map(H=>[H[0],H[H.length-1]])]}).forEach(([O,$])=>{$.forEach(([j,H])=>{s.push(gr``)})}),s}},r$=jt`@keyframes fadeIn{0%{opacity:0}100%{opacity:1}}div{position:relative;user-select:none;display:block;overflow:hidden;aspect-ratio:1/1;animation:fadeIn ease .2s}.wcm-dark{background-color:#fff;border-radius:var(--wcm-container-border-radius);padding:18px;box-shadow:0 2px 5px #000}svg:first-child,wcm-wallet-image{position:absolute;top:50%;left:50%;transform:translateY(-50%) translateX(-50%)}wcm-wallet-image{transform:translateY(-50%) translateX(-50%)}wcm-wallet-image{width:25%;height:25%;border-radius:var(--wcm-wallet-icon-border-radius)}svg:first-child{transform:translateY(-50%) translateX(-50%) scale(.9)}svg:first-child path:first-child{fill:var(--wcm-accent-color)}svg:first-child path:last-child{stroke:var(--wcm-color-overlay)}`;var i$=Object.defineProperty,n$=Object.getOwnPropertyDescriptor,sc=(r,e,t,i)=>{for(var n=i>1?void 0:i?n$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&i$(e,t,n),n};let Cs=class extends Ct{constructor(){super(...arguments),this.uri="",this.size=0,this.imageId=void 0,this.walletId=void 0,this.imageUrl=void 0}svgTemplate(){const e=Xs.state.themeMode==="light"?this.size:this.size-18*2;return gr`${t$.generate(this.uri,e,e/4)}`}render(){const r={"wcm-dark":Xs.state.themeMode==="dark"};return Ee`
${this.walletId||this.imageUrl?Ee``:Kt.WALLET_CONNECT_ICON_COLORED} ${this.svgTemplate()}
`}};Cs.styles=[Lt.globalCss,r$],sc([At()],Cs.prototype,"uri",2),sc([At({type:Number})],Cs.prototype,"size",2),sc([At()],Cs.prototype,"imageId",2),sc([At()],Cs.prototype,"walletId",2),sc([At()],Cs.prototype,"imageUrl",2),Cs=sc([Ut("wcm-qrcode")],Cs);const s$=jt`:host{position:relative;height:28px;width:80%}input{width:100%;height:100%;line-height:28px!important;border-radius:var(--wcm-input-border-radius);font-style:normal;font-family:-apple-system,system-ui,BlinkMacSystemFont,'Segoe UI',Roboto,Ubuntu,'Helvetica Neue',sans-serif;font-feature-settings:'case' on;font-weight:500;font-size:16px;letter-spacing:-.03em;padding:0 10px 0 34px;transition:.2s all ease;color:var(--wcm-color-fg-1);background-color:var(--wcm-color-bg-3);box-shadow:inset 0 0 0 1px var(--wcm-color-overlay);caret-color:var(--wcm-accent-color)}input::placeholder{color:var(--wcm-color-fg-2)}svg{left:10px;top:4px;pointer-events:none;position:absolute;width:20px;height:20px}input:focus-within{box-shadow:inset 0 0 0 1px var(--wcm-accent-color)}path{fill:var(--wcm-color-fg-2)}`;var o$=Object.defineProperty,a$=Object.getOwnPropertyDescriptor,zw=(r,e,t,i)=>{for(var n=i>1?void 0:i?a$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&o$(e,t,n),n};let Bh=class extends Ct{constructor(){super(...arguments),this.onChange=()=>null}render(){return Ee` ${Kt.SEARCH_ICON}`}};Bh.styles=[Lt.globalCss,s$],zw([At()],Bh.prototype,"onChange",2),Bh=zw([Ut("wcm-search-input")],Bh);const c$=jt`@keyframes rotate{100%{transform:rotate(360deg)}}@keyframes dash{0%{stroke-dasharray:1,150;stroke-dashoffset:0}50%{stroke-dasharray:90,150;stroke-dashoffset:-35}100%{stroke-dasharray:90,150;stroke-dashoffset:-124}}svg{animation:rotate 2s linear infinite;display:flex;justify-content:center;align-items:center}svg circle{stroke-linecap:round;animation:dash 1.5s ease infinite;stroke:var(--wcm-accent-color)}`;var f$=Object.defineProperty,l$=Object.getOwnPropertyDescriptor,h$=(r,e,t,i)=>{for(var n=i>1?void 0:i?l$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&f$(e,t,n),n};let Tp=class extends Ct{render(){return Ee``}};Tp.styles=[Lt.globalCss,c$],Tp=h$([Ut("wcm-spinner")],Tp);const u$=jt`span{font-style:normal;font-family:var(--wcm-font-family);font-feature-settings:var(--wcm-font-feature-settings)}.wcm-xsmall-bold{font-family:var(--wcm-text-xsmall-bold-font-family);font-weight:var(--wcm-text-xsmall-bold-weight);font-size:var(--wcm-text-xsmall-bold-size);line-height:var(--wcm-text-xsmall-bold-line-height);letter-spacing:var(--wcm-text-xsmall-bold-letter-spacing);text-transform:var(--wcm-text-xsmall-bold-text-transform)}.wcm-xsmall-regular{font-family:var(--wcm-text-xsmall-regular-font-family);font-weight:var(--wcm-text-xsmall-regular-weight);font-size:var(--wcm-text-xsmall-regular-size);line-height:var(--wcm-text-xsmall-regular-line-height);letter-spacing:var(--wcm-text-xsmall-regular-letter-spacing);text-transform:var(--wcm-text-xsmall-regular-text-transform)}.wcm-small-thin{font-family:var(--wcm-text-small-thin-font-family);font-weight:var(--wcm-text-small-thin-weight);font-size:var(--wcm-text-small-thin-size);line-height:var(--wcm-text-small-thin-line-height);letter-spacing:var(--wcm-text-small-thin-letter-spacing);text-transform:var(--wcm-text-small-thin-text-transform)}.wcm-small-regular{font-family:var(--wcm-text-small-regular-font-family);font-weight:var(--wcm-text-small-regular-weight);font-size:var(--wcm-text-small-regular-size);line-height:var(--wcm-text-small-regular-line-height);letter-spacing:var(--wcm-text-small-regular-letter-spacing);text-transform:var(--wcm-text-small-regular-text-transform)}.wcm-medium-regular{font-family:var(--wcm-text-medium-regular-font-family);font-weight:var(--wcm-text-medium-regular-weight);font-size:var(--wcm-text-medium-regular-size);line-height:var(--wcm-text-medium-regular-line-height);letter-spacing:var(--wcm-text-medium-regular-letter-spacing);text-transform:var(--wcm-text-medium-regular-text-transform)}.wcm-big-bold{font-family:var(--wcm-text-big-bold-font-family);font-weight:var(--wcm-text-big-bold-weight);font-size:var(--wcm-text-big-bold-size);line-height:var(--wcm-text-big-bold-line-height);letter-spacing:var(--wcm-text-big-bold-letter-spacing);text-transform:var(--wcm-text-big-bold-text-transform)}:host(*){color:var(--wcm-color-fg-1)}.wcm-color-primary{color:var(--wcm-color-fg-1)}.wcm-color-secondary{color:var(--wcm-color-fg-2)}.wcm-color-tertiary{color:var(--wcm-color-fg-3)}.wcm-color-inverse{color:var(--wcm-accent-fill-color)}.wcm-color-accnt{color:var(--wcm-accent-color)}.wcm-color-error{color:var(--wcm-error-color)}`;var d$=Object.defineProperty,p$=Object.getOwnPropertyDescriptor,$p=(r,e,t,i)=>{for(var n=i>1?void 0:i?p$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&d$(e,t,n),n};let Rf=class extends Ct{constructor(){super(...arguments),this.variant="medium-regular",this.color="primary"}render(){const r={"wcm-big-bold":this.variant==="big-bold","wcm-medium-regular":this.variant==="medium-regular","wcm-small-regular":this.variant==="small-regular","wcm-small-thin":this.variant==="small-thin","wcm-xsmall-regular":this.variant==="xsmall-regular","wcm-xsmall-bold":this.variant==="xsmall-bold","wcm-color-primary":this.color==="primary","wcm-color-secondary":this.color==="secondary","wcm-color-tertiary":this.color==="tertiary","wcm-color-inverse":this.color==="inverse","wcm-color-accnt":this.color==="accent","wcm-color-error":this.color==="error"};return Ee``}};Rf.styles=[Lt.globalCss,u$],$p([At()],Rf.prototype,"variant",2),$p([At()],Rf.prototype,"color",2),Rf=$p([Ut("wcm-text")],Rf);const g$=jt`button{width:100%;height:100%;border-radius:var(--wcm-button-hover-highlight-border-radius);display:flex;align-items:flex-start}button:active{background-color:var(--wcm-color-overlay)}@media(hover:hover){button:hover{background-color:var(--wcm-color-overlay)}}button>div{width:80px;padding:5px 0;display:flex;flex-direction:column;align-items:center}wcm-text{width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:center}wcm-wallet-image{height:60px;width:60px;transition:all .2s ease;border-radius:var(--wcm-wallet-icon-border-radius);margin-bottom:5px}.wcm-sublabel{margin-top:2px}`;var v$=Object.defineProperty,m$=Object.getOwnPropertyDescriptor,oo=(r,e,t,i)=>{for(var n=i>1?void 0:i?m$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&v$(e,t,n),n};let as=class extends Ct{constructor(){super(...arguments),this.onClick=()=>null,this.name="",this.walletId="",this.label=void 0,this.imageId=void 0,this.installed=!1,this.recent=!1}sublabelTemplate(){return this.recent?Ee`RECENT`:this.installed?Ee`INSTALLED`:null}handleClick(){S3.click({name:"WALLET_BUTTON",walletId:this.walletId}),this.onClick()}render(){var r;return Ee``}};as.styles=[Lt.globalCss,g$],oo([At()],as.prototype,"onClick",2),oo([At()],as.prototype,"name",2),oo([At()],as.prototype,"walletId",2),oo([At()],as.prototype,"label",2),oo([At()],as.prototype,"imageId",2),oo([At({type:Boolean})],as.prototype,"installed",2),oo([At({type:Boolean})],as.prototype,"recent",2),as=oo([Ut("wcm-wallet-button")],as);const b$=jt`:host{display:block}div{overflow:hidden;position:relative;border-radius:inherit;width:100%;height:100%;background-color:var(--wcm-color-overlay)}svg{position:relative;width:100%;height:100%}div::after{content:'';position:absolute;top:0;bottom:0;left:0;right:0;border-radius:inherit;border:1px solid var(--wcm-color-overlay)}div img{width:100%;height:100%;object-fit:cover;object-position:center}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var w$=Object.defineProperty,y$=Object.getOwnPropertyDescriptor,Fh=(r,e,t,i)=>{for(var n=i>1?void 0:i?y$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&w$(e,t,n),n};let oc=class extends Ct{constructor(){super(...arguments),this.walletId="",this.imageId=void 0,this.imageUrl=void 0}render(){var r;const e=(r=this.imageUrl)!=null&&r.length?this.imageUrl:pt.getWalletIcon({id:this.walletId,image_id:this.imageId});return Ee`${e.length?Ee`
${this.id}
`:Kt.WALLET_PLACEHOLDER}`}};oc.styles=[Lt.globalCss,b$],Fh([At()],oc.prototype,"walletId",2),Fh([At()],oc.prototype,"imageId",2),Fh([At()],oc.prototype,"imageUrl",2),oc=Fh([Ut("wcm-wallet-image")],oc);var _$=Object.defineProperty,x$=Object.getOwnPropertyDescriptor,Hw=(r,e,t,i)=>{for(var n=i>1?void 0:i?x$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&_$(e,t,n),n};let Np=class extends Ct{constructor(){super(),this.preload=!0,this.preloadData()}async loadImages(r){try{r?.length&&await Promise.all(r.map(async e=>pt.preloadImage(e)))}catch{console.info("Unsuccessful attempt at preloading some images",r)}}async preloadListings(){if(qi.state.enableExplorer){await _i.getRecomendedWallets(),yr.setIsDataLoaded(!0);const{recomendedWallets:r}=_i.state,e=r.map(t=>pt.getWalletIcon(t));await this.loadImages(e)}else yr.setIsDataLoaded(!0)}async preloadCustomImages(){const r=pt.getCustomImageUrls();await this.loadImages(r)}async preloadData(){try{this.preload&&(this.preload=!1,await Promise.all([this.preloadListings(),this.preloadCustomImages()]))}catch(r){console.error(r),eo.openToast("Failed preloading","error")}}};Hw([xi()],Np.prototype,"preload",2),Np=Hw([Ut("wcm-explorer-context")],Np);var A$=Object.defineProperty,E$=Object.getOwnPropertyDescriptor,S$=(r,e,t,i)=>{for(var n=i>1?void 0:i?E$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&A$(e,t,n),n};let kw=class extends Ct{constructor(){super(),this.unsubscribeTheme=void 0,Lt.setTheme(),this.unsubscribeTheme=Xs.subscribe(Lt.setTheme)}disconnectedCallback(){var r;(r=this.unsubscribeTheme)==null||r.call(this)}};kw=S$([Ut("wcm-theme-context")],kw);const I$=jt`@keyframes scroll{0%{transform:translate3d(0,0,0)}100%{transform:translate3d(calc(-70px * 9),0,0)}}.wcm-slider{position:relative;overflow-x:hidden;padding:10px 0;margin:0 -20px;width:calc(100% + 40px)}.wcm-track{display:flex;width:calc(70px * 18);animation:scroll 20s linear infinite;opacity:.7}.wcm-track svg{margin:0 5px}wcm-wallet-image{width:60px;height:60px;margin:0 5px;border-radius:var(--wcm-wallet-icon-border-radius)}.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between}.wcm-title{display:flex;align-items:center;margin-bottom:10px}.wcm-title svg{margin-right:6px}.wcm-title path{fill:var(--wcm-accent-color)}wcm-modal-footer .wcm-title{padding:0 10px}wcm-button-big{position:absolute;top:50%;left:50%;transform:translateY(-50%) translateX(-50%);filter:drop-shadow(0 0 17px var(--wcm-color-bg-1))}wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-info-footer wcm-text{text-align:center;margin-bottom:15px}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var M$=Object.defineProperty,C$=Object.getOwnPropertyDescriptor,P$=(r,e,t,i)=>{for(var n=i>1?void 0:i?C$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&M$(e,t,n),n};let Lp=class extends Ct{onGoToQrcode(){lr.push("Qrcode")}render(){const{recomendedWallets:r}=_i.state,e=[...r,...r],t=je.RECOMMENDED_WALLET_AMOUNT*2;return Ee`
${Kt.MOBILE_ICON}WalletConnect
${[...Array(t)].map((i,n)=>{const s=e[n%e.length];return s?Ee``:Kt.WALLET_PLACEHOLDER})}
Select Wallet
Choose WalletConnect to see supported apps on your device`}};Lp.styles=[Lt.globalCss,I$],Lp=P$([Ut("wcm-android-wallet-selection")],Lp);const D$=jt`@keyframes loading{to{stroke-dashoffset:0}}@keyframes shake{10%,90%{transform:translate3d(-1px,0,0)}20%,80%{transform:translate3d(1px,0,0)}30%,50%,70%{transform:translate3d(-2px,0,0)}40%,60%{transform:translate3d(2px,0,0)}}:host{display:flex;flex-direction:column;align-items:center}div{position:relative;width:110px;height:110px;display:flex;justify-content:center;align-items:center;margin:40px 0 20px 0;transform:translate3d(0,0,0)}svg{position:absolute;width:110px;height:110px;fill:none;stroke:transparent;stroke-linecap:round;stroke-width:2px;top:0;left:0}use{stroke:var(--wcm-accent-color);animation:loading 1s linear infinite}wcm-wallet-image{border-radius:var(--wcm-wallet-icon-large-border-radius);width:90px;height:90px}wcm-text{margin-bottom:40px}.wcm-error svg{stroke:var(--wcm-error-color)}.wcm-error use{display:none}.wcm-error{animation:shake .4s cubic-bezier(.36,.07,.19,.97) both}.wcm-stale svg,.wcm-stale use{display:none}`;var O$=Object.defineProperty,R$=Object.getOwnPropertyDescriptor,ac=(r,e,t,i)=>{for(var n=i>1?void 0:i?R$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&O$(e,t,n),n};let ao=class extends Ct{constructor(){super(...arguments),this.walletId=void 0,this.imageId=void 0,this.isError=!1,this.isStale=!1,this.label=""}svgLoaderTemplate(){var r,e;const s=(e=(r=Xs.state.themeVariables)==null?void 0:r["--wcm-wallet-icon-large-border-radius"])!=null?e:Lt.getPreset("--wcm-wallet-icon-large-border-radius");let a=0;s.includes("%")?a=88/100*parseInt(s,10):a=parseInt(s,10),a*=1.17;const f=317-a*1.57,h=425-a*1.8;return Ee``}render(){const r={"wcm-error":this.isError,"wcm-stale":this.isStale};return Ee`
${this.svgLoaderTemplate()}
${this.isError?"Connection declined":this.label}`}};ao.styles=[Lt.globalCss,D$],ac([At()],ao.prototype,"walletId",2),ac([At()],ao.prototype,"imageId",2),ac([At({type:Boolean})],ao.prototype,"isError",2),ac([At({type:Boolean})],ao.prototype,"isStale",2),ac([At()],ao.prototype,"label",2),ao=ac([Ut("wcm-connector-waiting")],ao);const cc={manualWallets(){var r,e;const{mobileWallets:t,desktopWallets:i}=qi.state,n=(r=cc.recentWallet())==null?void 0:r.id,s=je.isMobile()?t:i,a=s?.filter(f=>n!==f.id);return(e=je.isMobile()?a?.map(({id:f,name:h,links:u})=>({id:f,name:h,mobile:u,links:u})):a?.map(({id:f,name:h,links:u})=>({id:f,name:h,desktop:u,links:u})))!=null?e:[]},recentWallet(){return pt.getRecentWallet()},recomendedWallets(r=!1){var e;const t=r||(e=cc.recentWallet())==null?void 0:e.id,{recomendedWallets:i}=_i.state;return i.filter(s=>t!==s.id)}},co={onConnecting(r){pt.goToConnectingView(r)},manualWalletsTemplate(){return cc.manualWallets().map(e=>Ee``)},recomendedWalletsTemplate(r=!1){return cc.recomendedWallets(r).map(t=>Ee``)},recentWalletTemplate(){const r=cc.recentWallet();if(r)return Ee``}},T$=jt`.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between}.wcm-desktop-title,.wcm-mobile-title{display:flex;align-items:center}.wcm-mobile-title{justify-content:space-between;margin-bottom:20px;margin-top:-10px}.wcm-desktop-title{margin-bottom:10px;padding:0 10px}.wcm-subtitle{display:flex;align-items:center}.wcm-subtitle:last-child path{fill:var(--wcm-color-fg-3)}.wcm-desktop-title svg,.wcm-mobile-title svg{margin-right:6px}.wcm-desktop-title path,.wcm-mobile-title path{fill:var(--wcm-accent-color)}`;var $$=Object.defineProperty,N$=Object.getOwnPropertyDescriptor,L$=(r,e,t,i)=>{for(var n=i>1?void 0:i?N$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&$$(e,t,n),n};let Bp=class extends Ct{render(){const{explorerExcludedWalletIds:r,enableExplorer:e}=qi.state,t=r!=="ALL"&&e,i=co.manualWalletsTemplate(),n=co.recomendedWalletsTemplate();let a=[co.recentWalletTemplate(),...i,...n];a=a.filter(Boolean);const f=a.length>4||t;let h=[];f?h=a.slice(0,3):h=a;const u=!!h.length;return Ee`
${Kt.MOBILE_ICON}Mobile
${Kt.SCAN_ICON}Scan with your wallet
${u?Ee`
${Kt.DESKTOP_ICON}Desktop
${h} ${f?Ee``:null}
`:null}`}};Bp.styles=[Lt.globalCss,T$],Bp=L$([Ut("wcm-desktop-wallet-selection")],Bp);const B$=jt`div{background-color:var(--wcm-color-bg-2);padding:10px 20px 15px 20px;border-top:1px solid var(--wcm-color-bg-3);text-align:center}a{color:var(--wcm-accent-color);text-decoration:none;transition:opacity .2s ease-in-out;display:inline}a:active{opacity:.8}@media(hover:hover){a:hover{opacity:.8}}`;var F$=Object.defineProperty,U$=Object.getOwnPropertyDescriptor,q$=(r,e,t,i)=>{for(var n=i>1?void 0:i?U$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&F$(e,t,n),n};let Fp=class extends Ct{render(){const{termsOfServiceUrl:r,privacyPolicyUrl:e}=qi.state;return r??e?Ee`
By connecting your wallet to this app, you agree to the app's ${r?Ee`Terms of Service`:null} ${r&&e?"and":null} ${e?Ee`Privacy Policy`:null}
`:null}};Fp.styles=[Lt.globalCss,B$],Fp=q$([Ut("wcm-legal-notice")],Fp);const z$=jt`div{display:grid;grid-template-columns:repeat(4,80px);margin:0 -10px;justify-content:space-between;row-gap:10px}`;var H$=Object.defineProperty,k$=Object.getOwnPropertyDescriptor,j$=(r,e,t,i)=>{for(var n=i>1?void 0:i?k$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&H$(e,t,n),n};let Up=class extends Ct{onQrcode(){lr.push("Qrcode")}render(){const{explorerExcludedWalletIds:r,enableExplorer:e}=qi.state,t=r!=="ALL"&&e,i=co.manualWalletsTemplate(),n=co.recomendedWalletsTemplate();let a=[co.recentWalletTemplate(),...i,...n];a=a.filter(Boolean);const f=a.length>8||t;let h=[];f?h=a.slice(0,7):h=a;const u=!!h.length;return Ee`${u?Ee`
${h} ${f?Ee``:null}
`:null}`}};Up.styles=[Lt.globalCss,z$],Up=j$([Ut("wcm-mobile-wallet-selection")],Up);const W$=jt`:host{all:initial}.wcm-overlay{top:0;bottom:0;left:0;right:0;position:fixed;z-index:var(--wcm-z-index);overflow:hidden;display:flex;justify-content:center;align-items:center;opacity:0;pointer-events:none;background-color:var(--wcm-overlay-background-color);backdrop-filter:var(--wcm-overlay-backdrop-filter)}@media(max-height:720px) and (orientation:landscape){.wcm-overlay{overflow:scroll;align-items:flex-start;padding:20px 0}}.wcm-active{pointer-events:auto}.wcm-container{position:relative;max-width:360px;width:100%;outline:0;border-radius:var(--wcm-background-border-radius) var(--wcm-background-border-radius) var(--wcm-container-border-radius) var(--wcm-container-border-radius);border:1px solid var(--wcm-color-overlay);overflow:hidden}.wcm-card{width:100%;position:relative;border-radius:var(--wcm-container-border-radius);overflow:hidden;box-shadow:0 6px 14px -6px rgba(10,16,31,.12),0 10px 32px -4px rgba(10,16,31,.1),0 0 0 1px var(--wcm-color-overlay);background-color:var(--wcm-color-bg-1);color:var(--wcm-color-fg-1)}@media(max-width:600px){.wcm-container{max-width:440px;border-radius:var(--wcm-background-border-radius) var(--wcm-background-border-radius) 0 0}.wcm-card{border-radius:var(--wcm-container-border-radius) var(--wcm-container-border-radius) 0 0}.wcm-overlay{align-items:flex-end}}@media(max-width:440px){.wcm-container{border:0}}`;var K$=Object.defineProperty,V$=Object.getOwnPropertyDescriptor,qp=(r,e,t,i)=>{for(var n=i>1?void 0:i?V$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&K$(e,t,n),n};let fc=class extends Ct{constructor(){super(),this.open=!1,this.active=!1,this.unsubscribeModal=void 0,this.abortController=void 0,this.unsubscribeModal=Ko.subscribe(r=>{r.open?this.onOpenModalEvent():this.onCloseModalEvent()})}disconnectedCallback(){var r;(r=this.unsubscribeModal)==null||r.call(this)}get overlayEl(){return pt.getShadowRootElement(this,".wcm-overlay")}get containerEl(){return pt.getShadowRootElement(this,".wcm-container")}toggleBodyScroll(r){if(document.querySelector("body"))if(r){const t=document.getElementById("wcm-styles");t?.remove()}else document.head.insertAdjacentHTML("beforeend",'')}onCloseModal(r){r.target===r.currentTarget&&Ko.close()}onOpenModalEvent(){this.toggleBodyScroll(!1),this.addKeyboardEvents(),this.open=!0,setTimeout(async()=>{const r=pt.isMobileAnimation()?{y:["50vh","0vh"]}:{scale:[.98,1]},e=.1,t=.2;await Promise.all([Xo(this.overlayEl,{opacity:[0,1]},{delay:e,duration:t}).finished,Xo(this.containerEl,r,{delay:e,duration:t}).finished]),this.active=!0},0)}async onCloseModalEvent(){this.toggleBodyScroll(!0),this.removeKeyboardEvents();const r=pt.isMobileAnimation()?{y:["0vh","50vh"]}:{scale:[1,.98]},e=.2;await Promise.all([Xo(this.overlayEl,{opacity:[1,0]},{duration:e}).finished,Xo(this.containerEl,r,{duration:e}).finished]),this.containerEl.removeAttribute("style"),this.active=!1,this.open=!1}addKeyboardEvents(){this.abortController=new AbortController,window.addEventListener("keydown",r=>{var e;r.key==="Escape"?Ko.close():r.key==="Tab"&&((e=r.target)!=null&&e.tagName.includes("wcm-")||this.containerEl.focus())},this.abortController),this.containerEl.focus()}removeKeyboardEvents(){var r;(r=this.abortController)==null||r.abort(),this.abortController=void 0}render(){const r={"wcm-overlay":!0,"wcm-active":this.active};return Ee`
${this.open?Ee`
`:null}
`}};fc.styles=[Lt.globalCss,W$],qp([xi()],fc.prototype,"open",2),qp([xi()],fc.prototype,"active",2),fc=qp([Ut("wcm-modal")],fc);const G$=jt`div{display:flex;margin-top:15px}slot{display:inline-block;margin:0 5px}wcm-button{margin:0 5px}`;var Y$=Object.defineProperty,J$=Object.getOwnPropertyDescriptor,Tf=(r,e,t,i)=>{for(var n=i>1?void 0:i?J$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Y$(e,t,n),n};let ta=class extends Ct{constructor(){super(...arguments),this.isMobile=!1,this.isDesktop=!1,this.isWeb=!1,this.isRetry=!1}onMobile(){je.isMobile()?lr.replace("MobileConnecting"):lr.replace("MobileQrcodeConnecting")}onDesktop(){lr.replace("DesktopConnecting")}onWeb(){lr.replace("WebConnecting")}render(){return Ee`
${this.isRetry?Ee``:null} ${this.isMobile?Ee`Mobile`:null} ${this.isDesktop?Ee`Desktop`:null} ${this.isWeb?Ee`Web`:null}
`}};ta.styles=[Lt.globalCss,G$],Tf([At({type:Boolean})],ta.prototype,"isMobile",2),Tf([At({type:Boolean})],ta.prototype,"isDesktop",2),Tf([At({type:Boolean})],ta.prototype,"isWeb",2),Tf([At({type:Boolean})],ta.prototype,"isRetry",2),ta=Tf([Ut("wcm-platform-selection")],ta);const Q$=jt`button{display:flex;flex-direction:column;padding:5px 10px;border-radius:var(--wcm-button-hover-highlight-border-radius);height:100%;justify-content:flex-start}.wcm-icons{width:60px;height:60px;display:flex;flex-wrap:wrap;padding:7px;border-radius:var(--wcm-wallet-icon-border-radius);justify-content:space-between;align-items:center;margin-bottom:5px;background-color:var(--wcm-color-bg-2);box-shadow:inset 0 0 0 1px var(--wcm-color-overlay)}button:active{background-color:var(--wcm-color-overlay)}@media(hover:hover){button:hover{background-color:var(--wcm-color-overlay)}}.wcm-icons img{width:21px;height:21px;object-fit:cover;object-position:center;border-radius:calc(var(--wcm-wallet-icon-border-radius)/ 2);border:1px solid var(--wcm-color-overlay)}.wcm-icons svg{width:21px;height:21px}.wcm-icons img:nth-child(1),.wcm-icons img:nth-child(2),.wcm-icons svg:nth-child(1),.wcm-icons svg:nth-child(2){margin-bottom:4px}wcm-text{width:100%;text-align:center}#wallet-placeholder-fill{fill:var(--wcm-color-bg-3)}#wallet-placeholder-dash{stroke:var(--wcm-color-overlay)}`;var Z$=Object.defineProperty,X$=Object.getOwnPropertyDescriptor,eN=(r,e,t,i)=>{for(var n=i>1?void 0:i?X$(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Z$(e,t,n),n};let zp=class extends Ct{onClick(){lr.push("WalletExplorer")}render(){const{recomendedWallets:r}=_i.state,e=cc.manualWallets(),t=[...r,...e].reverse().slice(0,4);return Ee``}};zp.styles=[Lt.globalCss,Q$],zp=eN([Ut("wcm-view-all-wallets-button")],zp);const tN=jt`.wcm-qr-container{width:100%;display:flex;justify-content:center;align-items:center;aspect-ratio:1/1}`;var rN=Object.defineProperty,iN=Object.getOwnPropertyDescriptor,Uh=(r,e,t,i)=>{for(var n=i>1?void 0:i?iN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&rN(e,t,n),n};let lc=class extends Ct{constructor(){super(),this.walletId="",this.imageId="",this.uri="",setTimeout(()=>{const{walletConnectUri:r}=yr.state;this.uri=r},0)}get overlayEl(){return pt.getShadowRootElement(this,".wcm-qr-container")}render(){return Ee`
${this.uri?Ee``:Ee``}
`}};lc.styles=[Lt.globalCss,tN],Uh([At()],lc.prototype,"walletId",2),Uh([At()],lc.prototype,"imageId",2),Uh([xi()],lc.prototype,"uri",2),lc=Uh([Ut("wcm-walletconnect-qr")],lc);var nN=Object.defineProperty,sN=Object.getOwnPropertyDescriptor,oN=(r,e,t,i)=>{for(var n=i>1?void 0:i?sN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&nN(e,t,n),n};let Hp=class extends Ct{viewTemplate(){return je.isAndroid()&&!je.isTelegram()?Ee``:je.isMobile()?Ee``:Ee``}render(){return Ee`${this.viewTemplate()}`}};Hp.styles=[Lt.globalCss],Hp=oN([Ut("wcm-connect-wallet-view")],Hp);const aN=jt`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var cN=Object.defineProperty,fN=Object.getOwnPropertyDescriptor,jw=(r,e,t,i)=>{for(var n=i>1?void 0:i?fN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&cN(e,t,n),n};let qh=class extends Ct{constructor(){super(),this.isError=!1,this.openDesktopApp()}onFormatAndRedirect(r){const{desktop:e,name:t}=je.getWalletRouterData(),i=e?.native,n=e?.universal;if(i){const s=je.formatNativeUrl(i,r,t);je.openHref(s,"_self")}else if(n){const s=je.formatUniversalUrl(n,r,t);je.openHref(s,"_blank")}}openDesktopApp(){const{walletConnectUri:r}=yr.state,e=je.getWalletRouterData();pt.setRecentWallet(e),r&&this.onFormatAndRedirect(r)}render(){const{name:r,id:e,image_id:t}=je.getWalletRouterData(),{isMobile:i,isWeb:n}=pt.getCachedRouterWalletPlatforms();return Ee`${`Connection can continue loading if ${r} is not installed on your device`}Retry`}};qh.styles=[Lt.globalCss,aN],jw([xi()],qh.prototype,"isError",2),qh=jw([Ut("wcm-desktop-connecting-view")],qh);const lN=jt`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}wcm-button{margin-top:15px}`;var hN=Object.defineProperty,uN=Object.getOwnPropertyDescriptor,dN=(r,e,t,i)=>{for(var n=i>1?void 0:i?uN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&hN(e,t,n),n};let kp=class extends Ct{onInstall(r){r&&je.openHref(r,"_blank")}render(){const{name:r,id:e,image_id:t,homepage:i}=je.getWalletRouterData();return Ee`${`Download ${r} to continue. If multiple browser extensions are installed, disable non ${r} ones and try again`}Download`}};kp.styles=[Lt.globalCss,lN],kp=dN([Ut("wcm-install-wallet-view")],kp);const pN=jt`wcm-wallet-image{border-radius:var(--wcm-wallet-icon-large-border-radius);width:96px;height:96px;margin-bottom:20px}wcm-info-footer{display:flex;width:100%}.wcm-app-store{justify-content:space-between}.wcm-app-store wcm-wallet-image{margin-right:10px;margin-bottom:0;width:28px;height:28px;border-radius:var(--wcm-wallet-icon-small-border-radius)}.wcm-app-store div{display:flex;align-items:center}.wcm-app-store wcm-button{margin-right:-10px}.wcm-note{flex-direction:column;align-items:center;padding:5px 0}.wcm-note wcm-text{text-align:center}wcm-platform-selection{margin-top:-15px}.wcm-note wcm-text{margin-top:15px}.wcm-note wcm-text span{color:var(--wcm-accent-color)}`;var gN=Object.defineProperty,vN=Object.getOwnPropertyDescriptor,Ww=(r,e,t,i)=>{for(var n=i>1?void 0:i?vN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&gN(e,t,n),n};let zh=class extends Ct{constructor(){super(),this.isError=!1,this.openMobileApp()}onFormatAndRedirect(r,e=!1){const{mobile:t,name:i}=je.getWalletRouterData(),n=t?.native,s=t?.universal,a=je.isTelegram()?"_blank":"_self";if(r=je.isTelegram()&&je.isAndroid()?encodeURIComponent(r):r,n&&!e){const f=je.formatNativeUrl(n,r,i);je.openHref(f,a)}else if(s){const f=je.formatUniversalUrl(s,r,i);je.openHref(f,a)}}openMobileApp(r=!1){const{walletConnectUri:e}=yr.state,t=je.getWalletRouterData();e&&this.onFormatAndRedirect(e,r),pt.setRecentWallet(t)}onGoToAppStore(r){r&&je.openHref(r,"_blank")}render(){const{name:r,id:e,image_id:t,app:i,mobile:n}=je.getWalletRouterData(),{isWeb:s}=pt.getCachedRouterWalletPlatforms(),a=i?.ios,f=n?.universal;return Ee`Retry${f?Ee`Still doesn't work? Try this alternate link`:null}
${`Get ${r}`}
App Store
`}};zh.styles=[Lt.globalCss,pN],Ww([xi()],zh.prototype,"isError",2),zh=Ww([Ut("wcm-mobile-connecting-view")],zh);const mN=jt`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var bN=Object.defineProperty,wN=Object.getOwnPropertyDescriptor,yN=(r,e,t,i)=>{for(var n=i>1?void 0:i?wN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&bN(e,t,n),n};let jp=class extends Ct{render(){const{name:r,id:e,image_id:t}=je.getWalletRouterData(),{isDesktop:i,isWeb:n}=pt.getCachedRouterWalletPlatforms();return Ee`${`Scan this QR Code with your phone's camera or inside ${r} app`}`}};jp.styles=[Lt.globalCss,mN],jp=yN([Ut("wcm-mobile-qr-connecting-view")],jp);var _N=Object.defineProperty,xN=Object.getOwnPropertyDescriptor,AN=(r,e,t,i)=>{for(var n=i>1?void 0:i?xN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&_N(e,t,n),n};let Wp=class extends Ct{render(){return Ee``}};Wp.styles=[Lt.globalCss],Wp=AN([Ut("wcm-qrcode-view")],Wp);const EN=jt`wcm-modal-content{height:clamp(200px,60vh,600px);display:block;overflow:scroll;scrollbar-width:none;position:relative;margin-top:1px}.wcm-grid{display:grid;grid-template-columns:repeat(4,80px);justify-content:space-between;margin:-15px -10px;padding-top:20px}wcm-modal-content::after,wcm-modal-content::before{content:'';position:fixed;pointer-events:none;z-index:1;width:100%;height:20px;opacity:1}wcm-modal-content::before{box-shadow:0 -1px 0 0 var(--wcm-color-bg-1);background:linear-gradient(var(--wcm-color-bg-1),rgba(255,255,255,0))}wcm-modal-content::after{box-shadow:0 1px 0 0 var(--wcm-color-bg-1);background:linear-gradient(rgba(255,255,255,0),var(--wcm-color-bg-1));top:calc(100% - 20px)}wcm-modal-content::-webkit-scrollbar{display:none}.wcm-placeholder-block{display:flex;justify-content:center;align-items:center;height:100px;overflow:hidden}.wcm-empty,.wcm-loading{display:flex}.wcm-loading .wcm-placeholder-block{height:100%}.wcm-end-reached .wcm-placeholder-block{height:0;opacity:0}.wcm-empty .wcm-placeholder-block{opacity:1;height:100%}wcm-wallet-button{margin:calc((100% - 60px)/ 3) 0}`;var SN=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,$f=(r,e,t,i)=>{for(var n=i>1?void 0:i?IN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&SN(e,t,n),n};const Kp=40;let ra=class extends Ct{constructor(){super(...arguments),this.loading=!_i.state.wallets.listings.length,this.firstFetch=!_i.state.wallets.listings.length,this.search="",this.endReached=!1,this.intersectionObserver=void 0,this.searchDebounce=pt.debounce(r=>{r.length>=1?(this.firstFetch=!0,this.endReached=!1,this.search=r,_i.resetSearch(),this.fetchWallets()):this.search&&(this.search="",this.endReached=this.isLastPage(),_i.resetSearch())})}firstUpdated(){this.createPaginationObserver()}disconnectedCallback(){var r;(r=this.intersectionObserver)==null||r.disconnect()}get placeholderEl(){return pt.getShadowRootElement(this,".wcm-placeholder-block")}createPaginationObserver(){this.intersectionObserver=new IntersectionObserver(([r])=>{r.isIntersecting&&!(this.search&&this.firstFetch)&&this.fetchWallets()}),this.intersectionObserver.observe(this.placeholderEl)}isLastPage(){const{wallets:r,search:e}=_i.state,{listings:t,total:i}=this.search?e:r;return i<=Kp||t.length>=i}async fetchWallets(){var r;const{wallets:e,search:t}=_i.state,{listings:i,total:n,page:s}=this.search?t:e;if(!this.endReached&&(this.firstFetch||n>Kp&&i.lengthpt.getWalletIcon(u));await Promise.all([...h.map(async u=>pt.preloadImage(u)),je.wait(300)]),this.endReached=this.isLastPage()}catch(a){console.error(a),eo.openToast(pt.getErrorMessage(a),"error")}finally{this.loading=!1,this.firstFetch=!1}}onConnect(r){je.isAndroid()?pt.handleMobileLinking(r):pt.goToConnectingView(r)}onSearchChange(r){const{value:e}=r.target;this.searchDebounce(e)}render(){const{wallets:r,search:e}=_i.state,{listings:t}=this.search?e:r,i=this.loading&&!t.length,n=this.search.length>=3;let s=co.manualWalletsTemplate(),a=co.recomendedWalletsTemplate(!0);n&&(s=s.filter(({values:u})=>pt.caseSafeIncludes(u[0],this.search)),a=a.filter(({values:u})=>pt.caseSafeIncludes(u[0],this.search)));const f=!this.loading&&!t.length&&!a.length,h={"wcm-loading":i,"wcm-end-reached":this.endReached||!this.loading,"wcm-empty":f};return Ee`
${i?null:s} ${i?null:a} ${i?null:t.map(u=>Ee`${u?Ee``:null}`)}
${f?Ee`No results found`:null} ${!f&&this.loading?Ee``:null}
`}};ra.styles=[Lt.globalCss,EN],$f([xi()],ra.prototype,"loading",2),$f([xi()],ra.prototype,"firstFetch",2),$f([xi()],ra.prototype,"search",2),$f([xi()],ra.prototype,"endReached",2),ra=$f([Ut("wcm-wallet-explorer-view")],ra);const MN=jt`wcm-info-footer{flex-direction:column;align-items:center;display:flex;width:100%;padding:5px 0}wcm-text{text-align:center}`;var CN=Object.defineProperty,PN=Object.getOwnPropertyDescriptor,Kw=(r,e,t,i)=>{for(var n=i>1?void 0:i?PN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&CN(e,t,n),n};let Hh=class extends Ct{constructor(){super(),this.isError=!1,this.openWebWallet()}onFormatAndRedirect(r){const{desktop:e,name:t}=je.getWalletRouterData(),i=e?.universal;if(i){const n=je.formatUniversalUrl(i,r,t);je.openHref(n,"_blank")}}openWebWallet(){const{walletConnectUri:r}=yr.state,e=je.getWalletRouterData();pt.setRecentWallet(e),r&&this.onFormatAndRedirect(r)}render(){const{name:r,id:e,image_id:t}=je.getWalletRouterData(),{isMobile:i,isDesktop:n}=pt.getCachedRouterWalletPlatforms(),s=je.isMobile();return Ee`${`${r} web app has opened in a new tab. Go there, accept the connection, and come back`}Retry`}};Hh.styles=[Lt.globalCss,MN],Kw([xi()],Hh.prototype,"isError",2),Hh=Kw([Ut("wcm-web-connecting-view")],Hh);var DN=Object.freeze({__proto__:null,get WcmModal(){return fc},get WcmQrCode(){return Cs}});wn.EthereumProvider=XD,wn.OPTIONAL_EVENTS=y3,wn.OPTIONAL_METHODS=w3,wn.Provider=vh,wn.REQUIRED_EVENTS=dh,wn.REQUIRED_METHODS=uh,Object.defineProperty(wn,"__esModule",{value:!0})}); + //# sourceMappingURL=index.umd.js.map +diff --git a/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js.map b/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js.map +index 946e13b..05ab103 100644 +--- a/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js.map ++++ b/node_modules/@walletconnect/ethereum-provider/dist/index.umd.js.map +@@ -1 +1 @@ +-{"version":3,"file":"index.umd.js","sources":["../../../node_modules/events/events.js","../../../node_modules/detect-browser/es/index.js","../../../node_modules/@walletconnect/time/node_modules/tslib/tslib.es6.js","../../../node_modules/@walletconnect/time/dist/cjs/utils/delay.js","../../../node_modules/@walletconnect/time/dist/cjs/constants/misc.js","../../../node_modules/@walletconnect/time/dist/cjs/constants/time.js","../../../node_modules/@walletconnect/time/dist/cjs/constants/index.js","../../../node_modules/@walletconnect/time/dist/cjs/utils/convert.js","../../../node_modules/@walletconnect/time/dist/cjs/utils/index.js","../../../node_modules/@walletconnect/time/dist/cjs/watch.js","../../../node_modules/@walletconnect/time/dist/cjs/types/watch.js","../../../node_modules/@walletconnect/time/dist/cjs/types/index.js","../../../node_modules/@walletconnect/time/dist/cjs/index.js","../../../node_modules/@walletconnect/window-getters/dist/cjs/index.js","../../../node_modules/@walletconnect/window-metadata/dist/cjs/index.js","../../../node_modules/strict-uri-encode/index.js","../../../node_modules/decode-uri-component/index.js","../../../node_modules/split-on-first/index.js","../../../node_modules/filter-obj/index.js","../../../node_modules/query-string/index.js","../../../node_modules/js-sha3/src/sha3.js","../../../node_modules/@ethersproject/logger/lib.esm/_version.js","../../../node_modules/@ethersproject/logger/lib.esm/index.js","../../../node_modules/@ethersproject/bytes/lib.esm/_version.js","../../../node_modules/@ethersproject/bytes/lib.esm/index.js","../../../node_modules/@ethersproject/keccak256/lib.esm/index.js","../../../node_modules/bn.js/lib/bn.js","../../../node_modules/@ethersproject/bignumber/lib.esm/_version.js","../../../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js","../../../node_modules/@ethersproject/bignumber/lib.esm/fixednumber.js","../../../node_modules/@ethersproject/strings/lib.esm/_version.js","../../../node_modules/@ethersproject/strings/lib.esm/utf8.js","../../../node_modules/@ethersproject/strings/lib.esm/idna.js","../../../node_modules/@ethersproject/hash/lib.esm/_version.js","../../../node_modules/@ethersproject/base64/lib.esm/base64.js","../../../node_modules/@ethersproject/hash/lib.esm/ens-normalize/decoder.js","../../../node_modules/@ethersproject/hash/lib.esm/ens-normalize/include.js","../../../node_modules/@ethersproject/hash/lib.esm/ens-normalize/lib.js","../../../node_modules/@ethersproject/hash/lib.esm/namehash.js","../../../node_modules/@ethersproject/hash/lib.esm/message.js","../../../node_modules/@ethersproject/rlp/lib.esm/_version.js","../../../node_modules/@ethersproject/rlp/lib.esm/index.js","../../../node_modules/@ethersproject/address/lib.esm/_version.js","../../../node_modules/@ethersproject/address/lib.esm/index.js","../../../node_modules/@ethersproject/properties/lib.esm/_version.js","../../../node_modules/@ethersproject/properties/lib.esm/index.js","../../../node_modules/@ethersproject/hash/lib.esm/typed-data.js","../../../node_modules/minimalistic-assert/index.js","../../../node_modules/inherits/inherits_browser.js","../../../node_modules/hash.js/lib/hash/utils.js","../../../node_modules/hash.js/lib/hash/common.js","../../../node_modules/hash.js/lib/hash/sha/common.js","../../../node_modules/hash.js/lib/hash/sha/1.js","../../../node_modules/hash.js/lib/hash/sha/256.js","../../../node_modules/hash.js/lib/hash/sha/224.js","../../../node_modules/hash.js/lib/hash/sha/512.js","../../../node_modules/hash.js/lib/hash/sha/384.js","../../../node_modules/hash.js/lib/hash/sha.js","../../../node_modules/hash.js/lib/hash/ripemd.js","../../../node_modules/hash.js/lib/hash/hmac.js","../../../node_modules/hash.js/lib/hash.js","../../../node_modules/@ethersproject/signing-key/lib.esm/elliptic.js","../../../node_modules/@ethersproject/signing-key/lib.esm/_version.js","../../../node_modules/@ethersproject/signing-key/lib.esm/index.js","../../../node_modules/@ethersproject/transactions/lib.esm/_version.js","../../../node_modules/@ethersproject/transactions/lib.esm/index.js","../../../node_modules/@stablelib/int/lib/int.js","../../../node_modules/@stablelib/binary/lib/binary.js","../../../node_modules/@stablelib/wipe/lib/wipe.js","../../../node_modules/@stablelib/chacha/lib/chacha.js","../../../node_modules/@stablelib/constant-time/lib/constant-time.js","../../../node_modules/@stablelib/poly1305/lib/poly1305.js","../../../node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js","../../../node_modules/@stablelib/hash/lib/hash.js","../../../node_modules/@stablelib/hmac/lib/hmac.js","../../../node_modules/@stablelib/hkdf/lib/hkdf.js","../../../node_modules/@stablelib/random/lib/source/browser.js","../../../node_modules/@stablelib/random/lib/source/node.js","../../../node_modules/@stablelib/random/lib/source/system.js","../../../node_modules/@stablelib/random/lib/random.js","../../../node_modules/@stablelib/sha256/lib/sha256.js","../../../node_modules/@stablelib/x25519/lib/x25519.js","../../../packages/utils/node_modules/uint8arrays/esm/src/alloc.js","../../../packages/utils/node_modules/uint8arrays/esm/src/concat.js","../../../node_modules/multiformats/esm/vendor/base-x.js","../../../node_modules/multiformats/esm/src/bytes.js","../../../node_modules/multiformats/esm/src/bases/base.js","../../../node_modules/multiformats/esm/src/bases/identity.js","../../../node_modules/multiformats/esm/src/bases/base2.js","../../../node_modules/multiformats/esm/src/bases/base8.js","../../../node_modules/multiformats/esm/src/bases/base10.js","../../../node_modules/multiformats/esm/src/bases/base16.js","../../../node_modules/multiformats/esm/src/bases/base32.js","../../../node_modules/multiformats/esm/src/bases/base36.js","../../../node_modules/multiformats/esm/src/bases/base58.js","../../../node_modules/multiformats/esm/src/bases/base64.js","../../../node_modules/multiformats/esm/src/bases/base256emoji.js","../../../node_modules/multiformats/esm/vendor/varint.js","../../../node_modules/multiformats/esm/src/varint.js","../../../node_modules/multiformats/esm/src/hashes/digest.js","../../../node_modules/multiformats/esm/src/hashes/hasher.js","../../../node_modules/multiformats/esm/src/hashes/sha2-browser.js","../../../node_modules/multiformats/esm/src/hashes/identity.js","../../../node_modules/multiformats/esm/src/codecs/json.js","../../../node_modules/multiformats/esm/src/basics.js","../../../packages/utils/node_modules/uint8arrays/esm/src/util/bases.js","../../../packages/utils/node_modules/uint8arrays/esm/src/from-string.js","../../../packages/utils/node_modules/uint8arrays/esm/src/to-string.js","../../../node_modules/elliptic/node_modules/bn.js/lib/bn.js","../../../node_modules/minimalistic-crypto-utils/lib/utils.js","../../../node_modules/elliptic/lib/elliptic/utils.js","../../../node_modules/brorand/index.js","../../../node_modules/elliptic/lib/elliptic/curve/base.js","../../../node_modules/elliptic/lib/elliptic/curve/short.js","../../../node_modules/elliptic/lib/elliptic/curve/mont.js","../../../node_modules/elliptic/lib/elliptic/curve/edwards.js","../../../node_modules/elliptic/lib/elliptic/curve/index.js","../../../node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js","../../../node_modules/elliptic/lib/elliptic/curves.js","../../../node_modules/hmac-drbg/lib/hmac-drbg.js","../../../node_modules/elliptic/lib/elliptic/ec/key.js","../../../node_modules/elliptic/lib/elliptic/ec/signature.js","../../../node_modules/elliptic/lib/elliptic/ec/index.js","../../../node_modules/elliptic/lib/elliptic/eddsa/key.js","../../../node_modules/elliptic/lib/elliptic/eddsa/signature.js","../../../node_modules/elliptic/lib/elliptic/eddsa/index.js","../../../node_modules/elliptic/lib/elliptic.js","../../../node_modules/@stablelib/sha512/lib/sha512.js","../../../node_modules/@stablelib/ed25519/lib/ed25519.js","../../../node_modules/@walletconnect/relay-auth/dist/esm/constants.js","../../../node_modules/uint8arrays/esm/src/util/as-uint8array.js","../../../node_modules/uint8arrays/esm/src/alloc.js","../../../node_modules/uint8arrays/esm/src/concat.js","../../../node_modules/uint8arrays/esm/src/util/bases.js","../../../node_modules/uint8arrays/esm/src/to-string.js","../../../node_modules/uint8arrays/esm/src/from-string.js","../../../node_modules/@walletconnect/safe-json/dist/esm/index.js","../../../node_modules/@walletconnect/relay-auth/dist/esm/utils.js","../../../node_modules/@walletconnect/relay-auth/dist/esm/api.js","../../../node_modules/@walletconnect/relay-api/dist/index.es.js","../../../packages/utils/dist/index.es.js","../../../node_modules/@walletconnect/events/dist/esm/events.js","../../../node_modules/@walletconnect/heartbeat/dist/index.es.js","../../../node_modules/destr/dist/index.mjs","../../../node_modules/unstorage/dist/shared/unstorage.8581f561.mjs","../../../node_modules/unstorage/dist/index.mjs","../../../node_modules/idb-keyval/dist/index.js","../../../node_modules/@walletconnect/keyvaluestorage/dist/index.es.js","../../../node_modules/quick-format-unescaped/index.js","../../../node_modules/pino/browser.js","../../../node_modules/@walletconnect/logger/dist/index.es.js","../../../packages/types/dist/index.es.js","../../../packages/core/node_modules/uint8arrays/esm/src/alloc.js","../../../packages/core/node_modules/uint8arrays/esm/src/util/bases.js","../../../packages/core/node_modules/uint8arrays/esm/src/to-string.js","../../../node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js","../../../node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js","../../../node_modules/@walletconnect/environment/node_modules/tslib/tslib.es6.js","../../../node_modules/@walletconnect/environment/dist/cjs/crypto.js","../../../node_modules/@walletconnect/environment/dist/cjs/env.js","../../../node_modules/@walletconnect/environment/dist/cjs/index.js","../../../node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js","../../../node_modules/@walletconnect/jsonrpc-types/dist/index.es.js","../../../node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js","../../../node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js","../../../node_modules/@walletconnect/jsonrpc-provider/dist/index.es.js","../../../node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js","../../../node_modules/lodash.isequal/index.js","../../../packages/core/dist/index.es.js","../../../packages/sign-client/dist/index.es.js","../../../node_modules/lodash/lodash.js","../../../node_modules/cross-fetch/dist/browser-ponyfill.js","../../../node_modules/@walletconnect/jsonrpc-http-connection/dist/index.es.js","../../universal-provider/dist/index.es.js","../src/constants/values.ts","../src/constants/rpc.ts","../src/EthereumProvider.ts","../src/index.ts","../../../node_modules/proxy-compare/dist/index.modern.js","../../../node_modules/valtio/esm/vanilla.mjs","../../../node_modules/@walletconnect/modal-core/dist/index.js","../../../node_modules/@walletconnect/modal/dist/index.js","../../../node_modules/@lit/reactive-element/css-tag.js","../../../node_modules/@lit/reactive-element/reactive-element.js","../../../node_modules/lit-html/lit-html.js","../../../node_modules/lit-element/lit-element.js","../../../node_modules/@lit/reactive-element/decorators/custom-element.js","../../../node_modules/@lit/reactive-element/decorators/property.js","../../../node_modules/@lit/reactive-element/decorators/state.js","../../../node_modules/@lit/reactive-element/decorators/query-assigned-elements.js","../../../node_modules/lit-html/directive.js","../../../node_modules/lit-html/directives/class-map.js","../../../node_modules/@motionone/utils/dist/array.es.js","../../../node_modules/@motionone/utils/dist/clamp.es.js","../../../node_modules/@motionone/utils/dist/defaults.es.js","../../../node_modules/@motionone/utils/dist/is-number.es.js","../../../node_modules/@motionone/utils/dist/is-easing-list.es.js","../../../node_modules/@motionone/utils/dist/wrap.es.js","../../../node_modules/@motionone/utils/dist/easing.es.js","../../../node_modules/@motionone/utils/dist/mix.es.js","../../../node_modules/@motionone/utils/dist/noop.es.js","../../../node_modules/@motionone/utils/dist/progress.es.js","../../../node_modules/@motionone/utils/dist/offset.es.js","../../../node_modules/@motionone/utils/dist/interpolate.es.js","../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js","../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js","../../../node_modules/@motionone/utils/dist/is-function.es.js","../../../node_modules/@motionone/utils/dist/is-string.es.js","../../../node_modules/@motionone/utils/dist/time.es.js","../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js","../../../node_modules/@motionone/easing/dist/steps.es.js","../../../node_modules/@motionone/animation/dist/utils/easing.es.js","../../../node_modules/@motionone/animation/dist/Animation.es.js","../../../node_modules/hey-listen/dist/hey-listen.es.js","../../../node_modules/@motionone/types/dist/MotionValue.es.js","../../../node_modules/@motionone/dom/dist/animate/data.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js","../../../node_modules/@motionone/dom/dist/animate/style.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/get-unit.es.js","../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js","../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js","../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js","../../../node_modules/@motionone/dom/dist/utils/stagger.es.js","../../../node_modules/@motionone/dom/dist/animate/create-animate.es.js","../../../node_modules/@motionone/dom/dist/animate/index.es.js","../../../node_modules/tslib/tslib.es6.mjs","../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js","../../../node_modules/@motionone/dom/dist/state/utils/events.es.js","../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js","../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js","../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js","../../../node_modules/@motionone/dom/dist/state/index.es.js","../../../node_modules/motion/dist/animate.es.js","../../../node_modules/lit-html/directives/if-defined.js","../../../node_modules/qrcode/lib/can-promise.js","../../../node_modules/qrcode/lib/core/utils.js","../../../node_modules/qrcode/lib/core/error-correction-level.js","../../../node_modules/qrcode/lib/core/bit-buffer.js","../../../node_modules/qrcode/lib/core/bit-matrix.js","../../../node_modules/qrcode/lib/core/alignment-pattern.js","../../../node_modules/qrcode/lib/core/finder-pattern.js","../../../node_modules/qrcode/lib/core/mask-pattern.js","../../../node_modules/qrcode/lib/core/error-correction-code.js","../../../node_modules/qrcode/lib/core/galois-field.js","../../../node_modules/qrcode/lib/core/polynomial.js","../../../node_modules/qrcode/lib/core/reed-solomon-encoder.js","../../../node_modules/qrcode/lib/core/version-check.js","../../../node_modules/qrcode/lib/core/regex.js","../../../node_modules/qrcode/lib/core/mode.js","../../../node_modules/qrcode/lib/core/version.js","../../../node_modules/qrcode/lib/core/format-info.js","../../../node_modules/qrcode/lib/core/numeric-data.js","../../../node_modules/qrcode/lib/core/alphanumeric-data.js","../../../node_modules/encode-utf8/index.js","../../../node_modules/qrcode/lib/core/byte-data.js","../../../node_modules/qrcode/lib/core/kanji-data.js","../../../node_modules/dijkstrajs/dijkstra.js","../../../node_modules/qrcode/lib/core/segments.js","../../../node_modules/qrcode/lib/core/qrcode.js","../../../node_modules/qrcode/lib/renderer/utils.js","../../../node_modules/qrcode/lib/renderer/canvas.js","../../../node_modules/qrcode/lib/renderer/svg-tag.js","../../../node_modules/qrcode/lib/browser.js","../../../node_modules/@walletconnect/modal-ui/dist/index.js"],"sourcesContent":["// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar BrowserInfo = /** @class */ (function () {\n function BrowserInfo(name, version, os) {\n this.name = name;\n this.version = version;\n this.os = os;\n this.type = 'browser';\n }\n return BrowserInfo;\n}());\nexport { BrowserInfo };\nvar NodeInfo = /** @class */ (function () {\n function NodeInfo(version) {\n this.version = version;\n this.type = 'node';\n this.name = 'node';\n this.os = process.platform;\n }\n return NodeInfo;\n}());\nexport { NodeInfo };\nvar SearchBotDeviceInfo = /** @class */ (function () {\n function SearchBotDeviceInfo(name, version, os, bot) {\n this.name = name;\n this.version = version;\n this.os = os;\n this.bot = bot;\n this.type = 'bot-device';\n }\n return SearchBotDeviceInfo;\n}());\nexport { SearchBotDeviceInfo };\nvar BotInfo = /** @class */ (function () {\n function BotInfo() {\n this.type = 'bot';\n this.bot = true; // NOTE: deprecated test name instead\n this.name = 'bot';\n this.version = null;\n this.os = null;\n }\n return BotInfo;\n}());\nexport { BotInfo };\nvar ReactNativeInfo = /** @class */ (function () {\n function ReactNativeInfo() {\n this.type = 'react-native';\n this.name = 'react-native';\n this.version = null;\n this.os = null;\n }\n return ReactNativeInfo;\n}());\nexport { ReactNativeInfo };\n// tslint:disable-next-line:max-line-length\nvar SEARCHBOX_UA_REGEX = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/;\nvar SEARCHBOT_OS_REGEX = /(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\\ Jeeves\\/Teoma|ia_archiver)/;\nvar REQUIRED_VERSION_PARTS = 3;\nvar userAgentRules = [\n ['aol', /AOLShield\\/([0-9\\._]+)/],\n ['edge', /Edge\\/([0-9\\._]+)/],\n ['edge-ios', /EdgiOS\\/([0-9\\._]+)/],\n ['yandexbrowser', /YaBrowser\\/([0-9\\._]+)/],\n ['kakaotalk', /KAKAOTALK\\s([0-9\\.]+)/],\n ['samsung', /SamsungBrowser\\/([0-9\\.]+)/],\n ['silk', /\\bSilk\\/([0-9._-]+)\\b/],\n ['miui', /MiuiBrowser\\/([0-9\\.]+)$/],\n ['beaker', /BeakerBrowser\\/([0-9\\.]+)/],\n ['edge-chromium', /EdgA?\\/([0-9\\.]+)/],\n [\n 'chromium-webview',\n /(?!Chrom.*OPR)wv\\).*Chrom(?:e|ium)\\/([0-9\\.]+)(:?\\s|$)/,\n ],\n ['chrome', /(?!Chrom.*OPR)Chrom(?:e|ium)\\/([0-9\\.]+)(:?\\s|$)/],\n ['phantomjs', /PhantomJS\\/([0-9\\.]+)(:?\\s|$)/],\n ['crios', /CriOS\\/([0-9\\.]+)(:?\\s|$)/],\n ['firefox', /Firefox\\/([0-9\\.]+)(?:\\s|$)/],\n ['fxios', /FxiOS\\/([0-9\\.]+)/],\n ['opera-mini', /Opera Mini.*Version\\/([0-9\\.]+)/],\n ['opera', /Opera\\/([0-9\\.]+)(?:\\s|$)/],\n ['opera', /OPR\\/([0-9\\.]+)(:?\\s|$)/],\n ['pie', /^Microsoft Pocket Internet Explorer\\/(\\d+\\.\\d+)$/],\n ['pie', /^Mozilla\\/\\d\\.\\d+\\s\\(compatible;\\s(?:MSP?IE|MSInternet Explorer) (\\d+\\.\\d+);.*Windows CE.*\\)$/],\n ['netfront', /^Mozilla\\/\\d\\.\\d+.*NetFront\\/(\\d.\\d)/],\n ['ie', /Trident\\/7\\.0.*rv\\:([0-9\\.]+).*\\).*Gecko$/],\n ['ie', /MSIE\\s([0-9\\.]+);.*Trident\\/[4-7].0/],\n ['ie', /MSIE\\s(7\\.0)/],\n ['bb10', /BB10;\\sTouch.*Version\\/([0-9\\.]+)/],\n ['android', /Android\\s([0-9\\.]+)/],\n ['ios', /Version\\/([0-9\\._]+).*Mobile.*Safari.*/],\n ['safari', /Version\\/([0-9\\._]+).*Safari/],\n ['facebook', /FB[AS]V\\/([0-9\\.]+)/],\n ['instagram', /Instagram\\s([0-9\\.]+)/],\n ['ios-webview', /AppleWebKit\\/([0-9\\.]+).*Mobile/],\n ['ios-webview', /AppleWebKit\\/([0-9\\.]+).*Gecko\\)$/],\n ['curl', /^curl\\/([0-9\\.]+)$/],\n ['searchbot', SEARCHBOX_UA_REGEX],\n];\nvar operatingSystemRules = [\n ['iOS', /iP(hone|od|ad)/],\n ['Android OS', /Android/],\n ['BlackBerry OS', /BlackBerry|BB10/],\n ['Windows Mobile', /IEMobile/],\n ['Amazon OS', /Kindle/],\n ['Windows 3.11', /Win16/],\n ['Windows 95', /(Windows 95)|(Win95)|(Windows_95)/],\n ['Windows 98', /(Windows 98)|(Win98)/],\n ['Windows 2000', /(Windows NT 5.0)|(Windows 2000)/],\n ['Windows XP', /(Windows NT 5.1)|(Windows XP)/],\n ['Windows Server 2003', /(Windows NT 5.2)/],\n ['Windows Vista', /(Windows NT 6.0)/],\n ['Windows 7', /(Windows NT 6.1)/],\n ['Windows 8', /(Windows NT 6.2)/],\n ['Windows 8.1', /(Windows NT 6.3)/],\n ['Windows 10', /(Windows NT 10.0)/],\n ['Windows ME', /Windows ME/],\n ['Windows CE', /Windows CE|WinCE|Microsoft Pocket Internet Explorer/],\n ['Open BSD', /OpenBSD/],\n ['Sun OS', /SunOS/],\n ['Chrome OS', /CrOS/],\n ['Linux', /(Linux)|(X11)/],\n ['Mac OS', /(Mac_PowerPC)|(Macintosh)/],\n ['QNX', /QNX/],\n ['BeOS', /BeOS/],\n ['OS/2', /OS\\/2/],\n];\nexport function detect(userAgent) {\n if (!!userAgent) {\n return parseUserAgent(userAgent);\n }\n if (typeof document === 'undefined' &&\n typeof navigator !== 'undefined' &&\n navigator.product === 'ReactNative') {\n return new ReactNativeInfo();\n }\n if (typeof navigator !== 'undefined') {\n return parseUserAgent(navigator.userAgent);\n }\n return getNodeVersion();\n}\nfunction matchUserAgent(ua) {\n // opted for using reduce here rather than Array#first with a regex.test call\n // this is primarily because using the reduce we only perform the regex\n // execution once rather than once for the test and for the exec again below\n // probably something that needs to be benchmarked though\n return (ua !== '' &&\n userAgentRules.reduce(function (matched, _a) {\n var browser = _a[0], regex = _a[1];\n if (matched) {\n return matched;\n }\n var uaMatch = regex.exec(ua);\n return !!uaMatch && [browser, uaMatch];\n }, false));\n}\nexport function browserName(ua) {\n var data = matchUserAgent(ua);\n return data ? data[0] : null;\n}\nexport function parseUserAgent(ua) {\n var matchedRule = matchUserAgent(ua);\n if (!matchedRule) {\n return null;\n }\n var name = matchedRule[0], match = matchedRule[1];\n if (name === 'searchbot') {\n return new BotInfo();\n }\n // Do not use RegExp for split operation as some browser do not support it (See: http://blog.stevenlevithan.com/archives/cross-browser-split)\n var versionParts = match[1] && match[1].split('.').join('_').split('_').slice(0, 3);\n if (versionParts) {\n if (versionParts.length < REQUIRED_VERSION_PARTS) {\n versionParts = __spreadArray(__spreadArray([], versionParts, true), createVersionParts(REQUIRED_VERSION_PARTS - versionParts.length), true);\n }\n }\n else {\n versionParts = [];\n }\n var version = versionParts.join('.');\n var os = detectOS(ua);\n var searchBotMatch = SEARCHBOT_OS_REGEX.exec(ua);\n if (searchBotMatch && searchBotMatch[1]) {\n return new SearchBotDeviceInfo(name, version, os, searchBotMatch[1]);\n }\n return new BrowserInfo(name, version, os);\n}\nexport function detectOS(ua) {\n for (var ii = 0, count = operatingSystemRules.length; ii < count; ii++) {\n var _a = operatingSystemRules[ii], os = _a[0], regex = _a[1];\n var match = regex.exec(ua);\n if (match) {\n return os;\n }\n }\n return null;\n}\nexport function getNodeVersion() {\n var isNode = typeof process !== 'undefined' && process.version;\n return isNode ? new NodeInfo(process.version.slice(1)) : null;\n}\nfunction createVersionParts(count) {\n var output = [];\n for (var ii = 0; ii < count; ii++) {\n output.push('0');\n }\n return output;\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.delay = void 0;\nfunction delay(timeout) {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(true);\n }, timeout);\n });\n}\nexports.delay = delay;\n//# sourceMappingURL=delay.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ONE_THOUSAND = exports.ONE_HUNDRED = void 0;\nexports.ONE_HUNDRED = 100;\nexports.ONE_THOUSAND = 1000;\n//# sourceMappingURL=misc.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ONE_YEAR = exports.FOUR_WEEKS = exports.THREE_WEEKS = exports.TWO_WEEKS = exports.ONE_WEEK = exports.THIRTY_DAYS = exports.SEVEN_DAYS = exports.FIVE_DAYS = exports.THREE_DAYS = exports.ONE_DAY = exports.TWENTY_FOUR_HOURS = exports.TWELVE_HOURS = exports.SIX_HOURS = exports.THREE_HOURS = exports.ONE_HOUR = exports.SIXTY_MINUTES = exports.THIRTY_MINUTES = exports.TEN_MINUTES = exports.FIVE_MINUTES = exports.ONE_MINUTE = exports.SIXTY_SECONDS = exports.THIRTY_SECONDS = exports.TEN_SECONDS = exports.FIVE_SECONDS = exports.ONE_SECOND = void 0;\nexports.ONE_SECOND = 1;\nexports.FIVE_SECONDS = 5;\nexports.TEN_SECONDS = 10;\nexports.THIRTY_SECONDS = 30;\nexports.SIXTY_SECONDS = 60;\nexports.ONE_MINUTE = exports.SIXTY_SECONDS;\nexports.FIVE_MINUTES = exports.ONE_MINUTE * 5;\nexports.TEN_MINUTES = exports.ONE_MINUTE * 10;\nexports.THIRTY_MINUTES = exports.ONE_MINUTE * 30;\nexports.SIXTY_MINUTES = exports.ONE_MINUTE * 60;\nexports.ONE_HOUR = exports.SIXTY_MINUTES;\nexports.THREE_HOURS = exports.ONE_HOUR * 3;\nexports.SIX_HOURS = exports.ONE_HOUR * 6;\nexports.TWELVE_HOURS = exports.ONE_HOUR * 12;\nexports.TWENTY_FOUR_HOURS = exports.ONE_HOUR * 24;\nexports.ONE_DAY = exports.TWENTY_FOUR_HOURS;\nexports.THREE_DAYS = exports.ONE_DAY * 3;\nexports.FIVE_DAYS = exports.ONE_DAY * 5;\nexports.SEVEN_DAYS = exports.ONE_DAY * 7;\nexports.THIRTY_DAYS = exports.ONE_DAY * 30;\nexports.ONE_WEEK = exports.SEVEN_DAYS;\nexports.TWO_WEEKS = exports.ONE_WEEK * 2;\nexports.THREE_WEEKS = exports.ONE_WEEK * 3;\nexports.FOUR_WEEKS = exports.ONE_WEEK * 4;\nexports.ONE_YEAR = exports.ONE_DAY * 365;\n//# sourceMappingURL=time.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./misc\"), exports);\ntslib_1.__exportStar(require(\"./time\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.fromMiliseconds = exports.toMiliseconds = void 0;\nconst constants_1 = require(\"../constants\");\nfunction toMiliseconds(seconds) {\n return seconds * constants_1.ONE_THOUSAND;\n}\nexports.toMiliseconds = toMiliseconds;\nfunction fromMiliseconds(miliseconds) {\n return Math.floor(miliseconds / constants_1.ONE_THOUSAND);\n}\nexports.fromMiliseconds = fromMiliseconds;\n//# sourceMappingURL=convert.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./delay\"), exports);\ntslib_1.__exportStar(require(\"./convert\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Watch = void 0;\nclass Watch {\n constructor() {\n this.timestamps = new Map();\n }\n start(label) {\n if (this.timestamps.has(label)) {\n throw new Error(`Watch already started for label: ${label}`);\n }\n this.timestamps.set(label, { started: Date.now() });\n }\n stop(label) {\n const timestamp = this.get(label);\n if (typeof timestamp.elapsed !== \"undefined\") {\n throw new Error(`Watch already stopped for label: ${label}`);\n }\n const elapsed = Date.now() - timestamp.started;\n this.timestamps.set(label, { started: timestamp.started, elapsed });\n }\n get(label) {\n const timestamp = this.timestamps.get(label);\n if (typeof timestamp === \"undefined\") {\n throw new Error(`No timestamp found for label: ${label}`);\n }\n return timestamp;\n }\n elapsed(label) {\n const timestamp = this.get(label);\n const elapsed = timestamp.elapsed || Date.now() - timestamp.started;\n return elapsed;\n }\n}\nexports.Watch = Watch;\nexports.default = Watch;\n//# sourceMappingURL=watch.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IWatch = void 0;\nclass IWatch {\n}\nexports.IWatch = IWatch;\n//# sourceMappingURL=watch.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./watch\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./utils\"), exports);\ntslib_1.__exportStar(require(\"./watch\"), exports);\ntslib_1.__exportStar(require(\"./types\"), exports);\ntslib_1.__exportStar(require(\"./constants\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getLocalStorage = exports.getLocalStorageOrThrow = exports.getCrypto = exports.getCryptoOrThrow = exports.getLocation = exports.getLocationOrThrow = exports.getNavigator = exports.getNavigatorOrThrow = exports.getDocument = exports.getDocumentOrThrow = exports.getFromWindowOrThrow = exports.getFromWindow = void 0;\nfunction getFromWindow(name) {\n let res = undefined;\n if (typeof window !== \"undefined\" && typeof window[name] !== \"undefined\") {\n res = window[name];\n }\n return res;\n}\nexports.getFromWindow = getFromWindow;\nfunction getFromWindowOrThrow(name) {\n const res = getFromWindow(name);\n if (!res) {\n throw new Error(`${name} is not defined in Window`);\n }\n return res;\n}\nexports.getFromWindowOrThrow = getFromWindowOrThrow;\nfunction getDocumentOrThrow() {\n return getFromWindowOrThrow(\"document\");\n}\nexports.getDocumentOrThrow = getDocumentOrThrow;\nfunction getDocument() {\n return getFromWindow(\"document\");\n}\nexports.getDocument = getDocument;\nfunction getNavigatorOrThrow() {\n return getFromWindowOrThrow(\"navigator\");\n}\nexports.getNavigatorOrThrow = getNavigatorOrThrow;\nfunction getNavigator() {\n return getFromWindow(\"navigator\");\n}\nexports.getNavigator = getNavigator;\nfunction getLocationOrThrow() {\n return getFromWindowOrThrow(\"location\");\n}\nexports.getLocationOrThrow = getLocationOrThrow;\nfunction getLocation() {\n return getFromWindow(\"location\");\n}\nexports.getLocation = getLocation;\nfunction getCryptoOrThrow() {\n return getFromWindowOrThrow(\"crypto\");\n}\nexports.getCryptoOrThrow = getCryptoOrThrow;\nfunction getCrypto() {\n return getFromWindow(\"crypto\");\n}\nexports.getCrypto = getCrypto;\nfunction getLocalStorageOrThrow() {\n return getFromWindowOrThrow(\"localStorage\");\n}\nexports.getLocalStorageOrThrow = getLocalStorageOrThrow;\nfunction getLocalStorage() {\n return getFromWindow(\"localStorage\");\n}\nexports.getLocalStorage = getLocalStorage;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getWindowMetadata = void 0;\nconst window_getters_1 = require(\"@walletconnect/window-getters\");\nfunction getWindowMetadata() {\n let doc;\n let loc;\n try {\n doc = window_getters_1.getDocumentOrThrow();\n loc = window_getters_1.getLocationOrThrow();\n }\n catch (e) {\n return null;\n }\n function getIcons() {\n const links = doc.getElementsByTagName(\"link\");\n const icons = [];\n for (let i = 0; i < links.length; i++) {\n const link = links[i];\n const rel = link.getAttribute(\"rel\");\n if (rel) {\n if (rel.toLowerCase().indexOf(\"icon\") > -1) {\n const href = link.getAttribute(\"href\");\n if (href) {\n if (href.toLowerCase().indexOf(\"https:\") === -1 &&\n href.toLowerCase().indexOf(\"http:\") === -1 &&\n href.indexOf(\"//\") !== 0) {\n let absoluteHref = loc.protocol + \"//\" + loc.host;\n if (href.indexOf(\"/\") === 0) {\n absoluteHref += href;\n }\n else {\n const path = loc.pathname.split(\"/\");\n path.pop();\n const finalPath = path.join(\"/\");\n absoluteHref += finalPath + \"/\" + href;\n }\n icons.push(absoluteHref);\n }\n else if (href.indexOf(\"//\") === 0) {\n const absoluteUrl = loc.protocol + href;\n icons.push(absoluteUrl);\n }\n else {\n icons.push(href);\n }\n }\n }\n }\n }\n return icons;\n }\n function getWindowMetadataOfAny(...args) {\n const metaTags = doc.getElementsByTagName(\"meta\");\n for (let i = 0; i < metaTags.length; i++) {\n const tag = metaTags[i];\n const attributes = [\"itemprop\", \"property\", \"name\"]\n .map((target) => tag.getAttribute(target))\n .filter((attr) => {\n if (attr) {\n return args.includes(attr);\n }\n return false;\n });\n if (attributes.length && attributes) {\n const content = tag.getAttribute(\"content\");\n if (content) {\n return content;\n }\n }\n }\n return \"\";\n }\n function getName() {\n let name = getWindowMetadataOfAny(\"name\", \"og:site_name\", \"og:title\", \"twitter:title\");\n if (!name) {\n name = doc.title;\n }\n return name;\n }\n function getDescription() {\n const description = getWindowMetadataOfAny(\"description\", \"og:description\", \"twitter:description\", \"keywords\");\n return description;\n }\n const name = getName();\n const description = getDescription();\n const url = loc.origin;\n const icons = getIcons();\n const meta = {\n description,\n url,\n icons,\n name,\n };\n return meta;\n}\nexports.getWindowMetadata = getWindowMetadata;\n//# sourceMappingURL=index.js.map","'use strict';\nmodule.exports = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);\n","'use strict';\nvar token = '%[a-f0-9]{2}';\nvar singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi');\nvar multiMatcher = new RegExp('(' + token + ')+', 'gi');\n\nfunction decodeComponents(components, split) {\n\ttry {\n\t\t// Try to decode the entire string first\n\t\treturn [decodeURIComponent(components.join(''))];\n\t} catch (err) {\n\t\t// Do nothing\n\t}\n\n\tif (components.length === 1) {\n\t\treturn components;\n\t}\n\n\tsplit = split || 1;\n\n\t// Split the array in 2 parts\n\tvar left = components.slice(0, split);\n\tvar right = components.slice(split);\n\n\treturn Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));\n}\n\nfunction decode(input) {\n\ttry {\n\t\treturn decodeURIComponent(input);\n\t} catch (err) {\n\t\tvar tokens = input.match(singleMatcher) || [];\n\n\t\tfor (var i = 1; i < tokens.length; i++) {\n\t\t\tinput = decodeComponents(tokens, i).join('');\n\n\t\t\ttokens = input.match(singleMatcher) || [];\n\t\t}\n\n\t\treturn input;\n\t}\n}\n\nfunction customDecodeURIComponent(input) {\n\t// Keep track of all the replacements and prefill the map with the `BOM`\n\tvar replaceMap = {\n\t\t'%FE%FF': '\\uFFFD\\uFFFD',\n\t\t'%FF%FE': '\\uFFFD\\uFFFD'\n\t};\n\n\tvar match = multiMatcher.exec(input);\n\twhile (match) {\n\t\ttry {\n\t\t\t// Decode as big chunks as possible\n\t\t\treplaceMap[match[0]] = decodeURIComponent(match[0]);\n\t\t} catch (err) {\n\t\t\tvar result = decode(match[0]);\n\n\t\t\tif (result !== match[0]) {\n\t\t\t\treplaceMap[match[0]] = result;\n\t\t\t}\n\t\t}\n\n\t\tmatch = multiMatcher.exec(input);\n\t}\n\n\t// Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else\n\treplaceMap['%C2'] = '\\uFFFD';\n\n\tvar entries = Object.keys(replaceMap);\n\n\tfor (var i = 0; i < entries.length; i++) {\n\t\t// Replace all decoded components\n\t\tvar key = entries[i];\n\t\tinput = input.replace(new RegExp(key, 'g'), replaceMap[key]);\n\t}\n\n\treturn input;\n}\n\nmodule.exports = function (encodedURI) {\n\tif (typeof encodedURI !== 'string') {\n\t\tthrow new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');\n\t}\n\n\ttry {\n\t\tencodedURI = encodedURI.replace(/\\+/g, ' ');\n\n\t\t// Try the built in decoder first\n\t\treturn decodeURIComponent(encodedURI);\n\t} catch (err) {\n\t\t// Fallback to a more advanced decoder\n\t\treturn customDecodeURIComponent(encodedURI);\n\t}\n};\n","'use strict';\n\nmodule.exports = (string, separator) => {\n\tif (!(typeof string === 'string' && typeof separator === 'string')) {\n\t\tthrow new TypeError('Expected the arguments to be of type `string`');\n\t}\n\n\tif (separator === '') {\n\t\treturn [string];\n\t}\n\n\tconst separatorIndex = string.indexOf(separator);\n\n\tif (separatorIndex === -1) {\n\t\treturn [string];\n\t}\n\n\treturn [\n\t\tstring.slice(0, separatorIndex),\n\t\tstring.slice(separatorIndex + separator.length)\n\t];\n};\n","'use strict';\nmodule.exports = function (obj, predicate) {\n\tvar ret = {};\n\tvar keys = Object.keys(obj);\n\tvar isArr = Array.isArray(predicate);\n\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar key = keys[i];\n\t\tvar val = obj[key];\n\n\t\tif (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {\n\t\t\tret[key] = val;\n\t\t}\n\t}\n\n\treturn ret;\n};\n","'use strict';\nconst strictUriEncode = require('strict-uri-encode');\nconst decodeComponent = require('decode-uri-component');\nconst splitOnFirst = require('split-on-first');\nconst filterObject = require('filter-obj');\n\nconst isNullOrUndefined = value => value === null || value === undefined;\n\nconst encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier');\n\nfunction encoderForArrayFormat(options) {\n\tswitch (options.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tconst index = result.length;\n\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), '[', index, ']'].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [\n\t\t\t\t\t...result,\n\t\t\t\t\t[encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('')\n\t\t\t\t];\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), '[]'].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), '[]=', encode(value, options)].join('')];\n\t\t\t};\n\n\t\tcase 'colon-list-separator':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), ':list='].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), ':list=', encode(value, options)].join('')];\n\t\t\t};\n\n\t\tcase 'comma':\n\t\tcase 'separator':\n\t\tcase 'bracket-separator': {\n\t\t\tconst keyValueSep = options.arrayFormat === 'bracket-separator' ?\n\t\t\t\t'[]=' :\n\t\t\t\t'=';\n\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\t// Translate null to an empty string so that it doesn't serialize as 'null'\n\t\t\t\tvalue = value === null ? '' : value;\n\n\t\t\t\tif (result.length === 0) {\n\t\t\t\t\treturn [[encode(key, options), keyValueSep, encode(value, options)].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [[result, encode(value, options)].join(options.arrayFormatSeparator)];\n\t\t\t};\n\t\t}\n\n\t\tdefault:\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, encode(key, options)];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), '=', encode(value, options)].join('')];\n\t\t\t};\n\t}\n}\n\nfunction parserForArrayFormat(options) {\n\tlet result;\n\n\tswitch (options.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /\\[(\\d*)\\]$/.exec(key);\n\n\t\t\t\tkey = key.replace(/\\[\\d*\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = {};\n\t\t\t\t}\n\n\t\t\t\taccumulator[key][result[1]] = value;\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /(\\[\\])$/.exec(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tcase 'colon-list-separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /(:list)$/.exec(key);\n\t\t\t\tkey = key.replace(/:list$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tcase 'comma':\n\t\tcase 'separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tconst isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);\n\t\t\t\tconst isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator));\n\t\t\t\tvalue = isEncodedArray ? decode(value, options) : value;\n\t\t\t\tconst newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : value === null ? value : decode(value, options);\n\t\t\t\taccumulator[key] = newValue;\n\t\t\t};\n\n\t\tcase 'bracket-separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tconst isArray = /(\\[\\])$/.test(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!isArray) {\n\t\t\t\t\taccumulator[key] = value ? decode(value, options) : value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst arrayValue = value === null ?\n\t\t\t\t\t[] :\n\t\t\t\t\tvalue.split(options.arrayFormatSeparator).map(item => decode(item, options));\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = arrayValue;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], arrayValue);\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\t}\n}\n\nfunction validateArrayFormatSeparator(value) {\n\tif (typeof value !== 'string' || value.length !== 1) {\n\t\tthrow new TypeError('arrayFormatSeparator must be single character string');\n\t}\n}\n\nfunction encode(value, options) {\n\tif (options.encode) {\n\t\treturn options.strict ? strictUriEncode(value) : encodeURIComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction decode(value, options) {\n\tif (options.decode) {\n\t\treturn decodeComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction keysSorter(input) {\n\tif (Array.isArray(input)) {\n\t\treturn input.sort();\n\t}\n\n\tif (typeof input === 'object') {\n\t\treturn keysSorter(Object.keys(input))\n\t\t\t.sort((a, b) => Number(a) - Number(b))\n\t\t\t.map(key => input[key]);\n\t}\n\n\treturn input;\n}\n\nfunction removeHash(input) {\n\tconst hashStart = input.indexOf('#');\n\tif (hashStart !== -1) {\n\t\tinput = input.slice(0, hashStart);\n\t}\n\n\treturn input;\n}\n\nfunction getHash(url) {\n\tlet hash = '';\n\tconst hashStart = url.indexOf('#');\n\tif (hashStart !== -1) {\n\t\thash = url.slice(hashStart);\n\t}\n\n\treturn hash;\n}\n\nfunction extract(input) {\n\tinput = removeHash(input);\n\tconst queryStart = input.indexOf('?');\n\tif (queryStart === -1) {\n\t\treturn '';\n\t}\n\n\treturn input.slice(queryStart + 1);\n}\n\nfunction parseValue(value, options) {\n\tif (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {\n\t\tvalue = Number(value);\n\t} else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {\n\t\tvalue = value.toLowerCase() === 'true';\n\t}\n\n\treturn value;\n}\n\nfunction parse(query, options) {\n\toptions = Object.assign({\n\t\tdecode: true,\n\t\tsort: true,\n\t\tarrayFormat: 'none',\n\t\tarrayFormatSeparator: ',',\n\t\tparseNumbers: false,\n\t\tparseBooleans: false\n\t}, options);\n\n\tvalidateArrayFormatSeparator(options.arrayFormatSeparator);\n\n\tconst formatter = parserForArrayFormat(options);\n\n\t// Create an object with no prototype\n\tconst ret = Object.create(null);\n\n\tif (typeof query !== 'string') {\n\t\treturn ret;\n\t}\n\n\tquery = query.trim().replace(/^[?#&]/, '');\n\n\tif (!query) {\n\t\treturn ret;\n\t}\n\n\tfor (const param of query.split('&')) {\n\t\tif (param === '') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [key, value] = splitOnFirst(options.decode ? param.replace(/\\+/g, ' ') : param, '=');\n\n\t\t// Missing `=` should be `null`:\n\t\t// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters\n\t\tvalue = value === undefined ? null : ['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options);\n\t\tformatter(decode(key, options), value, ret);\n\t}\n\n\tfor (const key of Object.keys(ret)) {\n\t\tconst value = ret[key];\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\tfor (const k of Object.keys(value)) {\n\t\t\t\tvalue[k] = parseValue(value[k], options);\n\t\t\t}\n\t\t} else {\n\t\t\tret[key] = parseValue(value, options);\n\t\t}\n\t}\n\n\tif (options.sort === false) {\n\t\treturn ret;\n\t}\n\n\treturn (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => {\n\t\tconst value = ret[key];\n\t\tif (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) {\n\t\t\t// Sort object keys, not values\n\t\t\tresult[key] = keysSorter(value);\n\t\t} else {\n\t\t\tresult[key] = value;\n\t\t}\n\n\t\treturn result;\n\t}, Object.create(null));\n}\n\nexports.extract = extract;\nexports.parse = parse;\n\nexports.stringify = (object, options) => {\n\tif (!object) {\n\t\treturn '';\n\t}\n\n\toptions = Object.assign({\n\t\tencode: true,\n\t\tstrict: true,\n\t\tarrayFormat: 'none',\n\t\tarrayFormatSeparator: ','\n\t}, options);\n\n\tvalidateArrayFormatSeparator(options.arrayFormatSeparator);\n\n\tconst shouldFilter = key => (\n\t\t(options.skipNull && isNullOrUndefined(object[key])) ||\n\t\t(options.skipEmptyString && object[key] === '')\n\t);\n\n\tconst formatter = encoderForArrayFormat(options);\n\n\tconst objectCopy = {};\n\n\tfor (const key of Object.keys(object)) {\n\t\tif (!shouldFilter(key)) {\n\t\t\tobjectCopy[key] = object[key];\n\t\t}\n\t}\n\n\tconst keys = Object.keys(objectCopy);\n\n\tif (options.sort !== false) {\n\t\tkeys.sort(options.sort);\n\t}\n\n\treturn keys.map(key => {\n\t\tconst value = object[key];\n\n\t\tif (value === undefined) {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn encode(key, options);\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length === 0 && options.arrayFormat === 'bracket-separator') {\n\t\t\t\treturn encode(key, options) + '[]';\n\t\t\t}\n\n\t\t\treturn value\n\t\t\t\t.reduce(formatter(key), [])\n\t\t\t\t.join('&');\n\t\t}\n\n\t\treturn encode(key, options) + '=' + encode(value, options);\n\t}).filter(x => x.length > 0).join('&');\n};\n\nexports.parseUrl = (url, options) => {\n\toptions = Object.assign({\n\t\tdecode: true\n\t}, options);\n\n\tconst [url_, hash] = splitOnFirst(url, '#');\n\n\treturn Object.assign(\n\t\t{\n\t\t\turl: url_.split('?')[0] || '',\n\t\t\tquery: parse(extract(url), options)\n\t\t},\n\t\toptions && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}\n\t);\n};\n\nexports.stringifyUrl = (object, options) => {\n\toptions = Object.assign({\n\t\tencode: true,\n\t\tstrict: true,\n\t\t[encodeFragmentIdentifier]: true\n\t}, options);\n\n\tconst url = removeHash(object.url).split('?')[0] || '';\n\tconst queryFromUrl = exports.extract(object.url);\n\tconst parsedQueryFromUrl = exports.parse(queryFromUrl, {sort: false});\n\n\tconst query = Object.assign(parsedQueryFromUrl, object.query);\n\tlet queryString = exports.stringify(query, options);\n\tif (queryString) {\n\t\tqueryString = `?${queryString}`;\n\t}\n\n\tlet hash = getHash(object.url);\n\tif (object.fragmentIdentifier) {\n\t\thash = `#${options[encodeFragmentIdentifier] ? encode(object.fragmentIdentifier, options) : object.fragmentIdentifier}`;\n\t}\n\n\treturn `${url}${queryString}${hash}`;\n};\n\nexports.pick = (input, filter, options) => {\n\toptions = Object.assign({\n\t\tparseFragmentIdentifier: true,\n\t\t[encodeFragmentIdentifier]: false\n\t}, options);\n\n\tconst {url, query, fragmentIdentifier} = exports.parseUrl(input, options);\n\treturn exports.stringifyUrl({\n\t\turl,\n\t\tquery: filterObject(query, filter),\n\t\tfragmentIdentifier\n\t}, options);\n};\n\nexports.exclude = (input, filter, options) => {\n\tconst exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);\n\n\treturn exports.pick(input, exclusionFilter, options);\n};\n","/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.8.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = global;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;\n var AMD = typeof define === 'function' && define.amd;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) {\n Array.isArray = function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n };\n }\n\n if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {\n ArrayBuffer.isView = function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n };\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (!n && !s) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var notString, type = typeof message;\n if (type !== 'string') {\n if (type === 'object') {\n if (message === null) {\n throw new Error(INPUT_ERROR);\n } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n message = new Uint8Array(message);\n } else if (!Array.isArray(message)) {\n if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n }\n } else {\n throw new Error(INPUT_ERROR);\n }\n notString = true;\n }\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (notString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var notString, type = typeof str;\n if (type !== 'string') {\n if (type === 'object') {\n if (str === null) {\n throw new Error(INPUT_ERROR);\n } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) {\n str = new Uint8Array(str);\n } else if (!Array.isArray(str)) {\n if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) {\n throw new Error(INPUT_ERROR);\n }\n }\n } else {\n throw new Error(INPUT_ERROR);\n }\n notString = true;\n }\n var bytes = 0, length = str.length;\n if (notString) {\n bytes = length;\n } else {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = w - bytes % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n f(s);\n }\n }\n if (extraBytes) {\n array[i] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n define(function () {\n return methods;\n });\n }\n }\n})();\n","export const version = \"logger/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nlet _permanentCensorErrors = false;\nlet _censorErrors = false;\nconst LogLevels = { debug: 1, \"default\": 2, info: 2, warning: 3, error: 4, off: 5 };\nlet _logLevel = LogLevels[\"default\"];\nimport { version } from \"./_version\";\nlet _globalLogger = null;\nfunction _checkNormalize() {\n try {\n const missing = [];\n // Make sure all forms of normalization are supported\n [\"NFD\", \"NFC\", \"NFKD\", \"NFKC\"].forEach((form) => {\n try {\n if (\"test\".normalize(form) !== \"test\") {\n throw new Error(\"bad normalize\");\n }\n ;\n }\n catch (error) {\n missing.push(form);\n }\n });\n if (missing.length) {\n throw new Error(\"missing \" + missing.join(\", \"));\n }\n if (String.fromCharCode(0xe9).normalize(\"NFD\") !== String.fromCharCode(0x65, 0x0301)) {\n throw new Error(\"broken implementation\");\n }\n }\n catch (error) {\n return error.message;\n }\n return null;\n}\nconst _normalizeError = _checkNormalize();\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[\"DEBUG\"] = \"DEBUG\";\n LogLevel[\"INFO\"] = \"INFO\";\n LogLevel[\"WARNING\"] = \"WARNING\";\n LogLevel[\"ERROR\"] = \"ERROR\";\n LogLevel[\"OFF\"] = \"OFF\";\n})(LogLevel || (LogLevel = {}));\nexport var ErrorCode;\n(function (ErrorCode) {\n ///////////////////\n // Generic Errors\n // Unknown Error\n ErrorCode[\"UNKNOWN_ERROR\"] = \"UNKNOWN_ERROR\";\n // Not Implemented\n ErrorCode[\"NOT_IMPLEMENTED\"] = \"NOT_IMPLEMENTED\";\n // Unsupported Operation\n // - operation\n ErrorCode[\"UNSUPPORTED_OPERATION\"] = \"UNSUPPORTED_OPERATION\";\n // Network Error (i.e. Ethereum Network, such as an invalid chain ID)\n // - event (\"noNetwork\" is not re-thrown in provider.ready; otherwise thrown)\n ErrorCode[\"NETWORK_ERROR\"] = \"NETWORK_ERROR\";\n // Some sort of bad response from the server\n ErrorCode[\"SERVER_ERROR\"] = \"SERVER_ERROR\";\n // Timeout\n ErrorCode[\"TIMEOUT\"] = \"TIMEOUT\";\n ///////////////////\n // Operational Errors\n // Buffer Overrun\n ErrorCode[\"BUFFER_OVERRUN\"] = \"BUFFER_OVERRUN\";\n // Numeric Fault\n // - operation: the operation being executed\n // - fault: the reason this faulted\n ErrorCode[\"NUMERIC_FAULT\"] = \"NUMERIC_FAULT\";\n ///////////////////\n // Argument Errors\n // Missing new operator to an object\n // - name: The name of the class\n ErrorCode[\"MISSING_NEW\"] = \"MISSING_NEW\";\n // Invalid argument (e.g. value is incompatible with type) to a function:\n // - argument: The argument name that was invalid\n // - value: The value of the argument\n ErrorCode[\"INVALID_ARGUMENT\"] = \"INVALID_ARGUMENT\";\n // Missing argument to a function:\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"MISSING_ARGUMENT\"] = \"MISSING_ARGUMENT\";\n // Too many arguments\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"UNEXPECTED_ARGUMENT\"] = \"UNEXPECTED_ARGUMENT\";\n ///////////////////\n // Blockchain Errors\n // Call exception\n // - transaction: the transaction\n // - address?: the contract address\n // - args?: The arguments passed into the function\n // - method?: The Solidity method signature\n // - errorSignature?: The EIP848 error signature\n // - errorArgs?: The EIP848 error parameters\n // - reason: The reason (only for EIP848 \"Error(string)\")\n ErrorCode[\"CALL_EXCEPTION\"] = \"CALL_EXCEPTION\";\n // Insufficient funds (< value + gasLimit * gasPrice)\n // - transaction: the transaction attempted\n ErrorCode[\"INSUFFICIENT_FUNDS\"] = \"INSUFFICIENT_FUNDS\";\n // Nonce has already been used\n // - transaction: the transaction attempted\n ErrorCode[\"NONCE_EXPIRED\"] = \"NONCE_EXPIRED\";\n // The replacement fee for the transaction is too low\n // - transaction: the transaction attempted\n ErrorCode[\"REPLACEMENT_UNDERPRICED\"] = \"REPLACEMENT_UNDERPRICED\";\n // The gas limit could not be estimated\n // - transaction: the transaction passed to estimateGas\n ErrorCode[\"UNPREDICTABLE_GAS_LIMIT\"] = \"UNPREDICTABLE_GAS_LIMIT\";\n // The transaction was replaced by one with a higher gas price\n // - reason: \"cancelled\", \"replaced\" or \"repriced\"\n // - cancelled: true if reason == \"cancelled\" or reason == \"replaced\")\n // - hash: original transaction hash\n // - replacement: the full TransactionsResponse for the replacement\n // - receipt: the receipt of the replacement\n ErrorCode[\"TRANSACTION_REPLACED\"] = \"TRANSACTION_REPLACED\";\n ///////////////////\n // Interaction Errors\n // The user rejected the action, such as signing a message or sending\n // a transaction\n ErrorCode[\"ACTION_REJECTED\"] = \"ACTION_REJECTED\";\n})(ErrorCode || (ErrorCode = {}));\n;\nconst HEX = \"0123456789abcdef\";\nexport class Logger {\n constructor(version) {\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n value: version,\n writable: false\n });\n }\n _log(logLevel, args) {\n const level = logLevel.toLowerCase();\n if (LogLevels[level] == null) {\n this.throwArgumentError(\"invalid log level name\", \"logLevel\", logLevel);\n }\n if (_logLevel > LogLevels[level]) {\n return;\n }\n console.log.apply(console, args);\n }\n debug(...args) {\n this._log(Logger.levels.DEBUG, args);\n }\n info(...args) {\n this._log(Logger.levels.INFO, args);\n }\n warn(...args) {\n this._log(Logger.levels.WARNING, args);\n }\n makeError(message, code, params) {\n // Errors are being censored\n if (_censorErrors) {\n return this.makeError(\"censored error\", code, {});\n }\n if (!code) {\n code = Logger.errors.UNKNOWN_ERROR;\n }\n if (!params) {\n params = {};\n }\n const messageDetails = [];\n Object.keys(params).forEach((key) => {\n const value = params[key];\n try {\n if (value instanceof Uint8Array) {\n let hex = \"\";\n for (let i = 0; i < value.length; i++) {\n hex += HEX[value[i] >> 4];\n hex += HEX[value[i] & 0x0f];\n }\n messageDetails.push(key + \"=Uint8Array(0x\" + hex + \")\");\n }\n else {\n messageDetails.push(key + \"=\" + JSON.stringify(value));\n }\n }\n catch (error) {\n messageDetails.push(key + \"=\" + JSON.stringify(params[key].toString()));\n }\n });\n messageDetails.push(`code=${code}`);\n messageDetails.push(`version=${this.version}`);\n const reason = message;\n let url = \"\";\n switch (code) {\n case ErrorCode.NUMERIC_FAULT: {\n url = \"NUMERIC_FAULT\";\n const fault = message;\n switch (fault) {\n case \"overflow\":\n case \"underflow\":\n case \"division-by-zero\":\n url += \"-\" + fault;\n break;\n case \"negative-power\":\n case \"negative-width\":\n url += \"-unsupported\";\n break;\n case \"unbound-bitwise-result\":\n url += \"-unbound-result\";\n break;\n }\n break;\n }\n case ErrorCode.CALL_EXCEPTION:\n case ErrorCode.INSUFFICIENT_FUNDS:\n case ErrorCode.MISSING_NEW:\n case ErrorCode.NONCE_EXPIRED:\n case ErrorCode.REPLACEMENT_UNDERPRICED:\n case ErrorCode.TRANSACTION_REPLACED:\n case ErrorCode.UNPREDICTABLE_GAS_LIMIT:\n url = code;\n break;\n }\n if (url) {\n message += \" [ See: https:/\\/links.ethers.org/v5-errors-\" + url + \" ]\";\n }\n if (messageDetails.length) {\n message += \" (\" + messageDetails.join(\", \") + \")\";\n }\n // @TODO: Any??\n const error = new Error(message);\n error.reason = reason;\n error.code = code;\n Object.keys(params).forEach(function (key) {\n error[key] = params[key];\n });\n return error;\n }\n throwError(message, code, params) {\n throw this.makeError(message, code, params);\n }\n throwArgumentError(message, name, value) {\n return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {\n argument: name,\n value: value\n });\n }\n assert(condition, message, code, params) {\n if (!!condition) {\n return;\n }\n this.throwError(message, code, params);\n }\n assertArgument(condition, message, name, value) {\n if (!!condition) {\n return;\n }\n this.throwArgumentError(message, name, value);\n }\n checkNormalize(message) {\n if (message == null) {\n message = \"platform missing String.prototype.normalize\";\n }\n if (_normalizeError) {\n this.throwError(\"platform missing String.prototype.normalize\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"String.prototype.normalize\", form: _normalizeError\n });\n }\n }\n checkSafeUint53(value, message) {\n if (typeof (value) !== \"number\") {\n return;\n }\n if (message == null) {\n message = \"value not safe\";\n }\n if (value < 0 || value >= 0x1fffffffffffff) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"out-of-safe-range\",\n value: value\n });\n }\n if (value % 1) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"non-integer\",\n value: value\n });\n }\n }\n checkArgumentCount(count, expectedCount, message) {\n if (message) {\n message = \": \" + message;\n }\n else {\n message = \"\";\n }\n if (count < expectedCount) {\n this.throwError(\"missing argument\" + message, Logger.errors.MISSING_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n if (count > expectedCount) {\n this.throwError(\"too many arguments\" + message, Logger.errors.UNEXPECTED_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n }\n checkNew(target, kind) {\n if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n checkAbstract(target, kind) {\n if (target === kind) {\n this.throwError(\"cannot instantiate abstract class \" + JSON.stringify(kind.name) + \" directly; use a sub-class\", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: \"new\" });\n }\n else if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n static globalLogger() {\n if (!_globalLogger) {\n _globalLogger = new Logger(version);\n }\n return _globalLogger;\n }\n static setCensorship(censorship, permanent) {\n if (!censorship && permanent) {\n this.globalLogger().throwError(\"cannot permanently disable censorship\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n if (_permanentCensorErrors) {\n if (!censorship) {\n return;\n }\n this.globalLogger().throwError(\"error censorship permanent\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n _censorErrors = !!censorship;\n _permanentCensorErrors = !!permanent;\n }\n static setLogLevel(logLevel) {\n const level = LogLevels[logLevel.toLowerCase()];\n if (level == null) {\n Logger.globalLogger().warn(\"invalid log level - \" + logLevel);\n return;\n }\n _logLevel = level;\n }\n static from(version) {\n return new Logger(version);\n }\n}\nLogger.errors = ErrorCode;\nLogger.levels = LogLevel;\n//# sourceMappingURL=index.js.map","export const version = \"bytes/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\n///////////////////////////////\nfunction isHexable(value) {\n return !!(value.toHexString);\n}\nfunction addSlice(array) {\n if (array.slice) {\n return array;\n }\n array.slice = function () {\n const args = Array.prototype.slice.call(arguments);\n return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));\n };\n return array;\n}\nexport function isBytesLike(value) {\n return ((isHexString(value) && !(value.length % 2)) || isBytes(value));\n}\nfunction isInteger(value) {\n return (typeof (value) === \"number\" && value == value && (value % 1) === 0);\n}\nexport function isBytes(value) {\n if (value == null) {\n return false;\n }\n if (value.constructor === Uint8Array) {\n return true;\n }\n if (typeof (value) === \"string\") {\n return false;\n }\n if (!isInteger(value.length) || value.length < 0) {\n return false;\n }\n for (let i = 0; i < value.length; i++) {\n const v = value[i];\n if (!isInteger(v) || v < 0 || v >= 256) {\n return false;\n }\n }\n return true;\n}\nexport function arrayify(value, options) {\n if (!options) {\n options = {};\n }\n if (typeof (value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid arrayify value\");\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value = parseInt(String(value / 256));\n }\n if (result.length === 0) {\n result.push(0);\n }\n return addSlice(new Uint8Array(result));\n }\n if (options.allowMissingPrefix && typeof (value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n if (isHexable(value)) {\n value = value.toHexString();\n }\n if (isHexString(value)) {\n let hex = value.substring(2);\n if (hex.length % 2) {\n if (options.hexPad === \"left\") {\n hex = \"0\" + hex;\n }\n else if (options.hexPad === \"right\") {\n hex += \"0\";\n }\n else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n const result = [];\n for (let i = 0; i < hex.length; i += 2) {\n result.push(parseInt(hex.substring(i, i + 2), 16));\n }\n return addSlice(new Uint8Array(result));\n }\n if (isBytes(value)) {\n return addSlice(new Uint8Array(value));\n }\n return logger.throwArgumentError(\"invalid arrayify value\", \"value\", value);\n}\nexport function concat(items) {\n const objects = items.map(item => arrayify(item));\n const length = objects.reduce((accum, item) => (accum + item.length), 0);\n const result = new Uint8Array(length);\n objects.reduce((offset, object) => {\n result.set(object, offset);\n return offset + object.length;\n }, 0);\n return addSlice(result);\n}\nexport function stripZeros(value) {\n let result = arrayify(value);\n if (result.length === 0) {\n return result;\n }\n // Find the first non-zero entry\n let start = 0;\n while (start < result.length && result[start] === 0) {\n start++;\n }\n // If we started with zeros, strip them\n if (start) {\n result = result.slice(start);\n }\n return result;\n}\nexport function zeroPad(value, length) {\n value = arrayify(value);\n if (value.length > length) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[0]);\n }\n const result = new Uint8Array(length);\n result.set(value, length - value.length);\n return addSlice(result);\n}\nexport function isHexString(value, length) {\n if (typeof (value) !== \"string\" || !value.match(/^0x[0-9A-Fa-f]*$/)) {\n return false;\n }\n if (length && value.length !== 2 + 2 * length) {\n return false;\n }\n return true;\n}\nconst HexCharacters = \"0123456789abcdef\";\nexport function hexlify(value, options) {\n if (!options) {\n options = {};\n }\n if (typeof (value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid hexlify value\");\n let hex = \"\";\n while (value) {\n hex = HexCharacters[value & 0xf] + hex;\n value = Math.floor(value / 16);\n }\n if (hex.length) {\n if (hex.length % 2) {\n hex = \"0\" + hex;\n }\n return \"0x\" + hex;\n }\n return \"0x00\";\n }\n if (typeof (value) === \"bigint\") {\n value = value.toString(16);\n if (value.length % 2) {\n return (\"0x0\" + value);\n }\n return \"0x\" + value;\n }\n if (options.allowMissingPrefix && typeof (value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n if (isHexable(value)) {\n return value.toHexString();\n }\n if (isHexString(value)) {\n if (value.length % 2) {\n if (options.hexPad === \"left\") {\n value = \"0x0\" + value.substring(2);\n }\n else if (options.hexPad === \"right\") {\n value += \"0\";\n }\n else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n return value.toLowerCase();\n }\n if (isBytes(value)) {\n let result = \"0x\";\n for (let i = 0; i < value.length; i++) {\n let v = value[i];\n result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];\n }\n return result;\n }\n return logger.throwArgumentError(\"invalid hexlify value\", \"value\", value);\n}\n/*\nfunction unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {\n if (typeof(value) === \"string\" && value.length % 2 && value.substring(0, 2) === \"0x\") {\n return \"0x0\" + value.substring(2);\n }\n return value;\n}\n*/\nexport function hexDataLength(data) {\n if (typeof (data) !== \"string\") {\n data = hexlify(data);\n }\n else if (!isHexString(data) || (data.length % 2)) {\n return null;\n }\n return (data.length - 2) / 2;\n}\nexport function hexDataSlice(data, offset, endOffset) {\n if (typeof (data) !== \"string\") {\n data = hexlify(data);\n }\n else if (!isHexString(data) || (data.length % 2)) {\n logger.throwArgumentError(\"invalid hexData\", \"value\", data);\n }\n offset = 2 + 2 * offset;\n if (endOffset != null) {\n return \"0x\" + data.substring(offset, 2 + 2 * endOffset);\n }\n return \"0x\" + data.substring(offset);\n}\nexport function hexConcat(items) {\n let result = \"0x\";\n items.forEach((item) => {\n result += hexlify(item).substring(2);\n });\n return result;\n}\nexport function hexValue(value) {\n const trimmed = hexStripZeros(hexlify(value, { hexPad: \"left\" }));\n if (trimmed === \"0x\") {\n return \"0x0\";\n }\n return trimmed;\n}\nexport function hexStripZeros(value) {\n if (typeof (value) !== \"string\") {\n value = hexlify(value);\n }\n if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n value = value.substring(2);\n let offset = 0;\n while (offset < value.length && value[offset] === \"0\") {\n offset++;\n }\n return \"0x\" + value.substring(offset);\n}\nexport function hexZeroPad(value, length) {\n if (typeof (value) !== \"string\") {\n value = hexlify(value);\n }\n else if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n if (value.length > 2 * length + 2) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[1]);\n }\n while (value.length < 2 * length + 2) {\n value = \"0x0\" + value.substring(2);\n }\n return value;\n}\nexport function splitSignature(signature) {\n const result = {\n r: \"0x\",\n s: \"0x\",\n _vs: \"0x\",\n recoveryParam: 0,\n v: 0,\n yParityAndS: \"0x\",\n compact: \"0x\"\n };\n if (isBytesLike(signature)) {\n let bytes = arrayify(signature);\n // Get the r, s and v\n if (bytes.length === 64) {\n // EIP-2098; pull the v from the top bit of s and clear it\n result.v = 27 + (bytes[32] >> 7);\n bytes[32] &= 0x7f;\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n }\n else if (bytes.length === 65) {\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n result.v = bytes[64];\n }\n else {\n logger.throwArgumentError(\"invalid signature string\", \"signature\", signature);\n }\n // Allow a recid to be used as the v\n if (result.v < 27) {\n if (result.v === 0 || result.v === 1) {\n result.v += 27;\n }\n else {\n logger.throwArgumentError(\"signature invalid v byte\", \"signature\", signature);\n }\n }\n // Compute recoveryParam from v\n result.recoveryParam = 1 - (result.v % 2);\n // Compute _vs from recoveryParam and s\n if (result.recoveryParam) {\n bytes[32] |= 0x80;\n }\n result._vs = hexlify(bytes.slice(32, 64));\n }\n else {\n result.r = signature.r;\n result.s = signature.s;\n result.v = signature.v;\n result.recoveryParam = signature.recoveryParam;\n result._vs = signature._vs;\n // If the _vs is available, use it to populate missing s, v and recoveryParam\n // and verify non-missing s, v and recoveryParam\n if (result._vs != null) {\n const vs = zeroPad(arrayify(result._vs), 32);\n result._vs = hexlify(vs);\n // Set or check the recid\n const recoveryParam = ((vs[0] >= 128) ? 1 : 0);\n if (result.recoveryParam == null) {\n result.recoveryParam = recoveryParam;\n }\n else if (result.recoveryParam !== recoveryParam) {\n logger.throwArgumentError(\"signature recoveryParam mismatch _vs\", \"signature\", signature);\n }\n // Set or check the s\n vs[0] &= 0x7f;\n const s = hexlify(vs);\n if (result.s == null) {\n result.s = s;\n }\n else if (result.s !== s) {\n logger.throwArgumentError(\"signature v mismatch _vs\", \"signature\", signature);\n }\n }\n // Use recid and v to populate each other\n if (result.recoveryParam == null) {\n if (result.v == null) {\n logger.throwArgumentError(\"signature missing v and recoveryParam\", \"signature\", signature);\n }\n else if (result.v === 0 || result.v === 1) {\n result.recoveryParam = result.v;\n }\n else {\n result.recoveryParam = 1 - (result.v % 2);\n }\n }\n else {\n if (result.v == null) {\n result.v = 27 + result.recoveryParam;\n }\n else {\n const recId = (result.v === 0 || result.v === 1) ? result.v : (1 - (result.v % 2));\n if (result.recoveryParam !== recId) {\n logger.throwArgumentError(\"signature recoveryParam mismatch v\", \"signature\", signature);\n }\n }\n }\n if (result.r == null || !isHexString(result.r)) {\n logger.throwArgumentError(\"signature missing or invalid r\", \"signature\", signature);\n }\n else {\n result.r = hexZeroPad(result.r, 32);\n }\n if (result.s == null || !isHexString(result.s)) {\n logger.throwArgumentError(\"signature missing or invalid s\", \"signature\", signature);\n }\n else {\n result.s = hexZeroPad(result.s, 32);\n }\n const vs = arrayify(result.s);\n if (vs[0] >= 128) {\n logger.throwArgumentError(\"signature s out of range\", \"signature\", signature);\n }\n if (result.recoveryParam) {\n vs[0] |= 0x80;\n }\n const _vs = hexlify(vs);\n if (result._vs) {\n if (!isHexString(result._vs)) {\n logger.throwArgumentError(\"signature invalid _vs\", \"signature\", signature);\n }\n result._vs = hexZeroPad(result._vs, 32);\n }\n // Set or check the _vs\n if (result._vs == null) {\n result._vs = _vs;\n }\n else if (result._vs !== _vs) {\n logger.throwArgumentError(\"signature _vs mismatch v and s\", \"signature\", signature);\n }\n }\n result.yParityAndS = result._vs;\n result.compact = result.r + result.yParityAndS.substring(2);\n return result;\n}\nexport function joinSignature(signature) {\n signature = splitSignature(signature);\n return hexlify(concat([\n signature.r,\n signature.s,\n (signature.recoveryParam ? \"0x1c\" : \"0x1b\")\n ]));\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nimport sha3 from \"js-sha3\";\nimport { arrayify } from \"@ethersproject/bytes\";\nexport function keccak256(data) {\n return '0x' + sha3.keccak_256(arrayify(data));\n}\n//# sourceMappingURL=index.js.map","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [number & 0x3ffffff];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [0];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this._strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // '0' - '9'\n if (c >= 48 && c <= 57) {\n return c - 48;\n // 'A' - 'F'\n } else if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n } else {\n assert(false, 'Invalid character in ' + string);\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this._strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var b = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n b = c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n b = c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n b = c;\n }\n assert(c >= 0 && b < mul, 'Invalid character');\n r += b;\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [0];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this._strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n function move (dest, src) {\n dest.words = src.words;\n dest.length = src.length;\n dest.negative = src.negative;\n dest.red = src.red;\n }\n\n BN.prototype._move = function _move (dest) {\n move(dest, this);\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype._strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n // Check Symbol.for because not everywhere where Symbol defined\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility\n if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {\n try {\n BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;\n } catch (e) {\n BN.prototype.inspect = inspect;\n }\n } else {\n BN.prototype.inspect = inspect;\n }\n\n function inspect () {\n return (this.red ? '';\n }\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modrn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16, 2);\n };\n\n if (Buffer) {\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n return this.toArrayLike(Buffer, endian, length);\n };\n }\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n var allocate = function allocate (ArrayType, size) {\n if (ArrayType.allocUnsafe) {\n return ArrayType.allocUnsafe(size);\n }\n return new ArrayType(size);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n this._strip();\n\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n var res = allocate(ArrayType, reqLength);\n var postfix = endian === 'le' ? 'LE' : 'BE';\n this['_toArrayLike' + postfix](res, byteLength);\n return res;\n };\n\n BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {\n var position = 0;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position++] = word & 0xff;\n if (position < res.length) {\n res[position++] = (word >> 8) & 0xff;\n }\n if (position < res.length) {\n res[position++] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position < res.length) {\n res[position++] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position < res.length) {\n res[position++] = carry;\n\n while (position < res.length) {\n res[position++] = 0;\n }\n }\n };\n\n BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {\n var position = res.length - 1;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position--] = word & 0xff;\n if (position >= 0) {\n res[position--] = (word >> 8) & 0xff;\n }\n if (position >= 0) {\n res[position--] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position >= 0) {\n res[position--] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position >= 0) {\n res[position--] = carry;\n\n while (position >= 0) {\n res[position--] = 0;\n }\n }\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] >>> wbit) & 0x01;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this._strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this._strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this._strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this._strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this._strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this._strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n function jumboMulTo (self, num, out) {\n // Temporary disable, see https://github.com/indutny/bn.js/issues/211\n // var fftm = new FFTM();\n // return fftm.mulp(self, num, out);\n return bigMulTo(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out._strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this._strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) <= num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this._strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this._strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this._strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q._strip();\n }\n a._strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modrn = function modrn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return isNegNum ? -acc : acc;\n };\n\n // WARNING: DEPRECATED\n BN.prototype.modn = function modn (num) {\n return this.modrn(num);\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n this._strip();\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this._strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is a BN v4 instance\n r.strip();\n } else {\n // r is a BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n\n move(a, a.umod(this.m)._forceRed(this));\n return a;\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","export const version = \"bignumber/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\n/**\n * BigNumber\n *\n * A wrapper around the BN.js object. We use the BN.js library\n * because it is used by elliptic, so it is required regardless.\n *\n */\nimport _BN from \"bn.js\";\nvar BN = _BN.BN;\nimport { hexlify, isBytes, isHexString } from \"@ethersproject/bytes\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nconst _constructorGuard = {};\nconst MAX_SAFE = 0x1fffffffffffff;\nexport function isBigNumberish(value) {\n return (value != null) && (BigNumber.isBigNumber(value) ||\n (typeof (value) === \"number\" && (value % 1) === 0) ||\n (typeof (value) === \"string\" && !!value.match(/^-?[0-9]+$/)) ||\n isHexString(value) ||\n (typeof (value) === \"bigint\") ||\n isBytes(value));\n}\n// Only warn about passing 10 into radix once\nlet _warnedToStringRadix = false;\nexport class BigNumber {\n constructor(constructorGuard, hex) {\n if (constructorGuard !== _constructorGuard) {\n logger.throwError(\"cannot call constructor directly; use BigNumber.from\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"new (BigNumber)\"\n });\n }\n this._hex = hex;\n this._isBigNumber = true;\n Object.freeze(this);\n }\n fromTwos(value) {\n return toBigNumber(toBN(this).fromTwos(value));\n }\n toTwos(value) {\n return toBigNumber(toBN(this).toTwos(value));\n }\n abs() {\n if (this._hex[0] === \"-\") {\n return BigNumber.from(this._hex.substring(1));\n }\n return this;\n }\n add(other) {\n return toBigNumber(toBN(this).add(toBN(other)));\n }\n sub(other) {\n return toBigNumber(toBN(this).sub(toBN(other)));\n }\n div(other) {\n const o = BigNumber.from(other);\n if (o.isZero()) {\n throwFault(\"division-by-zero\", \"div\");\n }\n return toBigNumber(toBN(this).div(toBN(other)));\n }\n mul(other) {\n return toBigNumber(toBN(this).mul(toBN(other)));\n }\n mod(other) {\n const value = toBN(other);\n if (value.isNeg()) {\n throwFault(\"division-by-zero\", \"mod\");\n }\n return toBigNumber(toBN(this).umod(value));\n }\n pow(other) {\n const value = toBN(other);\n if (value.isNeg()) {\n throwFault(\"negative-power\", \"pow\");\n }\n return toBigNumber(toBN(this).pow(value));\n }\n and(other) {\n const value = toBN(other);\n if (this.isNegative() || value.isNeg()) {\n throwFault(\"unbound-bitwise-result\", \"and\");\n }\n return toBigNumber(toBN(this).and(value));\n }\n or(other) {\n const value = toBN(other);\n if (this.isNegative() || value.isNeg()) {\n throwFault(\"unbound-bitwise-result\", \"or\");\n }\n return toBigNumber(toBN(this).or(value));\n }\n xor(other) {\n const value = toBN(other);\n if (this.isNegative() || value.isNeg()) {\n throwFault(\"unbound-bitwise-result\", \"xor\");\n }\n return toBigNumber(toBN(this).xor(value));\n }\n mask(value) {\n if (this.isNegative() || value < 0) {\n throwFault(\"negative-width\", \"mask\");\n }\n return toBigNumber(toBN(this).maskn(value));\n }\n shl(value) {\n if (this.isNegative() || value < 0) {\n throwFault(\"negative-width\", \"shl\");\n }\n return toBigNumber(toBN(this).shln(value));\n }\n shr(value) {\n if (this.isNegative() || value < 0) {\n throwFault(\"negative-width\", \"shr\");\n }\n return toBigNumber(toBN(this).shrn(value));\n }\n eq(other) {\n return toBN(this).eq(toBN(other));\n }\n lt(other) {\n return toBN(this).lt(toBN(other));\n }\n lte(other) {\n return toBN(this).lte(toBN(other));\n }\n gt(other) {\n return toBN(this).gt(toBN(other));\n }\n gte(other) {\n return toBN(this).gte(toBN(other));\n }\n isNegative() {\n return (this._hex[0] === \"-\");\n }\n isZero() {\n return toBN(this).isZero();\n }\n toNumber() {\n try {\n return toBN(this).toNumber();\n }\n catch (error) {\n throwFault(\"overflow\", \"toNumber\", this.toString());\n }\n return null;\n }\n toBigInt() {\n try {\n return BigInt(this.toString());\n }\n catch (e) { }\n return logger.throwError(\"this platform does not support BigInt\", Logger.errors.UNSUPPORTED_OPERATION, {\n value: this.toString()\n });\n }\n toString() {\n // Lots of people expect this, which we do not support, so check (See: #889)\n if (arguments.length > 0) {\n if (arguments[0] === 10) {\n if (!_warnedToStringRadix) {\n _warnedToStringRadix = true;\n logger.warn(\"BigNumber.toString does not accept any parameters; base-10 is assumed\");\n }\n }\n else if (arguments[0] === 16) {\n logger.throwError(\"BigNumber.toString does not accept any parameters; use bigNumber.toHexString()\", Logger.errors.UNEXPECTED_ARGUMENT, {});\n }\n else {\n logger.throwError(\"BigNumber.toString does not accept parameters\", Logger.errors.UNEXPECTED_ARGUMENT, {});\n }\n }\n return toBN(this).toString(10);\n }\n toHexString() {\n return this._hex;\n }\n toJSON(key) {\n return { type: \"BigNumber\", hex: this.toHexString() };\n }\n static from(value) {\n if (value instanceof BigNumber) {\n return value;\n }\n if (typeof (value) === \"string\") {\n if (value.match(/^-?0x[0-9a-f]+$/i)) {\n return new BigNumber(_constructorGuard, toHex(value));\n }\n if (value.match(/^-?[0-9]+$/)) {\n return new BigNumber(_constructorGuard, toHex(new BN(value)));\n }\n return logger.throwArgumentError(\"invalid BigNumber string\", \"value\", value);\n }\n if (typeof (value) === \"number\") {\n if (value % 1) {\n throwFault(\"underflow\", \"BigNumber.from\", value);\n }\n if (value >= MAX_SAFE || value <= -MAX_SAFE) {\n throwFault(\"overflow\", \"BigNumber.from\", value);\n }\n return BigNumber.from(String(value));\n }\n const anyValue = value;\n if (typeof (anyValue) === \"bigint\") {\n return BigNumber.from(anyValue.toString());\n }\n if (isBytes(anyValue)) {\n return BigNumber.from(hexlify(anyValue));\n }\n if (anyValue) {\n // Hexable interface (takes priority)\n if (anyValue.toHexString) {\n const hex = anyValue.toHexString();\n if (typeof (hex) === \"string\") {\n return BigNumber.from(hex);\n }\n }\n else {\n // For now, handle legacy JSON-ified values (goes away in v6)\n let hex = anyValue._hex;\n // New-form JSON\n if (hex == null && anyValue.type === \"BigNumber\") {\n hex = anyValue.hex;\n }\n if (typeof (hex) === \"string\") {\n if (isHexString(hex) || (hex[0] === \"-\" && isHexString(hex.substring(1)))) {\n return BigNumber.from(hex);\n }\n }\n }\n }\n return logger.throwArgumentError(\"invalid BigNumber value\", \"value\", value);\n }\n static isBigNumber(value) {\n return !!(value && value._isBigNumber);\n }\n}\n// Normalize the hex string\nfunction toHex(value) {\n // For BN, call on the hex string\n if (typeof (value) !== \"string\") {\n return toHex(value.toString(16));\n }\n // If negative, prepend the negative sign to the normalized positive value\n if (value[0] === \"-\") {\n // Strip off the negative sign\n value = value.substring(1);\n // Cannot have multiple negative signs (e.g. \"--0x04\")\n if (value[0] === \"-\") {\n logger.throwArgumentError(\"invalid hex\", \"value\", value);\n }\n // Call toHex on the positive component\n value = toHex(value);\n // Do not allow \"-0x00\"\n if (value === \"0x00\") {\n return value;\n }\n // Negate the value\n return \"-\" + value;\n }\n // Add a \"0x\" prefix if missing\n if (value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n // Normalize zero\n if (value === \"0x\") {\n return \"0x00\";\n }\n // Make the string even length\n if (value.length % 2) {\n value = \"0x0\" + value.substring(2);\n }\n // Trim to smallest even-length string\n while (value.length > 4 && value.substring(0, 4) === \"0x00\") {\n value = \"0x\" + value.substring(4);\n }\n return value;\n}\nfunction toBigNumber(value) {\n return BigNumber.from(toHex(value));\n}\nfunction toBN(value) {\n const hex = BigNumber.from(value).toHexString();\n if (hex[0] === \"-\") {\n return (new BN(\"-\" + hex.substring(3), 16));\n }\n return new BN(hex.substring(2), 16);\n}\nfunction throwFault(fault, operation, value) {\n const params = { fault: fault, operation: operation };\n if (value != null) {\n params.value = value;\n }\n return logger.throwError(fault, Logger.errors.NUMERIC_FAULT, params);\n}\n// value should have no prefix\nexport function _base36To16(value) {\n return (new BN(value, 36)).toString(16);\n}\n// value should have no prefix\nexport function _base16To36(value) {\n return (new BN(value, 16)).toString(36);\n}\n//# sourceMappingURL=bignumber.js.map","\"use strict\";\nimport { arrayify, hexZeroPad, isBytes } from \"@ethersproject/bytes\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nimport { BigNumber, isBigNumberish } from \"./bignumber\";\nconst _constructorGuard = {};\nconst Zero = BigNumber.from(0);\nconst NegativeOne = BigNumber.from(-1);\nfunction throwFault(message, fault, operation, value) {\n const params = { fault: fault, operation: operation };\n if (value !== undefined) {\n params.value = value;\n }\n return logger.throwError(message, Logger.errors.NUMERIC_FAULT, params);\n}\n// Constant to pull zeros from for multipliers\nlet zeros = \"0\";\nwhile (zeros.length < 256) {\n zeros += zeros;\n}\n// Returns a string \"1\" followed by decimal \"0\"s\nfunction getMultiplier(decimals) {\n if (typeof (decimals) !== \"number\") {\n try {\n decimals = BigNumber.from(decimals).toNumber();\n }\n catch (e) { }\n }\n if (typeof (decimals) === \"number\" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) {\n return (\"1\" + zeros.substring(0, decimals));\n }\n return logger.throwArgumentError(\"invalid decimal size\", \"decimals\", decimals);\n}\nexport function formatFixed(value, decimals) {\n if (decimals == null) {\n decimals = 0;\n }\n const multiplier = getMultiplier(decimals);\n // Make sure wei is a big number (convert as necessary)\n value = BigNumber.from(value);\n const negative = value.lt(Zero);\n if (negative) {\n value = value.mul(NegativeOne);\n }\n let fraction = value.mod(multiplier).toString();\n while (fraction.length < multiplier.length - 1) {\n fraction = \"0\" + fraction;\n }\n // Strip training 0\n fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];\n const whole = value.div(multiplier).toString();\n if (multiplier.length === 1) {\n value = whole;\n }\n else {\n value = whole + \".\" + fraction;\n }\n if (negative) {\n value = \"-\" + value;\n }\n return value;\n}\nexport function parseFixed(value, decimals) {\n if (decimals == null) {\n decimals = 0;\n }\n const multiplier = getMultiplier(decimals);\n if (typeof (value) !== \"string\" || !value.match(/^-?[0-9.]+$/)) {\n logger.throwArgumentError(\"invalid decimal value\", \"value\", value);\n }\n // Is it negative?\n const negative = (value.substring(0, 1) === \"-\");\n if (negative) {\n value = value.substring(1);\n }\n if (value === \".\") {\n logger.throwArgumentError(\"missing value\", \"value\", value);\n }\n // Split it into a whole and fractional part\n const comps = value.split(\".\");\n if (comps.length > 2) {\n logger.throwArgumentError(\"too many decimal points\", \"value\", value);\n }\n let whole = comps[0], fraction = comps[1];\n if (!whole) {\n whole = \"0\";\n }\n if (!fraction) {\n fraction = \"0\";\n }\n // Trim trailing zeros\n while (fraction[fraction.length - 1] === \"0\") {\n fraction = fraction.substring(0, fraction.length - 1);\n }\n // Check the fraction doesn't exceed our decimals size\n if (fraction.length > multiplier.length - 1) {\n throwFault(\"fractional component exceeds decimals\", \"underflow\", \"parseFixed\");\n }\n // If decimals is 0, we have an empty string for fraction\n if (fraction === \"\") {\n fraction = \"0\";\n }\n // Fully pad the string with zeros to get to wei\n while (fraction.length < multiplier.length - 1) {\n fraction += \"0\";\n }\n const wholeValue = BigNumber.from(whole);\n const fractionValue = BigNumber.from(fraction);\n let wei = (wholeValue.mul(multiplier)).add(fractionValue);\n if (negative) {\n wei = wei.mul(NegativeOne);\n }\n return wei;\n}\nexport class FixedFormat {\n constructor(constructorGuard, signed, width, decimals) {\n if (constructorGuard !== _constructorGuard) {\n logger.throwError(\"cannot use FixedFormat constructor; use FixedFormat.from\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"new FixedFormat\"\n });\n }\n this.signed = signed;\n this.width = width;\n this.decimals = decimals;\n this.name = (signed ? \"\" : \"u\") + \"fixed\" + String(width) + \"x\" + String(decimals);\n this._multiplier = getMultiplier(decimals);\n Object.freeze(this);\n }\n static from(value) {\n if (value instanceof FixedFormat) {\n return value;\n }\n if (typeof (value) === \"number\") {\n value = `fixed128x${value}`;\n }\n let signed = true;\n let width = 128;\n let decimals = 18;\n if (typeof (value) === \"string\") {\n if (value === \"fixed\") {\n // defaults...\n }\n else if (value === \"ufixed\") {\n signed = false;\n }\n else {\n const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);\n if (!match) {\n logger.throwArgumentError(\"invalid fixed format\", \"format\", value);\n }\n signed = (match[1] !== \"u\");\n width = parseInt(match[2]);\n decimals = parseInt(match[3]);\n }\n }\n else if (value) {\n const check = (key, type, defaultValue) => {\n if (value[key] == null) {\n return defaultValue;\n }\n if (typeof (value[key]) !== type) {\n logger.throwArgumentError(\"invalid fixed format (\" + key + \" not \" + type + \")\", \"format.\" + key, value[key]);\n }\n return value[key];\n };\n signed = check(\"signed\", \"boolean\", signed);\n width = check(\"width\", \"number\", width);\n decimals = check(\"decimals\", \"number\", decimals);\n }\n if (width % 8) {\n logger.throwArgumentError(\"invalid fixed format width (not byte aligned)\", \"format.width\", width);\n }\n if (decimals > 80) {\n logger.throwArgumentError(\"invalid fixed format (decimals too large)\", \"format.decimals\", decimals);\n }\n return new FixedFormat(_constructorGuard, signed, width, decimals);\n }\n}\nexport class FixedNumber {\n constructor(constructorGuard, hex, value, format) {\n if (constructorGuard !== _constructorGuard) {\n logger.throwError(\"cannot use FixedNumber constructor; use FixedNumber.from\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"new FixedFormat\"\n });\n }\n this.format = format;\n this._hex = hex;\n this._value = value;\n this._isFixedNumber = true;\n Object.freeze(this);\n }\n _checkFormat(other) {\n if (this.format.name !== other.format.name) {\n logger.throwArgumentError(\"incompatible format; use fixedNumber.toFormat\", \"other\", other);\n }\n }\n addUnsafe(other) {\n this._checkFormat(other);\n const a = parseFixed(this._value, this.format.decimals);\n const b = parseFixed(other._value, other.format.decimals);\n return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format);\n }\n subUnsafe(other) {\n this._checkFormat(other);\n const a = parseFixed(this._value, this.format.decimals);\n const b = parseFixed(other._value, other.format.decimals);\n return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format);\n }\n mulUnsafe(other) {\n this._checkFormat(other);\n const a = parseFixed(this._value, this.format.decimals);\n const b = parseFixed(other._value, other.format.decimals);\n return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format);\n }\n divUnsafe(other) {\n this._checkFormat(other);\n const a = parseFixed(this._value, this.format.decimals);\n const b = parseFixed(other._value, other.format.decimals);\n return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format);\n }\n floor() {\n const comps = this.toString().split(\".\");\n if (comps.length === 1) {\n comps.push(\"0\");\n }\n let result = FixedNumber.from(comps[0], this.format);\n const hasFraction = !comps[1].match(/^(0*)$/);\n if (this.isNegative() && hasFraction) {\n result = result.subUnsafe(ONE.toFormat(result.format));\n }\n return result;\n }\n ceiling() {\n const comps = this.toString().split(\".\");\n if (comps.length === 1) {\n comps.push(\"0\");\n }\n let result = FixedNumber.from(comps[0], this.format);\n const hasFraction = !comps[1].match(/^(0*)$/);\n if (!this.isNegative() && hasFraction) {\n result = result.addUnsafe(ONE.toFormat(result.format));\n }\n return result;\n }\n // @TODO: Support other rounding algorithms\n round(decimals) {\n if (decimals == null) {\n decimals = 0;\n }\n // If we are already in range, we're done\n const comps = this.toString().split(\".\");\n if (comps.length === 1) {\n comps.push(\"0\");\n }\n if (decimals < 0 || decimals > 80 || (decimals % 1)) {\n logger.throwArgumentError(\"invalid decimal count\", \"decimals\", decimals);\n }\n if (comps[1].length <= decimals) {\n return this;\n }\n const factor = FixedNumber.from(\"1\" + zeros.substring(0, decimals), this.format);\n const bump = BUMP.toFormat(this.format);\n return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor);\n }\n isZero() {\n return (this._value === \"0.0\" || this._value === \"0\");\n }\n isNegative() {\n return (this._value[0] === \"-\");\n }\n toString() { return this._value; }\n toHexString(width) {\n if (width == null) {\n return this._hex;\n }\n if (width % 8) {\n logger.throwArgumentError(\"invalid byte width\", \"width\", width);\n }\n const hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();\n return hexZeroPad(hex, width / 8);\n }\n toUnsafeFloat() { return parseFloat(this.toString()); }\n toFormat(format) {\n return FixedNumber.fromString(this._value, format);\n }\n static fromValue(value, decimals, format) {\n // If decimals looks more like a format, and there is no format, shift the parameters\n if (format == null && decimals != null && !isBigNumberish(decimals)) {\n format = decimals;\n decimals = null;\n }\n if (decimals == null) {\n decimals = 0;\n }\n if (format == null) {\n format = \"fixed\";\n }\n return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format));\n }\n static fromString(value, format) {\n if (format == null) {\n format = \"fixed\";\n }\n const fixedFormat = FixedFormat.from(format);\n const numeric = parseFixed(value, fixedFormat.decimals);\n if (!fixedFormat.signed && numeric.lt(Zero)) {\n throwFault(\"unsigned value cannot be negative\", \"overflow\", \"value\", value);\n }\n let hex = null;\n if (fixedFormat.signed) {\n hex = numeric.toTwos(fixedFormat.width).toHexString();\n }\n else {\n hex = numeric.toHexString();\n hex = hexZeroPad(hex, fixedFormat.width / 8);\n }\n const decimal = formatFixed(numeric, fixedFormat.decimals);\n return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);\n }\n static fromBytes(value, format) {\n if (format == null) {\n format = \"fixed\";\n }\n const fixedFormat = FixedFormat.from(format);\n if (arrayify(value).length > fixedFormat.width / 8) {\n throw new Error(\"overflow\");\n }\n let numeric = BigNumber.from(value);\n if (fixedFormat.signed) {\n numeric = numeric.fromTwos(fixedFormat.width);\n }\n const hex = numeric.toTwos((fixedFormat.signed ? 0 : 1) + fixedFormat.width).toHexString();\n const decimal = formatFixed(numeric, fixedFormat.decimals);\n return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);\n }\n static from(value, format) {\n if (typeof (value) === \"string\") {\n return FixedNumber.fromString(value, format);\n }\n if (isBytes(value)) {\n return FixedNumber.fromBytes(value, format);\n }\n try {\n return FixedNumber.fromValue(value, 0, format);\n }\n catch (error) {\n // Allow NUMERIC_FAULT to bubble up\n if (error.code !== Logger.errors.INVALID_ARGUMENT) {\n throw error;\n }\n }\n return logger.throwArgumentError(\"invalid FixedNumber value\", \"value\", value);\n }\n static isFixedNumber(value) {\n return !!(value && value._isFixedNumber);\n }\n}\nconst ONE = FixedNumber.from(1);\nconst BUMP = FixedNumber.from(\"0.5\");\n//# sourceMappingURL=fixednumber.js.map","export const version = \"strings/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { arrayify } from \"@ethersproject/bytes\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\n///////////////////////////////\nexport var UnicodeNormalizationForm;\n(function (UnicodeNormalizationForm) {\n UnicodeNormalizationForm[\"current\"] = \"\";\n UnicodeNormalizationForm[\"NFC\"] = \"NFC\";\n UnicodeNormalizationForm[\"NFD\"] = \"NFD\";\n UnicodeNormalizationForm[\"NFKC\"] = \"NFKC\";\n UnicodeNormalizationForm[\"NFKD\"] = \"NFKD\";\n})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {}));\n;\nexport var Utf8ErrorReason;\n(function (Utf8ErrorReason) {\n // A continuation byte was present where there was nothing to continue\n // - offset = the index the codepoint began in\n Utf8ErrorReason[\"UNEXPECTED_CONTINUE\"] = \"unexpected continuation byte\";\n // An invalid (non-continuation) byte to start a UTF-8 codepoint was found\n // - offset = the index the codepoint began in\n Utf8ErrorReason[\"BAD_PREFIX\"] = \"bad codepoint prefix\";\n // The string is too short to process the expected codepoint\n // - offset = the index the codepoint began in\n Utf8ErrorReason[\"OVERRUN\"] = \"string overrun\";\n // A missing continuation byte was expected but not found\n // - offset = the index the continuation byte was expected at\n Utf8ErrorReason[\"MISSING_CONTINUE\"] = \"missing continuation byte\";\n // The computed code point is outside the range for UTF-8\n // - offset = start of this codepoint\n // - badCodepoint = the computed codepoint; outside the UTF-8 range\n Utf8ErrorReason[\"OUT_OF_RANGE\"] = \"out of UTF-8 range\";\n // UTF-8 strings may not contain UTF-16 surrogate pairs\n // - offset = start of this codepoint\n // - badCodepoint = the computed codepoint; inside the UTF-16 surrogate range\n Utf8ErrorReason[\"UTF16_SURROGATE\"] = \"UTF-16 surrogate\";\n // The string is an overlong representation\n // - offset = start of this codepoint\n // - badCodepoint = the computed codepoint; already bounds checked\n Utf8ErrorReason[\"OVERLONG\"] = \"overlong representation\";\n})(Utf8ErrorReason || (Utf8ErrorReason = {}));\n;\nfunction errorFunc(reason, offset, bytes, output, badCodepoint) {\n return logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, \"bytes\", bytes);\n}\nfunction ignoreFunc(reason, offset, bytes, output, badCodepoint) {\n // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes\n if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) {\n let i = 0;\n for (let o = offset + 1; o < bytes.length; o++) {\n if (bytes[o] >> 6 !== 0x02) {\n break;\n }\n i++;\n }\n return i;\n }\n // This byte runs us past the end of the string, so just jump to the end\n // (but the first byte was read already read and therefore skipped)\n if (reason === Utf8ErrorReason.OVERRUN) {\n return bytes.length - offset - 1;\n }\n // Nothing to skip\n return 0;\n}\nfunction replaceFunc(reason, offset, bytes, output, badCodepoint) {\n // Overlong representations are otherwise \"valid\" code points; just non-deistingtished\n if (reason === Utf8ErrorReason.OVERLONG) {\n output.push(badCodepoint);\n return 0;\n }\n // Put the replacement character into the output\n output.push(0xfffd);\n // Otherwise, process as if ignoring errors\n return ignoreFunc(reason, offset, bytes, output, badCodepoint);\n}\n// Common error handing strategies\nexport const Utf8ErrorFuncs = Object.freeze({\n error: errorFunc,\n ignore: ignoreFunc,\n replace: replaceFunc\n});\n// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499\nfunction getUtf8CodePoints(bytes, onError) {\n if (onError == null) {\n onError = Utf8ErrorFuncs.error;\n }\n bytes = arrayify(bytes);\n const result = [];\n let i = 0;\n // Invalid bytes are ignored\n while (i < bytes.length) {\n const c = bytes[i++];\n // 0xxx xxxx\n if (c >> 7 === 0) {\n result.push(c);\n continue;\n }\n // Multibyte; how many bytes left for this character?\n let extraLength = null;\n let overlongMask = null;\n // 110x xxxx 10xx xxxx\n if ((c & 0xe0) === 0xc0) {\n extraLength = 1;\n overlongMask = 0x7f;\n // 1110 xxxx 10xx xxxx 10xx xxxx\n }\n else if ((c & 0xf0) === 0xe0) {\n extraLength = 2;\n overlongMask = 0x7ff;\n // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx\n }\n else if ((c & 0xf8) === 0xf0) {\n extraLength = 3;\n overlongMask = 0xffff;\n }\n else {\n if ((c & 0xc0) === 0x80) {\n i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes, result);\n }\n else {\n i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes, result);\n }\n continue;\n }\n // Do we have enough bytes in our data?\n if (i - 1 + extraLength >= bytes.length) {\n i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes, result);\n continue;\n }\n // Remove the length prefix from the char\n let res = c & ((1 << (8 - extraLength - 1)) - 1);\n for (let j = 0; j < extraLength; j++) {\n let nextChar = bytes[i];\n // Invalid continuation byte\n if ((nextChar & 0xc0) != 0x80) {\n i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes, result);\n res = null;\n break;\n }\n ;\n res = (res << 6) | (nextChar & 0x3f);\n i++;\n }\n // See above loop for invalid continuation byte\n if (res === null) {\n continue;\n }\n // Maximum code point\n if (res > 0x10ffff) {\n i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes, result, res);\n continue;\n }\n // Reserved for UTF-16 surrogate halves\n if (res >= 0xd800 && res <= 0xdfff) {\n i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes, result, res);\n continue;\n }\n // Check for overlong sequences (more bytes than needed)\n if (res <= overlongMask) {\n i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes, result, res);\n continue;\n }\n result.push(res);\n }\n return result;\n}\n// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array\nexport function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) {\n if (form != UnicodeNormalizationForm.current) {\n logger.checkNormalize();\n str = str.normalize(form);\n }\n let result = [];\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 0x80) {\n result.push(c);\n }\n else if (c < 0x800) {\n result.push((c >> 6) | 0xc0);\n result.push((c & 0x3f) | 0x80);\n }\n else if ((c & 0xfc00) == 0xd800) {\n i++;\n const c2 = str.charCodeAt(i);\n if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) {\n throw new Error(\"invalid utf-8 string\");\n }\n // Surrogate Pair\n const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);\n result.push((pair >> 18) | 0xf0);\n result.push(((pair >> 12) & 0x3f) | 0x80);\n result.push(((pair >> 6) & 0x3f) | 0x80);\n result.push((pair & 0x3f) | 0x80);\n }\n else {\n result.push((c >> 12) | 0xe0);\n result.push(((c >> 6) & 0x3f) | 0x80);\n result.push((c & 0x3f) | 0x80);\n }\n }\n return arrayify(result);\n}\n;\nfunction escapeChar(value) {\n const hex = (\"0000\" + value.toString(16));\n return \"\\\\u\" + hex.substring(hex.length - 4);\n}\nexport function _toEscapedUtf8String(bytes, onError) {\n return '\"' + getUtf8CodePoints(bytes, onError).map((codePoint) => {\n if (codePoint < 256) {\n switch (codePoint) {\n case 8: return \"\\\\b\";\n case 9: return \"\\\\t\";\n case 10: return \"\\\\n\";\n case 13: return \"\\\\r\";\n case 34: return \"\\\\\\\"\";\n case 92: return \"\\\\\\\\\";\n }\n if (codePoint >= 32 && codePoint < 127) {\n return String.fromCharCode(codePoint);\n }\n }\n if (codePoint <= 0xffff) {\n return escapeChar(codePoint);\n }\n codePoint -= 0x10000;\n return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00);\n }).join(\"\") + '\"';\n}\nexport function _toUtf8String(codePoints) {\n return codePoints.map((codePoint) => {\n if (codePoint <= 0xffff) {\n return String.fromCharCode(codePoint);\n }\n codePoint -= 0x10000;\n return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00));\n }).join(\"\");\n}\nexport function toUtf8String(bytes, onError) {\n return _toUtf8String(getUtf8CodePoints(bytes, onError));\n}\nexport function toUtf8CodePoints(str, form = UnicodeNormalizationForm.current) {\n return getUtf8CodePoints(toUtf8Bytes(str, form));\n}\n//# sourceMappingURL=utf8.js.map","\"use strict\";\nimport { toUtf8CodePoints, _toUtf8String, UnicodeNormalizationForm } from \"./utf8\";\nfunction bytes2(data) {\n if ((data.length % 4) !== 0) {\n throw new Error(\"bad data\");\n }\n let result = [];\n for (let i = 0; i < data.length; i += 4) {\n result.push(parseInt(data.substring(i, i + 4), 16));\n }\n return result;\n}\nfunction createTable(data, func) {\n if (!func) {\n func = function (value) { return [parseInt(value, 16)]; };\n }\n let lo = 0;\n let result = {};\n data.split(\",\").forEach((pair) => {\n let comps = pair.split(\":\");\n lo += parseInt(comps[0], 16);\n result[lo] = func(comps[1]);\n });\n return result;\n}\nfunction createRangeTable(data) {\n let hi = 0;\n return data.split(\",\").map((v) => {\n let comps = v.split(\"-\");\n if (comps.length === 1) {\n comps[1] = \"0\";\n }\n else if (comps[1] === \"\") {\n comps[1] = \"1\";\n }\n let lo = hi + parseInt(comps[0], 16);\n hi = parseInt(comps[1], 16);\n return { l: lo, h: hi };\n });\n}\nfunction matchMap(value, ranges) {\n let lo = 0;\n for (let i = 0; i < ranges.length; i++) {\n let range = ranges[i];\n lo += range.l;\n if (value >= lo && value <= lo + range.h && ((value - lo) % (range.d || 1)) === 0) {\n if (range.e && range.e.indexOf(value - lo) !== -1) {\n continue;\n }\n return range;\n }\n }\n return null;\n}\nconst Table_A_1_ranges = createRangeTable(\"221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d\");\n// @TODO: Make this relative...\nconst Table_B_1_flags = \"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff\".split(\",\").map((v) => parseInt(v, 16));\nconst Table_B_2_ranges = [\n { h: 25, s: 32, l: 65 },\n { h: 30, s: 32, e: [23], l: 127 },\n { h: 54, s: 1, e: [48], l: 64, d: 2 },\n { h: 14, s: 1, l: 57, d: 2 },\n { h: 44, s: 1, l: 17, d: 2 },\n { h: 10, s: 1, e: [2, 6, 8], l: 61, d: 2 },\n { h: 16, s: 1, l: 68, d: 2 },\n { h: 84, s: 1, e: [18, 24, 66], l: 19, d: 2 },\n { h: 26, s: 32, e: [17], l: 435 },\n { h: 22, s: 1, l: 71, d: 2 },\n { h: 15, s: 80, l: 40 },\n { h: 31, s: 32, l: 16 },\n { h: 32, s: 1, l: 80, d: 2 },\n { h: 52, s: 1, l: 42, d: 2 },\n { h: 12, s: 1, l: 55, d: 2 },\n { h: 40, s: 1, e: [38], l: 15, d: 2 },\n { h: 14, s: 1, l: 48, d: 2 },\n { h: 37, s: 48, l: 49 },\n { h: 148, s: 1, l: 6351, d: 2 },\n { h: 88, s: 1, l: 160, d: 2 },\n { h: 15, s: 16, l: 704 },\n { h: 25, s: 26, l: 854 },\n { h: 25, s: 32, l: 55915 },\n { h: 37, s: 40, l: 1247 },\n { h: 25, s: -119711, l: 53248 },\n { h: 25, s: -119763, l: 52 },\n { h: 25, s: -119815, l: 52 },\n { h: 25, s: -119867, e: [1, 4, 5, 7, 8, 11, 12, 17], l: 52 },\n { h: 25, s: -119919, l: 52 },\n { h: 24, s: -119971, e: [2, 7, 8, 17], l: 52 },\n { h: 24, s: -120023, e: [2, 7, 13, 15, 16, 17], l: 52 },\n { h: 25, s: -120075, l: 52 },\n { h: 25, s: -120127, l: 52 },\n { h: 25, s: -120179, l: 52 },\n { h: 25, s: -120231, l: 52 },\n { h: 25, s: -120283, l: 52 },\n { h: 25, s: -120335, l: 52 },\n { h: 24, s: -119543, e: [17], l: 56 },\n { h: 24, s: -119601, e: [17], l: 58 },\n { h: 24, s: -119659, e: [17], l: 58 },\n { h: 24, s: -119717, e: [17], l: 58 },\n { h: 24, s: -119775, e: [17], l: 58 }\n];\nconst Table_B_2_lut_abs = createTable(\"b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3\");\nconst Table_B_2_lut_rel = createTable(\"179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7\");\nconst Table_B_2_complex = createTable(\"df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D\", bytes2);\nconst Table_C_ranges = createRangeTable(\"80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001\");\nfunction flatten(values) {\n return values.reduce((accum, value) => {\n value.forEach((value) => { accum.push(value); });\n return accum;\n }, []);\n}\nexport function _nameprepTableA1(codepoint) {\n return !!matchMap(codepoint, Table_A_1_ranges);\n}\nexport function _nameprepTableB2(codepoint) {\n let range = matchMap(codepoint, Table_B_2_ranges);\n if (range) {\n return [codepoint + range.s];\n }\n let codes = Table_B_2_lut_abs[codepoint];\n if (codes) {\n return codes;\n }\n let shift = Table_B_2_lut_rel[codepoint];\n if (shift) {\n return [codepoint + shift[0]];\n }\n let complex = Table_B_2_complex[codepoint];\n if (complex) {\n return complex;\n }\n return null;\n}\nexport function _nameprepTableC(codepoint) {\n return !!matchMap(codepoint, Table_C_ranges);\n}\nexport function nameprep(value) {\n // This allows platforms with incomplete normalize to bypass\n // it for very basic names which the built-in toLowerCase\n // will certainly handle correctly\n if (value.match(/^[a-z0-9-]*$/i) && value.length <= 59) {\n return value.toLowerCase();\n }\n // Get the code points (keeping the current normalization)\n let codes = toUtf8CodePoints(value);\n codes = flatten(codes.map((code) => {\n // Substitute Table B.1 (Maps to Nothing)\n if (Table_B_1_flags.indexOf(code) >= 0) {\n return [];\n }\n if (code >= 0xfe00 && code <= 0xfe0f) {\n return [];\n }\n // Substitute Table B.2 (Case Folding)\n let codesTableB2 = _nameprepTableB2(code);\n if (codesTableB2) {\n return codesTableB2;\n }\n // No Substitution\n return [code];\n }));\n // Normalize using form KC\n codes = toUtf8CodePoints(_toUtf8String(codes), UnicodeNormalizationForm.NFKC);\n // Prohibit Tables C.1.2, C.2.2, C.3, C.4, C.5, C.6, C.7, C.8, C.9\n codes.forEach((code) => {\n if (_nameprepTableC(code)) {\n throw new Error(\"STRINGPREP_CONTAINS_PROHIBITED\");\n }\n });\n // Prohibit Unassigned Code Points (Table A.1)\n codes.forEach((code) => {\n if (_nameprepTableA1(code)) {\n throw new Error(\"STRINGPREP_CONTAINS_UNASSIGNED\");\n }\n });\n // IDNA extras\n let name = _toUtf8String(codes);\n // IDNA: 4.2.3.1\n if (name.substring(0, 1) === \"-\" || name.substring(2, 4) === \"--\" || name.substring(name.length - 1) === \"-\") {\n throw new Error(\"invalid hyphen\");\n }\n return name;\n}\n//# sourceMappingURL=idna.js.map","export const version = \"hash/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { arrayify } from \"@ethersproject/bytes\";\nexport function decode(textData) {\n textData = atob(textData);\n const data = [];\n for (let i = 0; i < textData.length; i++) {\n data.push(textData.charCodeAt(i));\n }\n return arrayify(data);\n}\nexport function encode(data) {\n data = arrayify(data);\n let textData = \"\";\n for (let i = 0; i < data.length; i++) {\n textData += String.fromCharCode(data[i]);\n }\n return btoa(textData);\n}\n//# sourceMappingURL=base64.js.map","/**\n * MIT License\n *\n * Copyright (c) 2021 Andrew Raffensperger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * This is a near carbon-copy of the original source (link below) with the\n * TypeScript typings added and a few tweaks to make it ES3-compatible.\n *\n * See: https://github.com/adraffy/ens-normalize.js\n */\n// https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js\nfunction flat(array, depth) {\n if (depth == null) {\n depth = 1;\n }\n const result = [];\n const forEach = result.forEach;\n const flatDeep = function (arr, depth) {\n forEach.call(arr, function (val) {\n if (depth > 0 && Array.isArray(val)) {\n flatDeep(val, depth - 1);\n }\n else {\n result.push(val);\n }\n });\n };\n flatDeep(array, depth);\n return result;\n}\nfunction fromEntries(array) {\n const result = {};\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n result[value[0]] = value[1];\n }\n return result;\n}\nexport function decode_arithmetic(bytes) {\n let pos = 0;\n function u16() { return (bytes[pos++] << 8) | bytes[pos++]; }\n // decode the frequency table\n let symbol_count = u16();\n let total = 1;\n let acc = [0, 1]; // first symbol has frequency 1\n for (let i = 1; i < symbol_count; i++) {\n acc.push(total += u16());\n }\n // skip the sized-payload that the last 3 symbols index into\n let skip = u16();\n let pos_payload = pos;\n pos += skip;\n let read_width = 0;\n let read_buffer = 0;\n function read_bit() {\n if (read_width == 0) {\n // this will read beyond end of buffer\n // but (undefined|0) => zero pad\n read_buffer = (read_buffer << 8) | bytes[pos++];\n read_width = 8;\n }\n return (read_buffer >> --read_width) & 1;\n }\n const N = 31;\n const FULL = Math.pow(2, N);\n const HALF = FULL >>> 1;\n const QRTR = HALF >> 1;\n const MASK = FULL - 1;\n // fill register\n let register = 0;\n for (let i = 0; i < N; i++)\n register = (register << 1) | read_bit();\n let symbols = [];\n let low = 0;\n let range = FULL; // treat like a float\n while (true) {\n let value = Math.floor((((register - low + 1) * total) - 1) / range);\n let start = 0;\n let end = symbol_count;\n while (end - start > 1) { // binary search\n let mid = (start + end) >>> 1;\n if (value < acc[mid]) {\n end = mid;\n }\n else {\n start = mid;\n }\n }\n if (start == 0)\n break; // first symbol is end mark\n symbols.push(start);\n let a = low + Math.floor(range * acc[start] / total);\n let b = low + Math.floor(range * acc[start + 1] / total) - 1;\n while (((a ^ b) & HALF) == 0) {\n register = (register << 1) & MASK | read_bit();\n a = (a << 1) & MASK;\n b = (b << 1) & MASK | 1;\n }\n while (a & ~b & QRTR) {\n register = (register & HALF) | ((register << 1) & (MASK >>> 1)) | read_bit();\n a = (a << 1) ^ HALF;\n b = ((b ^ HALF) << 1) | HALF | 1;\n }\n low = a;\n range = 1 + b - a;\n }\n let offset = symbol_count - 4;\n return symbols.map(x => {\n switch (x - offset) {\n case 3: return offset + 0x10100 + ((bytes[pos_payload++] << 16) | (bytes[pos_payload++] << 8) | bytes[pos_payload++]);\n case 2: return offset + 0x100 + ((bytes[pos_payload++] << 8) | bytes[pos_payload++]);\n case 1: return offset + bytes[pos_payload++];\n default: return x - 1;\n }\n });\n}\n// returns an iterator which returns the next symbol\nexport function read_payload(v) {\n let pos = 0;\n return () => v[pos++];\n}\nexport function read_compressed_payload(bytes) {\n return read_payload(decode_arithmetic(bytes));\n}\n// eg. [0,1,2,3...] => [0,-1,1,-2,...]\nexport function signed(i) {\n return (i & 1) ? (~i >> 1) : (i >> 1);\n}\nfunction read_counts(n, next) {\n let v = Array(n);\n for (let i = 0; i < n; i++)\n v[i] = 1 + next();\n return v;\n}\nfunction read_ascending(n, next) {\n let v = Array(n);\n for (let i = 0, x = -1; i < n; i++)\n v[i] = x += 1 + next();\n return v;\n}\nfunction read_deltas(n, next) {\n let v = Array(n);\n for (let i = 0, x = 0; i < n; i++)\n v[i] = x += signed(next());\n return v;\n}\nexport function read_member_array(next, lookup) {\n let v = read_ascending(next(), next);\n let n = next();\n let vX = read_ascending(n, next);\n let vN = read_counts(n, next);\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < vN[i]; j++) {\n v.push(vX[i] + j);\n }\n }\n return lookup ? v.map(x => lookup[x]) : v;\n}\n// returns array of \n// [x, ys] => single replacement rule\n// [x, ys, n, dx, dx] => linear map\nexport function read_mapped_map(next) {\n let ret = [];\n while (true) {\n let w = next();\n if (w == 0)\n break;\n ret.push(read_linear_table(w, next));\n }\n while (true) {\n let w = next() - 1;\n if (w < 0)\n break;\n ret.push(read_replacement_table(w, next));\n }\n return fromEntries(flat(ret));\n}\nexport function read_zero_terminated_array(next) {\n let v = [];\n while (true) {\n let i = next();\n if (i == 0)\n break;\n v.push(i);\n }\n return v;\n}\nfunction read_transposed(n, w, next) {\n let m = Array(n).fill(undefined).map(() => []);\n for (let i = 0; i < w; i++) {\n read_deltas(n, next).forEach((x, j) => m[j].push(x));\n }\n return m;\n}\nfunction read_linear_table(w, next) {\n let dx = 1 + next();\n let dy = next();\n let vN = read_zero_terminated_array(next);\n let m = read_transposed(vN.length, 1 + w, next);\n return flat(m.map((v, i) => {\n const x = v[0], ys = v.slice(1);\n //let [x, ...ys] = v;\n //return Array(vN[i]).fill().map((_, j) => {\n return Array(vN[i]).fill(undefined).map((_, j) => {\n let j_dy = j * dy;\n return [x + j * dx, ys.map(y => y + j_dy)];\n });\n }));\n}\nfunction read_replacement_table(w, next) {\n let n = 1 + next();\n let m = read_transposed(n, 1 + w, next);\n return m.map(v => [v[0], v.slice(1)]);\n}\nexport function read_emoji_trie(next) {\n let sorted = read_member_array(next).sort((a, b) => a - b);\n return read();\n function read() {\n let branches = [];\n while (true) {\n let keys = read_member_array(next, sorted);\n if (keys.length == 0)\n break;\n branches.push({ set: new Set(keys), node: read() });\n }\n branches.sort((a, b) => b.set.size - a.set.size); // sort by likelihood\n let temp = next();\n let valid = temp % 3;\n temp = (temp / 3) | 0;\n let fe0f = !!(temp & 1);\n temp >>= 1;\n let save = temp == 1;\n let check = temp == 2;\n return { branches, valid, fe0f, save, check };\n }\n}\n//# sourceMappingURL=decoder.js.map","/**\n * MIT License\n *\n * Copyright (c) 2021 Andrew Raffensperger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * This is a near carbon-copy of the original source (link below) with the\n * TypeScript typings added and a few tweaks to make it ES3-compatible.\n *\n * See: https://github.com/adraffy/ens-normalize.js\n */\nimport { decode } from \"@ethersproject/base64\";\nimport { read_compressed_payload } from './decoder.js';\nexport function getData() {\n return read_compressed_payload(decode('AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=='));\n}\n//# sourceMappingURL=include.js.map","/**\n * MIT License\n *\n * Copyright (c) 2021 Andrew Raffensperger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * This is a near carbon-copy of the original source (link below) with the\n * TypeScript typings added and a few tweaks to make it ES3-compatible.\n *\n * See: https://github.com/adraffy/ens-normalize.js\n */\nimport { toUtf8CodePoints } from \"@ethersproject/strings\";\nimport { getData } from './include.js';\nconst r = getData();\nimport { read_member_array, read_mapped_map, read_emoji_trie } from './decoder.js';\n// @TODO: This should be lazily loaded\nconst VALID = new Set(read_member_array(r));\nconst IGNORED = new Set(read_member_array(r));\nconst MAPPED = read_mapped_map(r);\nconst EMOJI_ROOT = read_emoji_trie(r);\n//const NFC_CHECK = new Set(read_member_array(r, Array.from(VALID.values()).sort((a, b) => a - b)));\n//const STOP = 0x2E;\nconst HYPHEN = 0x2D;\nconst UNDERSCORE = 0x5F;\nfunction explode_cp(name) {\n return toUtf8CodePoints(name);\n}\nfunction filter_fe0f(cps) {\n return cps.filter(cp => cp != 0xFE0F);\n}\nexport function ens_normalize_post_check(name) {\n for (let label of name.split('.')) {\n let cps = explode_cp(label);\n try {\n for (let i = cps.lastIndexOf(UNDERSCORE) - 1; i >= 0; i--) {\n if (cps[i] !== UNDERSCORE) {\n throw new Error(`underscore only allowed at start`);\n }\n }\n if (cps.length >= 4 && cps.every(cp => cp < 0x80) && cps[2] === HYPHEN && cps[3] === HYPHEN) {\n throw new Error(`invalid label extension`);\n }\n }\n catch (err) {\n throw new Error(`Invalid label \"${label}\": ${err.message}`);\n }\n }\n return name;\n}\nexport function ens_normalize(name) {\n return ens_normalize_post_check(normalize(name, filter_fe0f));\n}\nfunction normalize(name, emoji_filter) {\n let input = explode_cp(name).reverse(); // flip for pop\n let output = [];\n while (input.length) {\n let emoji = consume_emoji_reversed(input);\n if (emoji) {\n output.push(...emoji_filter(emoji));\n continue;\n }\n let cp = input.pop();\n if (VALID.has(cp)) {\n output.push(cp);\n continue;\n }\n if (IGNORED.has(cp)) {\n continue;\n }\n let cps = MAPPED[cp];\n if (cps) {\n output.push(...cps);\n continue;\n }\n throw new Error(`Disallowed codepoint: 0x${cp.toString(16).toUpperCase()}`);\n }\n return ens_normalize_post_check(nfc(String.fromCodePoint(...output)));\n}\nfunction nfc(s) {\n return s.normalize('NFC');\n}\nfunction consume_emoji_reversed(cps, eaten) {\n var _a;\n let node = EMOJI_ROOT;\n let emoji;\n let saved;\n let stack = [];\n let pos = cps.length;\n if (eaten)\n eaten.length = 0; // clear input buffer (if needed)\n while (pos) {\n let cp = cps[--pos];\n node = (_a = node.branches.find(x => x.set.has(cp))) === null || _a === void 0 ? void 0 : _a.node;\n if (!node)\n break;\n if (node.save) { // remember\n saved = cp;\n }\n else if (node.check) { // check exclusion\n if (cp === saved)\n break;\n }\n stack.push(cp);\n if (node.fe0f) {\n stack.push(0xFE0F);\n if (pos > 0 && cps[pos - 1] == 0xFE0F)\n pos--; // consume optional FE0F\n }\n if (node.valid) { // this is a valid emoji (so far)\n emoji = stack.slice(); // copy stack\n if (node.valid == 2)\n emoji.splice(1, 1); // delete FE0F at position 1 (RGI ZWJ don't follow spec!)\n if (eaten)\n eaten.push(...cps.slice(pos).reverse()); // copy input (if needed)\n cps.length = pos; // truncate\n }\n }\n return emoji;\n}\n//# sourceMappingURL=lib.js.map","import { concat, hexlify } from \"@ethersproject/bytes\";\nimport { toUtf8Bytes, toUtf8String } from \"@ethersproject/strings\";\nimport { keccak256 } from \"@ethersproject/keccak256\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nimport { ens_normalize } from \"./ens-normalize/lib\";\nconst Zeros = new Uint8Array(32);\nZeros.fill(0);\nfunction checkComponent(comp) {\n if (comp.length === 0) {\n throw new Error(\"invalid ENS name; empty component\");\n }\n return comp;\n}\nfunction ensNameSplit(name) {\n const bytes = toUtf8Bytes(ens_normalize(name));\n const comps = [];\n if (name.length === 0) {\n return comps;\n }\n let last = 0;\n for (let i = 0; i < bytes.length; i++) {\n const d = bytes[i];\n // A separator (i.e. \".\"); copy this component\n if (d === 0x2e) {\n comps.push(checkComponent(bytes.slice(last, i)));\n last = i + 1;\n }\n }\n // There was a stray separator at the end of the name\n if (last >= bytes.length) {\n throw new Error(\"invalid ENS name; empty component\");\n }\n comps.push(checkComponent(bytes.slice(last)));\n return comps;\n}\nexport function ensNormalize(name) {\n return ensNameSplit(name).map((comp) => toUtf8String(comp)).join(\".\");\n}\nexport function isValidName(name) {\n try {\n return (ensNameSplit(name).length !== 0);\n }\n catch (error) { }\n return false;\n}\nexport function namehash(name) {\n /* istanbul ignore if */\n if (typeof (name) !== \"string\") {\n logger.throwArgumentError(\"invalid ENS name; not a string\", \"name\", name);\n }\n let result = Zeros;\n const comps = ensNameSplit(name);\n while (comps.length) {\n result = keccak256(concat([result, keccak256(comps.pop())]));\n }\n return hexlify(result);\n}\nexport function dnsEncode(name) {\n return hexlify(concat(ensNameSplit(name).map((comp) => {\n // DNS does not allow components over 63 bytes in length\n if (comp.length > 63) {\n throw new Error(\"invalid DNS encoded entry; length exceeds 63 bytes\");\n }\n const bytes = new Uint8Array(comp.length + 1);\n bytes.set(comp, 1);\n bytes[0] = bytes.length - 1;\n return bytes;\n }))) + \"00\";\n}\n//# sourceMappingURL=namehash.js.map","import { concat } from \"@ethersproject/bytes\";\nimport { keccak256 } from \"@ethersproject/keccak256\";\nimport { toUtf8Bytes } from \"@ethersproject/strings\";\nexport const messagePrefix = \"\\x19Ethereum Signed Message:\\n\";\nexport function hashMessage(message) {\n if (typeof (message) === \"string\") {\n message = toUtf8Bytes(message);\n }\n return keccak256(concat([\n toUtf8Bytes(messagePrefix),\n toUtf8Bytes(String(message.length)),\n message\n ]));\n}\n//# sourceMappingURL=message.js.map","export const version = \"rlp/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\n//See: https://github.com/ethereum/wiki/wiki/RLP\nimport { arrayify, hexlify, isBytesLike } from \"@ethersproject/bytes\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nfunction arrayifyInteger(value) {\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value >>= 8;\n }\n return result;\n}\nfunction unarrayifyInteger(data, offset, length) {\n let result = 0;\n for (let i = 0; i < length; i++) {\n result = (result * 256) + data[offset + i];\n }\n return result;\n}\nfunction _encode(object) {\n if (Array.isArray(object)) {\n let payload = [];\n object.forEach(function (child) {\n payload = payload.concat(_encode(child));\n });\n if (payload.length <= 55) {\n payload.unshift(0xc0 + payload.length);\n return payload;\n }\n const length = arrayifyInteger(payload.length);\n length.unshift(0xf7 + length.length);\n return length.concat(payload);\n }\n if (!isBytesLike(object)) {\n logger.throwArgumentError(\"RLP object must be BytesLike\", \"object\", object);\n }\n const data = Array.prototype.slice.call(arrayify(object));\n if (data.length === 1 && data[0] <= 0x7f) {\n return data;\n }\n else if (data.length <= 55) {\n data.unshift(0x80 + data.length);\n return data;\n }\n const length = arrayifyInteger(data.length);\n length.unshift(0xb7 + length.length);\n return length.concat(data);\n}\nexport function encode(object) {\n return hexlify(_encode(object));\n}\nfunction _decodeChildren(data, offset, childOffset, length) {\n const result = [];\n while (childOffset < offset + 1 + length) {\n const decoded = _decode(data, childOffset);\n result.push(decoded.result);\n childOffset += decoded.consumed;\n if (childOffset > offset + 1 + length) {\n logger.throwError(\"child data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n }\n return { consumed: (1 + length), result: result };\n}\n// returns { consumed: number, result: Object }\nfunction _decode(data, offset) {\n if (data.length === 0) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n // Array with extra length prefix\n if (data[offset] >= 0xf8) {\n const lengthLength = data[offset] - 0xf7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data short segment too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data long segment too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);\n }\n else if (data[offset] >= 0xc0) {\n const length = data[offset] - 0xc0;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n return _decodeChildren(data, offset, offset + 1, length);\n }\n else if (data[offset] >= 0xb8) {\n const lengthLength = data[offset] - 0xb7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));\n return { consumed: (1 + lengthLength + length), result: result };\n }\n else if (data[offset] >= 0x80) {\n const length = data[offset] - 0x80;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const result = hexlify(data.slice(offset + 1, offset + 1 + length));\n return { consumed: (1 + length), result: result };\n }\n return { consumed: 1, result: hexlify(data[offset]) };\n}\nexport function decode(data) {\n const bytes = arrayify(data);\n const decoded = _decode(bytes, 0);\n if (decoded.consumed !== bytes.length) {\n logger.throwArgumentError(\"invalid rlp data\", \"data\", data);\n }\n return decoded.result;\n}\n//# sourceMappingURL=index.js.map","export const version = \"address/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { arrayify, concat, hexDataLength, hexDataSlice, isHexString, stripZeros } from \"@ethersproject/bytes\";\nimport { BigNumber, _base16To36, _base36To16 } from \"@ethersproject/bignumber\";\nimport { keccak256 } from \"@ethersproject/keccak256\";\nimport { encode } from \"@ethersproject/rlp\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nfunction getChecksumAddress(address) {\n if (!isHexString(address, 20)) {\n logger.throwArgumentError(\"invalid address\", \"address\", address);\n }\n address = address.toLowerCase();\n const chars = address.substring(2).split(\"\");\n const expanded = new Uint8Array(40);\n for (let i = 0; i < 40; i++) {\n expanded[i] = chars[i].charCodeAt(0);\n }\n const hashed = arrayify(keccak256(expanded));\n for (let i = 0; i < 40; i += 2) {\n if ((hashed[i >> 1] >> 4) >= 8) {\n chars[i] = chars[i].toUpperCase();\n }\n if ((hashed[i >> 1] & 0x0f) >= 8) {\n chars[i + 1] = chars[i + 1].toUpperCase();\n }\n }\n return \"0x\" + chars.join(\"\");\n}\n// Shims for environments that are missing some required constants and functions\nconst MAX_SAFE_INTEGER = 0x1fffffffffffff;\nfunction log10(x) {\n if (Math.log10) {\n return Math.log10(x);\n }\n return Math.log(x) / Math.LN10;\n}\n// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number\n// Create lookup table\nconst ibanLookup = {};\nfor (let i = 0; i < 10; i++) {\n ibanLookup[String(i)] = String(i);\n}\nfor (let i = 0; i < 26; i++) {\n ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);\n}\n// How many decimal digits can we process? (for 64-bit float, this is 15)\nconst safeDigits = Math.floor(log10(MAX_SAFE_INTEGER));\nfunction ibanChecksum(address) {\n address = address.toUpperCase();\n address = address.substring(4) + address.substring(0, 2) + \"00\";\n let expanded = address.split(\"\").map((c) => { return ibanLookup[c]; }).join(\"\");\n // Javascript can handle integers safely up to 15 (decimal) digits\n while (expanded.length >= safeDigits) {\n let block = expanded.substring(0, safeDigits);\n expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);\n }\n let checksum = String(98 - (parseInt(expanded, 10) % 97));\n while (checksum.length < 2) {\n checksum = \"0\" + checksum;\n }\n return checksum;\n}\n;\nexport function getAddress(address) {\n let result = null;\n if (typeof (address) !== \"string\") {\n logger.throwArgumentError(\"invalid address\", \"address\", address);\n }\n if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {\n // Missing the 0x prefix\n if (address.substring(0, 2) !== \"0x\") {\n address = \"0x\" + address;\n }\n result = getChecksumAddress(address);\n // It is a checksummed address with a bad checksum\n if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) {\n logger.throwArgumentError(\"bad address checksum\", \"address\", address);\n }\n // Maybe ICAP? (we only support direct mode)\n }\n else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {\n // It is an ICAP address with a bad checksum\n if (address.substring(2, 4) !== ibanChecksum(address)) {\n logger.throwArgumentError(\"bad icap checksum\", \"address\", address);\n }\n result = _base36To16(address.substring(4));\n while (result.length < 40) {\n result = \"0\" + result;\n }\n result = getChecksumAddress(\"0x\" + result);\n }\n else {\n logger.throwArgumentError(\"invalid address\", \"address\", address);\n }\n return result;\n}\nexport function isAddress(address) {\n try {\n getAddress(address);\n return true;\n }\n catch (error) { }\n return false;\n}\nexport function getIcapAddress(address) {\n let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase();\n while (base36.length < 30) {\n base36 = \"0\" + base36;\n }\n return \"XE\" + ibanChecksum(\"XE00\" + base36) + base36;\n}\n// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed\nexport function getContractAddress(transaction) {\n let from = null;\n try {\n from = getAddress(transaction.from);\n }\n catch (error) {\n logger.throwArgumentError(\"missing from address\", \"transaction\", transaction);\n }\n const nonce = stripZeros(arrayify(BigNumber.from(transaction.nonce).toHexString()));\n return getAddress(hexDataSlice(keccak256(encode([from, nonce])), 12));\n}\nexport function getCreate2Address(from, salt, initCodeHash) {\n if (hexDataLength(salt) !== 32) {\n logger.throwArgumentError(\"salt must be 32 bytes\", \"salt\", salt);\n }\n if (hexDataLength(initCodeHash) !== 32) {\n logger.throwArgumentError(\"initCodeHash must be 32 bytes\", \"initCodeHash\", initCodeHash);\n }\n return getAddress(hexDataSlice(keccak256(concat([\"0xff\", getAddress(from), salt, initCodeHash])), 12));\n}\n//# sourceMappingURL=index.js.map","export const version = \"properties/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nexport function defineReadOnly(object, name, value) {\n Object.defineProperty(object, name, {\n enumerable: true,\n value: value,\n writable: false,\n });\n}\n// Crawl up the constructor chain to find a static method\nexport function getStatic(ctor, key) {\n for (let i = 0; i < 32; i++) {\n if (ctor[key]) {\n return ctor[key];\n }\n if (!ctor.prototype || typeof (ctor.prototype) !== \"object\") {\n break;\n }\n ctor = Object.getPrototypeOf(ctor.prototype).constructor;\n }\n return null;\n}\nexport function resolveProperties(object) {\n return __awaiter(this, void 0, void 0, function* () {\n const promises = Object.keys(object).map((key) => {\n const value = object[key];\n return Promise.resolve(value).then((v) => ({ key: key, value: v }));\n });\n const results = yield Promise.all(promises);\n return results.reduce((accum, result) => {\n accum[(result.key)] = result.value;\n return accum;\n }, {});\n });\n}\nexport function checkProperties(object, properties) {\n if (!object || typeof (object) !== \"object\") {\n logger.throwArgumentError(\"invalid object\", \"object\", object);\n }\n Object.keys(object).forEach((key) => {\n if (!properties[key]) {\n logger.throwArgumentError(\"invalid object key - \" + key, \"transaction:\" + key, object);\n }\n });\n}\nexport function shallowCopy(object) {\n const result = {};\n for (const key in object) {\n result[key] = object[key];\n }\n return result;\n}\nconst opaque = { bigint: true, boolean: true, \"function\": true, number: true, string: true };\nfunction _isFrozen(object) {\n // Opaque objects are not mutable, so safe to copy by assignment\n if (object === undefined || object === null || opaque[typeof (object)]) {\n return true;\n }\n if (Array.isArray(object) || typeof (object) === \"object\") {\n if (!Object.isFrozen(object)) {\n return false;\n }\n const keys = Object.keys(object);\n for (let i = 0; i < keys.length; i++) {\n let value = null;\n try {\n value = object[keys[i]];\n }\n catch (error) {\n // If accessing a value triggers an error, it is a getter\n // designed to do so (e.g. Result) and is therefore \"frozen\"\n continue;\n }\n if (!_isFrozen(value)) {\n return false;\n }\n }\n return true;\n }\n return logger.throwArgumentError(`Cannot deepCopy ${typeof (object)}`, \"object\", object);\n}\n// Returns a new copy of object, such that no properties may be replaced.\n// New properties may be added only to objects.\nfunction _deepCopy(object) {\n if (_isFrozen(object)) {\n return object;\n }\n // Arrays are mutable, so we need to create a copy\n if (Array.isArray(object)) {\n return Object.freeze(object.map((item) => deepCopy(item)));\n }\n if (typeof (object) === \"object\") {\n const result = {};\n for (const key in object) {\n const value = object[key];\n if (value === undefined) {\n continue;\n }\n defineReadOnly(result, key, deepCopy(value));\n }\n return result;\n }\n return logger.throwArgumentError(`Cannot deepCopy ${typeof (object)}`, \"object\", object);\n}\nexport function deepCopy(object) {\n return _deepCopy(object);\n}\nexport class Description {\n constructor(info) {\n for (const key in info) {\n this[key] = deepCopy(info[key]);\n }\n }\n}\n//# sourceMappingURL=index.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nimport { getAddress } from \"@ethersproject/address\";\nimport { BigNumber } from \"@ethersproject/bignumber\";\nimport { arrayify, hexConcat, hexlify, hexZeroPad, isHexString } from \"@ethersproject/bytes\";\nimport { keccak256 } from \"@ethersproject/keccak256\";\nimport { deepCopy, defineReadOnly, shallowCopy } from \"@ethersproject/properties\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nimport { id } from \"./id\";\nconst padding = new Uint8Array(32);\npadding.fill(0);\nconst NegativeOne = BigNumber.from(-1);\nconst Zero = BigNumber.from(0);\nconst One = BigNumber.from(1);\nconst MaxUint256 = BigNumber.from(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\nfunction hexPadRight(value) {\n const bytes = arrayify(value);\n const padOffset = bytes.length % 32;\n if (padOffset) {\n return hexConcat([bytes, padding.slice(padOffset)]);\n }\n return hexlify(bytes);\n}\nconst hexTrue = hexZeroPad(One.toHexString(), 32);\nconst hexFalse = hexZeroPad(Zero.toHexString(), 32);\nconst domainFieldTypes = {\n name: \"string\",\n version: \"string\",\n chainId: \"uint256\",\n verifyingContract: \"address\",\n salt: \"bytes32\"\n};\nconst domainFieldNames = [\n \"name\", \"version\", \"chainId\", \"verifyingContract\", \"salt\"\n];\nfunction checkString(key) {\n return function (value) {\n if (typeof (value) !== \"string\") {\n logger.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value);\n }\n return value;\n };\n}\nconst domainChecks = {\n name: checkString(\"name\"),\n version: checkString(\"version\"),\n chainId: function (value) {\n try {\n return BigNumber.from(value).toString();\n }\n catch (error) { }\n return logger.throwArgumentError(`invalid domain value for \"chainId\"`, \"domain.chainId\", value);\n },\n verifyingContract: function (value) {\n try {\n return getAddress(value).toLowerCase();\n }\n catch (error) { }\n return logger.throwArgumentError(`invalid domain value \"verifyingContract\"`, \"domain.verifyingContract\", value);\n },\n salt: function (value) {\n try {\n const bytes = arrayify(value);\n if (bytes.length !== 32) {\n throw new Error(\"bad length\");\n }\n return hexlify(bytes);\n }\n catch (error) { }\n return logger.throwArgumentError(`invalid domain value \"salt\"`, \"domain.salt\", value);\n }\n};\nfunction getBaseEncoder(type) {\n // intXX and uintXX\n {\n const match = type.match(/^(u?)int(\\d*)$/);\n if (match) {\n const signed = (match[1] === \"\");\n const width = parseInt(match[2] || \"256\");\n if (width % 8 !== 0 || width > 256 || (match[2] && match[2] !== String(width))) {\n logger.throwArgumentError(\"invalid numeric width\", \"type\", type);\n }\n const boundsUpper = MaxUint256.mask(signed ? (width - 1) : width);\n const boundsLower = signed ? boundsUpper.add(One).mul(NegativeOne) : Zero;\n return function (value) {\n const v = BigNumber.from(value);\n if (v.lt(boundsLower) || v.gt(boundsUpper)) {\n logger.throwArgumentError(`value out-of-bounds for ${type}`, \"value\", value);\n }\n return hexZeroPad(v.toTwos(256).toHexString(), 32);\n };\n }\n }\n // bytesXX\n {\n const match = type.match(/^bytes(\\d+)$/);\n if (match) {\n const width = parseInt(match[1]);\n if (width === 0 || width > 32 || match[1] !== String(width)) {\n logger.throwArgumentError(\"invalid bytes width\", \"type\", type);\n }\n return function (value) {\n const bytes = arrayify(value);\n if (bytes.length !== width) {\n logger.throwArgumentError(`invalid length for ${type}`, \"value\", value);\n }\n return hexPadRight(value);\n };\n }\n }\n switch (type) {\n case \"address\": return function (value) {\n return hexZeroPad(getAddress(value), 32);\n };\n case \"bool\": return function (value) {\n return ((!value) ? hexFalse : hexTrue);\n };\n case \"bytes\": return function (value) {\n return keccak256(value);\n };\n case \"string\": return function (value) {\n return id(value);\n };\n }\n return null;\n}\nfunction encodeType(name, fields) {\n return `${name}(${fields.map(({ name, type }) => (type + \" \" + name)).join(\",\")})`;\n}\nexport class TypedDataEncoder {\n constructor(types) {\n defineReadOnly(this, \"types\", Object.freeze(deepCopy(types)));\n defineReadOnly(this, \"_encoderCache\", {});\n defineReadOnly(this, \"_types\", {});\n // Link struct types to their direct child structs\n const links = {};\n // Link structs to structs which contain them as a child\n const parents = {};\n // Link all subtypes within a given struct\n const subtypes = {};\n Object.keys(types).forEach((type) => {\n links[type] = {};\n parents[type] = [];\n subtypes[type] = {};\n });\n for (const name in types) {\n const uniqueNames = {};\n types[name].forEach((field) => {\n // Check each field has a unique name\n if (uniqueNames[field.name]) {\n logger.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, \"types\", types);\n }\n uniqueNames[field.name] = true;\n // Get the base type (drop any array specifiers)\n const baseType = field.type.match(/^([^\\x5b]*)(\\x5b|$)/)[1];\n if (baseType === name) {\n logger.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`, \"types\", types);\n }\n // Is this a base encoding type?\n const encoder = getBaseEncoder(baseType);\n if (encoder) {\n return;\n }\n if (!parents[baseType]) {\n logger.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`, \"types\", types);\n }\n // Add linkage\n parents[baseType].push(name);\n links[name][baseType] = true;\n });\n }\n // Deduce the primary type\n const primaryTypes = Object.keys(parents).filter((n) => (parents[n].length === 0));\n if (primaryTypes.length === 0) {\n logger.throwArgumentError(\"missing primary type\", \"types\", types);\n }\n else if (primaryTypes.length > 1) {\n logger.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(\", \")}`, \"types\", types);\n }\n defineReadOnly(this, \"primaryType\", primaryTypes[0]);\n // Check for circular type references\n function checkCircular(type, found) {\n if (found[type]) {\n logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, \"types\", types);\n }\n found[type] = true;\n Object.keys(links[type]).forEach((child) => {\n if (!parents[child]) {\n return;\n }\n // Recursively check children\n checkCircular(child, found);\n // Mark all ancestors as having this decendant\n Object.keys(found).forEach((subtype) => {\n subtypes[subtype][child] = true;\n });\n });\n delete found[type];\n }\n checkCircular(this.primaryType, {});\n // Compute each fully describe type\n for (const name in subtypes) {\n const st = Object.keys(subtypes[name]);\n st.sort();\n this._types[name] = encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join(\"\");\n }\n }\n getEncoder(type) {\n let encoder = this._encoderCache[type];\n if (!encoder) {\n encoder = this._encoderCache[type] = this._getEncoder(type);\n }\n return encoder;\n }\n _getEncoder(type) {\n // Basic encoder type (address, bool, uint256, etc)\n {\n const encoder = getBaseEncoder(type);\n if (encoder) {\n return encoder;\n }\n }\n // Array\n const match = type.match(/^(.*)(\\x5b(\\d*)\\x5d)$/);\n if (match) {\n const subtype = match[1];\n const subEncoder = this.getEncoder(subtype);\n const length = parseInt(match[3]);\n return (value) => {\n if (length >= 0 && value.length !== length) {\n logger.throwArgumentError(\"array length mismatch; expected length ${ arrayLength }\", \"value\", value);\n }\n let result = value.map(subEncoder);\n if (this._types[subtype]) {\n result = result.map(keccak256);\n }\n return keccak256(hexConcat(result));\n };\n }\n // Struct\n const fields = this.types[type];\n if (fields) {\n const encodedType = id(this._types[type]);\n return (value) => {\n const values = fields.map(({ name, type }) => {\n const result = this.getEncoder(type)(value[name]);\n if (this._types[type]) {\n return keccak256(result);\n }\n return result;\n });\n values.unshift(encodedType);\n return hexConcat(values);\n };\n }\n return logger.throwArgumentError(`unknown type: ${type}`, \"type\", type);\n }\n encodeType(name) {\n const result = this._types[name];\n if (!result) {\n logger.throwArgumentError(`unknown type: ${JSON.stringify(name)}`, \"name\", name);\n }\n return result;\n }\n encodeData(type, value) {\n return this.getEncoder(type)(value);\n }\n hashStruct(name, value) {\n return keccak256(this.encodeData(name, value));\n }\n encode(value) {\n return this.encodeData(this.primaryType, value);\n }\n hash(value) {\n return this.hashStruct(this.primaryType, value);\n }\n _visit(type, value, callback) {\n // Basic encoder type (address, bool, uint256, etc)\n {\n const encoder = getBaseEncoder(type);\n if (encoder) {\n return callback(type, value);\n }\n }\n // Array\n const match = type.match(/^(.*)(\\x5b(\\d*)\\x5d)$/);\n if (match) {\n const subtype = match[1];\n const length = parseInt(match[3]);\n if (length >= 0 && value.length !== length) {\n logger.throwArgumentError(\"array length mismatch; expected length ${ arrayLength }\", \"value\", value);\n }\n return value.map((v) => this._visit(subtype, v, callback));\n }\n // Struct\n const fields = this.types[type];\n if (fields) {\n return fields.reduce((accum, { name, type }) => {\n accum[name] = this._visit(type, value[name], callback);\n return accum;\n }, {});\n }\n return logger.throwArgumentError(`unknown type: ${type}`, \"type\", type);\n }\n visit(value, callback) {\n return this._visit(this.primaryType, value, callback);\n }\n static from(types) {\n return new TypedDataEncoder(types);\n }\n static getPrimaryType(types) {\n return TypedDataEncoder.from(types).primaryType;\n }\n static hashStruct(name, types, value) {\n return TypedDataEncoder.from(types).hashStruct(name, value);\n }\n static hashDomain(domain) {\n const domainFields = [];\n for (const name in domain) {\n const type = domainFieldTypes[name];\n if (!type) {\n logger.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`, \"domain\", domain);\n }\n domainFields.push({ name, type });\n }\n domainFields.sort((a, b) => {\n return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name);\n });\n return TypedDataEncoder.hashStruct(\"EIP712Domain\", { EIP712Domain: domainFields }, domain);\n }\n static encode(domain, types, value) {\n return hexConcat([\n \"0x1901\",\n TypedDataEncoder.hashDomain(domain),\n TypedDataEncoder.from(types).hash(value)\n ]);\n }\n static hash(domain, types, value) {\n return keccak256(TypedDataEncoder.encode(domain, types, value));\n }\n // Replaces all address types with ENS names with their looked up address\n static resolveNames(domain, types, value, resolveName) {\n return __awaiter(this, void 0, void 0, function* () {\n // Make a copy to isolate it from the object passed in\n domain = shallowCopy(domain);\n // Look up all ENS names\n const ensCache = {};\n // Do we need to look up the domain's verifyingContract?\n if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) {\n ensCache[domain.verifyingContract] = \"0x\";\n }\n // We are going to use the encoder to visit all the base values\n const encoder = TypedDataEncoder.from(types);\n // Get a list of all the addresses\n encoder.visit(value, (type, value) => {\n if (type === \"address\" && !isHexString(value, 20)) {\n ensCache[value] = \"0x\";\n }\n return value;\n });\n // Lookup each name\n for (const name in ensCache) {\n ensCache[name] = yield resolveName(name);\n }\n // Replace the domain verifyingContract if needed\n if (domain.verifyingContract && ensCache[domain.verifyingContract]) {\n domain.verifyingContract = ensCache[domain.verifyingContract];\n }\n // Replace all ENS names with their address\n value = encoder.visit(value, (type, value) => {\n if (type === \"address\" && ensCache[value]) {\n return ensCache[value];\n }\n return value;\n });\n return { domain, value };\n });\n }\n static getPayload(domain, types, value) {\n // Validate the domain fields\n TypedDataEncoder.hashDomain(domain);\n // Derive the EIP712Domain Struct reference type\n const domainValues = {};\n const domainTypes = [];\n domainFieldNames.forEach((name) => {\n const value = domain[name];\n if (value == null) {\n return;\n }\n domainValues[name] = domainChecks[name](value);\n domainTypes.push({ name, type: domainFieldTypes[name] });\n });\n const encoder = TypedDataEncoder.from(types);\n const typesWithDomain = shallowCopy(types);\n if (typesWithDomain.EIP712Domain) {\n logger.throwArgumentError(\"types must not contain EIP712Domain type\", \"types.EIP712Domain\", types);\n }\n else {\n typesWithDomain.EIP712Domain = domainTypes;\n }\n // Validate the data structures and types\n encoder.encode(value);\n return {\n types: typesWithDomain,\n domain: domainValues,\n primaryType: encoder.primaryType,\n message: encoder.visit(value, (type, value) => {\n // bytes\n if (type.match(/^bytes(\\d*)/)) {\n return hexlify(arrayify(value));\n }\n // uint or int\n if (type.match(/^u?int/)) {\n return BigNumber.from(value).toString();\n }\n switch (type) {\n case \"address\":\n return value.toLowerCase();\n case \"bool\":\n return !!value;\n case \"string\":\n if (typeof (value) !== \"string\") {\n logger.throwArgumentError(`invalid string`, \"value\", value);\n }\n return value;\n }\n return logger.throwArgumentError(\"unsupported type\", \"type\", type);\n })\n };\n }\n}\n//# sourceMappingURL=typed-data.js.map","module.exports = assert;\n\nfunction assert(val, msg) {\n if (!val)\n throw new Error(msg || 'Assertion failed');\n}\n\nassert.equal = function assertEqual(l, r, msg) {\n if (l != r)\n throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));\n};\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nexports.inherits = inherits;\n\nfunction isSurrogatePair(msg, i) {\n if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {\n return false;\n }\n if (i < 0 || i + 1 >= msg.length) {\n return false;\n }\n return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;\n}\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg === 'string') {\n if (!enc) {\n // Inspired by stringToUtf8ByteArray() in closure-library by Google\n // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n // Apache License 2.0\n // https://github.com/google/closure-library/blob/master/LICENSE\n var p = 0;\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n if (c < 128) {\n res[p++] = c;\n } else if (c < 2048) {\n res[p++] = (c >> 6) | 192;\n res[p++] = (c & 63) | 128;\n } else if (isSurrogatePair(msg, i)) {\n c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);\n res[p++] = (c >> 18) | 240;\n res[p++] = ((c >> 12) & 63) | 128;\n res[p++] = ((c >> 6) & 63) | 128;\n res[p++] = (c & 63) | 128;\n } else {\n res[p++] = (c >> 12) | 224;\n res[p++] = ((c >> 6) & 63) | 128;\n res[p++] = (c & 63) | 128;\n }\n }\n } else if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n }\n } else {\n for (i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n }\n return res;\n}\nexports.toArray = toArray;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nexports.toHex = toHex;\n\nfunction htonl(w) {\n var res = (w >>> 24) |\n ((w >>> 8) & 0xff00) |\n ((w << 8) & 0xff0000) |\n ((w & 0xff) << 24);\n return res >>> 0;\n}\nexports.htonl = htonl;\n\nfunction toHex32(msg, endian) {\n var res = '';\n for (var i = 0; i < msg.length; i++) {\n var w = msg[i];\n if (endian === 'little')\n w = htonl(w);\n res += zero8(w.toString(16));\n }\n return res;\n}\nexports.toHex32 = toHex32;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nexports.zero2 = zero2;\n\nfunction zero8(word) {\n if (word.length === 7)\n return '0' + word;\n else if (word.length === 6)\n return '00' + word;\n else if (word.length === 5)\n return '000' + word;\n else if (word.length === 4)\n return '0000' + word;\n else if (word.length === 3)\n return '00000' + word;\n else if (word.length === 2)\n return '000000' + word;\n else if (word.length === 1)\n return '0000000' + word;\n else\n return word;\n}\nexports.zero8 = zero8;\n\nfunction join32(msg, start, end, endian) {\n var len = end - start;\n assert(len % 4 === 0);\n var res = new Array(len / 4);\n for (var i = 0, k = start; i < res.length; i++, k += 4) {\n var w;\n if (endian === 'big')\n w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];\n else\n w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];\n res[i] = w >>> 0;\n }\n return res;\n}\nexports.join32 = join32;\n\nfunction split32(msg, endian) {\n var res = new Array(msg.length * 4);\n for (var i = 0, k = 0; i < msg.length; i++, k += 4) {\n var m = msg[i];\n if (endian === 'big') {\n res[k] = m >>> 24;\n res[k + 1] = (m >>> 16) & 0xff;\n res[k + 2] = (m >>> 8) & 0xff;\n res[k + 3] = m & 0xff;\n } else {\n res[k + 3] = m >>> 24;\n res[k + 2] = (m >>> 16) & 0xff;\n res[k + 1] = (m >>> 8) & 0xff;\n res[k] = m & 0xff;\n }\n }\n return res;\n}\nexports.split32 = split32;\n\nfunction rotr32(w, b) {\n return (w >>> b) | (w << (32 - b));\n}\nexports.rotr32 = rotr32;\n\nfunction rotl32(w, b) {\n return (w << b) | (w >>> (32 - b));\n}\nexports.rotl32 = rotl32;\n\nfunction sum32(a, b) {\n return (a + b) >>> 0;\n}\nexports.sum32 = sum32;\n\nfunction sum32_3(a, b, c) {\n return (a + b + c) >>> 0;\n}\nexports.sum32_3 = sum32_3;\n\nfunction sum32_4(a, b, c, d) {\n return (a + b + c + d) >>> 0;\n}\nexports.sum32_4 = sum32_4;\n\nfunction sum32_5(a, b, c, d, e) {\n return (a + b + c + d + e) >>> 0;\n}\nexports.sum32_5 = sum32_5;\n\nfunction sum64(buf, pos, ah, al) {\n var bh = buf[pos];\n var bl = buf[pos + 1];\n\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n buf[pos] = hi >>> 0;\n buf[pos + 1] = lo;\n}\nexports.sum64 = sum64;\n\nfunction sum64_hi(ah, al, bh, bl) {\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n return hi >>> 0;\n}\nexports.sum64_hi = sum64_hi;\n\nfunction sum64_lo(ah, al, bh, bl) {\n var lo = al + bl;\n return lo >>> 0;\n}\nexports.sum64_lo = sum64_lo;\n\nfunction sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n\n var hi = ah + bh + ch + dh + carry;\n return hi >>> 0;\n}\nexports.sum64_4_hi = sum64_4_hi;\n\nfunction sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {\n var lo = al + bl + cl + dl;\n return lo >>> 0;\n}\nexports.sum64_4_lo = sum64_4_lo;\n\nfunction sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n lo = (lo + el) >>> 0;\n carry += lo < el ? 1 : 0;\n\n var hi = ah + bh + ch + dh + eh + carry;\n return hi >>> 0;\n}\nexports.sum64_5_hi = sum64_5_hi;\n\nfunction sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var lo = al + bl + cl + dl + el;\n\n return lo >>> 0;\n}\nexports.sum64_5_lo = sum64_5_lo;\n\nfunction rotr64_hi(ah, al, num) {\n var r = (al << (32 - num)) | (ah >>> num);\n return r >>> 0;\n}\nexports.rotr64_hi = rotr64_hi;\n\nfunction rotr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.rotr64_lo = rotr64_lo;\n\nfunction shr64_hi(ah, al, num) {\n return ah >>> num;\n}\nexports.shr64_hi = shr64_hi;\n\nfunction shr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.shr64_lo = shr64_lo;\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction BlockHash() {\n this.pending = null;\n this.pendingTotal = 0;\n this.blockSize = this.constructor.blockSize;\n this.outSize = this.constructor.outSize;\n this.hmacStrength = this.constructor.hmacStrength;\n this.padLength = this.constructor.padLength / 8;\n this.endian = 'big';\n\n this._delta8 = this.blockSize / 8;\n this._delta32 = this.blockSize / 32;\n}\nexports.BlockHash = BlockHash;\n\nBlockHash.prototype.update = function update(msg, enc) {\n // Convert message to array, pad it, and join into 32bit blocks\n msg = utils.toArray(msg, enc);\n if (!this.pending)\n this.pending = msg;\n else\n this.pending = this.pending.concat(msg);\n this.pendingTotal += msg.length;\n\n // Enough data, try updating\n if (this.pending.length >= this._delta8) {\n msg = this.pending;\n\n // Process pending data in blocks\n var r = msg.length % this._delta8;\n this.pending = msg.slice(msg.length - r, msg.length);\n if (this.pending.length === 0)\n this.pending = null;\n\n msg = utils.join32(msg, 0, msg.length - r, this.endian);\n for (var i = 0; i < msg.length; i += this._delta32)\n this._update(msg, i, i + this._delta32);\n }\n\n return this;\n};\n\nBlockHash.prototype.digest = function digest(enc) {\n this.update(this._pad());\n assert(this.pending === null);\n\n return this._digest(enc);\n};\n\nBlockHash.prototype._pad = function pad() {\n var len = this.pendingTotal;\n var bytes = this._delta8;\n var k = bytes - ((len + this.padLength) % bytes);\n var res = new Array(k + this.padLength);\n res[0] = 0x80;\n for (var i = 1; i < k; i++)\n res[i] = 0;\n\n // Append length\n len <<= 3;\n if (this.endian === 'big') {\n for (var t = 8; t < this.padLength; t++)\n res[i++] = 0;\n\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = len & 0xff;\n } else {\n res[i++] = len & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n\n for (t = 8; t < this.padLength; t++)\n res[i++] = 0;\n }\n\n return res;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar rotr32 = utils.rotr32;\n\nfunction ft_1(s, x, y, z) {\n if (s === 0)\n return ch32(x, y, z);\n if (s === 1 || s === 3)\n return p32(x, y, z);\n if (s === 2)\n return maj32(x, y, z);\n}\nexports.ft_1 = ft_1;\n\nfunction ch32(x, y, z) {\n return (x & y) ^ ((~x) & z);\n}\nexports.ch32 = ch32;\n\nfunction maj32(x, y, z) {\n return (x & y) ^ (x & z) ^ (y & z);\n}\nexports.maj32 = maj32;\n\nfunction p32(x, y, z) {\n return x ^ y ^ z;\n}\nexports.p32 = p32;\n\nfunction s0_256(x) {\n return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);\n}\nexports.s0_256 = s0_256;\n\nfunction s1_256(x) {\n return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);\n}\nexports.s1_256 = s1_256;\n\nfunction g0_256(x) {\n return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);\n}\nexports.g0_256 = g0_256;\n\nfunction g1_256(x) {\n return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);\n}\nexports.g1_256 = g1_256;\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_5 = utils.sum32_5;\nvar ft_1 = shaCommon.ft_1;\nvar BlockHash = common.BlockHash;\n\nvar sha1_K = [\n 0x5A827999, 0x6ED9EBA1,\n 0x8F1BBCDC, 0xCA62C1D6\n];\n\nfunction SHA1() {\n if (!(this instanceof SHA1))\n return new SHA1();\n\n BlockHash.call(this);\n this.h = [\n 0x67452301, 0xefcdab89, 0x98badcfe,\n 0x10325476, 0xc3d2e1f0 ];\n this.W = new Array(80);\n}\n\nutils.inherits(SHA1, BlockHash);\nmodule.exports = SHA1;\n\nSHA1.blockSize = 512;\nSHA1.outSize = 160;\nSHA1.hmacStrength = 80;\nSHA1.padLength = 64;\n\nSHA1.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n\n for(; i < W.length; i++)\n W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n\n for (i = 0; i < W.length; i++) {\n var s = ~~(i / 20);\n var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);\n e = d;\n d = c;\n c = rotl32(b, 30);\n b = a;\n a = t;\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n};\n\nSHA1.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\nvar assert = require('minimalistic-assert');\n\nvar sum32 = utils.sum32;\nvar sum32_4 = utils.sum32_4;\nvar sum32_5 = utils.sum32_5;\nvar ch32 = shaCommon.ch32;\nvar maj32 = shaCommon.maj32;\nvar s0_256 = shaCommon.s0_256;\nvar s1_256 = shaCommon.s1_256;\nvar g0_256 = shaCommon.g0_256;\nvar g1_256 = shaCommon.g1_256;\n\nvar BlockHash = common.BlockHash;\n\nvar sha256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n];\n\nfunction SHA256() {\n if (!(this instanceof SHA256))\n return new SHA256();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n ];\n this.k = sha256_K;\n this.W = new Array(64);\n}\nutils.inherits(SHA256, BlockHash);\nmodule.exports = SHA256;\n\nSHA256.blockSize = 512;\nSHA256.outSize = 256;\nSHA256.hmacStrength = 192;\nSHA256.padLength = 64;\n\nSHA256.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i++)\n W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n var f = this.h[5];\n var g = this.h[6];\n var h = this.h[7];\n\n assert(this.k.length === W.length);\n for (i = 0; i < W.length; i++) {\n var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);\n var T2 = sum32(s0_256(a), maj32(a, b, c));\n h = g;\n g = f;\n f = e;\n e = sum32(d, T1);\n d = c;\n c = b;\n b = a;\n a = sum32(T1, T2);\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n this.h[5] = sum32(this.h[5], f);\n this.h[6] = sum32(this.h[6], g);\n this.h[7] = sum32(this.h[7], h);\n};\n\nSHA256.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar SHA256 = require('./256');\n\nfunction SHA224() {\n if (!(this instanceof SHA224))\n return new SHA224();\n\n SHA256.call(this);\n this.h = [\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,\n 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];\n}\nutils.inherits(SHA224, SHA256);\nmodule.exports = SHA224;\n\nSHA224.blockSize = 512;\nSHA224.outSize = 224;\nSHA224.hmacStrength = 192;\nSHA224.padLength = 64;\n\nSHA224.prototype._digest = function digest(enc) {\n // Just truncate output\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 7), 'big');\n else\n return utils.split32(this.h.slice(0, 7), 'big');\n};\n\n","'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar assert = require('minimalistic-assert');\n\nvar rotr64_hi = utils.rotr64_hi;\nvar rotr64_lo = utils.rotr64_lo;\nvar shr64_hi = utils.shr64_hi;\nvar shr64_lo = utils.shr64_lo;\nvar sum64 = utils.sum64;\nvar sum64_hi = utils.sum64_hi;\nvar sum64_lo = utils.sum64_lo;\nvar sum64_4_hi = utils.sum64_4_hi;\nvar sum64_4_lo = utils.sum64_4_lo;\nvar sum64_5_hi = utils.sum64_5_hi;\nvar sum64_5_lo = utils.sum64_5_lo;\n\nvar BlockHash = common.BlockHash;\n\nvar sha512_K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction SHA512() {\n if (!(this instanceof SHA512))\n return new SHA512();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xf3bcc908,\n 0xbb67ae85, 0x84caa73b,\n 0x3c6ef372, 0xfe94f82b,\n 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1,\n 0x9b05688c, 0x2b3e6c1f,\n 0x1f83d9ab, 0xfb41bd6b,\n 0x5be0cd19, 0x137e2179 ];\n this.k = sha512_K;\n this.W = new Array(160);\n}\nutils.inherits(SHA512, BlockHash);\nmodule.exports = SHA512;\n\nSHA512.blockSize = 1024;\nSHA512.outSize = 512;\nSHA512.hmacStrength = 192;\nSHA512.padLength = 128;\n\nSHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {\n var W = this.W;\n\n // 32 x 32bit words\n for (var i = 0; i < 32; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i += 2) {\n var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2\n var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);\n var c1_hi = W[i - 14]; // i - 7\n var c1_lo = W[i - 13];\n var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15\n var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);\n var c3_hi = W[i - 32]; // i - 16\n var c3_lo = W[i - 31];\n\n W[i] = sum64_4_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n W[i + 1] = sum64_4_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n }\n};\n\nSHA512.prototype._update = function _update(msg, start) {\n this._prepareBlock(msg, start);\n\n var W = this.W;\n\n var ah = this.h[0];\n var al = this.h[1];\n var bh = this.h[2];\n var bl = this.h[3];\n var ch = this.h[4];\n var cl = this.h[5];\n var dh = this.h[6];\n var dl = this.h[7];\n var eh = this.h[8];\n var el = this.h[9];\n var fh = this.h[10];\n var fl = this.h[11];\n var gh = this.h[12];\n var gl = this.h[13];\n var hh = this.h[14];\n var hl = this.h[15];\n\n assert(this.k.length === W.length);\n for (var i = 0; i < W.length; i += 2) {\n var c0_hi = hh;\n var c0_lo = hl;\n var c1_hi = s1_512_hi(eh, el);\n var c1_lo = s1_512_lo(eh, el);\n var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);\n var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);\n var c3_hi = this.k[i];\n var c3_lo = this.k[i + 1];\n var c4_hi = W[i];\n var c4_lo = W[i + 1];\n\n var T1_hi = sum64_5_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n var T1_lo = sum64_5_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n\n c0_hi = s0_512_hi(ah, al);\n c0_lo = s0_512_lo(ah, al);\n c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);\n c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);\n\n var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);\n var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);\n\n hh = gh;\n hl = gl;\n\n gh = fh;\n gl = fl;\n\n fh = eh;\n fl = el;\n\n eh = sum64_hi(dh, dl, T1_hi, T1_lo);\n el = sum64_lo(dl, dl, T1_hi, T1_lo);\n\n dh = ch;\n dl = cl;\n\n ch = bh;\n cl = bl;\n\n bh = ah;\n bl = al;\n\n ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);\n al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);\n }\n\n sum64(this.h, 0, ah, al);\n sum64(this.h, 2, bh, bl);\n sum64(this.h, 4, ch, cl);\n sum64(this.h, 6, dh, dl);\n sum64(this.h, 8, eh, el);\n sum64(this.h, 10, fh, fl);\n sum64(this.h, 12, gh, gl);\n sum64(this.h, 14, hh, hl);\n};\n\nSHA512.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n\nfunction ch64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ ((~xh) & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction ch64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ ((~xl) & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 28);\n var c1_hi = rotr64_hi(xl, xh, 2); // 34\n var c2_hi = rotr64_hi(xl, xh, 7); // 39\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 28);\n var c1_lo = rotr64_lo(xl, xh, 2); // 34\n var c2_lo = rotr64_lo(xl, xh, 7); // 39\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 14);\n var c1_hi = rotr64_hi(xh, xl, 18);\n var c2_hi = rotr64_hi(xl, xh, 9); // 41\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 14);\n var c1_lo = rotr64_lo(xh, xl, 18);\n var c2_lo = rotr64_lo(xl, xh, 9); // 41\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 1);\n var c1_hi = rotr64_hi(xh, xl, 8);\n var c2_hi = shr64_hi(xh, xl, 7);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 1);\n var c1_lo = rotr64_lo(xh, xl, 8);\n var c2_lo = shr64_lo(xh, xl, 7);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 19);\n var c1_hi = rotr64_hi(xl, xh, 29); // 61\n var c2_hi = shr64_hi(xh, xl, 6);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 19);\n var c1_lo = rotr64_lo(xl, xh, 29); // 61\n var c2_lo = shr64_lo(xh, xl, 6);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n","'use strict';\n\nvar utils = require('../utils');\n\nvar SHA512 = require('./512');\n\nfunction SHA384() {\n if (!(this instanceof SHA384))\n return new SHA384();\n\n SHA512.call(this);\n this.h = [\n 0xcbbb9d5d, 0xc1059ed8,\n 0x629a292a, 0x367cd507,\n 0x9159015a, 0x3070dd17,\n 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31,\n 0x8eb44a87, 0x68581511,\n 0xdb0c2e0d, 0x64f98fa7,\n 0x47b5481d, 0xbefa4fa4 ];\n}\nutils.inherits(SHA384, SHA512);\nmodule.exports = SHA384;\n\nSHA384.blockSize = 1024;\nSHA384.outSize = 384;\nSHA384.hmacStrength = 192;\nSHA384.padLength = 128;\n\nSHA384.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 12), 'big');\n else\n return utils.split32(this.h.slice(0, 12), 'big');\n};\n","'use strict';\n\nexports.sha1 = require('./sha/1');\nexports.sha224 = require('./sha/224');\nexports.sha256 = require('./sha/256');\nexports.sha384 = require('./sha/384');\nexports.sha512 = require('./sha/512');\n","'use strict';\n\nvar utils = require('./utils');\nvar common = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_3 = utils.sum32_3;\nvar sum32_4 = utils.sum32_4;\nvar BlockHash = common.BlockHash;\n\nfunction RIPEMD160() {\n if (!(this instanceof RIPEMD160))\n return new RIPEMD160();\n\n BlockHash.call(this);\n\n this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];\n this.endian = 'little';\n}\nutils.inherits(RIPEMD160, BlockHash);\nexports.ripemd160 = RIPEMD160;\n\nRIPEMD160.blockSize = 512;\nRIPEMD160.outSize = 160;\nRIPEMD160.hmacStrength = 192;\nRIPEMD160.padLength = 64;\n\nRIPEMD160.prototype._update = function update(msg, start) {\n var A = this.h[0];\n var B = this.h[1];\n var C = this.h[2];\n var D = this.h[3];\n var E = this.h[4];\n var Ah = A;\n var Bh = B;\n var Ch = C;\n var Dh = D;\n var Eh = E;\n for (var j = 0; j < 80; j++) {\n var T = sum32(\n rotl32(\n sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),\n s[j]),\n E);\n A = E;\n E = D;\n D = rotl32(C, 10);\n C = B;\n B = T;\n T = sum32(\n rotl32(\n sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),\n sh[j]),\n Eh);\n Ah = Eh;\n Eh = Dh;\n Dh = rotl32(Ch, 10);\n Ch = Bh;\n Bh = T;\n }\n T = sum32_3(this.h[1], C, Dh);\n this.h[1] = sum32_3(this.h[2], D, Eh);\n this.h[2] = sum32_3(this.h[3], E, Ah);\n this.h[3] = sum32_3(this.h[4], A, Bh);\n this.h[4] = sum32_3(this.h[0], B, Ch);\n this.h[0] = T;\n};\n\nRIPEMD160.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'little');\n else\n return utils.split32(this.h, 'little');\n};\n\nfunction f(j, x, y, z) {\n if (j <= 15)\n return x ^ y ^ z;\n else if (j <= 31)\n return (x & y) | ((~x) & z);\n else if (j <= 47)\n return (x | (~y)) ^ z;\n else if (j <= 63)\n return (x & z) | (y & (~z));\n else\n return x ^ (y | (~z));\n}\n\nfunction K(j) {\n if (j <= 15)\n return 0x00000000;\n else if (j <= 31)\n return 0x5a827999;\n else if (j <= 47)\n return 0x6ed9eba1;\n else if (j <= 63)\n return 0x8f1bbcdc;\n else\n return 0xa953fd4e;\n}\n\nfunction Kh(j) {\n if (j <= 15)\n return 0x50a28be6;\n else if (j <= 31)\n return 0x5c4dd124;\n else if (j <= 47)\n return 0x6d703ef3;\n else if (j <= 63)\n return 0x7a6d76e9;\n else\n return 0x00000000;\n}\n\nvar r = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n];\n\nvar rh = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n];\n\nvar s = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n];\n\nvar sh = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n];\n","'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction Hmac(hash, key, enc) {\n if (!(this instanceof Hmac))\n return new Hmac(hash, key, enc);\n this.Hash = hash;\n this.blockSize = hash.blockSize / 8;\n this.outSize = hash.outSize / 8;\n this.inner = null;\n this.outer = null;\n\n this._init(utils.toArray(key, enc));\n}\nmodule.exports = Hmac;\n\nHmac.prototype._init = function init(key) {\n // Shorten key, if needed\n if (key.length > this.blockSize)\n key = new this.Hash().update(key).digest();\n assert(key.length <= this.blockSize);\n\n // Add padding to key\n for (var i = key.length; i < this.blockSize; i++)\n key.push(0);\n\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x36;\n this.inner = new this.Hash().update(key);\n\n // 0x36 ^ 0x5c = 0x6a\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x6a;\n this.outer = new this.Hash().update(key);\n};\n\nHmac.prototype.update = function update(msg, enc) {\n this.inner.update(msg, enc);\n return this;\n};\n\nHmac.prototype.digest = function digest(enc) {\n this.outer.update(this.inner.digest());\n return this.outer.digest(enc);\n};\n","var hash = exports;\n\nhash.utils = require('./hash/utils');\nhash.common = require('./hash/common');\nhash.sha = require('./hash/sha');\nhash.ripemd = require('./hash/ripemd');\nhash.hmac = require('./hash/hmac');\n\n// Proxy hash functions to the main object\nhash.sha1 = hash.sha.sha1;\nhash.sha256 = hash.sha.sha256;\nhash.sha224 = hash.sha.sha224;\nhash.sha384 = hash.sha.sha384;\nhash.sha512 = hash.sha.sha512;\nhash.ripemd160 = hash.ripemd.ripemd160;\n","import BN from 'bn.js';\nimport hash from 'hash.js';\n\nvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nfunction createCommonjsModule(fn, basedir, module) {\n\treturn module = {\n\t\tpath: basedir,\n\t\texports: {},\n\t\trequire: function (path, base) {\n\t\t\treturn commonjsRequire(path, (base === undefined || base === null) ? module.path : base);\n\t\t}\n\t}, fn(module, module.exports), module.exports;\n}\n\nfunction getDefaultExportFromNamespaceIfPresent (n) {\n\treturn n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;\n}\n\nfunction getDefaultExportFromNamespaceIfNotNamed (n) {\n\treturn n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;\n}\n\nfunction getAugmentedNamespace(n) {\n\tif (n.__esModule) return n;\n\tvar a = Object.defineProperty({}, '__esModule', {value: true});\n\tObject.keys(n).forEach(function (k) {\n\t\tvar d = Object.getOwnPropertyDescriptor(n, k);\n\t\tObject.defineProperty(a, k, d.get ? d : {\n\t\t\tenumerable: true,\n\t\t\tget: function () {\n\t\t\t\treturn n[k];\n\t\t\t}\n\t\t});\n\t});\n\treturn a;\n}\n\nfunction commonjsRequire () {\n\tthrow new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');\n}\n\nvar minimalisticAssert = assert;\n\nfunction assert(val, msg) {\n if (!val)\n throw new Error(msg || 'Assertion failed');\n}\n\nassert.equal = function assertEqual(l, r, msg) {\n if (l != r)\n throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));\n};\n\nvar utils_1 = createCommonjsModule(function (module, exports) {\n'use strict';\n\nvar utils = exports;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg !== 'string') {\n for (var i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n return res;\n }\n if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (var i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n } else {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n});\n\nvar utils_1$1 = createCommonjsModule(function (module, exports) {\n'use strict';\n\nvar utils = exports;\n\n\n\n\nutils.assert = minimalisticAssert;\nutils.toArray = utils_1.toArray;\nutils.zero2 = utils_1.zero2;\nutils.toHex = utils_1.toHex;\nutils.encode = utils_1.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w, bits) {\n var naf = new Array(Math.max(num.bitLength(), bits) + 1);\n naf.fill(0);\n\n var ws = 1 << (w + 1);\n var k = num.clone();\n\n for (var i = 0; i < naf.length; i++) {\n var z;\n var mod = k.andln(ws - 1);\n if (k.isOdd()) {\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n\n naf[i] = z;\n k.iushrn(1);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n [],\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n var m8;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n});\n\n'use strict';\n\n\n\nvar getNAF = utils_1$1.getNAF;\nvar getJSF = utils_1$1.getJSF;\nvar assert$1 = utils_1$1.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n this._bitLength = this.n ? this.n.bitLength() : 0;\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nvar base = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert$1(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1, this._bitLength);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n var j;\n var nafW;\n for (j = 0; j < naf.length; j += doubles.step) {\n nafW = 0;\n for (var l = j + doubles.step - 1; l >= j; l--)\n nafW = (nafW << 1) + naf[l];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (j = 0; j < repr.length; j++) {\n nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w, this._bitLength);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var l = 0; i >= 0 && naf[i] === 0; i--)\n l++;\n if (i >= 0)\n l++;\n acc = acc.dblp(l);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert$1(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n var i;\n var j;\n var p;\n for (i = 0; i < len; i++) {\n p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);\n naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b], /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3, /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (j = 0; j < len; j++) {\n var z = tmp[j];\n p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils_1$1.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert$1(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert$1(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len));\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils_1$1.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null,\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles,\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res,\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n\nvar inherits_browser = createCommonjsModule(function (module) {\nif (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor;\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n };\n}\n});\n\n'use strict';\n\n\n\n\n\n\nvar assert$2 = utils_1$1.assert;\n\nfunction ShortCurve(conf) {\n base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits_browser(ShortCurve, base);\nvar short_1 = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert$2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16),\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis,\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 },\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n };\n\nfunction Point(curve, x, y, isRed) {\n base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits_browser(Point, base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul),\n },\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1),\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1),\n },\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point)),\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point)),\n },\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate),\n },\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits_browser(JPoint, base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n var i;\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nvar curve_1 = createCommonjsModule(function (module, exports) {\n'use strict';\n\nvar curve = exports;\n\ncurve.base = base;\ncurve.short = short_1;\ncurve.mont = /*RicMoo:ethers:require(./mont)*/(null);\ncurve.edwards = /*RicMoo:ethers:require(./edwards)*/(null);\n});\n\nvar curves_1 = createCommonjsModule(function (module, exports) {\n'use strict';\n\nvar curves = exports;\n\n\n\n\n\nvar assert = utils_1$1.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve_1.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve_1.edwards(options);\n else\n this.curve = new curve_1.mont(options);\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve,\n });\n return curve;\n },\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',\n ],\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',\n ],\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',\n ],\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',\n ],\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650',\n ],\n});\n\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9',\n ],\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658',\n ],\n});\n\nvar pre;\ntry {\n pre = /*RicMoo:ethers:require(./precomputed/secp256k1)*/(null).crash();\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3',\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15',\n },\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre,\n ],\n});\n});\n\n'use strict';\n\n\n\n\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');\n minimalisticAssert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nvar hmacDrbg = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils_1.toArray(entropy, entropyEnc);\n add = utils_1.toArray(add, addEnc);\n\n minimalisticAssert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils_1.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils_1.encode(res, enc);\n};\n\n'use strict';\n\n\n\nvar assert$3 = utils_1$1.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nvar key = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc,\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc,\n });\n};\n\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(compact, enc) {\n // compact is optional argument\n if (typeof compact === 'string') {\n enc = compact;\n compact = null;\n }\n\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert$3(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert$3(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n if(!pub.validate()) {\n assert$3(pub.validate(), 'public point not validated');\n }\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature) {\n return this.ec.verify(msg, signature, this);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n\n'use strict';\n\n\n\n\nvar assert$4 = utils_1$1.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert$4(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nvar signature = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n\n // Indefinite length or overflow\n if (octetLen === 0 || octetLen > 4) {\n return false;\n }\n\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n val >>>= 0;\n }\n\n // Leading zeroes\n if (val <= 0x7f) {\n return false;\n }\n\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils_1$1.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if (len === false) {\n return false;\n }\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n if (rlen === false) {\n return false;\n }\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (slen === false) {\n return false;\n }\n if (data.length !== slen + p.place) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0) {\n if (r[1] & 0x80) {\n r = r.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n if (s[0] === 0) {\n if (s[1] & 0x80) {\n s = s.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils_1$1.encode(res, enc);\n};\n\n'use strict';\n\n\n\n\n\nvar rand = /*RicMoo:ethers:require(brorand)*/(function() { throw new Error('unsupported'); });\nvar assert$5 = utils_1$1.assert;\n\n\n\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert$5(Object.prototype.hasOwnProperty.call(curves_1, options),\n 'Unknown curve ' + options);\n\n options = curves_1[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves_1.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash for function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nvar ec = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new key(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return key.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return key.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new hmacDrbg({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray(),\n });\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n for (;;) {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n }\n};\n\nEC.prototype._truncateToN = function _truncateToN(msg, truncOnly) {\n var delta = msg.byteLength() * 8 - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this._truncateToN(new BN(msg, 16));\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new hmacDrbg({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; ; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature$1, key, enc) {\n msg = this._truncateToN(new BN(msg, 16));\n key = this.keyFromPublic(key, enc);\n signature$1 = new signature(signature$1, 'hex');\n\n // Perform primitive values validation\n var r = signature$1.r;\n var s = signature$1.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n var p;\n\n if (!this.curve._maxwellTrick) {\n p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature$1, j, enc) {\n assert$5((3 & j) === j, 'The recovery param is more than two bits');\n signature$1 = new signature(signature$1, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature$1.r;\n var s = signature$1.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature$1.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature$1, Q, enc) {\n signature$1 = new signature(signature$1, enc);\n if (signature$1.recoveryParam !== null)\n return signature$1.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature$1, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n\nvar elliptic_1 = createCommonjsModule(function (module, exports) {\n'use strict';\n\nvar elliptic = exports;\n\nelliptic.version = /*RicMoo:ethers*/{ version: \"6.5.4\" }.version;\nelliptic.utils = utils_1$1;\nelliptic.rand = /*RicMoo:ethers:require(brorand)*/(function() { throw new Error('unsupported'); });\nelliptic.curve = curve_1;\nelliptic.curves = curves_1;\n\n// Protocols\nelliptic.ec = ec;\nelliptic.eddsa = /*RicMoo:ethers:require(./elliptic/eddsa)*/(null);\n});\n\nvar EC$1 = elliptic_1.ec;\n\nexport { EC$1 as EC };\n//# sourceMappingURL=elliptic.js.map\n","export const version = \"signing-key/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { EC } from \"./elliptic\";\nimport { arrayify, hexDataLength, hexlify, hexZeroPad, splitSignature } from \"@ethersproject/bytes\";\nimport { defineReadOnly } from \"@ethersproject/properties\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nlet _curve = null;\nfunction getCurve() {\n if (!_curve) {\n _curve = new EC(\"secp256k1\");\n }\n return _curve;\n}\nexport class SigningKey {\n constructor(privateKey) {\n defineReadOnly(this, \"curve\", \"secp256k1\");\n defineReadOnly(this, \"privateKey\", hexlify(privateKey));\n if (hexDataLength(this.privateKey) !== 32) {\n logger.throwArgumentError(\"invalid private key\", \"privateKey\", \"[[ REDACTED ]]\");\n }\n const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));\n defineReadOnly(this, \"publicKey\", \"0x\" + keyPair.getPublic(false, \"hex\"));\n defineReadOnly(this, \"compressedPublicKey\", \"0x\" + keyPair.getPublic(true, \"hex\"));\n defineReadOnly(this, \"_isSigningKey\", true);\n }\n _addPoint(other) {\n const p0 = getCurve().keyFromPublic(arrayify(this.publicKey));\n const p1 = getCurve().keyFromPublic(arrayify(other));\n return \"0x\" + p0.pub.add(p1.pub).encodeCompressed(\"hex\");\n }\n signDigest(digest) {\n const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));\n const digestBytes = arrayify(digest);\n if (digestBytes.length !== 32) {\n logger.throwArgumentError(\"bad digest length\", \"digest\", digest);\n }\n const signature = keyPair.sign(digestBytes, { canonical: true });\n return splitSignature({\n recoveryParam: signature.recoveryParam,\n r: hexZeroPad(\"0x\" + signature.r.toString(16), 32),\n s: hexZeroPad(\"0x\" + signature.s.toString(16), 32),\n });\n }\n computeSharedSecret(otherKey) {\n const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));\n const otherKeyPair = getCurve().keyFromPublic(arrayify(computePublicKey(otherKey)));\n return hexZeroPad(\"0x\" + keyPair.derive(otherKeyPair.getPublic()).toString(16), 32);\n }\n static isSigningKey(value) {\n return !!(value && value._isSigningKey);\n }\n}\nexport function recoverPublicKey(digest, signature) {\n const sig = splitSignature(signature);\n const rs = { r: arrayify(sig.r), s: arrayify(sig.s) };\n return \"0x\" + getCurve().recoverPubKey(arrayify(digest), rs, sig.recoveryParam).encode(\"hex\", false);\n}\nexport function computePublicKey(key, compressed) {\n const bytes = arrayify(key);\n if (bytes.length === 32) {\n const signingKey = new SigningKey(bytes);\n if (compressed) {\n return \"0x\" + getCurve().keyFromPrivate(bytes).getPublic(true, \"hex\");\n }\n return signingKey.publicKey;\n }\n else if (bytes.length === 33) {\n if (compressed) {\n return hexlify(bytes);\n }\n return \"0x\" + getCurve().keyFromPublic(bytes).getPublic(false, \"hex\");\n }\n else if (bytes.length === 65) {\n if (!compressed) {\n return hexlify(bytes);\n }\n return \"0x\" + getCurve().keyFromPublic(bytes).getPublic(true, \"hex\");\n }\n return logger.throwArgumentError(\"invalid public or private key\", \"key\", \"[REDACTED]\");\n}\n//# sourceMappingURL=index.js.map","export const version = \"transactions/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { getAddress } from \"@ethersproject/address\";\nimport { BigNumber } from \"@ethersproject/bignumber\";\nimport { arrayify, hexConcat, hexDataLength, hexDataSlice, hexlify, hexZeroPad, isBytesLike, splitSignature, stripZeros, } from \"@ethersproject/bytes\";\nimport { Zero } from \"@ethersproject/constants\";\nimport { keccak256 } from \"@ethersproject/keccak256\";\nimport { checkProperties } from \"@ethersproject/properties\";\nimport * as RLP from \"@ethersproject/rlp\";\nimport { computePublicKey, recoverPublicKey } from \"@ethersproject/signing-key\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nexport var TransactionTypes;\n(function (TransactionTypes) {\n TransactionTypes[TransactionTypes[\"legacy\"] = 0] = \"legacy\";\n TransactionTypes[TransactionTypes[\"eip2930\"] = 1] = \"eip2930\";\n TransactionTypes[TransactionTypes[\"eip1559\"] = 2] = \"eip1559\";\n})(TransactionTypes || (TransactionTypes = {}));\n;\n///////////////////////////////\nfunction handleAddress(value) {\n if (value === \"0x\") {\n return null;\n }\n return getAddress(value);\n}\nfunction handleNumber(value) {\n if (value === \"0x\") {\n return Zero;\n }\n return BigNumber.from(value);\n}\n// Legacy Transaction Fields\nconst transactionFields = [\n { name: \"nonce\", maxLength: 32, numeric: true },\n { name: \"gasPrice\", maxLength: 32, numeric: true },\n { name: \"gasLimit\", maxLength: 32, numeric: true },\n { name: \"to\", length: 20 },\n { name: \"value\", maxLength: 32, numeric: true },\n { name: \"data\" },\n];\nconst allowedTransactionKeys = {\n chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, type: true, value: true\n};\nexport function computeAddress(key) {\n const publicKey = computePublicKey(key);\n return getAddress(hexDataSlice(keccak256(hexDataSlice(publicKey, 1)), 12));\n}\nexport function recoverAddress(digest, signature) {\n return computeAddress(recoverPublicKey(arrayify(digest), signature));\n}\nfunction formatNumber(value, name) {\n const result = stripZeros(BigNumber.from(value).toHexString());\n if (result.length > 32) {\n logger.throwArgumentError(\"invalid length for \" + name, (\"transaction:\" + name), value);\n }\n return result;\n}\nfunction accessSetify(addr, storageKeys) {\n return {\n address: getAddress(addr),\n storageKeys: (storageKeys || []).map((storageKey, index) => {\n if (hexDataLength(storageKey) !== 32) {\n logger.throwArgumentError(\"invalid access list storageKey\", `accessList[${addr}:${index}]`, storageKey);\n }\n return storageKey.toLowerCase();\n })\n };\n}\nexport function accessListify(value) {\n if (Array.isArray(value)) {\n return value.map((set, index) => {\n if (Array.isArray(set)) {\n if (set.length > 2) {\n logger.throwArgumentError(\"access list expected to be [ address, storageKeys[] ]\", `value[${index}]`, set);\n }\n return accessSetify(set[0], set[1]);\n }\n return accessSetify(set.address, set.storageKeys);\n });\n }\n const result = Object.keys(value).map((addr) => {\n const storageKeys = value[addr].reduce((accum, storageKey) => {\n accum[storageKey] = true;\n return accum;\n }, {});\n return accessSetify(addr, Object.keys(storageKeys).sort());\n });\n result.sort((a, b) => (a.address.localeCompare(b.address)));\n return result;\n}\nfunction formatAccessList(value) {\n return accessListify(value).map((set) => [set.address, set.storageKeys]);\n}\nfunction _serializeEip1559(transaction, signature) {\n // If there is an explicit gasPrice, make sure it matches the\n // EIP-1559 fees; otherwise they may not understand what they\n // think they are setting in terms of fee.\n if (transaction.gasPrice != null) {\n const gasPrice = BigNumber.from(transaction.gasPrice);\n const maxFeePerGas = BigNumber.from(transaction.maxFeePerGas || 0);\n if (!gasPrice.eq(maxFeePerGas)) {\n logger.throwArgumentError(\"mismatch EIP-1559 gasPrice != maxFeePerGas\", \"tx\", {\n gasPrice, maxFeePerGas\n });\n }\n }\n const fields = [\n formatNumber(transaction.chainId || 0, \"chainId\"),\n formatNumber(transaction.nonce || 0, \"nonce\"),\n formatNumber(transaction.maxPriorityFeePerGas || 0, \"maxPriorityFeePerGas\"),\n formatNumber(transaction.maxFeePerGas || 0, \"maxFeePerGas\"),\n formatNumber(transaction.gasLimit || 0, \"gasLimit\"),\n ((transaction.to != null) ? getAddress(transaction.to) : \"0x\"),\n formatNumber(transaction.value || 0, \"value\"),\n (transaction.data || \"0x\"),\n (formatAccessList(transaction.accessList || []))\n ];\n if (signature) {\n const sig = splitSignature(signature);\n fields.push(formatNumber(sig.recoveryParam, \"recoveryParam\"));\n fields.push(stripZeros(sig.r));\n fields.push(stripZeros(sig.s));\n }\n return hexConcat([\"0x02\", RLP.encode(fields)]);\n}\nfunction _serializeEip2930(transaction, signature) {\n const fields = [\n formatNumber(transaction.chainId || 0, \"chainId\"),\n formatNumber(transaction.nonce || 0, \"nonce\"),\n formatNumber(transaction.gasPrice || 0, \"gasPrice\"),\n formatNumber(transaction.gasLimit || 0, \"gasLimit\"),\n ((transaction.to != null) ? getAddress(transaction.to) : \"0x\"),\n formatNumber(transaction.value || 0, \"value\"),\n (transaction.data || \"0x\"),\n (formatAccessList(transaction.accessList || []))\n ];\n if (signature) {\n const sig = splitSignature(signature);\n fields.push(formatNumber(sig.recoveryParam, \"recoveryParam\"));\n fields.push(stripZeros(sig.r));\n fields.push(stripZeros(sig.s));\n }\n return hexConcat([\"0x01\", RLP.encode(fields)]);\n}\n// Legacy Transactions and EIP-155\nfunction _serialize(transaction, signature) {\n checkProperties(transaction, allowedTransactionKeys);\n const raw = [];\n transactionFields.forEach(function (fieldInfo) {\n let value = transaction[fieldInfo.name] || ([]);\n const options = {};\n if (fieldInfo.numeric) {\n options.hexPad = \"left\";\n }\n value = arrayify(hexlify(value, options));\n // Fixed-width field\n if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) {\n logger.throwArgumentError(\"invalid length for \" + fieldInfo.name, (\"transaction:\" + fieldInfo.name), value);\n }\n // Variable-width (with a maximum)\n if (fieldInfo.maxLength) {\n value = stripZeros(value);\n if (value.length > fieldInfo.maxLength) {\n logger.throwArgumentError(\"invalid length for \" + fieldInfo.name, (\"transaction:\" + fieldInfo.name), value);\n }\n }\n raw.push(hexlify(value));\n });\n let chainId = 0;\n if (transaction.chainId != null) {\n // A chainId was provided; if non-zero we'll use EIP-155\n chainId = transaction.chainId;\n if (typeof (chainId) !== \"number\") {\n logger.throwArgumentError(\"invalid transaction.chainId\", \"transaction\", transaction);\n }\n }\n else if (signature && !isBytesLike(signature) && signature.v > 28) {\n // No chainId provided, but the signature is signing with EIP-155; derive chainId\n chainId = Math.floor((signature.v - 35) / 2);\n }\n // We have an EIP-155 transaction (chainId was specified and non-zero)\n if (chainId !== 0) {\n raw.push(hexlify(chainId)); // @TODO: hexValue?\n raw.push(\"0x\");\n raw.push(\"0x\");\n }\n // Requesting an unsigned transaction\n if (!signature) {\n return RLP.encode(raw);\n }\n // The splitSignature will ensure the transaction has a recoveryParam in the\n // case that the signTransaction function only adds a v.\n const sig = splitSignature(signature);\n // We pushed a chainId and null r, s on for hashing only; remove those\n let v = 27 + sig.recoveryParam;\n if (chainId !== 0) {\n raw.pop();\n raw.pop();\n raw.pop();\n v += chainId * 2 + 8;\n // If an EIP-155 v (directly or indirectly; maybe _vs) was provided, check it!\n if (sig.v > 28 && sig.v !== v) {\n logger.throwArgumentError(\"transaction.chainId/signature.v mismatch\", \"signature\", signature);\n }\n }\n else if (sig.v !== v) {\n logger.throwArgumentError(\"transaction.chainId/signature.v mismatch\", \"signature\", signature);\n }\n raw.push(hexlify(v));\n raw.push(stripZeros(arrayify(sig.r)));\n raw.push(stripZeros(arrayify(sig.s)));\n return RLP.encode(raw);\n}\nexport function serialize(transaction, signature) {\n // Legacy and EIP-155 Transactions\n if (transaction.type == null || transaction.type === 0) {\n if (transaction.accessList != null) {\n logger.throwArgumentError(\"untyped transactions do not support accessList; include type: 1\", \"transaction\", transaction);\n }\n return _serialize(transaction, signature);\n }\n // Typed Transactions (EIP-2718)\n switch (transaction.type) {\n case 1:\n return _serializeEip2930(transaction, signature);\n case 2:\n return _serializeEip1559(transaction, signature);\n default:\n break;\n }\n return logger.throwError(`unsupported transaction type: ${transaction.type}`, Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"serializeTransaction\",\n transactionType: transaction.type\n });\n}\nfunction _parseEipSignature(tx, fields, serialize) {\n try {\n const recid = handleNumber(fields[0]).toNumber();\n if (recid !== 0 && recid !== 1) {\n throw new Error(\"bad recid\");\n }\n tx.v = recid;\n }\n catch (error) {\n logger.throwArgumentError(\"invalid v for transaction type: 1\", \"v\", fields[0]);\n }\n tx.r = hexZeroPad(fields[1], 32);\n tx.s = hexZeroPad(fields[2], 32);\n try {\n const digest = keccak256(serialize(tx));\n tx.from = recoverAddress(digest, { r: tx.r, s: tx.s, recoveryParam: tx.v });\n }\n catch (error) { }\n}\nfunction _parseEip1559(payload) {\n const transaction = RLP.decode(payload.slice(1));\n if (transaction.length !== 9 && transaction.length !== 12) {\n logger.throwArgumentError(\"invalid component count for transaction type: 2\", \"payload\", hexlify(payload));\n }\n const maxPriorityFeePerGas = handleNumber(transaction[2]);\n const maxFeePerGas = handleNumber(transaction[3]);\n const tx = {\n type: 2,\n chainId: handleNumber(transaction[0]).toNumber(),\n nonce: handleNumber(transaction[1]).toNumber(),\n maxPriorityFeePerGas: maxPriorityFeePerGas,\n maxFeePerGas: maxFeePerGas,\n gasPrice: null,\n gasLimit: handleNumber(transaction[4]),\n to: handleAddress(transaction[5]),\n value: handleNumber(transaction[6]),\n data: transaction[7],\n accessList: accessListify(transaction[8]),\n };\n // Unsigned EIP-1559 Transaction\n if (transaction.length === 9) {\n return tx;\n }\n tx.hash = keccak256(payload);\n _parseEipSignature(tx, transaction.slice(9), _serializeEip1559);\n return tx;\n}\nfunction _parseEip2930(payload) {\n const transaction = RLP.decode(payload.slice(1));\n if (transaction.length !== 8 && transaction.length !== 11) {\n logger.throwArgumentError(\"invalid component count for transaction type: 1\", \"payload\", hexlify(payload));\n }\n const tx = {\n type: 1,\n chainId: handleNumber(transaction[0]).toNumber(),\n nonce: handleNumber(transaction[1]).toNumber(),\n gasPrice: handleNumber(transaction[2]),\n gasLimit: handleNumber(transaction[3]),\n to: handleAddress(transaction[4]),\n value: handleNumber(transaction[5]),\n data: transaction[6],\n accessList: accessListify(transaction[7])\n };\n // Unsigned EIP-2930 Transaction\n if (transaction.length === 8) {\n return tx;\n }\n tx.hash = keccak256(payload);\n _parseEipSignature(tx, transaction.slice(8), _serializeEip2930);\n return tx;\n}\n// Legacy Transactions and EIP-155\nfunction _parse(rawTransaction) {\n const transaction = RLP.decode(rawTransaction);\n if (transaction.length !== 9 && transaction.length !== 6) {\n logger.throwArgumentError(\"invalid raw transaction\", \"rawTransaction\", rawTransaction);\n }\n const tx = {\n nonce: handleNumber(transaction[0]).toNumber(),\n gasPrice: handleNumber(transaction[1]),\n gasLimit: handleNumber(transaction[2]),\n to: handleAddress(transaction[3]),\n value: handleNumber(transaction[4]),\n data: transaction[5],\n chainId: 0\n };\n // Legacy unsigned transaction\n if (transaction.length === 6) {\n return tx;\n }\n try {\n tx.v = BigNumber.from(transaction[6]).toNumber();\n }\n catch (error) {\n // @TODO: What makes snese to do? The v is too big\n return tx;\n }\n tx.r = hexZeroPad(transaction[7], 32);\n tx.s = hexZeroPad(transaction[8], 32);\n if (BigNumber.from(tx.r).isZero() && BigNumber.from(tx.s).isZero()) {\n // EIP-155 unsigned transaction\n tx.chainId = tx.v;\n tx.v = 0;\n }\n else {\n // Signed Transaction\n tx.chainId = Math.floor((tx.v - 35) / 2);\n if (tx.chainId < 0) {\n tx.chainId = 0;\n }\n let recoveryParam = tx.v - 27;\n const raw = transaction.slice(0, 6);\n if (tx.chainId !== 0) {\n raw.push(hexlify(tx.chainId));\n raw.push(\"0x\");\n raw.push(\"0x\");\n recoveryParam -= tx.chainId * 2 + 8;\n }\n const digest = keccak256(RLP.encode(raw));\n try {\n tx.from = recoverAddress(digest, { r: hexlify(tx.r), s: hexlify(tx.s), recoveryParam: recoveryParam });\n }\n catch (error) { }\n tx.hash = keccak256(rawTransaction);\n }\n tx.type = null;\n return tx;\n}\nexport function parse(rawTransaction) {\n const payload = arrayify(rawTransaction);\n // Legacy and EIP-155 Transactions\n if (payload[0] > 0x7f) {\n return _parse(payload);\n }\n // Typed Transaction (EIP-2718)\n switch (payload[0]) {\n case 1:\n return _parseEip2930(payload);\n case 2:\n return _parseEip1559(payload);\n default:\n break;\n }\n return logger.throwError(`unsupported transaction type: ${payload[0]}`, Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"parseTransaction\",\n transactionType: payload[0]\n });\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Package int provides helper functions for integerss.\n */\n// Shim using 16-bit pieces.\nfunction imulShim(a, b) {\n var ah = (a >>> 16) & 0xffff, al = a & 0xffff;\n var bh = (b >>> 16) & 0xffff, bl = b & 0xffff;\n return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);\n}\n/** 32-bit integer multiplication. */\n// Use system Math.imul if available, otherwise use our shim.\nexports.mul = Math.imul || imulShim;\n/** 32-bit integer addition. */\nfunction add(a, b) {\n return (a + b) | 0;\n}\nexports.add = add;\n/** 32-bit integer subtraction. */\nfunction sub(a, b) {\n return (a - b) | 0;\n}\nexports.sub = sub;\n/** 32-bit integer left rotation */\nfunction rotl(x, n) {\n return x << n | x >>> (32 - n);\n}\nexports.rotl = rotl;\n/** 32-bit integer left rotation */\nfunction rotr(x, n) {\n return x << (32 - n) | x >>> n;\n}\nexports.rotr = rotr;\nfunction isIntegerShim(n) {\n return typeof n === \"number\" && isFinite(n) && Math.floor(n) === n;\n}\n/**\n * Returns true if the argument is an integer number.\n *\n * In ES2015, Number.isInteger.\n */\nexports.isInteger = Number.isInteger || isIntegerShim;\n/**\n * Math.pow(2, 53) - 1\n *\n * In ES2015 Number.MAX_SAFE_INTEGER.\n */\nexports.MAX_SAFE_INTEGER = 9007199254740991;\n/**\n * Returns true if the argument is a safe integer number\n * (-MIN_SAFE_INTEGER < number <= MAX_SAFE_INTEGER)\n *\n * In ES2015, Number.isSafeInteger.\n */\nexports.isSafeInteger = function (n) {\n return exports.isInteger(n) && (n >= -exports.MAX_SAFE_INTEGER && n <= exports.MAX_SAFE_INTEGER);\n};\n//# sourceMappingURL=int.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Package binary provides functions for encoding and decoding numbers in byte arrays.\n */\nvar int_1 = require(\"@stablelib/int\");\n// TODO(dchest): add asserts for correct value ranges and array offsets.\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * signed 16-bit integer and returns it.\n */\nfunction readInt16BE(array, offset) {\n if (offset === void 0) { offset = 0; }\n return (((array[offset + 0] << 8) | array[offset + 1]) << 16) >> 16;\n}\nexports.readInt16BE = readInt16BE;\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * unsigned 16-bit integer and returns it.\n */\nfunction readUint16BE(array, offset) {\n if (offset === void 0) { offset = 0; }\n return ((array[offset + 0] << 8) | array[offset + 1]) >>> 0;\n}\nexports.readUint16BE = readUint16BE;\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * signed 16-bit integer and returns it.\n */\nfunction readInt16LE(array, offset) {\n if (offset === void 0) { offset = 0; }\n return (((array[offset + 1] << 8) | array[offset]) << 16) >> 16;\n}\nexports.readInt16LE = readInt16LE;\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * unsigned 16-bit integer and returns it.\n */\nfunction readUint16LE(array, offset) {\n if (offset === void 0) { offset = 0; }\n return ((array[offset + 1] << 8) | array[offset]) >>> 0;\n}\nexports.readUint16LE = readUint16LE;\n/**\n * Writes 2-byte big-endian representation of 16-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeUint16BE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(2); }\n if (offset === void 0) { offset = 0; }\n out[offset + 0] = value >>> 8;\n out[offset + 1] = value >>> 0;\n return out;\n}\nexports.writeUint16BE = writeUint16BE;\nexports.writeInt16BE = writeUint16BE;\n/**\n * Writes 2-byte little-endian representation of 16-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeUint16LE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(2); }\n if (offset === void 0) { offset = 0; }\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n return out;\n}\nexports.writeUint16LE = writeUint16LE;\nexports.writeInt16LE = writeUint16LE;\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * signed 32-bit integer and returns it.\n */\nfunction readInt32BE(array, offset) {\n if (offset === void 0) { offset = 0; }\n return (array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3];\n}\nexports.readInt32BE = readInt32BE;\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * unsigned 32-bit integer and returns it.\n */\nfunction readUint32BE(array, offset) {\n if (offset === void 0) { offset = 0; }\n return ((array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3]) >>> 0;\n}\nexports.readUint32BE = readUint32BE;\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * signed 32-bit integer and returns it.\n */\nfunction readInt32LE(array, offset) {\n if (offset === void 0) { offset = 0; }\n return (array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset];\n}\nexports.readInt32LE = readInt32LE;\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * unsigned 32-bit integer and returns it.\n */\nfunction readUint32LE(array, offset) {\n if (offset === void 0) { offset = 0; }\n return ((array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset]) >>> 0;\n}\nexports.readUint32LE = readUint32LE;\n/**\n * Writes 4-byte big-endian representation of 32-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeUint32BE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(4); }\n if (offset === void 0) { offset = 0; }\n out[offset + 0] = value >>> 24;\n out[offset + 1] = value >>> 16;\n out[offset + 2] = value >>> 8;\n out[offset + 3] = value >>> 0;\n return out;\n}\nexports.writeUint32BE = writeUint32BE;\nexports.writeInt32BE = writeUint32BE;\n/**\n * Writes 4-byte little-endian representation of 32-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeUint32LE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(4); }\n if (offset === void 0) { offset = 0; }\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n out[offset + 2] = value >>> 16;\n out[offset + 3] = value >>> 24;\n return out;\n}\nexports.writeUint32LE = writeUint32LE;\nexports.writeInt32LE = writeUint32LE;\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nfunction readInt64BE(array, offset) {\n if (offset === void 0) { offset = 0; }\n var hi = readInt32BE(array, offset);\n var lo = readInt32BE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo >> 31) * 0x100000000);\n}\nexports.readInt64BE = readInt64BE;\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nfunction readUint64BE(array, offset) {\n if (offset === void 0) { offset = 0; }\n var hi = readUint32BE(array, offset);\n var lo = readUint32BE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\nexports.readUint64BE = readUint64BE;\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nfunction readInt64LE(array, offset) {\n if (offset === void 0) { offset = 0; }\n var lo = readInt32LE(array, offset);\n var hi = readInt32LE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo >> 31) * 0x100000000);\n}\nexports.readInt64LE = readInt64LE;\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nfunction readUint64LE(array, offset) {\n if (offset === void 0) { offset = 0; }\n var lo = readUint32LE(array, offset);\n var hi = readUint32LE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\nexports.readUint64LE = readUint64LE;\n/**\n * Writes 8-byte big-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeUint64BE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(8); }\n if (offset === void 0) { offset = 0; }\n writeUint32BE(value / 0x100000000 >>> 0, out, offset);\n writeUint32BE(value >>> 0, out, offset + 4);\n return out;\n}\nexports.writeUint64BE = writeUint64BE;\nexports.writeInt64BE = writeUint64BE;\n/**\n * Writes 8-byte little-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeUint64LE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(8); }\n if (offset === void 0) { offset = 0; }\n writeUint32LE(value >>> 0, out, offset);\n writeUint32LE(value / 0x100000000 >>> 0, out, offset + 4);\n return out;\n}\nexports.writeUint64LE = writeUint64LE;\nexports.writeInt64LE = writeUint64LE;\n/**\n * Reads bytes from array starting at offset as big-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nfunction readUintBE(bitLength, array, offset) {\n if (offset === void 0) { offset = 0; }\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintBE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintBE: array is too short for the given bitLength\");\n }\n var result = 0;\n var mul = 1;\n for (var i = bitLength / 8 + offset - 1; i >= offset; i--) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\nexports.readUintBE = readUintBE;\n/**\n * Reads bytes from array starting at offset as little-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nfunction readUintLE(bitLength, array, offset) {\n if (offset === void 0) { offset = 0; }\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintLE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintLE: array is too short for the given bitLength\");\n }\n var result = 0;\n var mul = 1;\n for (var i = offset; i < offset + bitLength / 8; i++) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\nexports.readUintLE = readUintLE;\n/**\n * Writes a big-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nfunction writeUintBE(bitLength, value, out, offset) {\n if (out === void 0) { out = new Uint8Array(bitLength / 8); }\n if (offset === void 0) { offset = 0; }\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintBE supports only bitLengths divisible by 8\");\n }\n if (!int_1.isSafeInteger(value)) {\n throw new Error(\"writeUintBE value must be an integer\");\n }\n var div = 1;\n for (var i = bitLength / 8 + offset - 1; i >= offset; i--) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\nexports.writeUintBE = writeUintBE;\n/**\n * Writes a little-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nfunction writeUintLE(bitLength, value, out, offset) {\n if (out === void 0) { out = new Uint8Array(bitLength / 8); }\n if (offset === void 0) { offset = 0; }\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintLE supports only bitLengths divisible by 8\");\n }\n if (!int_1.isSafeInteger(value)) {\n throw new Error(\"writeUintLE value must be an integer\");\n }\n var div = 1;\n for (var i = offset; i < offset + bitLength / 8; i++) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\nexports.writeUintLE = writeUintLE;\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * 32-bit floating-point number and returns it.\n */\nfunction readFloat32BE(array, offset) {\n if (offset === void 0) { offset = 0; }\n var view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset);\n}\nexports.readFloat32BE = readFloat32BE;\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * 32-bit floating-point number and returns it.\n */\nfunction readFloat32LE(array, offset) {\n if (offset === void 0) { offset = 0; }\n var view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset, true);\n}\nexports.readFloat32LE = readFloat32LE;\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nfunction readFloat64BE(array, offset) {\n if (offset === void 0) { offset = 0; }\n var view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset);\n}\nexports.readFloat64BE = readFloat64BE;\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nfunction readFloat64LE(array, offset) {\n if (offset === void 0) { offset = 0; }\n var view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset, true);\n}\nexports.readFloat64LE = readFloat64LE;\n/**\n * Writes 4-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeFloat32BE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(4); }\n if (offset === void 0) { offset = 0; }\n var view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value);\n return out;\n}\nexports.writeFloat32BE = writeFloat32BE;\n/**\n * Writes 4-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeFloat32LE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(4); }\n if (offset === void 0) { offset = 0; }\n var view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value, true);\n return out;\n}\nexports.writeFloat32LE = writeFloat32LE;\n/**\n * Writes 8-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeFloat64BE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(8); }\n if (offset === void 0) { offset = 0; }\n var view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value);\n return out;\n}\nexports.writeFloat64BE = writeFloat64BE;\n/**\n * Writes 8-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nfunction writeFloat64LE(value, out, offset) {\n if (out === void 0) { out = new Uint8Array(8); }\n if (offset === void 0) { offset = 0; }\n var view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value, true);\n return out;\n}\nexports.writeFloat64LE = writeFloat64LE;\n//# sourceMappingURL=binary.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Sets all values in the given array to zero and returns it.\n *\n * The fact that it sets bytes to zero can be relied on.\n *\n * There is no guarantee that this function makes data disappear from memory,\n * as runtime implementation can, for example, have copying garbage collector\n * that will make copies of sensitive data before we wipe it. Or that an\n * operating system will write our data to swap or sleep image. Another thing\n * is that an optimizing compiler can remove calls to this function or make it\n * no-op. There's nothing we can do with it, so we just do our best and hope\n * that everything will be okay and good will triumph over evil.\n */\nfunction wipe(array) {\n // Right now it's similar to array.fill(0). If it turns\n // out that runtimes optimize this call away, maybe\n // we can try something else.\n for (var i = 0; i < array.length; i++) {\n array[i] = 0;\n }\n return array;\n}\nexports.wipe = wipe;\n//# sourceMappingURL=wipe.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Package chacha implements ChaCha stream cipher.\n */\nvar binary_1 = require(\"@stablelib/binary\");\nvar wipe_1 = require(\"@stablelib/wipe\");\n// Number of ChaCha rounds (ChaCha20).\nvar ROUNDS = 20;\n// Applies the ChaCha core function to 16-byte input,\n// 32-byte key key, and puts the result into 64-byte array out.\nfunction core(out, input, key) {\n var j0 = 0x61707865; // \"expa\" -- ChaCha's \"sigma\" constant\n var j1 = 0x3320646E; // \"nd 3\" for 32-byte keys\n var j2 = 0x79622D32; // \"2-by\"\n var j3 = 0x6B206574; // \"te k\"\n var j4 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n var j5 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n var j6 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n var j7 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n var j8 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n var j9 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n var j10 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n var j11 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n var j12 = (input[3] << 24) | (input[2] << 16) | (input[1] << 8) | input[0];\n var j13 = (input[7] << 24) | (input[6] << 16) | (input[5] << 8) | input[4];\n var j14 = (input[11] << 24) | (input[10] << 16) | (input[9] << 8) | input[8];\n var j15 = (input[15] << 24) | (input[14] << 16) | (input[13] << 8) | input[12];\n var x0 = j0;\n var x1 = j1;\n var x2 = j2;\n var x3 = j3;\n var x4 = j4;\n var x5 = j5;\n var x6 = j6;\n var x7 = j7;\n var x8 = j8;\n var x9 = j9;\n var x10 = j10;\n var x11 = j11;\n var x12 = j12;\n var x13 = j13;\n var x14 = j14;\n var x15 = j15;\n for (var i = 0; i < ROUNDS; i += 2) {\n x0 = x0 + x4 | 0;\n x12 ^= x0;\n x12 = x12 >>> (32 - 16) | x12 << 16;\n x8 = x8 + x12 | 0;\n x4 ^= x8;\n x4 = x4 >>> (32 - 12) | x4 << 12;\n x1 = x1 + x5 | 0;\n x13 ^= x1;\n x13 = x13 >>> (32 - 16) | x13 << 16;\n x9 = x9 + x13 | 0;\n x5 ^= x9;\n x5 = x5 >>> (32 - 12) | x5 << 12;\n x2 = x2 + x6 | 0;\n x14 ^= x2;\n x14 = x14 >>> (32 - 16) | x14 << 16;\n x10 = x10 + x14 | 0;\n x6 ^= x10;\n x6 = x6 >>> (32 - 12) | x6 << 12;\n x3 = x3 + x7 | 0;\n x15 ^= x3;\n x15 = x15 >>> (32 - 16) | x15 << 16;\n x11 = x11 + x15 | 0;\n x7 ^= x11;\n x7 = x7 >>> (32 - 12) | x7 << 12;\n x2 = x2 + x6 | 0;\n x14 ^= x2;\n x14 = x14 >>> (32 - 8) | x14 << 8;\n x10 = x10 + x14 | 0;\n x6 ^= x10;\n x6 = x6 >>> (32 - 7) | x6 << 7;\n x3 = x3 + x7 | 0;\n x15 ^= x3;\n x15 = x15 >>> (32 - 8) | x15 << 8;\n x11 = x11 + x15 | 0;\n x7 ^= x11;\n x7 = x7 >>> (32 - 7) | x7 << 7;\n x1 = x1 + x5 | 0;\n x13 ^= x1;\n x13 = x13 >>> (32 - 8) | x13 << 8;\n x9 = x9 + x13 | 0;\n x5 ^= x9;\n x5 = x5 >>> (32 - 7) | x5 << 7;\n x0 = x0 + x4 | 0;\n x12 ^= x0;\n x12 = x12 >>> (32 - 8) | x12 << 8;\n x8 = x8 + x12 | 0;\n x4 ^= x8;\n x4 = x4 >>> (32 - 7) | x4 << 7;\n x0 = x0 + x5 | 0;\n x15 ^= x0;\n x15 = x15 >>> (32 - 16) | x15 << 16;\n x10 = x10 + x15 | 0;\n x5 ^= x10;\n x5 = x5 >>> (32 - 12) | x5 << 12;\n x1 = x1 + x6 | 0;\n x12 ^= x1;\n x12 = x12 >>> (32 - 16) | x12 << 16;\n x11 = x11 + x12 | 0;\n x6 ^= x11;\n x6 = x6 >>> (32 - 12) | x6 << 12;\n x2 = x2 + x7 | 0;\n x13 ^= x2;\n x13 = x13 >>> (32 - 16) | x13 << 16;\n x8 = x8 + x13 | 0;\n x7 ^= x8;\n x7 = x7 >>> (32 - 12) | x7 << 12;\n x3 = x3 + x4 | 0;\n x14 ^= x3;\n x14 = x14 >>> (32 - 16) | x14 << 16;\n x9 = x9 + x14 | 0;\n x4 ^= x9;\n x4 = x4 >>> (32 - 12) | x4 << 12;\n x2 = x2 + x7 | 0;\n x13 ^= x2;\n x13 = x13 >>> (32 - 8) | x13 << 8;\n x8 = x8 + x13 | 0;\n x7 ^= x8;\n x7 = x7 >>> (32 - 7) | x7 << 7;\n x3 = x3 + x4 | 0;\n x14 ^= x3;\n x14 = x14 >>> (32 - 8) | x14 << 8;\n x9 = x9 + x14 | 0;\n x4 ^= x9;\n x4 = x4 >>> (32 - 7) | x4 << 7;\n x1 = x1 + x6 | 0;\n x12 ^= x1;\n x12 = x12 >>> (32 - 8) | x12 << 8;\n x11 = x11 + x12 | 0;\n x6 ^= x11;\n x6 = x6 >>> (32 - 7) | x6 << 7;\n x0 = x0 + x5 | 0;\n x15 ^= x0;\n x15 = x15 >>> (32 - 8) | x15 << 8;\n x10 = x10 + x15 | 0;\n x5 ^= x10;\n x5 = x5 >>> (32 - 7) | x5 << 7;\n }\n binary_1.writeUint32LE(x0 + j0 | 0, out, 0);\n binary_1.writeUint32LE(x1 + j1 | 0, out, 4);\n binary_1.writeUint32LE(x2 + j2 | 0, out, 8);\n binary_1.writeUint32LE(x3 + j3 | 0, out, 12);\n binary_1.writeUint32LE(x4 + j4 | 0, out, 16);\n binary_1.writeUint32LE(x5 + j5 | 0, out, 20);\n binary_1.writeUint32LE(x6 + j6 | 0, out, 24);\n binary_1.writeUint32LE(x7 + j7 | 0, out, 28);\n binary_1.writeUint32LE(x8 + j8 | 0, out, 32);\n binary_1.writeUint32LE(x9 + j9 | 0, out, 36);\n binary_1.writeUint32LE(x10 + j10 | 0, out, 40);\n binary_1.writeUint32LE(x11 + j11 | 0, out, 44);\n binary_1.writeUint32LE(x12 + j12 | 0, out, 48);\n binary_1.writeUint32LE(x13 + j13 | 0, out, 52);\n binary_1.writeUint32LE(x14 + j14 | 0, out, 56);\n binary_1.writeUint32LE(x15 + j15 | 0, out, 60);\n}\n/**\n * Encrypt src with ChaCha20 stream generated for the given 32-byte key and\n * 8-byte (as in original implementation) or 12-byte (as in RFC7539) nonce and\n * write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * If nonce is 12 bytes, users should not encrypt more than 256 GiB with the\n * same key and nonce, otherwise the stream will repeat. The function will\n * throw error if counter overflows to prevent this.\n *\n * If nonce is 8 bytes, the output is practically unlimited (2^70 bytes, which\n * is more than a million petabytes). However, it is not recommended to\n * generate 8-byte nonces randomly, as the chance of collision is high.\n *\n * Never use the same key and nonce to encrypt more than one message.\n *\n * If nonceInplaceCounterLength is not 0, the nonce is assumed to be a 16-byte\n * array with stream counter in first nonceInplaceCounterLength bytes and nonce\n * in the last remaining bytes. The counter will be incremented inplace for\n * each ChaCha block. This is useful if you need to encrypt one stream of data\n * in chunks.\n */\nfunction streamXOR(key, nonce, src, dst, nonceInplaceCounterLength) {\n if (nonceInplaceCounterLength === void 0) { nonceInplaceCounterLength = 0; }\n // We only support 256-bit keys.\n if (key.length !== 32) {\n throw new Error(\"ChaCha: key size must be 32 bytes\");\n }\n if (dst.length < src.length) {\n throw new Error(\"ChaCha: destination is shorter than source\");\n }\n var nc;\n var counterLength;\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 8 && nonce.length !== 12) {\n throw new Error(\"ChaCha nonce must be 8 or 12 bytes\");\n }\n nc = new Uint8Array(16);\n // First counterLength bytes of nc are counter, starting with zero.\n counterLength = nc.length - nonce.length;\n // Last bytes of nc after counterLength are nonce, set them.\n nc.set(nonce, counterLength);\n }\n else {\n if (nonce.length !== 16) {\n throw new Error(\"ChaCha nonce with counter must be 16 bytes\");\n }\n // This will update passed nonce with counter inplace.\n nc = nonce;\n counterLength = nonceInplaceCounterLength;\n }\n // Allocate temporary space for ChaCha block.\n var block = new Uint8Array(64);\n for (var i = 0; i < src.length; i += 64) {\n // Generate a block.\n core(block, nc, key);\n // XOR block bytes with src into dst.\n for (var j = i; j < i + 64 && j < src.length; j++) {\n dst[j] = src[j] ^ block[j - i];\n }\n // Increment counter.\n incrementCounter(nc, 0, counterLength);\n }\n // Cleanup temporary space.\n wipe_1.wipe(block);\n if (nonceInplaceCounterLength === 0) {\n // Cleanup counter.\n wipe_1.wipe(nc);\n }\n return dst;\n}\nexports.streamXOR = streamXOR;\n/**\n * Generate ChaCha20 stream for the given 32-byte key and 8-byte or 12-byte\n * nonce and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * If nonceInplaceCounterLength is not 0, it behaves the same with respect to\n * the nonce as described in the streamXOR documentation.\n *\n * stream is like streamXOR with all-zero src.\n */\nfunction stream(key, nonce, dst, nonceInplaceCounterLength) {\n if (nonceInplaceCounterLength === void 0) { nonceInplaceCounterLength = 0; }\n wipe_1.wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\nexports.stream = stream;\nfunction incrementCounter(counter, pos, len) {\n var carry = 1;\n while (len--) {\n carry = carry + (counter[pos] & 0xff) | 0;\n counter[pos] = carry & 0xff;\n carry >>>= 8;\n pos++;\n }\n if (carry > 0) {\n throw new Error(\"ChaCha: counter overflow\");\n }\n}\n//# sourceMappingURL=chacha.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Package constant-time provides functions for performing algorithmically constant-time operations.\n */\n/**\n * NOTE! Due to the inability to guarantee real constant time evaluation of\n * anything in JavaScript VM, this is module is the best effort.\n */\n/**\n * Returns resultIfOne if subject is 1, or resultIfZero if subject is 0.\n *\n * Supports only 32-bit integers, so resultIfOne or resultIfZero are not\n * integers, they'll be converted to them with bitwise operations.\n */\nfunction select(subject, resultIfOne, resultIfZero) {\n return (~(subject - 1) & resultIfOne) | ((subject - 1) & resultIfZero);\n}\nexports.select = select;\n/**\n * Returns 1 if a <= b, or 0 if not.\n * Arguments must be positive 32-bit integers less than or equal to 2^31 - 1.\n */\nfunction lessOrEqual(a, b) {\n return (((a | 0) - (b | 0) - 1) >>> 31) & 1;\n}\nexports.lessOrEqual = lessOrEqual;\n/**\n * Returns 1 if a and b are of equal length and their contents\n * are equal, or 0 otherwise.\n *\n * Note that unlike in equal(), zero-length inputs are considered\n * the same, so this function will return 1.\n */\nfunction compare(a, b) {\n if (a.length !== b.length) {\n return 0;\n }\n var result = 0;\n for (var i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return (1 & ((result - 1) >>> 8));\n}\nexports.compare = compare;\n/**\n * Returns true if a and b are of equal non-zero length,\n * and their contents are equal, or false otherwise.\n *\n * Note that unlike in compare() zero-length inputs are considered\n * _not_ equal, so this function will return false.\n */\nfunction equal(a, b) {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n return compare(a, b) !== 0;\n}\nexports.equal = equal;\n//# sourceMappingURL=constant-time.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Package poly1305 implements Poly1305 one-time message authentication algorithm.\n */\nvar constant_time_1 = require(\"@stablelib/constant-time\");\nvar wipe_1 = require(\"@stablelib/wipe\");\nexports.DIGEST_LENGTH = 16;\n// Port of Andrew Moon's Poly1305-donna-16. Public domain.\n// https://github.com/floodyberry/poly1305-donna\n/**\n * Poly1305 computes 16-byte authenticator of message using\n * a one-time 32-byte key.\n *\n * Important: key should be used for only one message,\n * it should never repeat.\n */\nvar Poly1305 = /** @class */ (function () {\n function Poly1305(key) {\n this.digestLength = exports.DIGEST_LENGTH;\n this._buffer = new Uint8Array(16);\n this._r = new Uint16Array(10);\n this._h = new Uint16Array(10);\n this._pad = new Uint16Array(8);\n this._leftover = 0;\n this._fin = 0;\n this._finished = false;\n var t0 = key[0] | key[1] << 8;\n this._r[0] = (t0) & 0x1fff;\n var t1 = key[2] | key[3] << 8;\n this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n var t2 = key[4] | key[5] << 8;\n this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n var t3 = key[6] | key[7] << 8;\n this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n var t4 = key[8] | key[9] << 8;\n this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this._r[5] = ((t4 >>> 1)) & 0x1ffe;\n var t5 = key[10] | key[11] << 8;\n this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n var t6 = key[12] | key[13] << 8;\n this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n var t7 = key[14] | key[15] << 8;\n this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this._r[9] = ((t7 >>> 5)) & 0x007f;\n this._pad[0] = key[16] | key[17] << 8;\n this._pad[1] = key[18] | key[19] << 8;\n this._pad[2] = key[20] | key[21] << 8;\n this._pad[3] = key[22] | key[23] << 8;\n this._pad[4] = key[24] | key[25] << 8;\n this._pad[5] = key[26] | key[27] << 8;\n this._pad[6] = key[28] | key[29] << 8;\n this._pad[7] = key[30] | key[31] << 8;\n }\n Poly1305.prototype._blocks = function (m, mpos, bytes) {\n var hibit = this._fin ? 0 : 1 << 11;\n var h0 = this._h[0], h1 = this._h[1], h2 = this._h[2], h3 = this._h[3], h4 = this._h[4], h5 = this._h[5], h6 = this._h[6], h7 = this._h[7], h8 = this._h[8], h9 = this._h[9];\n var r0 = this._r[0], r1 = this._r[1], r2 = this._r[2], r3 = this._r[3], r4 = this._r[4], r5 = this._r[5], r6 = this._r[6], r7 = this._r[7], r8 = this._r[8], r9 = this._r[9];\n while (bytes >= 16) {\n var t0 = m[mpos + 0] | m[mpos + 1] << 8;\n h0 += (t0) & 0x1fff;\n var t1 = m[mpos + 2] | m[mpos + 3] << 8;\n h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n var t2 = m[mpos + 4] | m[mpos + 5] << 8;\n h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n var t3 = m[mpos + 6] | m[mpos + 7] << 8;\n h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n var t4 = m[mpos + 8] | m[mpos + 9] << 8;\n h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n var t5 = m[mpos + 10] | m[mpos + 11] << 8;\n h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n var t6 = m[mpos + 12] | m[mpos + 13] << 8;\n h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n var t7 = m[mpos + 14] | m[mpos + 15] << 8;\n h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n var c = 0;\n var d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13);\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13);\n d0 &= 0x1fff;\n var d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13);\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13);\n d1 &= 0x1fff;\n var d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13);\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13);\n d2 &= 0x1fff;\n var d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13);\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13);\n d3 &= 0x1fff;\n var d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13);\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13);\n d4 &= 0x1fff;\n var d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13);\n d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13);\n d5 &= 0x1fff;\n var d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13);\n d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13);\n d6 &= 0x1fff;\n var d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13);\n d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13);\n d7 &= 0x1fff;\n var d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13);\n d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13);\n d8 &= 0x1fff;\n var d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13);\n d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13);\n d9 &= 0x1fff;\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n mpos += 16;\n bytes -= 16;\n }\n this._h[0] = h0;\n this._h[1] = h1;\n this._h[2] = h2;\n this._h[3] = h3;\n this._h[4] = h4;\n this._h[5] = h5;\n this._h[6] = h6;\n this._h[7] = h7;\n this._h[8] = h8;\n this._h[9] = h9;\n };\n Poly1305.prototype.finish = function (mac, macpos) {\n if (macpos === void 0) { macpos = 0; }\n var g = new Uint16Array(10);\n var c;\n var mask;\n var f;\n var i;\n if (this._leftover) {\n i = this._leftover;\n this._buffer[i++] = 1;\n for (; i < 16; i++) {\n this._buffer[i] = 0;\n }\n this._fin = 1;\n this._blocks(this._buffer, 0, 16);\n }\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this._h[i] += c;\n c = this._h[i] >>> 13;\n this._h[i] &= 0x1fff;\n }\n this._h[0] += (c * 5);\n c = this._h[0] >>> 13;\n this._h[0] &= 0x1fff;\n this._h[1] += c;\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n this._h[2] += c;\n g[0] = this._h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this._h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) {\n g[i] &= mask;\n }\n mask = ~mask;\n for (i = 0; i < 10; i++) {\n this._h[i] = (this._h[i] & mask) | g[i];\n }\n this._h[0] = ((this._h[0]) | (this._h[1] << 13)) & 0xffff;\n this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;\n this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;\n this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;\n this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;\n this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;\n this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;\n this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;\n f = this._h[0] + this._pad[0];\n this._h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this._h[i] + this._pad[i]) | 0) + (f >>> 16)) | 0;\n this._h[i] = f & 0xffff;\n }\n mac[macpos + 0] = this._h[0] >>> 0;\n mac[macpos + 1] = this._h[0] >>> 8;\n mac[macpos + 2] = this._h[1] >>> 0;\n mac[macpos + 3] = this._h[1] >>> 8;\n mac[macpos + 4] = this._h[2] >>> 0;\n mac[macpos + 5] = this._h[2] >>> 8;\n mac[macpos + 6] = this._h[3] >>> 0;\n mac[macpos + 7] = this._h[3] >>> 8;\n mac[macpos + 8] = this._h[4] >>> 0;\n mac[macpos + 9] = this._h[4] >>> 8;\n mac[macpos + 10] = this._h[5] >>> 0;\n mac[macpos + 11] = this._h[5] >>> 8;\n mac[macpos + 12] = this._h[6] >>> 0;\n mac[macpos + 13] = this._h[6] >>> 8;\n mac[macpos + 14] = this._h[7] >>> 0;\n mac[macpos + 15] = this._h[7] >>> 8;\n this._finished = true;\n return this;\n };\n Poly1305.prototype.update = function (m) {\n var mpos = 0;\n var bytes = m.length;\n var want;\n if (this._leftover) {\n want = (16 - this._leftover);\n if (want > bytes) {\n want = bytes;\n }\n for (var i = 0; i < want; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n bytes -= want;\n mpos += want;\n this._leftover += want;\n if (this._leftover < 16) {\n return this;\n }\n this._blocks(this._buffer, 0, 16);\n this._leftover = 0;\n }\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this._blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n if (bytes) {\n for (var i = 0; i < bytes; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n this._leftover += bytes;\n }\n return this;\n };\n Poly1305.prototype.digest = function () {\n // TODO(dchest): it behaves differently than other hashes/HMAC,\n // because it throws when finished — others just return saved result.\n if (this._finished) {\n throw new Error(\"Poly1305 was finished\");\n }\n var mac = new Uint8Array(16);\n this.finish(mac);\n return mac;\n };\n Poly1305.prototype.clean = function () {\n wipe_1.wipe(this._buffer);\n wipe_1.wipe(this._r);\n wipe_1.wipe(this._h);\n wipe_1.wipe(this._pad);\n this._leftover = 0;\n this._fin = 0;\n this._finished = true; // mark as finished even if not\n return this;\n };\n return Poly1305;\n}());\nexports.Poly1305 = Poly1305;\n/**\n * Returns 16-byte authenticator of data using a one-time 32-byte key.\n *\n * Important: key should be used for only one message, it should never repeat.\n */\nfunction oneTimeAuth(key, data) {\n var h = new Poly1305(key);\n h.update(data);\n var digest = h.digest();\n h.clean();\n return digest;\n}\nexports.oneTimeAuth = oneTimeAuth;\n/**\n * Returns true if two authenticators are 16-byte long and equal.\n * Uses contant-time comparison to avoid leaking timing information.\n */\nfunction equal(a, b) {\n if (a.length !== exports.DIGEST_LENGTH || b.length !== exports.DIGEST_LENGTH) {\n return false;\n }\n return constant_time_1.equal(a, b);\n}\nexports.equal = equal;\n//# sourceMappingURL=poly1305.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar chacha_1 = require(\"@stablelib/chacha\");\nvar poly1305_1 = require(\"@stablelib/poly1305\");\nvar wipe_1 = require(\"@stablelib/wipe\");\nvar binary_1 = require(\"@stablelib/binary\");\nvar constant_time_1 = require(\"@stablelib/constant-time\");\nexports.KEY_LENGTH = 32;\nexports.NONCE_LENGTH = 12;\nexports.TAG_LENGTH = 16;\nvar ZEROS = new Uint8Array(16);\n/**\n * ChaCha20-Poly1305 Authenticated Encryption with Associated Data.\n *\n * Defined in RFC7539.\n */\nvar ChaCha20Poly1305 = /** @class */ (function () {\n /**\n * Creates a new instance with the given 32-byte key.\n */\n function ChaCha20Poly1305(key) {\n this.nonceLength = exports.NONCE_LENGTH;\n this.tagLength = exports.TAG_LENGTH;\n if (key.length !== exports.KEY_LENGTH) {\n throw new Error(\"ChaCha20Poly1305 needs 32-byte key\");\n }\n // Copy key.\n this._key = new Uint8Array(key);\n }\n /**\n * Encrypts and authenticates plaintext, authenticates associated data,\n * and returns sealed ciphertext, which includes authentication tag.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If dst is given (it must be the size of plaintext + the size of tag\n * length) the result will be put into it. Dst and plaintext must not\n * overlap.\n */\n ChaCha20Poly1305.prototype.seal = function (nonce, plaintext, associatedData, dst) {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n // Allocate space for counter, and set nonce as last bytes of it.\n var counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n // Generate authentication key by taking first 32-bytes of stream.\n // We pass full counter, which has 12-byte nonce and 4-byte block counter,\n // and it will get incremented after generating the block, which is\n // exactly what we need: we only use the first 32 bytes of 64-byte\n // ChaCha block and discard the next 32 bytes.\n var authKey = new Uint8Array(32);\n chacha_1.stream(this._key, counter, authKey, 4);\n // Allocate space for sealed ciphertext.\n var resultLength = plaintext.length + this.tagLength;\n var result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n }\n else {\n result = new Uint8Array(resultLength);\n }\n // Encrypt plaintext.\n chacha_1.streamXOR(this._key, counter, plaintext, result, 4);\n // Authenticate.\n // XXX: can \"simplify\" here: pass full result (which is already padded\n // due to zeroes prepared for tag), and ciphertext length instead of\n // subarray of result.\n this._authenticate(result.subarray(result.length - this.tagLength, result.length), authKey, result.subarray(0, result.length - this.tagLength), associatedData);\n // Cleanup.\n wipe_1.wipe(counter);\n return result;\n };\n /**\n * Authenticates sealed ciphertext (which includes authentication tag) and\n * associated data, decrypts ciphertext and returns decrypted plaintext.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If authentication fails, it returns null.\n *\n * If dst is given (it must be of ciphertext length minus tag length),\n * the result will be put into it. Dst and plaintext must not overlap.\n */\n ChaCha20Poly1305.prototype.open = function (nonce, sealed, associatedData, dst) {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n // Sealed ciphertext should at least contain tag.\n if (sealed.length < this.tagLength) {\n // TODO(dchest): should we throw here instead?\n return null;\n }\n // Allocate space for counter, and set nonce as last bytes of it.\n var counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n // Generate authentication key by taking first 32-bytes of stream.\n var authKey = new Uint8Array(32);\n chacha_1.stream(this._key, counter, authKey, 4);\n // Authenticate.\n // XXX: can simplify and avoid allocation: since authenticate()\n // already allocates tag (from Poly1305.digest(), it can return)\n // it instead of copying to calculatedTag. But then in seal()\n // we'll need to copy it.\n var calculatedTag = new Uint8Array(this.tagLength);\n this._authenticate(calculatedTag, authKey, sealed.subarray(0, sealed.length - this.tagLength), associatedData);\n // Constant-time compare tags and return null if they differ.\n if (!constant_time_1.equal(calculatedTag, sealed.subarray(sealed.length - this.tagLength, sealed.length))) {\n return null;\n }\n // Allocate space for decrypted plaintext.\n var resultLength = sealed.length - this.tagLength;\n var result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n }\n else {\n result = new Uint8Array(resultLength);\n }\n // Decrypt.\n chacha_1.streamXOR(this._key, counter, sealed.subarray(0, sealed.length - this.tagLength), result, 4);\n // Cleanup.\n wipe_1.wipe(counter);\n return result;\n };\n ChaCha20Poly1305.prototype.clean = function () {\n wipe_1.wipe(this._key);\n return this;\n };\n ChaCha20Poly1305.prototype._authenticate = function (tagOut, authKey, ciphertext, associatedData) {\n // Initialize Poly1305 with authKey.\n var h = new poly1305_1.Poly1305(authKey);\n // Authenticate padded associated data.\n if (associatedData) {\n h.update(associatedData);\n if (associatedData.length % 16 > 0) {\n h.update(ZEROS.subarray(associatedData.length % 16));\n }\n }\n // Authenticate padded ciphertext.\n h.update(ciphertext);\n if (ciphertext.length % 16 > 0) {\n h.update(ZEROS.subarray(ciphertext.length % 16));\n }\n // Authenticate length of associated data.\n // XXX: can avoid allocation here?\n var length = new Uint8Array(8);\n if (associatedData) {\n binary_1.writeUint64LE(associatedData.length, length);\n }\n h.update(length);\n // Authenticate length of ciphertext.\n binary_1.writeUint64LE(ciphertext.length, length);\n h.update(length);\n // Get tag and copy it into tagOut.\n var tag = h.digest();\n for (var i = 0; i < tag.length; i++) {\n tagOut[i] = tag[i];\n }\n // Cleanup.\n h.clean();\n wipe_1.wipe(tag);\n wipe_1.wipe(length);\n };\n return ChaCha20Poly1305;\n}());\nexports.ChaCha20Poly1305 = ChaCha20Poly1305;\n//# sourceMappingURL=chacha20poly1305.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isSerializableHash(h) {\n return (typeof h.saveState !== \"undefined\" &&\n typeof h.restoreState !== \"undefined\" &&\n typeof h.cleanSavedState !== \"undefined\");\n}\nexports.isSerializableHash = isSerializableHash;\n// TODO(dchest): figure out the standardized interface for XOF such as\n// SHAKE and BLAKE2X.\n//# sourceMappingURL=hash.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Package hmac implements HMAC algorithm.\n */\nvar hash_1 = require(\"@stablelib/hash\");\nvar constant_time_1 = require(\"@stablelib/constant-time\");\nvar wipe_1 = require(\"@stablelib/wipe\");\n/**\n * HMAC implements hash-based message authentication algorithm.\n */\nvar HMAC = /** @class */ (function () {\n /**\n * Constructs a new HMAC with the given Hash and secret key.\n */\n function HMAC(hash, key) {\n this._finished = false; // true if HMAC was finalized\n // Initialize inner and outer hashes.\n this._inner = new hash();\n this._outer = new hash();\n // Set block and digest sizes for this HMAC\n // instance to values from the hash.\n this.blockSize = this._outer.blockSize;\n this.digestLength = this._outer.digestLength;\n // Pad temporary stores a key (or its hash) padded with zeroes.\n var pad = new Uint8Array(this.blockSize);\n if (key.length > this.blockSize) {\n // If key is bigger than hash block size, it must be\n // hashed and this hash is used as a key instead.\n this._inner.update(key).finish(pad).clean();\n }\n else {\n // Otherwise, copy the key into pad.\n pad.set(key);\n }\n // Now two different keys are derived from padded key\n // by xoring a different byte value to each.\n // To make inner hash key, xor byte 0x36 into pad.\n for (var i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36;\n }\n // Update inner hash with the result.\n this._inner.update(pad);\n // To make outer hash key, xor byte 0x5c into pad.\n // But since we already xored 0x36 there, we must\n // first undo this by xoring it again.\n for (var i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36 ^ 0x5c;\n }\n // Update outer hash with the result.\n this._outer.update(pad);\n // Save states of both hashes, so that we can quickly restore\n // them later in reset() without the need to remember the actual\n // key and perform this initialization again.\n if (hash_1.isSerializableHash(this._inner) && hash_1.isSerializableHash(this._outer)) {\n this._innerKeyedState = this._inner.saveState();\n this._outerKeyedState = this._outer.saveState();\n }\n // Clean pad.\n wipe_1.wipe(pad);\n }\n /**\n * Returns HMAC state to the state initialized with key\n * to make it possible to run HMAC over the other data with the same\n * key without creating a new instance.\n */\n HMAC.prototype.reset = function () {\n if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't reset() because hash doesn't implement restoreState()\");\n }\n // Restore keyed states of inner and outer hashes.\n this._inner.restoreState(this._innerKeyedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n };\n /**\n * Cleans HMAC state.\n */\n HMAC.prototype.clean = function () {\n if (hash_1.isSerializableHash(this._inner)) {\n this._inner.cleanSavedState(this._innerKeyedState);\n }\n if (hash_1.isSerializableHash(this._outer)) {\n this._outer.cleanSavedState(this._outerKeyedState);\n }\n this._inner.clean();\n this._outer.clean();\n };\n /**\n * Updates state with provided data.\n */\n HMAC.prototype.update = function (data) {\n this._inner.update(data);\n return this;\n };\n /**\n * Finalizes HMAC and puts the result in out.\n */\n HMAC.prototype.finish = function (out) {\n if (this._finished) {\n // If HMAC was finalized, outer hash is also finalized,\n // so it produces the same digest it produced when it\n // was finalized.\n this._outer.finish(out);\n return this;\n }\n // Finalize inner hash and store the result temporarily.\n this._inner.finish(out);\n // Update outer hash with digest of inner hash and and finalize it.\n this._outer.update(out.subarray(0, this.digestLength)).finish(out);\n this._finished = true;\n return this;\n };\n /**\n * Returns the computed message authentication code.\n */\n HMAC.prototype.digest = function () {\n var out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n };\n /**\n * Saves HMAC state.\n * This function is needed for PBKDF2 optimization.\n */\n HMAC.prototype.saveState = function () {\n if (!hash_1.isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't saveState() because hash doesn't implement it\");\n }\n return this._inner.saveState();\n };\n HMAC.prototype.restoreState = function (savedState) {\n if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't restoreState() because hash doesn't implement it\");\n }\n this._inner.restoreState(savedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n };\n HMAC.prototype.cleanSavedState = function (savedState) {\n if (!hash_1.isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't cleanSavedState() because hash doesn't implement it\");\n }\n this._inner.cleanSavedState(savedState);\n };\n return HMAC;\n}());\nexports.HMAC = HMAC;\n/**\n * Returns HMAC using the given hash constructor for the key over data.\n */\nfunction hmac(hash, key, data) {\n var h = new HMAC(hash, key);\n h.update(data);\n var digest = h.digest();\n h.clean();\n return digest;\n}\nexports.hmac = hmac;\n/**\n * Returns true if two HMAC digests are equal.\n * Uses constant-time comparison to avoid leaking timing information.\n *\n * Example:\n *\n * const receivedDigest = ...\n * const realDigest = hmac(SHA256, key, data);\n * if (!equal(receivedDigest, realDigest)) {\n * throw new Error(\"Authentication error\");\n * }\n */\nexports.equal = constant_time_1.equal;\n//# sourceMappingURL=hmac.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar hmac_1 = require(\"@stablelib/hmac\");\nvar wipe_1 = require(\"@stablelib/wipe\");\n/**\n * HMAC-based Extract-and-Expand Key Derivation Function.\n *\n * Implements HKDF from RFC5869.\n *\n * Expands the given master key with salt and info into\n * a limited stream of key material.\n */\nvar HKDF = /** @class */ (function () {\n /**\n * Create a new HKDF instance for the given hash function\n * with the master key, optional salt, and info.\n *\n * - Master key is a high-entropy secret key (not a password).\n * - Salt is a non-secret random value.\n * - Info is application- and/or context-specific information.\n */\n function HKDF(hash, key, salt, info) {\n if (salt === void 0) { salt = new Uint8Array(0); }\n this._counter = new Uint8Array(1); // starts with zero\n this._hash = hash;\n this._info = info;\n // HKDF-Extract uses salt as HMAC key, and key as data.\n var okm = hmac_1.hmac(this._hash, salt, key);\n // Initialize HMAC for expanding with extracted key.\n this._hmac = new hmac_1.HMAC(hash, okm);\n // Allocate buffer.\n this._buffer = new Uint8Array(this._hmac.digestLength);\n this._bufpos = this._buffer.length;\n }\n // Fill buffer with new block of HKDF-Extract output.\n HKDF.prototype._fillBuffer = function () {\n // Increment counter.\n this._counter[0]++;\n var ctr = this._counter[0];\n // Check if counter overflowed.\n if (ctr === 0) {\n throw new Error(\"hkdf: cannot expand more\");\n }\n // Prepare HMAC instance for new data with old key.\n this._hmac.reset();\n // Hash in previous output if it was generated\n // (i.e. counter is greater than 1).\n if (ctr > 1) {\n this._hmac.update(this._buffer);\n }\n // Hash in info if it exists.\n if (this._info) {\n this._hmac.update(this._info);\n }\n // Hash in the counter.\n this._hmac.update(this._counter);\n // Output result to buffer and clean HMAC instance.\n this._hmac.finish(this._buffer);\n // Reset buffer position.\n this._bufpos = 0;\n };\n /**\n * Expand returns next key material of the given length.\n *\n * It throws if expansion limit is reached (which is\n * 254 digests of the underlying HMAC function).\n */\n HKDF.prototype.expand = function (length) {\n var out = new Uint8Array(length);\n for (var i = 0; i < out.length; i++) {\n if (this._bufpos === this._buffer.length) {\n this._fillBuffer();\n }\n out[i] = this._buffer[this._bufpos++];\n }\n return out;\n };\n HKDF.prototype.clean = function () {\n this._hmac.clean();\n wipe_1.wipe(this._buffer);\n wipe_1.wipe(this._counter);\n this._bufpos = 0;\n };\n return HKDF;\n}());\nexports.HKDF = HKDF;\n// TODO(dchest): maybe implement deriveKey?\n//# sourceMappingURL=hkdf.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BrowserRandomSource = void 0;\nconst QUOTA = 65536;\nclass BrowserRandomSource {\n constructor() {\n this.isAvailable = false;\n this.isInstantiated = false;\n const browserCrypto = typeof self !== 'undefined'\n ? (self.crypto || self.msCrypto) // IE11 has msCrypto\n : null;\n if (browserCrypto && browserCrypto.getRandomValues !== undefined) {\n this._crypto = browserCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n randomBytes(length) {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Browser random byte generator is not available.\");\n }\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i += QUOTA) {\n this._crypto.getRandomValues(out.subarray(i, i + Math.min(out.length - i, QUOTA)));\n }\n return out;\n }\n}\nexports.BrowserRandomSource = BrowserRandomSource;\n//# sourceMappingURL=browser.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NodeRandomSource = void 0;\nconst wipe_1 = require(\"@stablelib/wipe\");\nclass NodeRandomSource {\n constructor() {\n this.isAvailable = false;\n this.isInstantiated = false;\n if (typeof require !== \"undefined\") {\n const nodeCrypto = require(\"crypto\");\n if (nodeCrypto && nodeCrypto.randomBytes) {\n this._crypto = nodeCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n }\n randomBytes(length) {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Node.js random byte generator is not available.\");\n }\n // Get random bytes (result is Buffer).\n let buffer = this._crypto.randomBytes(length);\n // Make sure we got the length that we requested.\n if (buffer.length !== length) {\n throw new Error(\"NodeRandomSource: got fewer bytes than requested\");\n }\n // Allocate output array.\n const out = new Uint8Array(length);\n // Copy bytes from buffer to output.\n for (let i = 0; i < out.length; i++) {\n out[i] = buffer[i];\n }\n // Cleanup.\n (0, wipe_1.wipe)(buffer);\n return out;\n }\n}\nexports.NodeRandomSource = NodeRandomSource;\n//# sourceMappingURL=node.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SystemRandomSource = void 0;\nconst browser_1 = require(\"./browser\");\nconst node_1 = require(\"./node\");\nclass SystemRandomSource {\n constructor() {\n this.isAvailable = false;\n this.name = \"\";\n // Try browser.\n this._source = new browser_1.BrowserRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Browser\";\n return;\n }\n // If no browser source, try Node.\n this._source = new node_1.NodeRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Node\";\n return;\n }\n // No sources, we're out of options.\n }\n randomBytes(length) {\n if (!this.isAvailable) {\n throw new Error(\"System random byte generator is not available.\");\n }\n return this._source.randomBytes(length);\n }\n}\nexports.SystemRandomSource = SystemRandomSource;\n//# sourceMappingURL=system.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.randomStringForEntropy = exports.randomString = exports.randomUint32 = exports.randomBytes = exports.defaultRandomSource = void 0;\nconst system_1 = require(\"./source/system\");\nconst binary_1 = require(\"@stablelib/binary\");\nconst wipe_1 = require(\"@stablelib/wipe\");\nexports.defaultRandomSource = new system_1.SystemRandomSource();\nfunction randomBytes(length, prng = exports.defaultRandomSource) {\n return prng.randomBytes(length);\n}\nexports.randomBytes = randomBytes;\n/**\n * Returns a uniformly random unsigned 32-bit integer.\n */\nfunction randomUint32(prng = exports.defaultRandomSource) {\n // Generate 4-byte random buffer.\n const buf = randomBytes(4, prng);\n // Convert bytes from buffer into a 32-bit integer.\n // It's not important which byte order to use, since\n // the result is random.\n const result = (0, binary_1.readUint32LE)(buf);\n // Clean the buffer.\n (0, wipe_1.wipe)(buf);\n return result;\n}\nexports.randomUint32 = randomUint32;\n/** 62 alphanumeric characters for default charset of randomString() */\nconst ALPHANUMERIC = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n/**\n * Returns a uniform random string of the given length\n * with characters from the given charset.\n *\n * Charset must not have more than 256 characters.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nfunction randomString(length, charset = ALPHANUMERIC, prng = exports.defaultRandomSource) {\n if (charset.length < 2) {\n throw new Error(\"randomString charset is too short\");\n }\n if (charset.length > 256) {\n throw new Error(\"randomString charset is too long\");\n }\n let out = '';\n const charsLen = charset.length;\n const maxByte = 256 - (256 % charsLen);\n while (length > 0) {\n const buf = randomBytes(Math.ceil(length * 256 / maxByte), prng);\n for (let i = 0; i < buf.length && length > 0; i++) {\n const randomByte = buf[i];\n if (randomByte < maxByte) {\n out += charset.charAt(randomByte % charsLen);\n length--;\n }\n }\n (0, wipe_1.wipe)(buf);\n }\n return out;\n}\nexports.randomString = randomString;\n/**\n * Returns uniform random string containing at least the given\n * number of bits of entropy.\n *\n * For example, randomStringForEntropy(128) will return a 22-character\n * alphanumeric string, while randomStringForEntropy(128, \"0123456789\")\n * will return a 39-character numeric string, both will contain at\n * least 128 bits of entropy.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nfunction randomStringForEntropy(bits, charset = ALPHANUMERIC, prng = exports.defaultRandomSource) {\n const length = Math.ceil(bits / (Math.log(charset.length) / Math.LN2));\n return randomString(length, charset, prng);\n}\nexports.randomStringForEntropy = randomStringForEntropy;\n//# sourceMappingURL=random.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar binary_1 = require(\"@stablelib/binary\");\nvar wipe_1 = require(\"@stablelib/wipe\");\nexports.DIGEST_LENGTH = 32;\nexports.BLOCK_SIZE = 64;\n/**\n * SHA2-256 cryptographic hash algorithm.\n */\nvar SHA256 = /** @class */ (function () {\n function SHA256() {\n /** Length of hash output */\n this.digestLength = exports.DIGEST_LENGTH;\n /** Block size */\n this.blockSize = exports.BLOCK_SIZE;\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n this._state = new Int32Array(8); // hash state\n this._temp = new Int32Array(64); // temporary state\n this._buffer = new Uint8Array(128); // buffer for data to hash\n this._bufferLength = 0; // number of bytes in buffer\n this._bytesHashed = 0; // number of total bytes hashed\n this._finished = false; // indicates whether the hash was finalized\n this.reset();\n }\n SHA256.prototype._initState = function () {\n this._state[0] = 0x6a09e667;\n this._state[1] = 0xbb67ae85;\n this._state[2] = 0x3c6ef372;\n this._state[3] = 0xa54ff53a;\n this._state[4] = 0x510e527f;\n this._state[5] = 0x9b05688c;\n this._state[6] = 0x1f83d9ab;\n this._state[7] = 0x5be0cd19;\n };\n /**\n * Resets hash state making it possible\n * to re-use this instance to hash other data.\n */\n SHA256.prototype.reset = function () {\n this._initState();\n this._bufferLength = 0;\n this._bytesHashed = 0;\n this._finished = false;\n return this;\n };\n /**\n * Cleans internal buffers and resets hash state.\n */\n SHA256.prototype.clean = function () {\n wipe_1.wipe(this._buffer);\n wipe_1.wipe(this._temp);\n this.reset();\n };\n /**\n * Updates hash state with the given data.\n *\n * Throws error when trying to update already finalized hash:\n * instance must be reset to update it again.\n */\n SHA256.prototype.update = function (data, dataLength) {\n if (dataLength === void 0) { dataLength = data.length; }\n if (this._finished) {\n throw new Error(\"SHA256: can't update because hash was finished.\");\n }\n var dataPos = 0;\n this._bytesHashed += dataLength;\n if (this._bufferLength > 0) {\n while (this._bufferLength < this.blockSize && dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this._bufferLength === this.blockSize) {\n hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize);\n this._bufferLength = 0;\n }\n }\n if (dataLength >= this.blockSize) {\n dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength);\n dataLength %= this.blockSize;\n }\n while (dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n };\n /**\n * Finalizes hash state and puts hash into out.\n * If hash was already finalized, puts the same value.\n */\n SHA256.prototype.finish = function (out) {\n if (!this._finished) {\n var bytesHashed = this._bytesHashed;\n var left = this._bufferLength;\n var bitLenHi = (bytesHashed / 0x20000000) | 0;\n var bitLenLo = bytesHashed << 3;\n var padLength = (bytesHashed % 64 < 56) ? 64 : 128;\n this._buffer[left] = 0x80;\n for (var i = left + 1; i < padLength - 8; i++) {\n this._buffer[i] = 0;\n }\n binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8);\n binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4);\n hashBlocks(this._temp, this._state, this._buffer, 0, padLength);\n this._finished = true;\n }\n for (var i = 0; i < this.digestLength / 4; i++) {\n binary_1.writeUint32BE(this._state[i], out, i * 4);\n }\n return this;\n };\n /**\n * Returns the final hash digest.\n */\n SHA256.prototype.digest = function () {\n var out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n };\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Returns hash state to be used with restoreState().\n * Only chain value is saved, not buffers or other\n * state variables.\n */\n SHA256.prototype.saveState = function () {\n if (this._finished) {\n throw new Error(\"SHA256: cannot save finished state\");\n }\n return {\n state: new Int32Array(this._state),\n buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined,\n bufferLength: this._bufferLength,\n bytesHashed: this._bytesHashed\n };\n };\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Restores state saved by saveState() and sets bytesHashed\n * to the given value.\n */\n SHA256.prototype.restoreState = function (savedState) {\n this._state.set(savedState.state);\n this._bufferLength = savedState.bufferLength;\n if (savedState.buffer) {\n this._buffer.set(savedState.buffer);\n }\n this._bytesHashed = savedState.bytesHashed;\n this._finished = false;\n return this;\n };\n /**\n * Cleans state returned by saveState().\n */\n SHA256.prototype.cleanSavedState = function (savedState) {\n wipe_1.wipe(savedState.state);\n if (savedState.buffer) {\n wipe_1.wipe(savedState.buffer);\n }\n savedState.bufferLength = 0;\n savedState.bytesHashed = 0;\n };\n return SHA256;\n}());\nexports.SHA256 = SHA256;\n// Constants\nvar K = new Int32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,\n 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,\n 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,\n 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,\n 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,\n 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\nfunction hashBlocks(w, v, p, pos, len) {\n while (len >= 64) {\n var a = v[0];\n var b = v[1];\n var c = v[2];\n var d = v[3];\n var e = v[4];\n var f = v[5];\n var g = v[6];\n var h = v[7];\n for (var i = 0; i < 16; i++) {\n var j = pos + i * 4;\n w[i] = binary_1.readUint32BE(p, j);\n }\n for (var i = 16; i < 64; i++) {\n var u = w[i - 2];\n var t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10);\n u = w[i - 15];\n var t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3);\n w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);\n }\n for (var i = 0; i < 64; i++) {\n var t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^\n (e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) +\n ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;\n var t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^\n (a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n v[0] += a;\n v[1] += b;\n v[2] += c;\n v[3] += d;\n v[4] += e;\n v[5] += f;\n v[6] += g;\n v[7] += h;\n pos += 64;\n len -= 64;\n }\n return pos;\n}\nfunction hash(data) {\n var h = new SHA256();\n h.update(data);\n var digest = h.digest();\n h.clean();\n return digest;\n}\nexports.hash = hash;\n//# sourceMappingURL=sha256.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.sharedKey = exports.generateKeyPair = exports.generateKeyPairFromSeed = exports.scalarMultBase = exports.scalarMult = exports.SHARED_KEY_LENGTH = exports.SECRET_KEY_LENGTH = exports.PUBLIC_KEY_LENGTH = void 0;\n/**\n * Package x25519 implements X25519 key agreement.\n */\nconst random_1 = require(\"@stablelib/random\");\nconst wipe_1 = require(\"@stablelib/wipe\");\nexports.PUBLIC_KEY_LENGTH = 32;\nexports.SECRET_KEY_LENGTH = 32;\nexports.SHARED_KEY_LENGTH = 32;\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init) {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n// Base point.\nconst _9 = new Uint8Array(32);\n_9[0] = 9;\nconst _121665 = gf([0xdb41, 1]);\nfunction car25519(o) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\nfunction sel25519(p, q, b) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\nfunction pack25519(o, n) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\nfunction unpack25519(o, n) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\nfunction add(o, a, b) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\nfunction sub(o, a, b) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\nfunction mul(o, a, b) {\n let v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n // first car\n c = 1;\n v = t0 + c + 65535;\n c = Math.floor(v / 65536);\n t0 = v - c * 65536;\n v = t1 + c + 65535;\n c = Math.floor(v / 65536);\n t1 = v - c * 65536;\n v = t2 + c + 65535;\n c = Math.floor(v / 65536);\n t2 = v - c * 65536;\n v = t3 + c + 65535;\n c = Math.floor(v / 65536);\n t3 = v - c * 65536;\n v = t4 + c + 65535;\n c = Math.floor(v / 65536);\n t4 = v - c * 65536;\n v = t5 + c + 65535;\n c = Math.floor(v / 65536);\n t5 = v - c * 65536;\n v = t6 + c + 65535;\n c = Math.floor(v / 65536);\n t6 = v - c * 65536;\n v = t7 + c + 65535;\n c = Math.floor(v / 65536);\n t7 = v - c * 65536;\n v = t8 + c + 65535;\n c = Math.floor(v / 65536);\n t8 = v - c * 65536;\n v = t9 + c + 65535;\n c = Math.floor(v / 65536);\n t9 = v - c * 65536;\n v = t10 + c + 65535;\n c = Math.floor(v / 65536);\n t10 = v - c * 65536;\n v = t11 + c + 65535;\n c = Math.floor(v / 65536);\n t11 = v - c * 65536;\n v = t12 + c + 65535;\n c = Math.floor(v / 65536);\n t12 = v - c * 65536;\n v = t13 + c + 65535;\n c = Math.floor(v / 65536);\n t13 = v - c * 65536;\n v = t14 + c + 65535;\n c = Math.floor(v / 65536);\n t14 = v - c * 65536;\n v = t15 + c + 65535;\n c = Math.floor(v / 65536);\n t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n // second car\n c = 1;\n v = t0 + c + 65535;\n c = Math.floor(v / 65536);\n t0 = v - c * 65536;\n v = t1 + c + 65535;\n c = Math.floor(v / 65536);\n t1 = v - c * 65536;\n v = t2 + c + 65535;\n c = Math.floor(v / 65536);\n t2 = v - c * 65536;\n v = t3 + c + 65535;\n c = Math.floor(v / 65536);\n t3 = v - c * 65536;\n v = t4 + c + 65535;\n c = Math.floor(v / 65536);\n t4 = v - c * 65536;\n v = t5 + c + 65535;\n c = Math.floor(v / 65536);\n t5 = v - c * 65536;\n v = t6 + c + 65535;\n c = Math.floor(v / 65536);\n t6 = v - c * 65536;\n v = t7 + c + 65535;\n c = Math.floor(v / 65536);\n t7 = v - c * 65536;\n v = t8 + c + 65535;\n c = Math.floor(v / 65536);\n t8 = v - c * 65536;\n v = t9 + c + 65535;\n c = Math.floor(v / 65536);\n t9 = v - c * 65536;\n v = t10 + c + 65535;\n c = Math.floor(v / 65536);\n t10 = v - c * 65536;\n v = t11 + c + 65535;\n c = Math.floor(v / 65536);\n t11 = v - c * 65536;\n v = t12 + c + 65535;\n c = Math.floor(v / 65536);\n t12 = v - c * 65536;\n v = t13 + c + 65535;\n c = Math.floor(v / 65536);\n t13 = v - c * 65536;\n v = t14 + c + 65535;\n c = Math.floor(v / 65536);\n t14 = v - c * 65536;\n v = t15 + c + 65535;\n c = Math.floor(v / 65536);\n t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\nfunction square(o, a) {\n mul(o, a, a);\n}\nfunction inv25519(o, inp) {\n const c = gf();\n for (let i = 0; i < 16; i++) {\n c[i] = inp[i];\n }\n for (let i = 253; i >= 0; i--) {\n square(c, c);\n if (i !== 2 && i !== 4) {\n mul(c, c, inp);\n }\n }\n for (let i = 0; i < 16; i++) {\n o[i] = c[i];\n }\n}\nfunction scalarMult(n, p) {\n const z = new Uint8Array(32);\n const x = new Float64Array(80);\n const a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf();\n for (let i = 0; i < 31; i++) {\n z[i] = n[i];\n }\n z[31] = (n[31] & 127) | 64;\n z[0] &= 248;\n unpack25519(x, p);\n for (let i = 0; i < 16; i++) {\n b[i] = x[i];\n }\n a[0] = d[0] = 1;\n for (let i = 254; i >= 0; --i) {\n const r = (z[i >>> 3] >>> (i & 7)) & 1;\n sel25519(a, b, r);\n sel25519(c, d, r);\n add(e, a, c);\n sub(a, a, c);\n add(c, b, d);\n sub(b, b, d);\n square(d, e);\n square(f, a);\n mul(a, c, a);\n mul(c, b, e);\n add(e, a, c);\n sub(a, a, c);\n square(b, a);\n sub(c, d, f);\n mul(a, c, _121665);\n add(a, a, d);\n mul(c, c, a);\n mul(a, d, f);\n mul(d, b, x);\n square(b, e);\n sel25519(a, b, r);\n sel25519(c, d, r);\n }\n for (let i = 0; i < 16; i++) {\n x[i + 16] = a[i];\n x[i + 32] = c[i];\n x[i + 48] = b[i];\n x[i + 64] = d[i];\n }\n const x32 = x.subarray(32);\n const x16 = x.subarray(16);\n inv25519(x32, x32);\n mul(x16, x16, x32);\n const q = new Uint8Array(32);\n pack25519(q, x16);\n return q;\n}\nexports.scalarMult = scalarMult;\nfunction scalarMultBase(n) {\n return scalarMult(n, _9);\n}\nexports.scalarMultBase = scalarMultBase;\nfunction generateKeyPairFromSeed(seed) {\n if (seed.length !== exports.SECRET_KEY_LENGTH) {\n throw new Error(`x25519: seed must be ${exports.SECRET_KEY_LENGTH} bytes`);\n }\n const secretKey = new Uint8Array(seed);\n const publicKey = scalarMultBase(secretKey);\n return {\n publicKey,\n secretKey\n };\n}\nexports.generateKeyPairFromSeed = generateKeyPairFromSeed;\nfunction generateKeyPair(prng) {\n const seed = (0, random_1.randomBytes)(32, prng);\n const result = generateKeyPairFromSeed(seed);\n (0, wipe_1.wipe)(seed);\n return result;\n}\nexports.generateKeyPair = generateKeyPair;\n/**\n * Returns a shared key between our secret key and a peer's public key.\n *\n * Throws an error if the given keys are of wrong length.\n *\n * If rejectZero is true throws if the calculated shared key is all-zero.\n * From RFC 7748:\n *\n * > Protocol designers using Diffie-Hellman over the curves defined in\n * > this document must not assume \"contributory behavior\". Specially,\n * > contributory behavior means that both parties' private keys\n * > contribute to the resulting shared key. Since curve25519 and\n * > curve448 have cofactors of 8 and 4 (respectively), an input point of\n * > small order will eliminate any contribution from the other party's\n * > private key. This situation can be detected by checking for the all-\n * > zero output, which implementations MAY do, as specified in Section 6.\n * > However, a large number of existing implementations do not do this.\n *\n * IMPORTANT: the returned key is a raw result of scalar multiplication.\n * To use it as a key material, hash it with a cryptographic hash function.\n */\nfunction sharedKey(mySecretKey, theirPublicKey, rejectZero = false) {\n if (mySecretKey.length !== exports.PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect secret key length\");\n }\n if (theirPublicKey.length !== exports.PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect public key length\");\n }\n const result = scalarMult(mySecretKey, theirPublicKey);\n if (rejectZero) {\n let zeros = 0;\n for (let i = 0; i < result.length; i++) {\n zeros |= result[i];\n }\n if (zeros === 0) {\n throw new Error(\"X25519: invalid shared key\");\n }\n }\n return result;\n}\nexports.sharedKey = sharedKey;\n//# sourceMappingURL=x25519.js.map","export function alloc(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.alloc != null) {\n return globalThis.Buffer.alloc(size);\n }\n return new Uint8Array(size);\n}\nexport function allocUnsafe(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(size);\n }\n return new Uint8Array(size);\n}","import { allocUnsafe } from './alloc.js';\nexport function concat(arrays, length) {\n if (!length) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = allocUnsafe(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return output;\n}","function base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256);\n var iFACTOR = Math.log(256) / Math.log(BASE);\n function encode(source) {\n if (source instanceof Uint8Array);\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n var size = (pend - pbegin) * iFACTOR + 1 >>> 0;\n var b58 = new Uint8Array(size);\n while (pbegin !== pend) {\n var carry = source[pbegin];\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) {\n carry += 256 * b58[it1] >>> 0;\n b58[it1] = carry % BASE >>> 0;\n carry = carry / BASE >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n if (source[psz] === ' ') {\n return;\n }\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n var size = (source.length - psz) * FACTOR + 1 >>> 0;\n var b256 = new Uint8Array(size);\n while (source[psz]) {\n var carry = BASE_MAP[source.charCodeAt(psz)];\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) {\n carry += BASE * b256[it3] >>> 0;\n b256[it3] = carry % 256 >>> 0;\n carry = carry / 256 >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n if (source[psz] === ' ') {\n return;\n }\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${ name } character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;","const empty = new Uint8Array(0);\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\nconst fromHex = hex => {\n const hexes = hex.match(/../g);\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n};\nconst equals = (aa, bb) => {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n};\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n};\nconst isBinary = o => o instanceof ArrayBuffer || ArrayBuffer.isView(o);\nconst fromString = str => new TextEncoder().encode(str);\nconst toString = b => new TextDecoder().decode(b);\nexport {\n equals,\n coerce,\n isBinary,\n fromHex,\n toHex,\n fromString,\n toString,\n empty\n};","import basex from '../../vendor/base-x.js';\nimport { coerce } from '../bytes.js';\nclass Encoder {\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${ this.prefix }${ this.baseEncode(bytes) }`;\n } else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\nclass Decoder {\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${ JSON.stringify(text) }, ${ this.name } decoder only supports inputs prefixed with ${ this.prefix }`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n } else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder) {\n return decoder.decode(input);\n } else {\n throw RangeError(`Unable to decode multibase string ${ JSON.stringify(input) }, only inputs prefixed with ${ Object.keys(this.decoders) } are supported`);\n }\n }\n}\nexport const or = (left, right) => new ComposedDecoder({\n ...left.decoders || { [left.prefix]: left },\n ...right.decoders || { [right.prefix]: right }\n});\nexport class Codec {\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport const from = ({name, prefix, encode, decode}) => new Codec(name, prefix, encode, decode);\nexport const baseX = ({prefix, name, alphabet}) => {\n const {encode, decode} = basex(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: text => coerce(decode(text))\n });\n};\nconst decode = (string, alphabet, bitsPerChar, name) => {\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n const out = new Uint8Array(end * bitsPerChar / 8 | 0);\n let bits = 0;\n let buffer = 0;\n let written = 0;\n for (let i = 0; i < end; ++i) {\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${ name } character`);\n }\n buffer = buffer << bitsPerChar | value;\n bits += bitsPerChar;\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 255 & buffer >> bits;\n }\n }\n if (bits >= bitsPerChar || 255 & buffer << 8 - bits) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n};\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0;\n let buffer = 0;\n for (let i = 0; i < data.length; ++i) {\n buffer = buffer << 8 | data[i];\n bits += 8;\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & buffer >> bits];\n }\n }\n if (bits) {\n out += alphabet[mask & buffer << bitsPerChar - bits];\n }\n if (pad) {\n while (out.length * bitsPerChar & 7) {\n out += '=';\n }\n }\n return out;\n};\nexport const rfc4648 = ({name, prefix, bitsPerChar, alphabet}) => {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n};","import { from } from './base.js';\nimport {\n fromString,\n toString\n} from '../bytes.js';\nexport const identity = from({\n prefix: '\\0',\n name: 'identity',\n encode: buf => toString(buf),\n decode: str => fromString(str)\n});","import { rfc4648 } from './base.js';\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});","import { rfc4648 } from './base.js';\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});","import { baseX } from './base.js';\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});","import { rfc4648 } from './base.js';\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});","import { rfc4648 } from './base.js';\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});","import { baseX } from './base.js';\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});","import { baseX } from './base.js';\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});","import { rfc4648 } from './base.js';\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});","import { from } from './base.js';\nconst alphabet = Array.from('\\uD83D\\uDE80\\uD83E\\uDE90\\u2604\\uD83D\\uDEF0\\uD83C\\uDF0C\\uD83C\\uDF11\\uD83C\\uDF12\\uD83C\\uDF13\\uD83C\\uDF14\\uD83C\\uDF15\\uD83C\\uDF16\\uD83C\\uDF17\\uD83C\\uDF18\\uD83C\\uDF0D\\uD83C\\uDF0F\\uD83C\\uDF0E\\uD83D\\uDC09\\u2600\\uD83D\\uDCBB\\uD83D\\uDDA5\\uD83D\\uDCBE\\uD83D\\uDCBF\\uD83D\\uDE02\\u2764\\uD83D\\uDE0D\\uD83E\\uDD23\\uD83D\\uDE0A\\uD83D\\uDE4F\\uD83D\\uDC95\\uD83D\\uDE2D\\uD83D\\uDE18\\uD83D\\uDC4D\\uD83D\\uDE05\\uD83D\\uDC4F\\uD83D\\uDE01\\uD83D\\uDD25\\uD83E\\uDD70\\uD83D\\uDC94\\uD83D\\uDC96\\uD83D\\uDC99\\uD83D\\uDE22\\uD83E\\uDD14\\uD83D\\uDE06\\uD83D\\uDE44\\uD83D\\uDCAA\\uD83D\\uDE09\\u263A\\uD83D\\uDC4C\\uD83E\\uDD17\\uD83D\\uDC9C\\uD83D\\uDE14\\uD83D\\uDE0E\\uD83D\\uDE07\\uD83C\\uDF39\\uD83E\\uDD26\\uD83C\\uDF89\\uD83D\\uDC9E\\u270C\\u2728\\uD83E\\uDD37\\uD83D\\uDE31\\uD83D\\uDE0C\\uD83C\\uDF38\\uD83D\\uDE4C\\uD83D\\uDE0B\\uD83D\\uDC97\\uD83D\\uDC9A\\uD83D\\uDE0F\\uD83D\\uDC9B\\uD83D\\uDE42\\uD83D\\uDC93\\uD83E\\uDD29\\uD83D\\uDE04\\uD83D\\uDE00\\uD83D\\uDDA4\\uD83D\\uDE03\\uD83D\\uDCAF\\uD83D\\uDE48\\uD83D\\uDC47\\uD83C\\uDFB6\\uD83D\\uDE12\\uD83E\\uDD2D\\u2763\\uD83D\\uDE1C\\uD83D\\uDC8B\\uD83D\\uDC40\\uD83D\\uDE2A\\uD83D\\uDE11\\uD83D\\uDCA5\\uD83D\\uDE4B\\uD83D\\uDE1E\\uD83D\\uDE29\\uD83D\\uDE21\\uD83E\\uDD2A\\uD83D\\uDC4A\\uD83E\\uDD73\\uD83D\\uDE25\\uD83E\\uDD24\\uD83D\\uDC49\\uD83D\\uDC83\\uD83D\\uDE33\\u270B\\uD83D\\uDE1A\\uD83D\\uDE1D\\uD83D\\uDE34\\uD83C\\uDF1F\\uD83D\\uDE2C\\uD83D\\uDE43\\uD83C\\uDF40\\uD83C\\uDF37\\uD83D\\uDE3B\\uD83D\\uDE13\\u2B50\\u2705\\uD83E\\uDD7A\\uD83C\\uDF08\\uD83D\\uDE08\\uD83E\\uDD18\\uD83D\\uDCA6\\u2714\\uD83D\\uDE23\\uD83C\\uDFC3\\uD83D\\uDC90\\u2639\\uD83C\\uDF8A\\uD83D\\uDC98\\uD83D\\uDE20\\u261D\\uD83D\\uDE15\\uD83C\\uDF3A\\uD83C\\uDF82\\uD83C\\uDF3B\\uD83D\\uDE10\\uD83D\\uDD95\\uD83D\\uDC9D\\uD83D\\uDE4A\\uD83D\\uDE39\\uD83D\\uDDE3\\uD83D\\uDCAB\\uD83D\\uDC80\\uD83D\\uDC51\\uD83C\\uDFB5\\uD83E\\uDD1E\\uD83D\\uDE1B\\uD83D\\uDD34\\uD83D\\uDE24\\uD83C\\uDF3C\\uD83D\\uDE2B\\u26BD\\uD83E\\uDD19\\u2615\\uD83C\\uDFC6\\uD83E\\uDD2B\\uD83D\\uDC48\\uD83D\\uDE2E\\uD83D\\uDE46\\uD83C\\uDF7B\\uD83C\\uDF43\\uD83D\\uDC36\\uD83D\\uDC81\\uD83D\\uDE32\\uD83C\\uDF3F\\uD83E\\uDDE1\\uD83C\\uDF81\\u26A1\\uD83C\\uDF1E\\uD83C\\uDF88\\u274C\\u270A\\uD83D\\uDC4B\\uD83D\\uDE30\\uD83E\\uDD28\\uD83D\\uDE36\\uD83E\\uDD1D\\uD83D\\uDEB6\\uD83D\\uDCB0\\uD83C\\uDF53\\uD83D\\uDCA2\\uD83E\\uDD1F\\uD83D\\uDE41\\uD83D\\uDEA8\\uD83D\\uDCA8\\uD83E\\uDD2C\\u2708\\uD83C\\uDF80\\uD83C\\uDF7A\\uD83E\\uDD13\\uD83D\\uDE19\\uD83D\\uDC9F\\uD83C\\uDF31\\uD83D\\uDE16\\uD83D\\uDC76\\uD83E\\uDD74\\u25B6\\u27A1\\u2753\\uD83D\\uDC8E\\uD83D\\uDCB8\\u2B07\\uD83D\\uDE28\\uD83C\\uDF1A\\uD83E\\uDD8B\\uD83D\\uDE37\\uD83D\\uDD7A\\u26A0\\uD83D\\uDE45\\uD83D\\uDE1F\\uD83D\\uDE35\\uD83D\\uDC4E\\uD83E\\uDD32\\uD83E\\uDD20\\uD83E\\uDD27\\uD83D\\uDCCC\\uD83D\\uDD35\\uD83D\\uDC85\\uD83E\\uDDD0\\uD83D\\uDC3E\\uD83C\\uDF52\\uD83D\\uDE17\\uD83E\\uDD11\\uD83C\\uDF0A\\uD83E\\uDD2F\\uD83D\\uDC37\\u260E\\uD83D\\uDCA7\\uD83D\\uDE2F\\uD83D\\uDC86\\uD83D\\uDC46\\uD83C\\uDFA4\\uD83D\\uDE47\\uD83C\\uDF51\\u2744\\uD83C\\uDF34\\uD83D\\uDCA3\\uD83D\\uDC38\\uD83D\\uDC8C\\uD83D\\uDCCD\\uD83E\\uDD40\\uD83E\\uDD22\\uD83D\\uDC45\\uD83D\\uDCA1\\uD83D\\uDCA9\\uD83D\\uDC50\\uD83D\\uDCF8\\uD83D\\uDC7B\\uD83E\\uDD10\\uD83E\\uDD2E\\uD83C\\uDFBC\\uD83E\\uDD75\\uD83D\\uDEA9\\uD83C\\uDF4E\\uD83C\\uDF4A\\uD83D\\uDC7C\\uD83D\\uDC8D\\uD83D\\uDCE3\\uD83E\\uDD42');\nconst alphabetBytesToChars = alphabet.reduce((p, c, i) => {\n p[i] = c;\n return p;\n}, []);\nconst alphabetCharsToBytes = alphabet.reduce((p, c, i) => {\n p[c.codePointAt(0)] = i;\n return p;\n}, []);\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${ char }`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nexport const base256emoji = from({\n prefix: '\\uD83D\\uDE80',\n name: 'base256emoji',\n encode,\n decode\n});","var encode_1 = encode;\nvar MSB = 128, REST = 127, MSBALL = ~REST, INT = Math.pow(2, 31);\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = num & 255 | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = num & 255 | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 128, REST$1 = 127;\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (value) {\n return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;","import varint from '../vendor/varint.js';\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset);\n return [\n code,\n varint.decode.bytes\n ];\n};\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset);\n return target;\n};\nexport const encodingLength = int => {\n return varint.encodingLength(int);\n};","import {\n coerce,\n equals as equalBytes\n} from '../bytes.js';\nimport * as varint from '../varint.js';\nexport const create = (code, digest) => {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n};\nexport const decode = multihash => {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n};\nexport const equals = (a, b) => {\n if (a === b) {\n return true;\n } else {\n return a.code === b.code && a.size === b.size && equalBytes(a.bytes, b.bytes);\n }\n};\nexport class Digest {\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}","import * as Digest from './digest.js';\nexport const from = ({name, code, encode}) => new Hasher(name, code, encode);\nexport class Hasher {\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array ? Digest.create(this.code, result) : result.then(digest => Digest.create(this.code, digest));\n } else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}","import { from } from './hasher.js';\nconst sha = name => async data => new Uint8Array(await crypto.subtle.digest(name, data));\nexport const sha256 = from({\n name: 'sha2-256',\n code: 18,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 19,\n encode: sha('SHA-512')\n});","import { coerce } from '../bytes.js';\nimport * as Digest from './digest.js';\nconst code = 0;\nconst name = 'identity';\nconst encode = coerce;\nconst digest = input => Digest.create(code, encode(input));\nexport const identity = {\n code,\n name,\n encode,\n digest\n};","const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nexport const name = 'json';\nexport const code = 512;\nexport const encode = node => textEncoder.encode(JSON.stringify(node));\nexport const decode = data => JSON.parse(textDecoder.decode(data));","import * as identityBase from './bases/identity.js';\nimport * as base2 from './bases/base2.js';\nimport * as base8 from './bases/base8.js';\nimport * as base10 from './bases/base10.js';\nimport * as base16 from './bases/base16.js';\nimport * as base32 from './bases/base32.js';\nimport * as base36 from './bases/base36.js';\nimport * as base58 from './bases/base58.js';\nimport * as base64 from './bases/base64.js';\nimport * as base256emoji from './bases/base256emoji.js';\nimport * as sha2 from './hashes/sha2.js';\nimport * as identity from './hashes/identity.js';\nimport * as raw from './codecs/raw.js';\nimport * as json from './codecs/json.js';\nimport {\n CID,\n hasher,\n digest,\n varint,\n bytes\n} from './index.js';\nconst bases = {\n ...identityBase,\n ...base2,\n ...base8,\n ...base10,\n ...base16,\n ...base32,\n ...base36,\n ...base58,\n ...base64,\n ...base256emoji\n};\nconst hashes = {\n ...sha2,\n ...identity\n};\nconst codecs = {\n raw,\n json\n};\nexport {\n CID,\n hasher,\n digest,\n varint,\n bytes,\n hashes,\n bases,\n codecs\n};","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '../alloc.js';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: { decode }\n };\n}\nconst string = createCodec('utf8', 'u', buf => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, str => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', buf => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, str => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii: ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;","import bases from './util/bases.js';\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (!base) {\n throw new Error(`Unsupported encoding \"${ encoding }\"`);\n }\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(string, 'utf8');\n }\n return base.decoder.decode(`${ base.prefix }${ string }`);\n}","import bases from './util/bases.js';\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (!base) {\n throw new Error(`Unsupported encoding \"${ encoding }\"`);\n }\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');\n }\n return base.encoder.encode(array).substring(1);\n}","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","'use strict';\n\nvar utils = exports;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg !== 'string') {\n for (var i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n return res;\n }\n if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (var i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n } else {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n","'use strict';\n\nvar utils = exports;\nvar BN = require('bn.js');\nvar minAssert = require('minimalistic-assert');\nvar minUtils = require('minimalistic-crypto-utils');\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w, bits) {\n var naf = new Array(Math.max(num.bitLength(), bits) + 1);\n var i;\n for (i = 0; i < naf.length; i += 1) {\n naf[i] = 0;\n }\n\n var ws = 1 << (w + 1);\n var k = num.clone();\n\n for (i = 0; i < naf.length; i++) {\n var z;\n var mod = k.andln(ws - 1);\n if (k.isOdd()) {\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n\n naf[i] = z;\n k.iushrn(1);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n [],\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n var m8;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n","var r;\n\nmodule.exports = function rand(len) {\n if (!r)\n r = new Rand(null);\n\n return r.generate(len);\n};\n\nfunction Rand(rand) {\n this.rand = rand;\n}\nmodule.exports.Rand = Rand;\n\nRand.prototype.generate = function generate(len) {\n return this._rand(len);\n};\n\n// Emulate crypto API using randy\nRand.prototype._rand = function _rand(n) {\n if (this.rand.getBytes)\n return this.rand.getBytes(n);\n\n var res = new Uint8Array(n);\n for (var i = 0; i < res.length; i++)\n res[i] = this.rand.getByte();\n return res;\n};\n\nif (typeof self === 'object') {\n if (self.crypto && self.crypto.getRandomValues) {\n // Modern browsers\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.crypto.getRandomValues(arr);\n return arr;\n };\n } else if (self.msCrypto && self.msCrypto.getRandomValues) {\n // IE\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.msCrypto.getRandomValues(arr);\n return arr;\n };\n\n // Safari's WebWorkers do not have `crypto`\n } else if (typeof window === 'object') {\n // Old junk\n Rand.prototype._rand = function() {\n throw new Error('Not implemented yet');\n };\n }\n} else {\n // Node.js or Web worker with no crypto support\n try {\n var crypto = require('crypto');\n if (typeof crypto.randomBytes !== 'function')\n throw new Error('Not supported');\n\n Rand.prototype._rand = function _rand(n) {\n return crypto.randomBytes(n);\n };\n } catch (e) {\n }\n}\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n this._bitLength = this.n ? this.n.bitLength() : 0;\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1, this._bitLength);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n var j;\n var nafW;\n for (j = 0; j < naf.length; j += doubles.step) {\n nafW = 0;\n for (var l = j + doubles.step - 1; l >= j; l--)\n nafW = (nafW << 1) + naf[l];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (j = 0; j < repr.length; j++) {\n nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w, this._bitLength);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var l = 0; i >= 0 && naf[i] === 0; i--)\n l++;\n if (i >= 0)\n l++;\n acc = acc.dblp(l);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n var i;\n var j;\n var p;\n for (i = 0; i < len; i++) {\n p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);\n naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b], /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3, /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (j = 0; j < len; j++) {\n var z = tmp[j];\n p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len));\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null,\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles,\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res,\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16),\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis,\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 },\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n };\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul),\n },\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1),\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1),\n },\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point)),\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point)),\n },\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate),\n },\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n var i;\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar utils = require('../utils');\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n return this.point(utils.toArray(bytes, enc), 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode() {\n return this.getX().toArray('be', this.curve.p.byteLength());\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n var e;\n var h;\n var j;\n if (this.curve.twisted) {\n // E = a * C\n e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n h = this.z.redSqr();\n // J = F - 2 * H\n j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n e = c.redAdd(d);\n // H = (c * Z1)^2\n h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n","'use strict';\n\nvar curve = exports;\n\ncurve.base = require('./base');\ncurve.short = require('./short');\ncurve.mont = require('./mont');\ncurve.edwards = require('./edwards');\n","module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821',\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf',\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695',\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9',\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36',\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f',\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999',\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09',\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d',\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088',\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d',\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8',\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a',\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453',\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160',\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0',\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6',\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589',\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17',\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda',\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd',\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2',\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6',\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f',\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01',\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3',\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f',\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7',\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78',\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1',\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150',\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82',\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc',\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b',\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51',\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45',\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120',\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84',\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d',\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d',\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8',\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8',\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac',\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f',\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962',\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907',\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec',\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d',\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414',\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd',\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0',\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811',\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1',\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c',\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73',\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd',\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405',\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589',\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e',\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27',\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1',\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482',\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945',\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573',\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82',\n ],\n ],\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672',\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6',\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da',\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37',\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b',\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81',\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58',\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77',\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a',\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c',\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67',\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402',\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55',\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482',\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82',\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396',\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49',\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf',\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a',\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7',\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933',\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a',\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6',\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37',\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e',\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6',\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476',\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40',\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61',\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683',\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5',\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b',\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417',\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868',\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a',\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6',\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996',\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e',\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d',\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2',\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e',\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437',\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311',\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4',\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575',\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d',\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d',\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629',\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06',\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374',\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee',\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1',\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b',\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661',\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6',\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e',\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d',\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc',\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4',\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c',\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b',\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913',\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154',\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865',\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc',\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224',\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e',\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6',\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511',\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b',\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2',\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c',\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3',\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d',\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700',\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4',\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196',\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4',\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257',\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13',\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096',\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38',\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f',\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448',\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a',\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4',\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437',\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7',\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d',\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a',\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54',\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77',\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517',\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10',\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125',\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e',\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1',\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2',\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423',\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8',\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758',\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375',\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d',\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec',\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0',\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c',\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4',\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f',\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649',\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826',\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5',\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87',\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b',\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc',\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c',\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f',\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a',\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46',\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f',\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03',\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08',\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8',\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373',\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3',\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8',\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1',\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9',\n ],\n ],\n },\n};\n","'use strict';\n\nvar curves = exports;\n\nvar hash = require('hash.js');\nvar curve = require('./curve');\nvar utils = require('./utils');\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else\n this.curve = new curve.mont(options);\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve,\n });\n return curve;\n },\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',\n ],\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',\n ],\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',\n ],\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',\n ],\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650',\n ],\n});\n\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9',\n ],\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658',\n ],\n});\n\nvar pre;\ntry {\n pre = require('./precomputed/secp256k1');\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3',\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15',\n },\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre,\n ],\n});\n","'use strict';\n\nvar hash = require('hash.js');\nvar utils = require('minimalistic-crypto-utils');\nvar assert = require('minimalistic-assert');\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils.toArray(options.pers, options.persEnc || 'hex');\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nmodule.exports = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils.toArray(entropy, entropyEnc);\n add = utils.toArray(add, addEnc);\n\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc,\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc,\n });\n};\n\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(compact, enc) {\n // compact is optional argument\n if (typeof compact === 'string') {\n enc = compact;\n compact = null;\n }\n\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n if(!pub.validate()) {\n assert(pub.validate(), 'public point not validated');\n }\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature, options) {\n return this.ec.verify(msg, signature, this, undefined, options);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n","'use strict';\n\nvar BN = require('bn.js');\n\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n\n // Indefinite length or overflow\n if (octetLen === 0 || octetLen > 4) {\n return false;\n }\n\n if(buf[p.place] === 0x00) {\n return false;\n }\n\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n val >>>= 0;\n }\n\n // Leading zeroes\n if (val <= 0x7f) {\n return false;\n }\n\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if (len === false) {\n return false;\n }\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n if (rlen === false) {\n return false;\n }\n if ((data[p.place] & 128) !== 0) {\n return false;\n }\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (slen === false) {\n return false;\n }\n if (data.length !== slen + p.place) {\n return false;\n }\n if ((data[p.place] & 128) !== 0) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0) {\n if (r[1] & 0x80) {\n r = r.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n if (s[0] === 0) {\n if (s[1] & 0x80) {\n s = s.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n","'use strict';\n\nvar BN = require('bn.js');\nvar HmacDRBG = require('hmac-drbg');\nvar utils = require('../utils');\nvar curves = require('../curves');\nvar rand = require('brorand');\nvar assert = utils.assert;\n\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(Object.prototype.hasOwnProperty.call(curves, options),\n 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash for function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray(),\n });\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n for (;;) {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n }\n};\n\nEC.prototype._truncateToN = function _truncateToN(msg, truncOnly, bitLength) {\n var byteLength;\n if (BN.isBN(msg) || typeof msg === 'number') {\n msg = new BN(msg, 16);\n byteLength = msg.byteLength();\n } else if (typeof msg === 'object') {\n // BN assumes an array-like input and asserts length\n byteLength = msg.length;\n msg = new BN(msg, 16);\n } else {\n // BN converts the value to string\n var str = msg.toString();\n // HEX encoding\n byteLength = (str.length + 1) >>> 1;\n msg = new BN(str, 16);\n }\n // Allow overriding\n if (typeof bitLength !== 'number') {\n bitLength = byteLength * 8;\n }\n var delta = bitLength - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this._truncateToN(msg, false, options.msgBitLength);\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; ; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc, options) {\n if (!options)\n options = {};\n\n msg = this._truncateToN(msg, false, options.msgBitLength);\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n var p;\n\n if (!this.curve._maxwellTrick) {\n p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else\n this._pubBytes = parseBytes(params.pub);\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc) {\n return utils.encode(this.pubBytes(), enc);\n};\n\nmodule.exports = KeyPair;\n","'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n assert(sig.length === eddsa.encodingLength * 2, 'Signature has invalid size');\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength),\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n","'use strict';\n\nvar hash = require('hash.js');\nvar curves = require('../curves');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n if (sig.S().gte(sig.eddsa.curve.n) || sig.S().isNeg()) {\n return false;\n }\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n","'use strict';\n\nvar elliptic = exports;\n\nelliptic.version = require('../package.json').version;\nelliptic.utils = require('./elliptic/utils');\nelliptic.rand = require('brorand');\nelliptic.curve = require('./elliptic/curve');\nelliptic.curves = require('./elliptic/curves');\n\n// Protocols\nelliptic.ec = require('./elliptic/ec');\nelliptic.eddsa = require('./elliptic/eddsa');\n","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar binary_1 = require(\"@stablelib/binary\");\nvar wipe_1 = require(\"@stablelib/wipe\");\nexports.DIGEST_LENGTH = 64;\nexports.BLOCK_SIZE = 128;\n/**\n * SHA-2-512 cryptographic hash algorithm.\n */\nvar SHA512 = /** @class */ (function () {\n function SHA512() {\n /** Length of hash output */\n this.digestLength = exports.DIGEST_LENGTH;\n /** Block size */\n this.blockSize = exports.BLOCK_SIZE;\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n this._stateHi = new Int32Array(8); // hash state, high bytes\n this._stateLo = new Int32Array(8); // hash state, low bytes\n this._tempHi = new Int32Array(16); // temporary state, high bytes\n this._tempLo = new Int32Array(16); // temporary state, low bytes\n this._buffer = new Uint8Array(256); // buffer for data to hash\n this._bufferLength = 0; // number of bytes in buffer\n this._bytesHashed = 0; // number of total bytes hashed\n this._finished = false; // indicates whether the hash was finalized\n this.reset();\n }\n SHA512.prototype._initState = function () {\n this._stateHi[0] = 0x6a09e667;\n this._stateHi[1] = 0xbb67ae85;\n this._stateHi[2] = 0x3c6ef372;\n this._stateHi[3] = 0xa54ff53a;\n this._stateHi[4] = 0x510e527f;\n this._stateHi[5] = 0x9b05688c;\n this._stateHi[6] = 0x1f83d9ab;\n this._stateHi[7] = 0x5be0cd19;\n this._stateLo[0] = 0xf3bcc908;\n this._stateLo[1] = 0x84caa73b;\n this._stateLo[2] = 0xfe94f82b;\n this._stateLo[3] = 0x5f1d36f1;\n this._stateLo[4] = 0xade682d1;\n this._stateLo[5] = 0x2b3e6c1f;\n this._stateLo[6] = 0xfb41bd6b;\n this._stateLo[7] = 0x137e2179;\n };\n /**\n * Resets hash state making it possible\n * to re-use this instance to hash other data.\n */\n SHA512.prototype.reset = function () {\n this._initState();\n this._bufferLength = 0;\n this._bytesHashed = 0;\n this._finished = false;\n return this;\n };\n /**\n * Cleans internal buffers and resets hash state.\n */\n SHA512.prototype.clean = function () {\n wipe_1.wipe(this._buffer);\n wipe_1.wipe(this._tempHi);\n wipe_1.wipe(this._tempLo);\n this.reset();\n };\n /**\n * Updates hash state with the given data.\n *\n * Throws error when trying to update already finalized hash:\n * instance must be reset to update it again.\n */\n SHA512.prototype.update = function (data, dataLength) {\n if (dataLength === void 0) { dataLength = data.length; }\n if (this._finished) {\n throw new Error(\"SHA512: can't update because hash was finished.\");\n }\n var dataPos = 0;\n this._bytesHashed += dataLength;\n if (this._bufferLength > 0) {\n while (this._bufferLength < exports.BLOCK_SIZE && dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this._bufferLength === this.blockSize) {\n hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, this.blockSize);\n this._bufferLength = 0;\n }\n }\n if (dataLength >= this.blockSize) {\n dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, data, dataPos, dataLength);\n dataLength %= this.blockSize;\n }\n while (dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n };\n /**\n * Finalizes hash state and puts hash into out.\n * If hash was already finalized, puts the same value.\n */\n SHA512.prototype.finish = function (out) {\n if (!this._finished) {\n var bytesHashed = this._bytesHashed;\n var left = this._bufferLength;\n var bitLenHi = (bytesHashed / 0x20000000) | 0;\n var bitLenLo = bytesHashed << 3;\n var padLength = (bytesHashed % 128 < 112) ? 128 : 256;\n this._buffer[left] = 0x80;\n for (var i = left + 1; i < padLength - 8; i++) {\n this._buffer[i] = 0;\n }\n binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8);\n binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4);\n hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength);\n this._finished = true;\n }\n for (var i = 0; i < this.digestLength / 8; i++) {\n binary_1.writeUint32BE(this._stateHi[i], out, i * 8);\n binary_1.writeUint32BE(this._stateLo[i], out, i * 8 + 4);\n }\n return this;\n };\n /**\n * Returns the final hash digest.\n */\n SHA512.prototype.digest = function () {\n var out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n };\n /**\n * Function useful for HMAC/PBKDF2 optimization. Returns hash state to be\n * used with restoreState(). Only chain value is saved, not buffers or\n * other state variables.\n */\n SHA512.prototype.saveState = function () {\n if (this._finished) {\n throw new Error(\"SHA256: cannot save finished state\");\n }\n return {\n stateHi: new Int32Array(this._stateHi),\n stateLo: new Int32Array(this._stateLo),\n buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined,\n bufferLength: this._bufferLength,\n bytesHashed: this._bytesHashed\n };\n };\n /**\n * Function useful for HMAC/PBKDF2 optimization. Restores state saved by\n * saveState() and sets bytesHashed to the given value.\n */\n SHA512.prototype.restoreState = function (savedState) {\n this._stateHi.set(savedState.stateHi);\n this._stateLo.set(savedState.stateLo);\n this._bufferLength = savedState.bufferLength;\n if (savedState.buffer) {\n this._buffer.set(savedState.buffer);\n }\n this._bytesHashed = savedState.bytesHashed;\n this._finished = false;\n return this;\n };\n /**\n * Cleans state returned by saveState().\n */\n SHA512.prototype.cleanSavedState = function (savedState) {\n wipe_1.wipe(savedState.stateHi);\n wipe_1.wipe(savedState.stateLo);\n if (savedState.buffer) {\n wipe_1.wipe(savedState.buffer);\n }\n savedState.bufferLength = 0;\n savedState.bytesHashed = 0;\n };\n return SHA512;\n}());\nexports.SHA512 = SHA512;\n// Constants\nvar K = new Int32Array([\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n]);\nfunction hashBlocks(wh, wl, hh, hl, m, pos, len) {\n var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7];\n var h, l;\n var th, tl;\n var a, b, c, d;\n while (len >= 128) {\n for (var i = 0; i < 16; i++) {\n var j = 8 * i + pos;\n wh[i] = binary_1.readUint32BE(m, j);\n wl[i] = binary_1.readUint32BE(m, j + 4);\n }\n for (var i = 0; i < 80; i++) {\n var bh0 = ah0;\n var bh1 = ah1;\n var bh2 = ah2;\n var bh3 = ah3;\n var bh4 = ah4;\n var bh5 = ah5;\n var bh6 = ah6;\n var bh7 = ah7;\n var bl0 = al0;\n var bl1 = al1;\n var bl2 = al2;\n var bl3 = al3;\n var bl4 = al4;\n var bl5 = al5;\n var bl6 = al6;\n var bl7 = al7;\n // add\n h = ah7;\n l = al7;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32 - 14))) ^ ((ah4 >>> 18) |\n (al4 << (32 - 18))) ^ ((al4 >>> (41 - 32)) | (ah4 << (32 - (41 - 32))));\n l = ((al4 >>> 14) | (ah4 << (32 - 14))) ^ ((al4 >>> 18) |\n (ah4 << (32 - 18))) ^ ((ah4 >>> (41 - 32)) | (al4 << (32 - (41 - 32))));\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n // K\n h = K[i * 2];\n l = K[i * 2 + 1];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n // w\n h = wh[i % 16];\n l = wl[i % 16];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n // add\n h = th;\n l = tl;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32 - 28))) ^ ((al0 >>> (34 - 32)) |\n (ah0 << (32 - (34 - 32)))) ^ ((al0 >>> (39 - 32)) | (ah0 << (32 - (39 - 32))));\n l = ((al0 >>> 28) | (ah0 << (32 - 28))) ^ ((ah0 >>> (34 - 32)) |\n (al0 << (32 - (34 - 32)))) ^ ((ah0 >>> (39 - 32)) | (al0 << (32 - (39 - 32))));\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n // add\n h = bh3;\n l = bl3;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = th;\n l = tl;\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n if (i % 16 === 15) {\n for (var j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = wh[(j + 9) % 16];\n l = wl[(j + 9) % 16];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n // sigma0\n th = wh[(j + 1) % 16];\n tl = wl[(j + 1) % 16];\n h = ((th >>> 1) | (tl << (32 - 1))) ^ ((th >>> 8) |\n (tl << (32 - 8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32 - 1))) ^ ((tl >>> 8) |\n (th << (32 - 8))) ^ ((tl >>> 7) | (th << (32 - 7)));\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n // sigma1\n th = wh[(j + 14) % 16];\n tl = wl[(j + 14) % 16];\n h = ((th >>> 19) | (tl << (32 - 19))) ^ ((tl >>> (61 - 32)) |\n (th << (32 - (61 - 32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32 - 19))) ^ ((th >>> (61 - 32)) |\n (tl << (32 - (61 - 32)))) ^ ((tl >>> 6) | (th << (32 - 6)));\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n // add\n h = ah0;\n l = al0;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = hh[0];\n l = hl[0];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n h = ah1;\n l = al1;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = hh[1];\n l = hl[1];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n h = ah2;\n l = al2;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = hh[2];\n l = hl[2];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n h = ah3;\n l = al3;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = hh[3];\n l = hl[3];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n h = ah4;\n l = al4;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = hh[4];\n l = hl[4];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n h = ah5;\n l = al5;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = hh[5];\n l = hl[5];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n h = ah6;\n l = al6;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = hh[6];\n l = hl[6];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n h = ah7;\n l = al7;\n a = l & 0xffff;\n b = l >>> 16;\n c = h & 0xffff;\n d = h >>> 16;\n h = hh[7];\n l = hl[7];\n a += l & 0xffff;\n b += l >>> 16;\n c += h & 0xffff;\n d += h >>> 16;\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n pos += 128;\n len -= 128;\n }\n return pos;\n}\nfunction hash(data) {\n var h = new SHA512();\n h.update(data);\n var digest = h.digest();\n h.clean();\n return digest;\n}\nexports.hash = hash;\n//# sourceMappingURL=sha512.js.map","\"use strict\";\n// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.convertSecretKeyToX25519 = exports.convertPublicKeyToX25519 = exports.verify = exports.sign = exports.extractPublicKeyFromSecretKey = exports.generateKeyPair = exports.generateKeyPairFromSeed = exports.SEED_LENGTH = exports.SECRET_KEY_LENGTH = exports.PUBLIC_KEY_LENGTH = exports.SIGNATURE_LENGTH = void 0;\n/**\n * Package ed25519 implements Ed25519 public-key signature algorithm.\n */\nconst random_1 = require(\"@stablelib/random\");\nconst sha512_1 = require(\"@stablelib/sha512\");\nconst wipe_1 = require(\"@stablelib/wipe\");\nexports.SIGNATURE_LENGTH = 64;\nexports.PUBLIC_KEY_LENGTH = 32;\nexports.SECRET_KEY_LENGTH = 64;\nexports.SEED_LENGTH = 32;\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init) {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n// Base point.\nconst _9 = new Uint8Array(32);\n_9[0] = 9;\nconst gf0 = gf();\nconst gf1 = gf([1]);\nconst D = gf([\n 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,\n 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203\n]);\nconst D2 = gf([\n 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,\n 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406\n]);\nconst X = gf([\n 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,\n 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169\n]);\nconst Y = gf([\n 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,\n 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666\n]);\nconst I = gf([\n 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,\n 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83\n]);\nfunction set25519(r, a) {\n for (let i = 0; i < 16; i++) {\n r[i] = a[i] | 0;\n }\n}\nfunction car25519(o) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\nfunction sel25519(p, q, b) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\nfunction pack25519(o, n) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\nfunction verify32(x, y) {\n let d = 0;\n for (let i = 0; i < 32; i++) {\n d |= x[i] ^ y[i];\n }\n return (1 & ((d - 1) >>> 8)) - 1;\n}\nfunction neq25519(a, b) {\n const c = new Uint8Array(32);\n const d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return verify32(c, d);\n}\nfunction par25519(a) {\n const d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\nfunction unpack25519(o, n) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\nfunction add(o, a, b) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\nfunction sub(o, a, b) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\nfunction mul(o, a, b) {\n let v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n // first car\n c = 1;\n v = t0 + c + 65535;\n c = Math.floor(v / 65536);\n t0 = v - c * 65536;\n v = t1 + c + 65535;\n c = Math.floor(v / 65536);\n t1 = v - c * 65536;\n v = t2 + c + 65535;\n c = Math.floor(v / 65536);\n t2 = v - c * 65536;\n v = t3 + c + 65535;\n c = Math.floor(v / 65536);\n t3 = v - c * 65536;\n v = t4 + c + 65535;\n c = Math.floor(v / 65536);\n t4 = v - c * 65536;\n v = t5 + c + 65535;\n c = Math.floor(v / 65536);\n t5 = v - c * 65536;\n v = t6 + c + 65535;\n c = Math.floor(v / 65536);\n t6 = v - c * 65536;\n v = t7 + c + 65535;\n c = Math.floor(v / 65536);\n t7 = v - c * 65536;\n v = t8 + c + 65535;\n c = Math.floor(v / 65536);\n t8 = v - c * 65536;\n v = t9 + c + 65535;\n c = Math.floor(v / 65536);\n t9 = v - c * 65536;\n v = t10 + c + 65535;\n c = Math.floor(v / 65536);\n t10 = v - c * 65536;\n v = t11 + c + 65535;\n c = Math.floor(v / 65536);\n t11 = v - c * 65536;\n v = t12 + c + 65535;\n c = Math.floor(v / 65536);\n t12 = v - c * 65536;\n v = t13 + c + 65535;\n c = Math.floor(v / 65536);\n t13 = v - c * 65536;\n v = t14 + c + 65535;\n c = Math.floor(v / 65536);\n t14 = v - c * 65536;\n v = t15 + c + 65535;\n c = Math.floor(v / 65536);\n t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n // second car\n c = 1;\n v = t0 + c + 65535;\n c = Math.floor(v / 65536);\n t0 = v - c * 65536;\n v = t1 + c + 65535;\n c = Math.floor(v / 65536);\n t1 = v - c * 65536;\n v = t2 + c + 65535;\n c = Math.floor(v / 65536);\n t2 = v - c * 65536;\n v = t3 + c + 65535;\n c = Math.floor(v / 65536);\n t3 = v - c * 65536;\n v = t4 + c + 65535;\n c = Math.floor(v / 65536);\n t4 = v - c * 65536;\n v = t5 + c + 65535;\n c = Math.floor(v / 65536);\n t5 = v - c * 65536;\n v = t6 + c + 65535;\n c = Math.floor(v / 65536);\n t6 = v - c * 65536;\n v = t7 + c + 65535;\n c = Math.floor(v / 65536);\n t7 = v - c * 65536;\n v = t8 + c + 65535;\n c = Math.floor(v / 65536);\n t8 = v - c * 65536;\n v = t9 + c + 65535;\n c = Math.floor(v / 65536);\n t9 = v - c * 65536;\n v = t10 + c + 65535;\n c = Math.floor(v / 65536);\n t10 = v - c * 65536;\n v = t11 + c + 65535;\n c = Math.floor(v / 65536);\n t11 = v - c * 65536;\n v = t12 + c + 65535;\n c = Math.floor(v / 65536);\n t12 = v - c * 65536;\n v = t13 + c + 65535;\n c = Math.floor(v / 65536);\n t13 = v - c * 65536;\n v = t14 + c + 65535;\n c = Math.floor(v / 65536);\n t14 = v - c * 65536;\n v = t15 + c + 65535;\n c = Math.floor(v / 65536);\n t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\nfunction square(o, a) {\n mul(o, a, a);\n}\nfunction inv25519(o, i) {\n const c = gf();\n let a;\n for (a = 0; a < 16; a++) {\n c[a] = i[a];\n }\n for (a = 253; a >= 0; a--) {\n square(c, c);\n if (a !== 2 && a !== 4) {\n mul(c, c, i);\n }\n }\n for (a = 0; a < 16; a++) {\n o[a] = c[a];\n }\n}\nfunction pow2523(o, i) {\n const c = gf();\n let a;\n for (a = 0; a < 16; a++) {\n c[a] = i[a];\n }\n for (a = 250; a >= 0; a--) {\n square(c, c);\n if (a !== 1) {\n mul(c, c, i);\n }\n }\n for (a = 0; a < 16; a++) {\n o[a] = c[a];\n }\n}\nfunction edadd(p, q) {\n const a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf();\n sub(a, p[1], p[0]);\n sub(t, q[1], q[0]);\n mul(a, a, t);\n add(b, p[0], p[1]);\n add(t, q[0], q[1]);\n mul(b, b, t);\n mul(c, p[3], q[3]);\n mul(c, c, D2);\n mul(d, p[2], q[2]);\n add(d, d, d);\n sub(e, b, a);\n sub(f, d, c);\n add(g, d, c);\n add(h, b, a);\n mul(p[0], e, f);\n mul(p[1], h, g);\n mul(p[2], g, f);\n mul(p[3], e, h);\n}\nfunction cswap(p, q, b) {\n for (let i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\nfunction pack(r, p) {\n const tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n mul(tx, p[0], zi);\n mul(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\nfunction scalarmult(p, q, s) {\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (let i = 255; i >= 0; --i) {\n const b = (s[(i / 8) | 0] >> (i & 7)) & 1;\n cswap(p, q, b);\n edadd(q, p);\n edadd(p, p);\n cswap(p, q, b);\n }\n}\nfunction scalarbase(p, s) {\n const q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n mul(q[3], X, Y);\n scalarmult(p, q, s);\n}\n// Generates key pair from secret 32-byte seed.\nfunction generateKeyPairFromSeed(seed) {\n if (seed.length !== exports.SEED_LENGTH) {\n throw new Error(`ed25519: seed must be ${exports.SEED_LENGTH} bytes`);\n }\n const d = (0, sha512_1.hash)(seed);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n const publicKey = new Uint8Array(32);\n const p = [gf(), gf(), gf(), gf()];\n scalarbase(p, d);\n pack(publicKey, p);\n const secretKey = new Uint8Array(64);\n secretKey.set(seed);\n secretKey.set(publicKey, 32);\n return {\n publicKey,\n secretKey\n };\n}\nexports.generateKeyPairFromSeed = generateKeyPairFromSeed;\nfunction generateKeyPair(prng) {\n const seed = (0, random_1.randomBytes)(32, prng);\n const result = generateKeyPairFromSeed(seed);\n (0, wipe_1.wipe)(seed);\n return result;\n}\nexports.generateKeyPair = generateKeyPair;\nfunction extractPublicKeyFromSecretKey(secretKey) {\n if (secretKey.length !== exports.SECRET_KEY_LENGTH) {\n throw new Error(`ed25519: secret key must be ${exports.SECRET_KEY_LENGTH} bytes`);\n }\n return new Uint8Array(secretKey.subarray(32));\n}\nexports.extractPublicKeyFromSecretKey = extractPublicKeyFromSecretKey;\nconst L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2,\n 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10\n]);\nfunction modL(r, x) {\n let carry;\n let i;\n let j;\n let k;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) {\n x[j] -= carry * L[j];\n }\n for (i = 0; i < 32; i++) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\nfunction reduce(r) {\n const x = new Float64Array(64);\n for (let i = 0; i < 64; i++) {\n x[i] = r[i];\n }\n for (let i = 0; i < 64; i++) {\n r[i] = 0;\n }\n modL(r, x);\n}\n// Returns 64-byte signature of the message under the 64-byte secret key.\nfunction sign(secretKey, message) {\n const x = new Float64Array(64);\n const p = [gf(), gf(), gf(), gf()];\n const d = (0, sha512_1.hash)(secretKey.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n const signature = new Uint8Array(64);\n signature.set(d.subarray(32), 32);\n const hs = new sha512_1.SHA512();\n hs.update(signature.subarray(32));\n hs.update(message);\n const r = hs.digest();\n hs.clean();\n reduce(r);\n scalarbase(p, r);\n pack(signature, p);\n hs.reset();\n hs.update(signature.subarray(0, 32));\n hs.update(secretKey.subarray(32));\n hs.update(message);\n const h = hs.digest();\n reduce(h);\n for (let i = 0; i < 32; i++) {\n x[i] = r[i];\n }\n for (let i = 0; i < 32; i++) {\n for (let j = 0; j < 32; j++) {\n x[i + j] += h[i] * d[j];\n }\n }\n modL(signature.subarray(32), x);\n return signature;\n}\nexports.sign = sign;\nfunction unpackneg(r, p) {\n const t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n square(num, r[1]);\n mul(den, num, D);\n sub(num, num, r[2]);\n add(den, r[2], den);\n square(den2, den);\n square(den4, den2);\n mul(den6, den4, den2);\n mul(t, den6, num);\n mul(t, t, den);\n pow2523(t, t);\n mul(t, t, num);\n mul(t, t, den);\n mul(t, t, den);\n mul(r[0], t, den);\n square(chk, r[0]);\n mul(chk, chk, den);\n if (neq25519(chk, num)) {\n mul(r[0], r[0], I);\n }\n square(chk, r[0]);\n mul(chk, chk, den);\n if (neq25519(chk, num)) {\n return -1;\n }\n if (par25519(r[0]) === (p[31] >> 7)) {\n sub(r[0], gf0, r[0]);\n }\n mul(r[3], r[0], r[1]);\n return 0;\n}\nfunction verify(publicKey, message, signature) {\n const t = new Uint8Array(32);\n const p = [gf(), gf(), gf(), gf()];\n const q = [gf(), gf(), gf(), gf()];\n if (signature.length !== exports.SIGNATURE_LENGTH) {\n throw new Error(`ed25519: signature must be ${exports.SIGNATURE_LENGTH} bytes`);\n }\n if (unpackneg(q, publicKey)) {\n return false;\n }\n const hs = new sha512_1.SHA512();\n hs.update(signature.subarray(0, 32));\n hs.update(publicKey);\n hs.update(message);\n const h = hs.digest();\n reduce(h);\n scalarmult(p, q, h);\n scalarbase(q, signature.subarray(32));\n edadd(p, q);\n pack(t, p);\n if (verify32(signature, t)) {\n return false;\n }\n return true;\n}\nexports.verify = verify;\n/**\n * Convert Ed25519 public key to X25519 public key.\n *\n * Throws if given an invalid public key.\n */\nfunction convertPublicKeyToX25519(publicKey) {\n let q = [gf(), gf(), gf(), gf()];\n if (unpackneg(q, publicKey)) {\n throw new Error(\"Ed25519: invalid public key\");\n }\n // Formula: montgomeryX = (edwardsY + 1)*inverse(1 - edwardsY) mod p\n let a = gf();\n let b = gf();\n let y = q[1];\n add(a, gf1, y);\n sub(b, gf1, y);\n inv25519(b, b);\n mul(a, a, b);\n let z = new Uint8Array(32);\n pack25519(z, a);\n return z;\n}\nexports.convertPublicKeyToX25519 = convertPublicKeyToX25519;\n/**\n * Convert Ed25519 secret (private) key to X25519 secret key.\n */\nfunction convertSecretKeyToX25519(secretKey) {\n const d = (0, sha512_1.hash)(secretKey.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n const o = new Uint8Array(d.subarray(0, 32));\n (0, wipe_1.wipe)(d);\n return o;\n}\nexports.convertSecretKeyToX25519 = convertSecretKeyToX25519;\n//# sourceMappingURL=ed25519.js.map","export const JWT_IRIDIUM_ALG = \"EdDSA\";\nexport const JWT_IRIDIUM_TYP = \"JWT\";\nexport const JWT_DELIMITER = \".\";\nexport const JWT_ENCODING = \"base64url\";\nexport const JSON_ENCODING = \"utf8\";\nexport const DATA_ENCODING = \"utf8\";\nexport const DID_DELIMITER = \":\";\nexport const DID_PREFIX = \"did\";\nexport const DID_METHOD = \"key\";\nexport const MULTICODEC_ED25519_ENCODING = \"base58btc\";\nexport const MULTICODEC_ED25519_BASE = \"z\";\nexport const MULTICODEC_ED25519_HEADER = \"K36\";\nexport const MULTICODEC_ED25519_LENGTH = 32;\nexport const KEY_PAIR_SEED_LENGTH = 32;\n//# sourceMappingURL=constants.js.map","export function asUint8Array(buf) {\n if (globalThis.Buffer != null) {\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n }\n return buf;\n}","import { asUint8Array } from './util/as-uint8array.js';\nexport function alloc(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.alloc != null) {\n return asUint8Array(globalThis.Buffer.alloc(size));\n }\n return new Uint8Array(size);\n}\nexport function allocUnsafe(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) {\n return asUint8Array(globalThis.Buffer.allocUnsafe(size));\n }\n return new Uint8Array(size);\n}","import { allocUnsafe } from './alloc.js';\nimport { asUint8Array } from './util/as-uint8array.js';\nexport function concat(arrays, length) {\n if (!length) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = allocUnsafe(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return asUint8Array(output);\n}","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '../alloc.js';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: { decode }\n };\n}\nconst string = createCodec('utf8', 'u', buf => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, str => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', buf => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, str => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii: ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;","import bases from './util/bases.js';\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (!base) {\n throw new Error(`Unsupported encoding \"${ encoding }\"`);\n }\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');\n }\n return base.encoder.encode(array).substring(1);\n}","import bases from './util/bases.js';\nimport { asUint8Array } from './util/as-uint8array.js';\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (!base) {\n throw new Error(`Unsupported encoding \"${ encoding }\"`);\n }\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));\n }\n return base.decoder.decode(`${ base.prefix }${ string }`);\n}","const JSONStringify = data => JSON.stringify(data, (_, value) => typeof value === \"bigint\" ? value.toString() + \"n\" : value);\nconst JSONParse = json => {\n const numbersBiggerThanMaxInt = /([\\[:])?(\\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;\n const serializedData = json.replace(numbersBiggerThanMaxInt, \"$1\\\"$2n\\\"$3\");\n return JSON.parse(serializedData, (_, value) => {\n const isCustomFormatBigInt = typeof value === \"string\" && value.match(/^\\d+n$/);\n if (isCustomFormatBigInt)\n return BigInt(value.substring(0, value.length - 1));\n return value;\n });\n};\nexport function safeJsonParse(value) {\n if (typeof value !== \"string\") {\n throw new Error(`Cannot safe json parse value of type ${typeof value}`);\n }\n try {\n return JSONParse(value);\n }\n catch (_a) {\n return value;\n }\n}\nexport function safeJsonStringify(value) {\n return typeof value === \"string\" ? value : JSONStringify(value) || \"\";\n}\n//# sourceMappingURL=index.js.map","import { concat } from \"uint8arrays/concat\";\nimport { toString } from \"uint8arrays/to-string\";\nimport { fromString } from \"uint8arrays/from-string\";\nimport { safeJsonParse, safeJsonStringify } from \"@walletconnect/safe-json\";\nimport { DATA_ENCODING, DID_DELIMITER, DID_METHOD, DID_PREFIX, JSON_ENCODING, JWT_DELIMITER, JWT_ENCODING, MULTICODEC_ED25519_BASE, MULTICODEC_ED25519_ENCODING, MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_LENGTH, } from \"./constants\";\nexport function decodeJSON(str) {\n return safeJsonParse(toString(fromString(str, JWT_ENCODING), JSON_ENCODING));\n}\nexport function encodeJSON(val) {\n return toString(fromString(safeJsonStringify(val), JSON_ENCODING), JWT_ENCODING);\n}\nexport function encodeIss(publicKey) {\n const header = fromString(MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_ENCODING);\n const multicodec = MULTICODEC_ED25519_BASE +\n toString(concat([header, publicKey]), MULTICODEC_ED25519_ENCODING);\n return [DID_PREFIX, DID_METHOD, multicodec].join(DID_DELIMITER);\n}\nexport function decodeIss(issuer) {\n const [prefix, method, multicodec] = issuer.split(DID_DELIMITER);\n if (prefix !== DID_PREFIX || method !== DID_METHOD) {\n throw new Error(`Issuer must be a DID with method \"key\"`);\n }\n const base = multicodec.slice(0, 1);\n if (base !== MULTICODEC_ED25519_BASE) {\n throw new Error(`Issuer must be a key in mulicodec format`);\n }\n const bytes = fromString(multicodec.slice(1), MULTICODEC_ED25519_ENCODING);\n const type = toString(bytes.slice(0, 2), MULTICODEC_ED25519_ENCODING);\n if (type !== MULTICODEC_ED25519_HEADER) {\n throw new Error(`Issuer must be a public key with type \"Ed25519\"`);\n }\n const publicKey = bytes.slice(2);\n if (publicKey.length !== MULTICODEC_ED25519_LENGTH) {\n throw new Error(`Issuer must be a public key with length 32 bytes`);\n }\n return publicKey;\n}\nexport function encodeSig(bytes) {\n return toString(bytes, JWT_ENCODING);\n}\nexport function decodeSig(encoded) {\n return fromString(encoded, JWT_ENCODING);\n}\nexport function encodeData(params) {\n return fromString([encodeJSON(params.header), encodeJSON(params.payload)].join(JWT_DELIMITER), DATA_ENCODING);\n}\nexport function decodeData(data) {\n const params = toString(data, DATA_ENCODING).split(JWT_DELIMITER);\n const header = decodeJSON(params[0]);\n const payload = decodeJSON(params[1]);\n return { header, payload };\n}\nexport function encodeJWT(params) {\n return [\n encodeJSON(params.header),\n encodeJSON(params.payload),\n encodeSig(params.signature),\n ].join(JWT_DELIMITER);\n}\nexport function decodeJWT(jwt) {\n const params = jwt.split(JWT_DELIMITER);\n const header = decodeJSON(params[0]);\n const payload = decodeJSON(params[1]);\n const signature = decodeSig(params[2]);\n const data = fromString(params.slice(0, 2).join(JWT_DELIMITER), DATA_ENCODING);\n return { header, payload, signature, data };\n}\n//# sourceMappingURL=utils.js.map","import * as ed25519 from \"@stablelib/ed25519\";\nimport { randomBytes } from \"@stablelib/random\";\nimport { fromMiliseconds } from \"@walletconnect/time\";\nimport { JWT_IRIDIUM_ALG, JWT_IRIDIUM_TYP, KEY_PAIR_SEED_LENGTH, } from \"./constants\";\nimport { decodeIss, decodeJWT, encodeData, encodeIss, encodeJWT, } from \"./utils\";\nexport function generateKeyPair(seed = randomBytes(KEY_PAIR_SEED_LENGTH)) {\n return ed25519.generateKeyPairFromSeed(seed);\n}\nexport async function signJWT(sub, aud, ttl, keyPair, iat = fromMiliseconds(Date.now())) {\n const header = { alg: JWT_IRIDIUM_ALG, typ: JWT_IRIDIUM_TYP };\n const iss = encodeIss(keyPair.publicKey);\n const exp = iat + ttl;\n const payload = { iss, sub, aud, iat, exp };\n const data = encodeData({ header, payload });\n const signature = ed25519.sign(keyPair.secretKey, data);\n return encodeJWT({ header, payload, signature });\n}\nexport async function verifyJWT(jwt) {\n const { header, payload, data, signature } = decodeJWT(jwt);\n if (header.alg !== JWT_IRIDIUM_ALG || header.typ !== JWT_IRIDIUM_TYP) {\n throw new Error(\"JWT must use EdDSA algorithm\");\n }\n const publicKey = decodeIss(payload.iss);\n return ed25519.verify(publicKey, data, signature);\n}\n//# sourceMappingURL=api.js.map","function e(s,r,i=\"string\"){if(!s[r]||typeof s[r]!==i)throw new Error(`Missing or invalid \"${r}\" param`)}function l(s,r){let i=!0;return r.forEach(t=>{t in s||(i=!1)}),i}function f(s,r){return Array.isArray(s)?s.length===r:Object.keys(s).length===r}function w(s,r){return Array.isArray(s)?s.length>=r:Object.keys(s).length>=r}function u(s,r,i){return(i.length?w(s,r.length):f(s,r.length))?l(s,r):!1}function n(s,r,i=\"_\"){const t=s.split(i);return t[t.length-1].trim().toLowerCase()===r.trim().toLowerCase()}function R(s){return b(s.method)&&a(s.params)}function b(s){return n(s,\"subscribe\")}function a(s){return u(s,[\"topic\"],[])}function P(s){return c(s.method)&&h(s.params)}function c(s){return n(s,\"publish\")}function h(s){return u(s,[\"message\",\"topic\",\"ttl\"],[\"prompt\",\"tag\"])}function _(s){return o(s.method)&&p(s.params)}function o(s){return n(s,\"unsubscribe\")}function p(s){return u(s,[\"id\",\"topic\"],[])}function S(s){return m(s.method)&&d(s.params)}function m(s){return n(s,\"subscription\")}function d(s){return u(s,[\"id\",\"data\"],[])}function g(s){if(!b(s.method))throw new Error(\"JSON-RPC Request has invalid subscribe method\");if(!a(s.params))throw new Error(\"JSON-RPC Request has invalid subscribe params\");const r=s.params;return e(r,\"topic\"),r}function q(s){if(!c(s.method))throw new Error(\"JSON-RPC Request has invalid publish method\");if(!h(s.params))throw new Error(\"JSON-RPC Request has invalid publish params\");const r=s.params;return e(r,\"topic\"),e(r,\"message\"),e(r,\"ttl\",\"number\"),r}function E(s){if(!o(s.method))throw new Error(\"JSON-RPC Request has invalid unsubscribe method\");if(!p(s.params))throw new Error(\"JSON-RPC Request has invalid unsubscribe params\");const r=s.params;return e(r,\"id\"),r}function k(s){if(!m(s.method))throw new Error(\"JSON-RPC Request has invalid subscription method\");if(!d(s.params))throw new Error(\"JSON-RPC Request has invalid subscription params\");const r=s.params;return e(r,\"id\"),e(r,\"data\"),r}const C={waku:{publish:\"waku_publish\",batchPublish:\"waku_batchPublish\",subscribe:\"waku_subscribe\",batchSubscribe:\"waku_batchSubscribe\",subscription:\"waku_subscription\",unsubscribe:\"waku_unsubscribe\",batchUnsubscribe:\"waku_batchUnsubscribe\",batchFetchMessages:\"waku_batchFetchMessages\"},irn:{publish:\"irn_publish\",batchPublish:\"irn_batchPublish\",subscribe:\"irn_subscribe\",batchSubscribe:\"irn_batchSubscribe\",subscription:\"irn_subscription\",unsubscribe:\"irn_unsubscribe\",batchUnsubscribe:\"irn_batchUnsubscribe\",batchFetchMessages:\"irn_batchFetchMessages\"},iridium:{publish:\"iridium_publish\",batchPublish:\"iridium_batchPublish\",subscribe:\"iridium_subscribe\",batchSubscribe:\"iridium_batchSubscribe\",subscription:\"iridium_subscription\",unsubscribe:\"iridium_unsubscribe\",batchUnsubscribe:\"iridium_batchUnsubscribe\",batchFetchMessages:\"iridium_batchFetchMessages\"}};export{C as RELAY_JSONRPC,c as isPublishMethod,h as isPublishParams,P as isPublishRequest,b as isSubscribeMethod,a as isSubscribeParams,R as isSubscribeRequest,m as isSubscriptionMethod,d as isSubscriptionParams,S as isSubscriptionRequest,o as isUnsubscribeMethod,p as isUnsubscribeParams,_ as isUnsubscribeRequest,q as parsePublishRequest,g as parseSubscribeRequest,k as parseSubscriptionRequest,E as parseUnsubscribeRequest};\n//# sourceMappingURL=index.es.js.map\n","import{detect as ot}from\"detect-browser\";import{toMiliseconds as ee,FIVE_MINUTES as Ie,fromMiliseconds as st}from\"@walletconnect/time\";import{getDocument as ne,getNavigator as je,getLocation as Te}from\"@walletconnect/window-getters\";import{getWindowMetadata as it}from\"@walletconnect/window-metadata\";import*as q from\"query-string\";import{hashMessage as Pe}from\"@ethersproject/hash\";import{recoverAddress as ct}from\"@ethersproject/transactions\";import{ChaCha20Poly1305 as Ae}from\"@stablelib/chacha20poly1305\";import{HKDF as at}from\"@stablelib/hkdf\";import{randomBytes as B}from\"@stablelib/random\";import{SHA256 as Ce,hash as Ue}from\"@stablelib/sha256\";import*as _e from\"@stablelib/x25519\";import{toString as v,fromString as w,concat as te}from\"uint8arrays\";import{ec as ut}from\"elliptic\";import{decodeJWT as lt}from\"@walletconnect/relay-auth\";import{RELAY_JSONRPC as dt}from\"@walletconnect/relay-api\";const H=\":\";function re(e){const[n,t]=e.split(H);return{namespace:n,reference:t}}function ke(e){const{namespace:n,reference:t}=e;return[n,t].join(H)}function oe(e){const[n,t,r]=e.split(H);return{namespace:n,reference:t,address:r}}function De(e){const{namespace:n,reference:t,address:r}=e;return[n,t,r].join(H)}function se(e,n){const t=[];return e.forEach(r=>{const o=n(r);t.includes(o)||t.push(o)}),t}function xe(e){const{address:n}=oe(e);return n}function Ve(e){const{namespace:n,reference:t}=oe(e);return ke({namespace:n,reference:t})}function ft(e,n){const{namespace:t,reference:r}=re(n);return De({namespace:t,reference:r,address:e})}function pt(e){return se(e,xe)}function Me(e){return se(e,Ve)}function mt(e,n=[]){const t=[];return Object.keys(e).forEach(r=>{if(n.length&&!n.includes(r))return;const o=e[r];t.push(...o.accounts)}),t}function ht(e,n=[]){const t=[];return Object.keys(e).forEach(r=>{if(n.length&&!n.includes(r))return;const o=e[r];t.push(...Me(o.accounts))}),t}function yt(e,n=[]){const t=[];return Object.keys(e).forEach(r=>{if(n.length&&!n.includes(r))return;const o=e[r];t.push(...W(r,o))}),t}function W(e,n){return e.includes(\":\")?[e]:n.chains||[]}var gt=Object.defineProperty,Ke=Object.getOwnPropertySymbols,vt=Object.prototype.hasOwnProperty,bt=Object.prototype.propertyIsEnumerable,Le=(e,n,t)=>n in e?gt(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,Fe=(e,n)=>{for(var t in n||(n={}))vt.call(n,t)&&Le(e,t,n[t]);if(Ke)for(var t of Ke(n))bt.call(n,t)&&Le(e,t,n[t]);return e};const qe=\"ReactNative\",y={reactNative:\"react-native\",node:\"node\",browser:\"browser\",unknown:\"unknown\"},J=\" \",Et=\":\",Be=\"/\",ie=2,wt=1e3,He=\"js\";function ce(){return typeof process<\"u\"&&typeof process.versions<\"u\"&&typeof process.versions.node<\"u\"}function _(){return!ne()&&!!je()&&navigator.product===qe}function V(){return!ce()&&!!je()&&!!ne()}function P(){return _()?y.reactNative:ce()?y.node:V()?y.browser:y.unknown}function Ot(){var e;try{return _()&&typeof global<\"u\"&&typeof(global==null?void 0:global.Application)<\"u\"?(e=global.Application)==null?void 0:e.applicationId:void 0}catch{return}}function We(e,n){let t=q.parse(e);return t=Fe(Fe({},t),n),e=q.stringify(t),e}function Nt(){return it()||{name:\"\",description:\"\",url:\"\",icons:[\"\"]}}function St(e,n){var t;const r=P(),o={protocol:e,version:n,env:r};return r===\"browser\"&&(o.host=((t=Te())==null?void 0:t.host)||\"unknown\"),o}function Je(){if(P()===y.reactNative&&typeof global<\"u\"&&typeof(global==null?void 0:global.Platform)<\"u\"){const{OS:t,Version:r}=global.Platform;return[t,r].join(\"-\")}const e=ot();if(e===null)return\"unknown\";const n=e.os?e.os.replace(\" \",\"\").toLowerCase():\"unknown\";return e.type===\"browser\"?[n,e.name,e.version].join(\"-\"):[n,e.version].join(\"-\")}function ze(){var e;const n=P();return n===y.browser?[n,((e=Te())==null?void 0:e.host)||\"unknown\"].join(\":\"):n}function Ge(e,n,t){const r=Je(),o=ze();return[[e,n].join(\"-\"),[He,t].join(\"-\"),r,o].join(\"/\")}function $t({protocol:e,version:n,relayUrl:t,sdkVersion:r,auth:o,projectId:s,useOnCloseEvent:i,bundleId:u}){const l=t.split(\"?\"),c=Ge(e,n,r),d={auth:o,ua:c,projectId:s,useOnCloseEvent:i||void 0,origin:u||void 0},a=We(l[1]||\"\",d);return l[0]+\"?\"+a}function Rt(e){let n=(e.match(/^[^:]+(?=:\\/\\/)/gi)||[])[0];const t=typeof n<\"u\"?e.split(\"://\")[1]:e;return n=n===\"wss\"?\"https\":\"http\",[n,t].join(\"://\")}function It(e,n,t){if(!e[n]||typeof e[n]!==t)throw new Error(`Missing or invalid \"${n}\" param`)}function Ye(e,n=ie){return Qe(e.split(Be),n)}function jt(e){return Ye(e).join(J)}function $(e,n){return e.filter(t=>n.includes(t)).length===e.length}function Qe(e,n=ie){return e.slice(Math.max(e.length-n,0))}function Tt(e){return Object.fromEntries(e.entries())}function Pt(e){return new Map(Object.entries(e))}function At(e,n){const t={};return Object.keys(e).forEach(r=>{t[r]=n(e[r])}),t}const Ct=e=>e;function Ze(e){return e.trim().replace(/^\\w/,n=>n.toUpperCase())}function Ut(e){return e.split(J).map(n=>Ze(n)).join(J)}function _t(e=Ie,n){const t=ee(e||Ie);let r,o,s;return{resolve:i=>{s&&r&&(clearTimeout(s),r(i))},reject:i=>{s&&o&&(clearTimeout(s),o(i))},done:()=>new Promise((i,u)=>{s=setTimeout(()=>{u(new Error(n))},t),r=i,o=u})}}function kt(e,n,t){return new Promise(async(r,o)=>{const s=setTimeout(()=>o(new Error(t)),n);try{const i=await e;r(i)}catch(i){o(i)}clearTimeout(s)})}function ae(e,n){if(typeof n==\"string\"&&n.startsWith(`${e}:`))return n;if(e.toLowerCase()===\"topic\"){if(typeof n!=\"string\")throw new Error('Value must be \"string\" for expirer target type: topic');return`topic:${n}`}else if(e.toLowerCase()===\"id\"){if(typeof n!=\"number\")throw new Error('Value must be \"number\" for expirer target type: id');return`id:${n}`}throw new Error(`Unknown expirer target type: ${e}`)}function Dt(e){return ae(\"topic\",e)}function xt(e){return ae(\"id\",e)}function Vt(e){const[n,t]=e.split(\":\"),r={id:void 0,topic:void 0};if(n===\"topic\"&&typeof t==\"string\")r.topic=t;else if(n===\"id\"&&Number.isInteger(Number(t)))r.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${n}:${t}`);return r}function Mt(e,n){return st((n||Date.now())+ee(e))}function Kt(e){return Date.now()>=ee(e)}function Lt(e,n){return`${e}${n?`:${n}`:\"\"}`}function N(e=[],n=[]){return[...new Set([...e,...n])]}async function Ft({id:e,topic:n,wcDeepLink:t}){var r;try{if(!t)return;const o=typeof t==\"string\"?JSON.parse(t):t,s=o?.href;if(typeof s!=\"string\")return;const i=Xe(s,e,n),u=P();if(u===y.browser){if(!((r=ne())!=null&&r.hasFocus())){console.warn(\"Document does not have focus, skipping deeplink.\");return}i.startsWith(\"https://\")||i.startsWith(\"http://\")?window.open(i,\"_blank\",\"noreferrer noopener\"):window.open(i,en()?\"_blank\":\"_self\",\"noreferrer noopener\")}else u===y.reactNative&&typeof(global==null?void 0:global.Linking)<\"u\"&&await global.Linking.openURL(i)}catch(o){console.error(o)}}function Xe(e,n,t){const r=`requestId=${n}&sessionTopic=${t}`;e.endsWith(\"/\")&&(e=e.slice(0,-1));let o=`${e}`;if(e.startsWith(\"https://t.me\")){const s=e.includes(\"?\")?\"&startapp=\":\"?startapp=\";o=`${o}${s}${nn(r,!0)}`}else o=`${o}/wc?${r}`;return o}async function qt(e,n){let t=\"\";try{if(V()&&(t=localStorage.getItem(n),t))return t;t=await e.getItem(n)}catch(r){console.error(r)}return t}function ue(e,n){return e.filter(t=>n.includes(t))}function Bt(e,n){if(!e.includes(n))return null;const t=e.split(/([&,?,=])/),r=t.indexOf(n);return t[r+2]}function Ht(){return typeof crypto<\"u\"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():\"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/gu,e=>{const n=Math.random()*16|0;return(e===\"x\"?n:n&3|8).toString(16)})}function Wt(){return typeof process<\"u\"&&process.env.IS_VITEST===\"true\"}function en(){return typeof window<\"u\"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function nn(e,n=!1){const t=Buffer.from(e).toString(\"base64\");return n?t.replace(/[=]/g,\"\"):t}function le(e){return Buffer.from(e,\"base64\").toString(\"utf-8\")}const Jt=\"https://rpc.walletconnect.org/v1\";async function tn(e,n,t,r,o,s){switch(t.t){case\"eip191\":return rn(e,n,t.s);case\"eip1271\":return await on(e,n,t.s,r,o,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}function rn(e,n,t){return ct(Pe(n),t).toLowerCase()===e.toLowerCase()}async function on(e,n,t,r,o,s){const i=re(r);if(!i.namespace||!i.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const u=\"0x1626ba7e\",l=\"0000000000000000000000000000000000000000000000000000000000000040\",c=\"0000000000000000000000000000000000000000000000000000000000000041\",d=t.substring(2),a=Pe(n).substring(2),f=u+a+l+c+d,h=await fetch(`${s||Jt}/?chainId=${r}&projectId=${o}`,{method:\"POST\",body:JSON.stringify({id:zt(),jsonrpc:\"2.0\",method:\"eth_call\",params:[{to:e,data:f},\"latest\"]})}),{result:p}=await h.json();return p?p.slice(0,u.length).toLowerCase()===u.toLowerCase():!1}catch(u){return console.error(\"isValidEip1271Signature: \",u),!1}}function zt(){return Date.now()+Math.floor(Math.random()*1e3)}var Gt=Object.defineProperty,Yt=Object.defineProperties,Qt=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,Zt=Object.prototype.hasOwnProperty,Xt=Object.prototype.propertyIsEnumerable,cn=(e,n,t)=>n in e?Gt(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,de=(e,n)=>{for(var t in n||(n={}))Zt.call(n,t)&&cn(e,t,n[t]);if(sn)for(var t of sn(n))Xt.call(n,t)&&cn(e,t,n[t]);return e},an=(e,n)=>Yt(e,Qt(n));const er=\"did:pkh:\",z=e=>e?.split(\":\"),un=e=>{const n=e&&z(e);if(n)return e.includes(er)?n[3]:n[1]},ln=e=>{const n=e&&z(e);if(n)return n[2]+\":\"+n[3]},fe=e=>{const n=e&&z(e);if(n)return n.pop()};async function nr(e){const{cacao:n,projectId:t}=e,{s:r,p:o}=n,s=dn(o,o.iss),i=fe(o.iss);return await tn(i,s,r,ln(o.iss),t)}const dn=(e,n)=>{const t=`${e.domain} wants you to sign in with your Ethereum account:`,r=fe(n);if(!e.aud&&!e.uri)throw new Error(\"Either `aud` or `uri` is required to construct the message\");let o=e.statement||void 0;const s=`URI: ${e.aud||e.uri}`,i=`Version: ${e.version}`,u=`Chain ID: ${un(n)}`,l=`Nonce: ${e.nonce}`,c=`Issued At: ${e.iat}`,d=e.exp?`Expiration Time: ${e.exp}`:void 0,a=e.nbf?`Not Before: ${e.nbf}`:void 0,f=e.requestId?`Request ID: ${e.requestId}`:void 0,h=e.resources?`Resources:${e.resources.map(m=>`\n- ${m}`).join(\"\")}`:void 0,p=Y(e.resources);if(p){const m=R(p);o=he(o,m)}return[t,r,\"\",o,\"\",s,i,u,l,c,d,a,f,h].filter(m=>m!=null).join(`\n`)};function tr(e,n,t){return t.includes(\"did:pkh:\")||(t=`did:pkh:${t}`),{h:{t:\"caip122\"},p:{iss:t,domain:e.domain,aud:e.aud,version:e.version,nonce:e.nonce,iat:e.iat,statement:e.statement,requestId:e.requestId,resources:e.resources,nbf:e.nbf,exp:e.exp},s:n}}function rr(e){var n;const{authPayload:t,chains:r,methods:o}=e,s=t.statement||\"\";if(!(r!=null&&r.length))return t;const i=t.chains,u=ue(i,r);if(!(u!=null&&u.length))throw new Error(\"No supported chains\");const l=fn(t.resources);if(!l)return t;O(l);const c=pn(l,\"eip155\");let d=t?.resources||[];if(c!=null&&c.length){const a=mn(c),f=ue(a,o);if(!(f!=null&&f.length))throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(a)}, supported: ${JSON.stringify(o)}`);const h=pe(\"request\",f,{chains:u}),p=vn(l,\"eip155\",h);d=((n=t?.resources)==null?void 0:n.slice(0,-1))||[],d.push(G(p))}return an(de({},t),{statement:En(s,Y(d)),chains:u,resources:t!=null&&t.resources||d.length>0?d:void 0})}function fn(e){const n=Y(e);if(n&&me(n))return R(n)}function or(e,n){var t;return(t=e?.att)==null?void 0:t.hasOwnProperty(n)}function pn(e,n){var t,r;return(t=e?.att)!=null&&t[n]?Object.keys((r=e?.att)==null?void 0:r[n]):[]}function sr(e){return e?.map(n=>Object.keys(n))||[]}function mn(e){return e?.map(n=>{var t;return(t=n.split(\"/\"))==null?void 0:t[1]})||[]}function hn(e){return Buffer.from(JSON.stringify(e)).toString(\"base64\")}function yn(e){return JSON.parse(Buffer.from(e,\"base64\").toString(\"utf-8\"))}function O(e){if(!e)throw new Error(\"No recap provided, value is undefined\");if(!e.att)throw new Error(\"No `att` property found\");const n=Object.keys(e.att);if(!(n!=null&&n.length))throw new Error(\"No resources found in `att` property\");n.forEach(t=>{const r=e.att[t];if(Array.isArray(r))throw new Error(`Resource must be an object: ${t}`);if(typeof r!=\"object\")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(r).forEach(o=>{const s=r[o];if(!Array.isArray(s))throw new Error(`Ability limits ${o} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${o} is empty array, must be an array with objects`);s.forEach(i=>{if(typeof i!=\"object\")throw new Error(`Ability limits (${o}) must be an array of objects, found: ${i}`)})})})}function gn(e,n,t,r={}){return t?.sort((o,s)=>o.localeCompare(s)),{att:{[e]:pe(n,t,r)}}}function vn(e,n,t){var r;return e.att[n]=de({},t),((r=Object.keys(e.att))==null?void 0:r.sort((o,s)=>o.localeCompare(s))).reduce((o,s)=>(o.att[s]=e.att[s],o),{att:{}})}function pe(e,n,t={}){n=n?.sort((o,s)=>o.localeCompare(s));const r=n.map(o=>({[`${e}/${o}`]:[t]}));return Object.assign({},...r)}function G(e){return O(e),`urn:recap:${hn(e).replace(/=/g,\"\")}`}function R(e){const n=yn(e.replace(\"urn:recap:\",\"\"));return O(n),n}function ir(e,n,t){const r=gn(e,n,t);return G(r)}function me(e){return e&&e.includes(\"urn:recap:\")}function cr(e,n){const t=R(e),r=R(n),o=bn(t,r);return G(o)}function bn(e,n){O(e),O(n);const t=Object.keys(e.att).concat(Object.keys(n.att)).sort((o,s)=>o.localeCompare(s)),r={att:{}};return t.forEach(o=>{var s,i;Object.keys(((s=e.att)==null?void 0:s[o])||{}).concat(Object.keys(((i=n.att)==null?void 0:i[o])||{})).sort((u,l)=>u.localeCompare(l)).forEach(u=>{var l,c;r.att[o]=an(de({},r.att[o]),{[u]:((l=e.att[o])==null?void 0:l[u])||((c=n.att[o])==null?void 0:c[u])})})}),r}function he(e=\"\",n){O(n);const t=\"I further authorize the stated URI to perform the following actions on my behalf: \";if(e.includes(t))return e;const r=[];let o=0;Object.keys(n.att).forEach(u=>{const l=Object.keys(n.att[u]).map(a=>({ability:a.split(\"/\")[0],action:a.split(\"/\")[1]}));l.sort((a,f)=>a.action.localeCompare(f.action));const c={};l.forEach(a=>{c[a.ability]||(c[a.ability]=[]),c[a.ability].push(a.action)});const d=Object.keys(c).map(a=>(o++,`(${o}) '${a}': '${c[a].join(\"', '\")}' for '${u}'.`));r.push(d.join(\", \").replace(\".,\",\".\"))});const s=r.join(\" \"),i=`${t}${s}`;return`${e?e+\" \":\"\"}${i}`}function ar(e){var n;const t=R(e);O(t);const r=(n=t.att)==null?void 0:n.eip155;return r?Object.keys(r).map(o=>o.split(\"/\")[1]):[]}function ur(e){const n=R(e);O(n);const t=[];return Object.values(n.att).forEach(r=>{Object.values(r).forEach(o=>{var s;(s=o?.[0])!=null&&s.chains&&t.push(o[0].chains)})}),[...new Set(t.flat())]}function En(e,n){if(!n)return e;const t=R(n);return O(t),he(e,t)}function Y(e){if(!e)return;const n=e?.[e.length-1];return me(n)?n:void 0}const ye=\"base10\",g=\"base16\",ge=\"base64pad\",lr=\"base64url\",k=\"utf8\",ve=0,D=1,M=2,dr=0,wn=1,K=12,be=32;function fr(){const e=_e.generateKeyPair();return{privateKey:v(e.secretKey,g),publicKey:v(e.publicKey,g)}}function pr(){const e=B(be);return v(e,g)}function mr(e,n){const t=_e.sharedKey(w(e,g),w(n,g),!0),r=new at(Ce,t).expand(be);return v(r,g)}function hr(e){const n=Ue(w(e,g));return v(n,g)}function yr(e){const n=Ue(w(e,k));return v(n,g)}function Ee(e){return w(`${e}`,ye)}function A(e){return Number(v(e,ye))}function gr(e){const n=Ee(typeof e.type<\"u\"?e.type:ve);if(A(n)===D&&typeof e.senderPublicKey>\"u\")throw new Error(\"Missing sender public key for type 1 envelope\");const t=typeof e.senderPublicKey<\"u\"?w(e.senderPublicKey,g):void 0,r=typeof e.iv<\"u\"?w(e.iv,g):B(K),o=new Ae(w(e.symKey,g)).seal(r,w(e.message,k));return we({type:n,sealed:o,iv:r,senderPublicKey:t,encoding:e.encoding})}function vr(e,n){const t=Ee(M),r=B(K),o=w(e,k);return we({type:t,sealed:o,iv:r,encoding:n})}function br(e){const n=new Ae(w(e.symKey,g)),{sealed:t,iv:r}=Q({encoded:e.encoded,encoding:e?.encoding}),o=n.open(r,t);if(o===null)throw new Error(\"Failed to decrypt\");return v(o,k)}function Er(e,n){const{sealed:t}=Q({encoded:e,encoding:n});return v(t,k)}function we(e){const{encoding:n=ge}=e;if(A(e.type)===M)return v(te([e.type,e.sealed]),n);if(A(e.type)===D){if(typeof e.senderPublicKey>\"u\")throw new Error(\"Missing sender public key for type 1 envelope\");return v(te([e.type,e.senderPublicKey,e.iv,e.sealed]),n)}return v(te([e.type,e.iv,e.sealed]),n)}function Q(e){const{encoded:n,encoding:t=ge}=e,r=w(n,t),o=r.slice(dr,wn),s=wn;if(A(o)===D){const c=s+be,d=c+K,a=r.slice(s,c),f=r.slice(c,d),h=r.slice(d);return{type:o,sealed:h,iv:f,senderPublicKey:a}}if(A(o)===M){const c=r.slice(s),d=B(K);return{type:o,sealed:c,iv:d}}const i=s+K,u=r.slice(s,i),l=r.slice(i);return{type:o,sealed:l,iv:u}}function wr(e,n){const t=Q({encoded:e,encoding:n?.encoding});return On({type:A(t.type),senderPublicKey:typeof t.senderPublicKey<\"u\"?v(t.senderPublicKey,g):void 0,receiverPublicKey:n?.receiverPublicKey})}function On(e){const n=e?.type||ve;if(n===D){if(typeof e?.senderPublicKey>\"u\")throw new Error(\"missing sender public key\");if(typeof e?.receiverPublicKey>\"u\")throw new Error(\"missing receiver public key\")}return{type:n,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function Or(e){return e.type===D&&typeof e.senderPublicKey==\"string\"&&typeof e.receiverPublicKey==\"string\"}function Nr(e){return e.type===M}function Nn(e){return new ut(\"p256\").keyFromPublic({x:Buffer.from(e.x,\"base64\").toString(\"hex\"),y:Buffer.from(e.y,\"base64\").toString(\"hex\")},\"hex\")}function Sr(e){let n=e.replace(/-/g,\"+\").replace(/_/g,\"/\");const t=n.length%4;return t>0&&(n+=\"=\".repeat(4-t)),n}function $r(e){return Buffer.from(Sr(e),\"base64\")}function Rr(e,n){const[t,r,o]=e.split(\".\"),s=$r(o);if(s.length!==64)throw new Error(\"Invalid signature length\");const i=s.slice(0,32).toString(\"hex\"),u=s.slice(32,64).toString(\"hex\"),l=`${t}.${r}`,c=new Ce().update(Buffer.from(l)).digest(),d=Nn(n),a=Buffer.from(c).toString(\"hex\");if(!d.verify(a,{r:i,s:u}))throw new Error(\"Invalid signature\");return lt(e).payload}const Sn=\"irn\";function Ir(e){return e?.relay||{protocol:Sn}}function jr(e){const n=dt[e];if(typeof n>\"u\")throw new Error(`Relay Protocol not supported: ${e}`);return n}var Tr=Object.defineProperty,Pr=Object.defineProperties,Ar=Object.getOwnPropertyDescriptors,$n=Object.getOwnPropertySymbols,Cr=Object.prototype.hasOwnProperty,Ur=Object.prototype.propertyIsEnumerable,Rn=(e,n,t)=>n in e?Tr(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,In=(e,n)=>{for(var t in n||(n={}))Cr.call(n,t)&&Rn(e,t,n[t]);if($n)for(var t of $n(n))Ur.call(n,t)&&Rn(e,t,n[t]);return e},_r=(e,n)=>Pr(e,Ar(n));function jn(e,n=\"-\"){const t={},r=\"relay\"+n;return Object.keys(e).forEach(o=>{if(o.startsWith(r)){const s=o.replace(r,\"\"),i=e[o];t[s]=i}}),t}function kr(e){if(!e.includes(\"wc:\")){const l=le(e);l!=null&&l.includes(\"wc:\")&&(e=l)}e=e.includes(\"wc://\")?e.replace(\"wc://\",\"\"):e,e=e.includes(\"wc:\")?e.replace(\"wc:\",\"\"):e;const n=e.indexOf(\":\"),t=e.indexOf(\"?\")!==-1?e.indexOf(\"?\"):void 0,r=e.substring(0,n),o=e.substring(n+1,t).split(\"@\"),s=typeof t<\"u\"?e.substring(t):\"\",i=q.parse(s),u=typeof i.methods==\"string\"?i.methods.split(\",\"):void 0;return{protocol:r,topic:Tn(o[0]),version:parseInt(o[1],10),symKey:i.symKey,relay:jn(i),methods:u,expiryTimestamp:i.expiryTimestamp?parseInt(i.expiryTimestamp,10):void 0}}function Tn(e){return e.startsWith(\"//\")?e.substring(2):e}function Pn(e,n=\"-\"){const t=\"relay\",r={};return Object.keys(e).forEach(o=>{const s=t+n+o;e[o]&&(r[s]=e[o])}),r}function Dr(e){return`${e.protocol}:${e.topic}@${e.version}?`+q.stringify(In(_r(In({symKey:e.symKey},Pn(e.relay)),{expiryTimestamp:e.expiryTimestamp}),e.methods?{methods:e.methods.join(\",\")}:{}))}function xr(e,n,t){return`${e}?wc_ev=${t}&topic=${n}`}var Vr=Object.defineProperty,Mr=Object.defineProperties,Kr=Object.getOwnPropertyDescriptors,An=Object.getOwnPropertySymbols,Lr=Object.prototype.hasOwnProperty,Fr=Object.prototype.propertyIsEnumerable,Cn=(e,n,t)=>n in e?Vr(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,qr=(e,n)=>{for(var t in n||(n={}))Lr.call(n,t)&&Cn(e,t,n[t]);if(An)for(var t of An(n))Fr.call(n,t)&&Cn(e,t,n[t]);return e},Br=(e,n)=>Mr(e,Kr(n));function C(e){const n=[];return e.forEach(t=>{const[r,o]=t.split(\":\");n.push(`${r}:${o}`)}),n}function Un(e){const n=[];return Object.values(e).forEach(t=>{n.push(...C(t.accounts))}),n}function _n(e,n){const t=[];return Object.values(e).forEach(r=>{C(r.accounts).includes(n)&&t.push(...r.methods)}),t}function kn(e,n){const t=[];return Object.values(e).forEach(r=>{C(r.accounts).includes(n)&&t.push(...r.events)}),t}function Hr(e,n){const t=Wn(e,n);if(t)throw new Error(t.message);const r={};for(const[o,s]of Object.entries(e))r[o]={methods:s.methods,events:s.events,chains:s.accounts.map(i=>`${i.split(\":\")[0]}:${i.split(\":\")[1]}`)};return r}function Wr(e){const{proposal:{requiredNamespaces:n,optionalNamespaces:t={}},supportedNamespaces:r}=e,o=Ne(n),s=Ne(t),i={};Object.keys(r).forEach(c=>{const d=r[c].chains,a=r[c].methods,f=r[c].events,h=r[c].accounts;d.forEach(p=>{if(!h.some(m=>m.includes(p)))throw new Error(`No accounts provided for chain ${p} in namespace ${c}`)}),i[c]={chains:d,methods:a,events:f,accounts:h}});const u=zn(n,i,\"approve()\");if(u)throw new Error(u.message);const l={};return!Object.keys(n).length&&!Object.keys(t).length?i:(Object.keys(o).forEach(c=>{const d=r[c].chains.filter(p=>{var m,E;return(E=(m=o[c])==null?void 0:m.chains)==null?void 0:E.includes(p)}),a=r[c].methods.filter(p=>{var m,E;return(E=(m=o[c])==null?void 0:m.methods)==null?void 0:E.includes(p)}),f=r[c].events.filter(p=>{var m,E;return(E=(m=o[c])==null?void 0:m.events)==null?void 0:E.includes(p)}),h=d.map(p=>r[c].accounts.filter(m=>m.includes(`${p}:`))).flat();l[c]={chains:d,methods:a,events:f,accounts:h}}),Object.keys(s).forEach(c=>{var d,a,f,h,p,m;if(!r[c])return;const E=(a=(d=s[c])==null?void 0:d.chains)==null?void 0:a.filter(j=>r[c].chains.includes(j)),nt=r[c].methods.filter(j=>{var T,x;return(x=(T=s[c])==null?void 0:T.methods)==null?void 0:x.includes(j)}),tt=r[c].events.filter(j=>{var T,x;return(x=(T=s[c])==null?void 0:T.events)==null?void 0:x.includes(j)}),rt=E?.map(j=>r[c].accounts.filter(T=>T.includes(`${j}:`))).flat();l[c]={chains:N((f=l[c])==null?void 0:f.chains,E),methods:N((h=l[c])==null?void 0:h.methods,nt),events:N((p=l[c])==null?void 0:p.events,tt),accounts:N((m=l[c])==null?void 0:m.accounts,rt)}}),l)}function Oe(e){return e.includes(\":\")}function Dn(e){return Oe(e)?e.split(\":\")[0]:e}function Ne(e){var n,t,r;const o={};if(!Z(e))return o;for(const[s,i]of Object.entries(e)){const u=Oe(s)?[s]:i.chains,l=i.methods||[],c=i.events||[],d=Dn(s);o[d]=Br(qr({},o[d]),{chains:N(u,(n=o[d])==null?void 0:n.chains),methods:N(l,(t=o[d])==null?void 0:t.methods),events:N(c,(r=o[d])==null?void 0:r.events)})}return o}function xn(e){const n={};return e?.forEach(t=>{const[r,o]=t.split(\":\");n[r]||(n[r]={accounts:[],chains:[],events:[]}),n[r].accounts.push(t),n[r].chains.push(`${r}:${o}`)}),n}function Jr(e,n){n=n.map(r=>r.replace(\"did:pkh:\",\"\"));const t=xn(n);for(const[r,o]of Object.entries(t))o.methods?o.methods=N(o.methods,e):o.methods=e,o.events=[\"chainChanged\",\"accountsChanged\"];return t}const Vn={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}},Mn={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 S(e,n){const{message:t,code:r}=Mn[e];return{message:n?`${t} ${n}`:t,code:r}}function U(e,n){const{message:t,code:r}=Vn[e];return{message:n?`${t} ${n}`:t,code:r}}function L(e,n){return Array.isArray(e)?typeof n<\"u\"&&e.length?e.every(n):!0:!1}function Z(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function I(e){return typeof e>\"u\"}function b(e,n){return n&&I(e)?!0:typeof e==\"string\"&&!!e.trim().length}function X(e,n){return n&&I(e)?!0:typeof e==\"number\"&&!isNaN(e)}function zr(e,n){const{requiredNamespaces:t}=n,r=Object.keys(e.namespaces),o=Object.keys(t);let s=!0;return $(o,r)?(r.forEach(i=>{const{accounts:u,methods:l,events:c}=e.namespaces[i],d=C(u),a=t[i];(!$(W(i,a),d)||!$(a.methods,l)||!$(a.events,c))&&(s=!1)}),s):!1}function F(e){return b(e,!1)&&e.includes(\":\")?e.split(\":\").length===2:!1}function Kn(e){if(b(e,!1)&&e.includes(\":\")){const n=e.split(\":\");if(n.length===3){const t=n[0]+\":\"+n[1];return!!n[2]&&F(t)}}return!1}function Gr(e){function n(t){try{return typeof new URL(t)<\"u\"}catch{return!1}}try{if(b(e,!1)){if(n(e))return!0;const t=le(e);return n(t)}}catch{}return!1}function Yr(e){var n;return(n=e?.proposer)==null?void 0:n.publicKey}function Qr(e){return e?.topic}function Zr(e,n){let t=null;return b(e?.publicKey,!1)||(t=S(\"MISSING_OR_INVALID\",`${n} controller public key should be a string`)),t}function Se(e){let n=!0;return L(e)?e.length&&(n=e.every(t=>b(t,!1))):n=!1,n}function Ln(e,n,t){let r=null;return L(n)&&n.length?n.forEach(o=>{r||F(o)||(r=U(\"UNSUPPORTED_CHAINS\",`${t}, chain ${o} should be a string and conform to \"namespace:chainId\" format`))}):F(e)||(r=U(\"UNSUPPORTED_CHAINS\",`${t}, 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\"] }`)),r}function Fn(e,n,t){let r=null;return Object.entries(e).forEach(([o,s])=>{if(r)return;const i=Ln(o,W(o,s),`${n} ${t}`);i&&(r=i)}),r}function qn(e,n){let t=null;return L(e)?e.forEach(r=>{t||Kn(r)||(t=U(\"UNSUPPORTED_ACCOUNTS\",`${n}, account ${r} should be a string and conform to \"namespace:chainId:address\" format`))}):t=U(\"UNSUPPORTED_ACCOUNTS\",`${n}, accounts should be an array of strings conforming to \"namespace:chainId:address\" format`),t}function Bn(e,n){let t=null;return Object.values(e).forEach(r=>{if(t)return;const o=qn(r?.accounts,`${n} namespace`);o&&(t=o)}),t}function Hn(e,n){let t=null;return Se(e?.methods)?Se(e?.events)||(t=U(\"UNSUPPORTED_EVENTS\",`${n}, events should be an array of strings or empty array for no events`)):t=U(\"UNSUPPORTED_METHODS\",`${n}, methods should be an array of strings or empty array for no methods`),t}function $e(e,n){let t=null;return Object.values(e).forEach(r=>{if(t)return;const o=Hn(r,`${n}, namespace`);o&&(t=o)}),t}function Xr(e,n,t){let r=null;if(e&&Z(e)){const o=$e(e,n);o&&(r=o);const s=Fn(e,n,t);s&&(r=s)}else r=S(\"MISSING_OR_INVALID\",`${n}, ${t} should be an object with data`);return r}function Wn(e,n){let t=null;if(e&&Z(e)){const r=$e(e,n);r&&(t=r);const o=Bn(e,n);o&&(t=o)}else t=S(\"MISSING_OR_INVALID\",`${n}, namespaces should be an object with data`);return t}function Jn(e){return b(e.protocol,!0)}function eo(e,n){let t=!1;return n&&!e?t=!0:e&&L(e)&&e.length&&e.forEach(r=>{t=Jn(r)}),t}function no(e){return typeof e==\"number\"}function to(e){return typeof e<\"u\"&&typeof e!==null}function ro(e){return!(!e||typeof e!=\"object\"||!e.code||!X(e.code,!1)||!e.message||!b(e.message,!1))}function oo(e){return!(I(e)||!b(e.method,!1))}function so(e){return!(I(e)||I(e.result)&&I(e.error)||!X(e.id,!1)||!b(e.jsonrpc,!1))}function io(e){return!(I(e)||!b(e.name,!1))}function co(e,n){return!(!F(n)||!Un(e).includes(n))}function ao(e,n,t){return b(t,!1)?_n(e,n).includes(t):!1}function uo(e,n,t){return b(t,!1)?kn(e,n).includes(t):!1}function zn(e,n,t){let r=null;const o=lo(e),s=fo(n),i=Object.keys(o),u=Object.keys(s),l=Gn(Object.keys(e)),c=Gn(Object.keys(n)),d=l.filter(a=>!c.includes(a));return d.length&&(r=S(\"NON_CONFORMING_NAMESPACES\",`${t} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(n).toString()}`)),$(i,u)||(r=S(\"NON_CONFORMING_NAMESPACES\",`${t} namespaces chains don't satisfy required namespaces.\n Required: ${i.toString()}\n Approved: ${u.toString()}`)),Object.keys(n).forEach(a=>{if(!a.includes(\":\")||r)return;const f=C(n[a].accounts);f.includes(a)||(r=S(\"NON_CONFORMING_NAMESPACES\",`${t} namespaces accounts don't satisfy namespace accounts for ${a}\n Required: ${a}\n Approved: ${f.toString()}`))}),i.forEach(a=>{r||($(o[a].methods,s[a].methods)?$(o[a].events,s[a].events)||(r=S(\"NON_CONFORMING_NAMESPACES\",`${t} namespaces events don't satisfy namespace events for ${a}`)):r=S(\"NON_CONFORMING_NAMESPACES\",`${t} namespaces methods don't satisfy namespace methods for ${a}`))}),r}function lo(e){const n={};return Object.keys(e).forEach(t=>{var r;t.includes(\":\")?n[t]=e[t]:(r=e[t].chains)==null||r.forEach(o=>{n[o]={methods:e[t].methods,events:e[t].events}})}),n}function Gn(e){return[...new Set(e.map(n=>n.includes(\":\")?n.split(\":\")[0]:n))]}function fo(e){const n={};return Object.keys(e).forEach(t=>{if(t.includes(\":\"))n[t]=e[t];else{const r=C(e[t].accounts);r?.forEach(o=>{n[o]={accounts:e[t].accounts.filter(s=>s.includes(`${o}:`)),methods:e[t].methods,events:e[t].events}})}}),n}function po(e,n){return X(e,!1)&&e<=n.max&&e>=n.min}function mo(){const e=P();return new Promise(n=>{switch(e){case y.browser:n(Yn());break;case y.reactNative:n(Qn());break;case y.node:n(Zn());break;default:n(!0)}})}function Yn(){return V()&&navigator?.onLine}async function Qn(){if(_()&&typeof global<\"u\"&&global!=null&&global.NetInfo){const e=await(global==null?void 0:global.NetInfo.fetch());return e?.isConnected}return!0}function Zn(){return!0}function ho(e){switch(P()){case y.browser:Xn(e);break;case y.reactNative:et(e);break;case y.node:break}}function Xn(e){!_()&&V()&&(window.addEventListener(\"online\",()=>e(!0)),window.addEventListener(\"offline\",()=>e(!1)))}function et(e){_()&&typeof global<\"u\"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(n=>e(n?.isConnected))}const Re={};class yo{static get(n){return Re[n]}static set(n,t){Re[n]=t}static delete(n){delete Re[n]}}export{ye as BASE10,g as BASE16,ge as BASE64,lr as BASE64URL,Et as COLON,ie as DEFAULT_DEPTH,J as EMPTY_SPACE,y as ENV_MAP,Mn as INTERNAL_ERRORS,yo as MemoryStore,wt as ONE_THOUSAND,qe as REACT_NATIVE_PRODUCT,Sn as RELAYER_DEFAULT_PROTOCOL,Vn as SDK_ERRORS,He as SDK_TYPE,Be as SLASH,ve as TYPE_0,D as TYPE_1,M as TYPE_2,k as UTF8,vn as addResourceToRecap,We as appendToQueryString,It as assertType,pe as assignAbilityToActions,yn as base64Decode,hn as base64Encode,Wr as buildApprovedNamespaces,tr as buildAuthObject,Jr as buildNamespacesFromAuth,En as buildRecapStatement,Mt as calcExpiry,Ut as capitalize,Ze as capitalizeWord,_t as createDelayedPromise,ir as createEncodedRecap,kt as createExpiringPromise,gn as createRecap,R as decodeRecap,A as decodeTypeByte,Er as decodeTypeTwoEnvelope,br as decrypt,mr as deriveSymKey,Q as deserialize,G as encodeRecap,Ee as encodeTypeByte,vr as encodeTypeTwoEnvelope,gr as encrypt,Lt as engineEvent,Ct as enumify,De as formatAccountId,ft as formatAccountWithChain,ke as formatChainId,Xe as formatDeeplinkUrl,ae as formatExpirerTarget,xt as formatIdTarget,dn as formatMessage,jt as formatMessageContext,Pn as formatRelayParams,$t as formatRelayRpcUrl,he as formatStatementFromRecap,Dt as formatTopicTarget,Ge as formatUA,Dr as formatUri,le as fromBase64,fr as generateKeyPair,pr as generateRandomBytes32,C as getAccountsChains,mt as getAccountsFromNamespaces,xe as getAddressFromAccount,pt as getAddressesFromAccounts,Nt as getAppMetadata,Yn as getBrowserOnlineStatus,Ot as getBundleId,Ve as getChainFromAccount,Me as getChainsFromAccounts,W as getChainsFromNamespace,ht as getChainsFromNamespaces,ur as getChainsFromRecap,yt as getChainsFromRequiredNamespaces,ue as getCommonValuesInArrays,Nn as getCryptoKeyFromKeyData,fn as getDecodedRecapFromResources,qt as getDeepLink,fe as getDidAddress,z as getDidAddressSegments,un as getDidChainId,P as getEnvironment,Rt as getHttpUrl,S as getInternalError,ze as getJavascriptID,Je as getJavascriptOS,Qe as getLastItems,xr as getLinkModeURL,ar as getMethodsFromRecap,ln as getNamespacedDidChainId,Un as getNamespacesChains,kn as getNamespacesEventsForChainId,xn as getNamespacesFromAccounts,_n as getNamespacesMethodsForChainId,Zn as getNodeOnlineStatus,mn as getReCapActions,Qn as getReactNativeOnlineStatus,sr as getRecapAbilitiesFromResource,Y as getRecapFromResources,pn as getRecapResource,St as getRelayClientMetadata,jr as getRelayProtocolApi,Ir as getRelayProtocolName,Hr as getRequiredNamespacesFromNamespaces,U as getSdkError,Bt as getSearchParamFromURL,se as getUniqueValues,Ft as handleDeeplinkRedirect,$ as hasOverlap,hr as hashKey,yr as hashMessage,V as isBrowser,Oe as isCaipNamespace,zn as isConformingNamespaces,Kt as isExpired,ce as isNode,mo as isOnline,Yr as isProposalStruct,_ as isReactNative,me as isRecap,zr as isSessionCompatible,Qr as isSessionStruct,en as isTelegram,Wt as isTestRun,Or as isTypeOneEnvelope,Nr as isTypeTwoEnvelope,I as isUndefined,Kn as isValidAccountId,qn as isValidAccounts,Hn as isValidActions,L as isValidArray,F as isValidChainId,Ln as isValidChains,Zr as isValidController,on as isValidEip1271Signature,rn as isValidEip191Signature,ro as isValidErrorReason,io as isValidEvent,no as isValidId,Bn as isValidNamespaceAccounts,$e as isValidNamespaceActions,Fn as isValidNamespaceChains,Se as isValidNamespaceMethodsOrEvents,Wn as isValidNamespaces,co as isValidNamespacesChainId,uo as isValidNamespacesEvent,ao as isValidNamespacesRequest,X as isValidNumber,Z as isValidObject,to as isValidParams,O as isValidRecap,Jn as isValidRelay,eo as isValidRelays,oo as isValidRequest,po as isValidRequestExpiry,Xr as isValidRequiredNamespaces,so as isValidResponse,b as isValidString,Gr as isValidUrl,At as mapEntries,Tt as mapToObj,N as mergeArrays,cr as mergeEncodedRecaps,bn as mergeRecaps,Ne as normalizeNamespaces,Pt as objToMap,oe as parseAccountId,re as parseChainId,Ye as parseContextNames,Vt as parseExpirerTarget,Dn as parseNamespaceKey,jn as parseRelayParams,Tn as parseTopic,kr as parseUri,rr as populateAuthPayload,or as recapHasResource,we as serialize,Xn as subscribeToBrowserNetworkChange,ho as subscribeToNetworkChange,et as subscribeToReactNativeNetworkChange,nn as toBase64,Ht as uuidv4,wr as validateDecoding,On as validateEncoding,nr as validateSignedCacao,Rr as verifyP256Jwt,tn as verifySignature};\n//# sourceMappingURL=index.es.js.map\n","export class IEvents {\n}\n//# sourceMappingURL=events.js.map","import{EventEmitter as a}from\"events\";import{FIVE_SECONDS as o,toMiliseconds as l}from\"@walletconnect/time\";import{IEvents as v}from\"@walletconnect/events\";class n extends v{constructor(e){super()}}const s=o,r={pulse:\"heartbeat_pulse\"};class i extends n{constructor(e){super(e),this.events=new a,this.interval=s,this.interval=e?.interval||s}static async init(e){const t=new i(e);return await t.init(),t}async init(){await 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)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),l(this.interval))}pulse(){this.events.emit(r.pulse)}}export{r as HEARTBEAT_EVENTS,s as HEARTBEAT_INTERVAL,i as HeartBeat,n as IHeartBeat};\n//# sourceMappingURL=index.es.js.map\n","const suspectProtoRx = /\"(?:_|\\\\u0{2}5[Ff]){2}(?:p|\\\\u0{2}70)(?:r|\\\\u0{2}72)(?:o|\\\\u0{2}6[Ff])(?:t|\\\\u0{2}74)(?:o|\\\\u0{2}6[Ff])(?:_|\\\\u0{2}5[Ff]){2}\"\\s*:/;\nconst suspectConstructorRx = /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\nconst JsonSigRx = /^\\s*[\"[{]|^\\s*-?\\d{1,16}(\\.\\d{1,17})?([Ee][+-]?\\d+)?\\s*$/;\nfunction jsonParseTransform(key, value) {\n if (key === \"__proto__\" || key === \"constructor\" && value && typeof value === \"object\" && \"prototype\" in value) {\n warnKeyDropped(key);\n return;\n }\n return value;\n}\nfunction warnKeyDropped(key) {\n console.warn(`[destr] Dropping \"${key}\" key to prevent prototype pollution.`);\n}\nfunction destr(value, options = {}) {\n if (typeof value !== \"string\") {\n return value;\n }\n const _value = value.trim();\n if (\n // eslint-disable-next-line unicorn/prefer-at\n value[0] === '\"' && value.at(-1) === '\"' && !value.includes(\"\\\\\")\n ) {\n return _value.slice(1, -1);\n }\n if (_value.length <= 9) {\n const _lval = _value.toLowerCase();\n if (_lval === \"true\") {\n return true;\n }\n if (_lval === \"false\") {\n return false;\n }\n if (_lval === \"undefined\") {\n return void 0;\n }\n if (_lval === \"null\") {\n return null;\n }\n if (_lval === \"nan\") {\n return Number.NaN;\n }\n if (_lval === \"infinity\") {\n return Number.POSITIVE_INFINITY;\n }\n if (_lval === \"-infinity\") {\n return Number.NEGATIVE_INFINITY;\n }\n }\n if (!JsonSigRx.test(value)) {\n if (options.strict) {\n throw new SyntaxError(\"[destr] Invalid JSON\");\n }\n return value;\n }\n try {\n if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {\n if (options.strict) {\n throw new Error(\"[destr] Possible prototype pollution\");\n }\n return JSON.parse(value, jsonParseTransform);\n }\n return JSON.parse(value);\n } catch (error) {\n if (options.strict) {\n throw error;\n }\n return value;\n }\n}\nfunction safeDestr(value, options = {}) {\n return destr(value, { ...options, strict: true });\n}\n\nexport { destr as default, destr, safeDestr };\n","function wrapToPromise(value) {\n if (!value || typeof value.then !== \"function\") {\n return Promise.resolve(value);\n }\n return value;\n}\nfunction asyncCall(function_, ...arguments_) {\n try {\n return wrapToPromise(function_(...arguments_));\n } catch (error) {\n return Promise.reject(error);\n }\n}\nfunction isPrimitive(value) {\n const type = typeof value;\n return value === null || type !== \"object\" && type !== \"function\";\n}\nfunction isPureObject(value) {\n const proto = Object.getPrototypeOf(value);\n return !proto || proto.isPrototypeOf(Object);\n}\nfunction stringify(value) {\n if (isPrimitive(value)) {\n return String(value);\n }\n if (isPureObject(value) || Array.isArray(value)) {\n return JSON.stringify(value);\n }\n if (typeof value.toJSON === \"function\") {\n return stringify(value.toJSON());\n }\n throw new Error(\"[unstorage] Cannot stringify value!\");\n}\nfunction checkBufferSupport() {\n if (typeof Buffer === void 0) {\n throw new TypeError(\"[unstorage] Buffer is not supported!\");\n }\n}\nconst BASE64_PREFIX = \"base64:\";\nfunction serializeRaw(value) {\n if (typeof value === \"string\") {\n return value;\n }\n checkBufferSupport();\n const base64 = Buffer.from(value).toString(\"base64\");\n return BASE64_PREFIX + base64;\n}\nfunction deserializeRaw(value) {\n if (typeof value !== \"string\") {\n return value;\n }\n if (!value.startsWith(BASE64_PREFIX)) {\n return value;\n }\n checkBufferSupport();\n return Buffer.from(value.slice(BASE64_PREFIX.length), \"base64\");\n}\n\nconst storageKeyProperties = [\n \"hasItem\",\n \"getItem\",\n \"getItemRaw\",\n \"setItem\",\n \"setItemRaw\",\n \"removeItem\",\n \"getMeta\",\n \"setMeta\",\n \"removeMeta\",\n \"getKeys\",\n \"clear\",\n \"mount\",\n \"unmount\"\n];\nfunction prefixStorage(storage, base) {\n base = normalizeBaseKey(base);\n if (!base) {\n return storage;\n }\n const nsStorage = { ...storage };\n for (const property of storageKeyProperties) {\n nsStorage[property] = (key = \"\", ...args) => (\n // @ts-ignore\n storage[property](base + key, ...args)\n );\n }\n nsStorage.getKeys = (key = \"\", ...arguments_) => storage.getKeys(base + key, ...arguments_).then((keys) => keys.map((key2) => key2.slice(base.length)));\n return nsStorage;\n}\nfunction normalizeKey(key) {\n if (!key) {\n return \"\";\n }\n return key.split(\"?\")[0].replace(/[/\\\\]/g, \":\").replace(/:+/g, \":\").replace(/^:|:$/g, \"\");\n}\nfunction joinKeys(...keys) {\n return normalizeKey(keys.join(\":\"));\n}\nfunction normalizeBaseKey(base) {\n base = normalizeKey(base);\n return base ? base + \":\" : \"\";\n}\n\nexport { normalizeKey as a, asyncCall as b, serializeRaw as c, deserializeRaw as d, joinKeys as j, normalizeBaseKey as n, prefixStorage as p, stringify as s };\n","import destr from 'destr';\nimport { n as normalizeBaseKey, a as normalizeKey, b as asyncCall, d as deserializeRaw, s as stringify, c as serializeRaw, j as joinKeys } from './shared/unstorage.8581f561.mjs';\nexport { p as prefixStorage } from './shared/unstorage.8581f561.mjs';\n\nfunction defineDriver(factory) {\n return factory;\n}\n\nconst DRIVER_NAME = \"memory\";\nconst memory = defineDriver(() => {\n const data = /* @__PURE__ */ new Map();\n return {\n name: DRIVER_NAME,\n options: {},\n hasItem(key) {\n return data.has(key);\n },\n getItem(key) {\n return data.get(key) || null;\n },\n getItemRaw(key) {\n return data.get(key) || null;\n },\n setItem(key, value) {\n data.set(key, value);\n },\n setItemRaw(key, value) {\n data.set(key, value);\n },\n removeItem(key) {\n data.delete(key);\n },\n getKeys() {\n return Array.from(data.keys());\n },\n clear() {\n data.clear();\n },\n dispose() {\n data.clear();\n }\n };\n});\n\nfunction createStorage(options = {}) {\n const context = {\n mounts: { \"\": options.driver || memory() },\n mountpoints: [\"\"],\n watching: false,\n watchListeners: [],\n unwatch: {}\n };\n const getMount = (key) => {\n for (const base of context.mountpoints) {\n if (key.startsWith(base)) {\n return {\n base,\n relativeKey: key.slice(base.length),\n driver: context.mounts[base]\n };\n }\n }\n return {\n base: \"\",\n relativeKey: key,\n driver: context.mounts[\"\"]\n };\n };\n const getMounts = (base, includeParent) => {\n return context.mountpoints.filter(\n (mountpoint) => mountpoint.startsWith(base) || includeParent && base.startsWith(mountpoint)\n ).map((mountpoint) => ({\n relativeBase: base.length > mountpoint.length ? base.slice(mountpoint.length) : void 0,\n mountpoint,\n driver: context.mounts[mountpoint]\n }));\n };\n const onChange = (event, key) => {\n if (!context.watching) {\n return;\n }\n key = normalizeKey(key);\n for (const listener of context.watchListeners) {\n listener(event, key);\n }\n };\n const startWatch = async () => {\n if (context.watching) {\n return;\n }\n context.watching = true;\n for (const mountpoint in context.mounts) {\n context.unwatch[mountpoint] = await watch(\n context.mounts[mountpoint],\n onChange,\n mountpoint\n );\n }\n };\n const stopWatch = async () => {\n if (!context.watching) {\n return;\n }\n for (const mountpoint in context.unwatch) {\n await context.unwatch[mountpoint]();\n }\n context.unwatch = {};\n context.watching = false;\n };\n const runBatch = (items, commonOptions, cb) => {\n const batches = /* @__PURE__ */ new Map();\n const getBatch = (mount) => {\n let batch = batches.get(mount.base);\n if (!batch) {\n batch = {\n driver: mount.driver,\n base: mount.base,\n items: []\n };\n batches.set(mount.base, batch);\n }\n return batch;\n };\n for (const item of items) {\n const isStringItem = typeof item === \"string\";\n const key = normalizeKey(isStringItem ? item : item.key);\n const value = isStringItem ? void 0 : item.value;\n const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options };\n const mount = getMount(key);\n getBatch(mount).items.push({\n key,\n value,\n relativeKey: mount.relativeKey,\n options: options2\n });\n }\n return Promise.all([...batches.values()].map((batch) => cb(batch))).then(\n (r) => r.flat()\n );\n };\n const storage = {\n // Item\n hasItem(key, opts = {}) {\n key = normalizeKey(key);\n const { relativeKey, driver } = getMount(key);\n return asyncCall(driver.hasItem, relativeKey, opts);\n },\n getItem(key, opts = {}) {\n key = normalizeKey(key);\n const { relativeKey, driver } = getMount(key);\n return asyncCall(driver.getItem, relativeKey, opts).then(\n (value) => destr(value)\n );\n },\n getItems(items, commonOptions) {\n return runBatch(items, commonOptions, (batch) => {\n if (batch.driver.getItems) {\n return asyncCall(\n batch.driver.getItems,\n batch.items.map((item) => ({\n key: item.relativeKey,\n options: item.options\n })),\n commonOptions\n ).then(\n (r) => r.map((item) => ({\n key: joinKeys(batch.base, item.key),\n value: destr(item.value)\n }))\n );\n }\n return Promise.all(\n batch.items.map((item) => {\n return asyncCall(\n batch.driver.getItem,\n item.relativeKey,\n item.options\n ).then((value) => ({\n key: item.key,\n value: destr(value)\n }));\n })\n );\n });\n },\n getItemRaw(key, opts = {}) {\n key = normalizeKey(key);\n const { relativeKey, driver } = getMount(key);\n if (driver.getItemRaw) {\n return asyncCall(driver.getItemRaw, relativeKey, opts);\n }\n return asyncCall(driver.getItem, relativeKey, opts).then(\n (value) => deserializeRaw(value)\n );\n },\n async setItem(key, value, opts = {}) {\n if (value === void 0) {\n return storage.removeItem(key);\n }\n key = normalizeKey(key);\n const { relativeKey, driver } = getMount(key);\n if (!driver.setItem) {\n return;\n }\n await asyncCall(driver.setItem, relativeKey, stringify(value), opts);\n if (!driver.watch) {\n onChange(\"update\", key);\n }\n },\n async setItems(items, commonOptions) {\n await runBatch(items, commonOptions, async (batch) => {\n if (batch.driver.setItems) {\n await asyncCall(\n batch.driver.setItems,\n batch.items.map((item) => ({\n key: item.relativeKey,\n value: stringify(item.value),\n options: item.options\n })),\n commonOptions\n );\n }\n if (!batch.driver.setItem) {\n return;\n }\n await Promise.all(\n batch.items.map((item) => {\n return asyncCall(\n batch.driver.setItem,\n item.relativeKey,\n stringify(item.value),\n item.options\n );\n })\n );\n });\n },\n async setItemRaw(key, value, opts = {}) {\n if (value === void 0) {\n return storage.removeItem(key, opts);\n }\n key = normalizeKey(key);\n const { relativeKey, driver } = getMount(key);\n if (driver.setItemRaw) {\n await asyncCall(driver.setItemRaw, relativeKey, value, opts);\n } else if (driver.setItem) {\n await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts);\n } else {\n return;\n }\n if (!driver.watch) {\n onChange(\"update\", key);\n }\n },\n async removeItem(key, opts = {}) {\n if (typeof opts === \"boolean\") {\n opts = { removeMeta: opts };\n }\n key = normalizeKey(key);\n const { relativeKey, driver } = getMount(key);\n if (!driver.removeItem) {\n return;\n }\n await asyncCall(driver.removeItem, relativeKey, opts);\n if (opts.removeMeta || opts.removeMata) {\n await asyncCall(driver.removeItem, relativeKey + \"$\", opts);\n }\n if (!driver.watch) {\n onChange(\"remove\", key);\n }\n },\n // Meta\n async getMeta(key, opts = {}) {\n if (typeof opts === \"boolean\") {\n opts = { nativeOnly: opts };\n }\n key = normalizeKey(key);\n const { relativeKey, driver } = getMount(key);\n const meta = /* @__PURE__ */ Object.create(null);\n if (driver.getMeta) {\n Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts));\n }\n if (!opts.nativeOnly) {\n const value = await asyncCall(\n driver.getItem,\n relativeKey + \"$\",\n opts\n ).then((value_) => destr(value_));\n if (value && typeof value === \"object\") {\n if (typeof value.atime === \"string\") {\n value.atime = new Date(value.atime);\n }\n if (typeof value.mtime === \"string\") {\n value.mtime = new Date(value.mtime);\n }\n Object.assign(meta, value);\n }\n }\n return meta;\n },\n setMeta(key, value, opts = {}) {\n return this.setItem(key + \"$\", value, opts);\n },\n removeMeta(key, opts = {}) {\n return this.removeItem(key + \"$\", opts);\n },\n // Keys\n async getKeys(base, opts = {}) {\n base = normalizeBaseKey(base);\n const mounts = getMounts(base, true);\n let maskedMounts = [];\n const allKeys = [];\n for (const mount of mounts) {\n const rawKeys = await asyncCall(\n mount.driver.getKeys,\n mount.relativeBase,\n opts\n );\n const keys = rawKeys.map((key) => mount.mountpoint + normalizeKey(key)).filter((key) => !maskedMounts.some((p) => key.startsWith(p)));\n allKeys.push(...keys);\n maskedMounts = [\n mount.mountpoint,\n ...maskedMounts.filter((p) => !p.startsWith(mount.mountpoint))\n ];\n }\n return base ? allKeys.filter((key) => key.startsWith(base) && !key.endsWith(\"$\")) : allKeys.filter((key) => !key.endsWith(\"$\"));\n },\n // Utils\n async clear(base, opts = {}) {\n base = normalizeBaseKey(base);\n await Promise.all(\n getMounts(base, false).map(async (m) => {\n if (m.driver.clear) {\n return asyncCall(m.driver.clear, m.relativeBase, opts);\n }\n if (m.driver.removeItem) {\n const keys = await m.driver.getKeys(m.relativeBase || \"\", opts);\n return Promise.all(\n keys.map((key) => m.driver.removeItem(key, opts))\n );\n }\n })\n );\n },\n async dispose() {\n await Promise.all(\n Object.values(context.mounts).map((driver) => dispose(driver))\n );\n },\n async watch(callback) {\n await startWatch();\n context.watchListeners.push(callback);\n return async () => {\n context.watchListeners = context.watchListeners.filter(\n (listener) => listener !== callback\n );\n if (context.watchListeners.length === 0) {\n await stopWatch();\n }\n };\n },\n async unwatch() {\n context.watchListeners = [];\n await stopWatch();\n },\n // Mount\n mount(base, driver) {\n base = normalizeBaseKey(base);\n if (base && context.mounts[base]) {\n throw new Error(`already mounted at ${base}`);\n }\n if (base) {\n context.mountpoints.push(base);\n context.mountpoints.sort((a, b) => b.length - a.length);\n }\n context.mounts[base] = driver;\n if (context.watching) {\n Promise.resolve(watch(driver, onChange, base)).then((unwatcher) => {\n context.unwatch[base] = unwatcher;\n }).catch(console.error);\n }\n return storage;\n },\n async unmount(base, _dispose = true) {\n base = normalizeBaseKey(base);\n if (!base || !context.mounts[base]) {\n return;\n }\n if (context.watching && base in context.unwatch) {\n context.unwatch[base]();\n delete context.unwatch[base];\n }\n if (_dispose) {\n await dispose(context.mounts[base]);\n }\n context.mountpoints = context.mountpoints.filter((key) => key !== base);\n delete context.mounts[base];\n },\n getMount(key = \"\") {\n key = normalizeKey(key) + \":\";\n const m = getMount(key);\n return {\n driver: m.driver,\n base: m.base\n };\n },\n getMounts(base = \"\", opts = {}) {\n base = normalizeKey(base);\n const mounts = getMounts(base, opts.parents);\n return mounts.map((m) => ({\n driver: m.driver,\n base: m.mountpoint\n }));\n }\n };\n return storage;\n}\nasync function snapshot(storage, base) {\n base = normalizeBaseKey(base);\n const keys = await storage.getKeys(base);\n const snapshot2 = {};\n await Promise.all(\n keys.map(async (key) => {\n snapshot2[key.slice(base.length)] = await storage.getItem(key);\n })\n );\n return snapshot2;\n}\nasync function restoreSnapshot(driver, snapshot2, base = \"\") {\n base = normalizeBaseKey(base);\n await Promise.all(\n Object.entries(snapshot2).map((e) => driver.setItem(base + e[0], e[1]))\n );\n}\nfunction watch(driver, onChange, base) {\n return driver.watch ? driver.watch((event, key) => onChange(event, base + key)) : () => {\n };\n}\nasync function dispose(driver) {\n if (typeof driver.dispose === \"function\") {\n await asyncCall(driver.dispose);\n }\n}\n\nconst builtinDrivers = {\n azureAppConfiguration: \"unstorage/drivers/azure-app-configuration\",\n azureCosmos: \"unstorage/drivers/azure-cosmos\",\n azureKeyVault: \"unstorage/drivers/azure-key-vault\",\n azureStorageBlob: \"unstorage/drivers/azure-storage-blob\",\n azureStorageTable: \"unstorage/drivers/azure-storage-table\",\n cloudflareKVBinding: \"unstorage/drivers/cloudflare-kv-binding\",\n cloudflareKVHTTP: \"unstorage/drivers/cloudflare-kv-http\",\n cloudflareR2Binding: \"unstorage/drivers/cloudflare-r2-binding\",\n fs: \"unstorage/drivers/fs\",\n fsLite: \"unstorage/drivers/fs-lite\",\n github: \"unstorage/drivers/github\",\n http: \"unstorage/drivers/http\",\n indexedb: \"unstorage/drivers/indexedb\",\n localStorage: \"unstorage/drivers/localstorage\",\n lruCache: \"unstorage/drivers/lru-cache\",\n memory: \"unstorage/drivers/memory\",\n mongodb: \"unstorage/drivers/mongodb\",\n overlay: \"unstorage/drivers/overlay\",\n planetscale: \"unstorage/drivers/planetscale\",\n redis: \"unstorage/drivers/redis\",\n sessionStorage: \"unstorage/drivers/session-storage\",\n vercelKV: \"unstorage/drivers/vercel-kv\",\n /** @deprecated */\n \"cloudflare-kv-binding\": \"unstorage/drivers/cloudflare-kv-binding\",\n /** @deprecated */\n \"cloudflare-kv-http\": \"unstorage/drivers/cloudflare-kv-http\"\n};\n\nexport { builtinDrivers, createStorage, defineDriver, joinKeys, normalizeBaseKey, normalizeKey, restoreSnapshot, snapshot };\n","function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Delete multiple keys at once.\n *\n * @param keys List of keys to delete.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction delMany(keys, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n keys.forEach((key) => store.delete(key));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(store, callback) {\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAllKeys) {\n return promisifyRequest(store.getAllKeys());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items);\n });\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAll) {\n return promisifyRequest(store.getAll());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.value)).then(() => items);\n });\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n // (although, hopefully we'll get a simpler path some day)\n if (store.getAll && store.getAllKeys) {\n return Promise.all([\n promisifyRequest(store.getAllKeys()),\n promisifyRequest(store.getAll()),\n ]).then(([keys, values]) => keys.map((key, i) => [key, values[i]]));\n }\n const items = [];\n return customStore('readonly', (store) => eachCursor(store, (cursor) => items.push([cursor.key, cursor.value])).then(() => items));\n });\n}\n\nexport { clear, createStore, del, delMany, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","import{createStorage as w}from\"unstorage\";import{createStore as I,get as u,set as p,del as b,keys as v,clear as S}from\"idb-keyval\";import{safeJsonStringify as g,safeJsonParse as d}from\"@walletconnect/safe-json\";function C(i){return i}const x=\"idb-keyval\";var z=(i={})=>{const t=i.base&&i.base.length>0?`${i.base}:`:\"\",e=s=>t+s;let n;return i.dbName&&i.storeName&&(n=I(i.dbName,i.storeName)),{name:x,options:i,async hasItem(s){return!(typeof await u(e(s),n)>\"u\")},async getItem(s){return await u(e(s),n)??null},setItem(s,a){return p(e(s),a,n)},removeItem(s){return b(e(s),n)},getKeys(){return v(n)},clear(){return S(n)}}};const D=\"WALLET_CONNECT_V2_INDEXED_DB\",E=\"keyvaluestorage\";class _{constructor(){this.indexedDb=w({driver:z({dbName:D,storeName:E})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(t=>[t.key,t.value])}async getItem(t){const e=await this.indexedDb.getItem(t);if(e!==null)return e}async setItem(t,e){await this.indexedDb.setItem(t,g(e))}async removeItem(t){await this.indexedDb.removeItem(t)}}var l=typeof globalThis<\"u\"?globalThis:typeof window<\"u\"?window:typeof global<\"u\"?global:typeof self<\"u\"?self:{},c={exports:{}};(function(){let i;function t(){}i=t,i.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},i.prototype.setItem=function(e,n){this[e]=String(n)},i.prototype.removeItem=function(e){delete this[e]},i.prototype.clear=function(){const e=this;Object.keys(e).forEach(function(n){e[n]=void 0,delete e[n]})},i.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},i.prototype.__defineGetter__(\"length\",function(){return Object.keys(this).length}),typeof l<\"u\"&&l.localStorage?c.exports=l.localStorage:typeof window<\"u\"&&window.localStorage?c.exports=window.localStorage:c.exports=new t})();function k(i){var t;return[i[0],d((t=i[1])!=null?t:\"\")]}class K{constructor(){this.localStorage=c.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(k)}async getItem(t){const e=this.localStorage.getItem(t);if(e!==null)return d(e)}async setItem(t,e){this.localStorage.setItem(t,g(e))}async removeItem(t){this.localStorage.removeItem(t)}}const N=\"wc_storage_version\",y=1,O=async(i,t,e)=>{const n=N,s=await t.getItem(n);if(s&&s>=y){e(t);return}const a=await i.getKeys();if(!a.length){e(t);return}const m=[];for(;a.length;){const r=a.shift();if(!r)continue;const o=r.toLowerCase();if(o.includes(\"wc@\")||o.includes(\"walletconnect\")||o.includes(\"wc_\")||o.includes(\"wallet_connect\")){const f=await i.getItem(r);await t.setItem(r,f),m.push(r)}}await t.setItem(n,y),e(t),j(i,m)},j=async(i,t)=>{t.length&&t.forEach(async e=>{await i.removeItem(e)})};class h{constructor(){this.initialized=!1,this.setInitialized=e=>{this.storage=e,this.initialized=!0};const t=new K;this.storage=t;try{const e=new _;O(t,e,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(t){return await this.initialize(),this.storage.getItem(t)}async setItem(t,e){return await this.initialize(),this.storage.setItem(t,e)}async removeItem(t){return await this.initialize(),this.storage.removeItem(t)}async initialize(){this.initialized||await new Promise(t=>{const e=setInterval(()=>{this.initialized&&(clearInterval(e),t())},20)})}}export{h as KeyValueStorage,h as default};\n//# sourceMappingURL=index.es.js.map\n","'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n","'use strict'\n\nconst format = require('quick-format-unescaped')\n\nmodule.exports = pino\n\nconst _console = pfGlobalThisOrFallback().console || {}\nconst stdSerializers = {\n mapHttpRequest: mock,\n mapHttpResponse: mock,\n wrapRequestSerializer: passthrough,\n wrapResponseSerializer: passthrough,\n wrapErrorSerializer: passthrough,\n req: mock,\n res: mock,\n err: asErrValue\n}\n\nfunction shouldSerialize (serialize, serializers) {\n if (Array.isArray(serialize)) {\n const hasToFilter = serialize.filter(function (k) {\n return k !== '!stdSerializers.err'\n })\n return hasToFilter\n } else if (serialize === true) {\n return Object.keys(serializers)\n }\n\n return false\n}\n\nfunction pino (opts) {\n opts = opts || {}\n opts.browser = opts.browser || {}\n\n const transmit = opts.browser.transmit\n if (transmit && typeof transmit.send !== 'function') { throw Error('pino: transmit option must have a send function') }\n\n const proto = opts.browser.write || _console\n if (opts.browser.write) opts.browser.asObject = true\n const serializers = opts.serializers || {}\n const serialize = shouldSerialize(opts.browser.serialize, serializers)\n let stdErrSerialize = opts.browser.serialize\n\n if (\n Array.isArray(opts.browser.serialize) &&\n opts.browser.serialize.indexOf('!stdSerializers.err') > -1\n ) stdErrSerialize = false\n\n const levels = ['error', 'fatal', 'warn', 'info', 'debug', 'trace']\n\n if (typeof proto === 'function') {\n proto.error = proto.fatal = proto.warn =\n proto.info = proto.debug = proto.trace = proto\n }\n if (opts.enabled === false) opts.level = 'silent'\n const level = opts.level || 'info'\n const logger = Object.create(proto)\n if (!logger.log) logger.log = noop\n\n Object.defineProperty(logger, 'levelVal', {\n get: getLevelVal\n })\n Object.defineProperty(logger, 'level', {\n get: getLevel,\n set: setLevel\n })\n\n const setOpts = {\n transmit,\n serialize,\n asObject: opts.browser.asObject,\n levels,\n timestamp: getTimeFunction(opts)\n }\n logger.levels = pino.levels\n logger.level = level\n\n logger.setMaxListeners = logger.getMaxListeners =\n logger.emit = logger.addListener = logger.on =\n logger.prependListener = logger.once =\n logger.prependOnceListener = logger.removeListener =\n logger.removeAllListeners = logger.listeners =\n logger.listenerCount = logger.eventNames =\n logger.write = logger.flush = noop\n logger.serializers = serializers\n logger._serialize = serialize\n logger._stdErrSerialize = stdErrSerialize\n logger.child = child\n\n if (transmit) logger._logEvent = createLogEventShape()\n\n function getLevelVal () {\n return this.level === 'silent'\n ? Infinity\n : this.levels.values[this.level]\n }\n\n function getLevel () {\n return this._level\n }\n function setLevel (level) {\n if (level !== 'silent' && !this.levels.values[level]) {\n throw Error('unknown level ' + level)\n }\n this._level = level\n\n set(setOpts, logger, 'error', 'log') // <-- must stay first\n set(setOpts, logger, 'fatal', 'error')\n set(setOpts, logger, 'warn', 'error')\n set(setOpts, logger, 'info', 'log')\n set(setOpts, logger, 'debug', 'log')\n set(setOpts, logger, 'trace', 'log')\n }\n\n function child (bindings, childOptions) {\n if (!bindings) {\n throw new Error('missing bindings for child Pino')\n }\n childOptions = childOptions || {}\n if (serialize && bindings.serializers) {\n childOptions.serializers = bindings.serializers\n }\n const childOptionsSerializers = childOptions.serializers\n if (serialize && childOptionsSerializers) {\n var childSerializers = Object.assign({}, serializers, childOptionsSerializers)\n var childSerialize = opts.browser.serialize === true\n ? Object.keys(childSerializers)\n : serialize\n delete bindings.serializers\n applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize)\n }\n function Child (parent) {\n this._childLevel = (parent._childLevel | 0) + 1\n this.error = bind(parent, bindings, 'error')\n this.fatal = bind(parent, bindings, 'fatal')\n this.warn = bind(parent, bindings, 'warn')\n this.info = bind(parent, bindings, 'info')\n this.debug = bind(parent, bindings, 'debug')\n this.trace = bind(parent, bindings, 'trace')\n if (childSerializers) {\n this.serializers = childSerializers\n this._serialize = childSerialize\n }\n if (transmit) {\n this._logEvent = createLogEventShape(\n [].concat(parent._logEvent.bindings, bindings)\n )\n }\n }\n Child.prototype = this\n return new Child(this)\n }\n return logger\n}\n\npino.levels = {\n values: {\n fatal: 60,\n error: 50,\n warn: 40,\n info: 30,\n debug: 20,\n trace: 10\n },\n labels: {\n 10: 'trace',\n 20: 'debug',\n 30: 'info',\n 40: 'warn',\n 50: 'error',\n 60: 'fatal'\n }\n}\n\npino.stdSerializers = stdSerializers\npino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime })\n\nfunction set (opts, logger, level, fallback) {\n const proto = Object.getPrototypeOf(logger)\n logger[level] = logger.levelVal > logger.levels.values[level]\n ? noop\n : (proto[level] ? proto[level] : (_console[level] || _console[fallback] || noop))\n\n wrap(opts, logger, level)\n}\n\nfunction wrap (opts, logger, level) {\n if (!opts.transmit && logger[level] === noop) return\n\n logger[level] = (function (write) {\n return function LOG () {\n const ts = opts.timestamp()\n const args = new Array(arguments.length)\n const proto = (Object.getPrototypeOf && Object.getPrototypeOf(this) === _console) ? _console : this\n for (var i = 0; i < args.length; i++) args[i] = arguments[i]\n\n if (opts.serialize && !opts.asObject) {\n applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize)\n }\n if (opts.asObject) write.call(proto, asObject(this, level, args, ts))\n else write.apply(proto, args)\n\n if (opts.transmit) {\n const transmitLevel = opts.transmit.level || logger.level\n const transmitValue = pino.levels.values[transmitLevel]\n const methodValue = pino.levels.values[level]\n if (methodValue < transmitValue) return\n transmit(this, {\n ts,\n methodLevel: level,\n methodValue,\n transmitLevel,\n transmitValue: pino.levels.values[opts.transmit.level || logger.level],\n send: opts.transmit.send,\n val: logger.levelVal\n }, args)\n }\n }\n })(logger[level])\n}\n\nfunction asObject (logger, level, args, ts) {\n if (logger._serialize) applySerializers(args, logger._serialize, logger.serializers, logger._stdErrSerialize)\n const argsCloned = args.slice()\n let msg = argsCloned[0]\n const o = {}\n if (ts) {\n o.time = ts\n }\n o.level = pino.levels.values[level]\n let lvl = (logger._childLevel | 0) + 1\n if (lvl < 1) lvl = 1\n // deliberate, catching objects, arrays\n if (msg !== null && typeof msg === 'object') {\n while (lvl-- && typeof argsCloned[0] === 'object') {\n Object.assign(o, argsCloned.shift())\n }\n msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : undefined\n } else if (typeof msg === 'string') msg = format(argsCloned.shift(), argsCloned)\n if (msg !== undefined) o.msg = msg\n return o\n}\n\nfunction applySerializers (args, serialize, serializers, stdErrSerialize) {\n for (const i in args) {\n if (stdErrSerialize && args[i] instanceof Error) {\n args[i] = pino.stdSerializers.err(args[i])\n } else if (typeof args[i] === 'object' && !Array.isArray(args[i])) {\n for (const k in args[i]) {\n if (serialize && serialize.indexOf(k) > -1 && k in serializers) {\n args[i][k] = serializers[k](args[i][k])\n }\n }\n }\n }\n}\n\nfunction bind (parent, bindings, level) {\n return function () {\n const args = new Array(1 + arguments.length)\n args[0] = bindings\n for (var i = 1; i < args.length; i++) {\n args[i] = arguments[i - 1]\n }\n return parent[level].apply(this, args)\n }\n}\n\nfunction transmit (logger, opts, args) {\n const send = opts.send\n const ts = opts.ts\n const methodLevel = opts.methodLevel\n const methodValue = opts.methodValue\n const val = opts.val\n const bindings = logger._logEvent.bindings\n\n applySerializers(\n args,\n logger._serialize || Object.keys(logger.serializers),\n logger.serializers,\n logger._stdErrSerialize === undefined ? true : logger._stdErrSerialize\n )\n logger._logEvent.ts = ts\n logger._logEvent.messages = args.filter(function (arg) {\n // bindings can only be objects, so reference equality check via indexOf is fine\n return bindings.indexOf(arg) === -1\n })\n\n logger._logEvent.level.label = methodLevel\n logger._logEvent.level.value = methodValue\n\n send(methodLevel, logger._logEvent, val)\n\n logger._logEvent = createLogEventShape(bindings)\n}\n\nfunction createLogEventShape (bindings) {\n return {\n ts: 0,\n messages: [],\n bindings: bindings || [],\n level: { label: '', value: 0 }\n }\n}\n\nfunction asErrValue (err) {\n const obj = {\n type: err.constructor.name,\n msg: err.message,\n stack: err.stack\n }\n for (const key in err) {\n if (obj[key] === undefined) {\n obj[key] = err[key]\n }\n }\n return obj\n}\n\nfunction getTimeFunction (opts) {\n if (typeof opts.timestamp === 'function') {\n return opts.timestamp\n }\n if (opts.timestamp === false) {\n return nullTime\n }\n return epochTime\n}\n\nfunction mock () { return {} }\nfunction passthrough (a) { return a }\nfunction noop () {}\n\nfunction nullTime () { return false }\nfunction epochTime () { return Date.now() }\nfunction unixTime () { return Math.round(Date.now() / 1000.0) }\nfunction isoTime () { return new Date(Date.now()).toISOString() } // using Date.now() for testability\n\n/* eslint-disable */\n/* istanbul ignore next */\nfunction pfGlobalThisOrFallback () {\n function defd (o) { return typeof o !== 'undefined' && o }\n try {\n if (typeof globalThis !== 'undefined') return globalThis\n Object.defineProperty(Object.prototype, 'globalThis', {\n get: function () {\n delete Object.prototype.globalThis\n return (this.globalThis = this)\n },\n configurable: true\n })\n return globalThis\n } catch (e) {\n return defd(self) || defd(window) || defd(this) || {}\n }\n}\n/* eslint-enable */\n","import h,{levels as s}from\"pino\";import{default as U}from\"pino\";import{safeJsonStringify as u}from\"@walletconnect/safe-json\";const c={level:\"info\"},n=\"custom_context\",l=1e3*1024;class O{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class d{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new O(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}}class L{constructor(e,t=l){this.level=e??\"error\",this.levelValue=s.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new d(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===s.values.error?console.error(e):t===s.values.warn?console.warn(e):t===s.values.debug?console.debug(e):t===s.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(u({timestamp:new Date().toISOString(),log:e}));const t=typeof e==\"string\"?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new d(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(u({extraMetadata:e})),new Blob(t,{type:\"application/json\"})}}class m{constructor(e,t=l){this.baseChunkLogger=new L(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),o=document.createElement(\"a\");o.href=t,o.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(t)}}class B{constructor(e,t=l){this.baseChunkLogger=new L(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var x=Object.defineProperty,S=Object.defineProperties,_=Object.getOwnPropertyDescriptors,p=Object.getOwnPropertySymbols,T=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable,f=(r,e,t)=>e in r?x(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,i=(r,e)=>{for(var t in e||(e={}))T.call(e,t)&&f(r,t,e[t]);if(p)for(var t of p(e))z.call(e,t)&&f(r,t,e[t]);return r},g=(r,e)=>S(r,_(e));function k(r){return g(i({},r),{level:r?.level||c.level})}function v(r,e=n){return r[e]||\"\"}function b(r,e,t=n){return r[t]=e,r}function y(r,e=n){let t=\"\";return typeof r.bindings>\"u\"?t=v(r,e):t=r.bindings().context||\"\",t}function w(r,e,t=n){const o=y(r,t);return o.trim()?`${o}/${e}`:e}function E(r,e,t=n){const o=w(r,e,t),a=r.child({context:o});return b(a,o,t)}function C(r){var e,t;const o=new m((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:h(g(i({},r.opts),{level:\"trace\",browser:g(i({},(t=r.opts)==null?void 0:t.browser),{write:a=>o.write(a)})})),chunkLoggerController:o}}function I(r){var e;const t=new B((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:h(g(i({},r.opts),{level:\"trace\"}),t),chunkLoggerController:t}}function A(r){return typeof r.loggerOverride<\"u\"&&typeof r.loggerOverride!=\"string\"?{logger:r.loggerOverride,chunkLoggerController:null}:typeof window<\"u\"?C(r):I(r)}export{l as MAX_LOG_SIZE_IN_BYTES_DEFAULT,n as PINO_CUSTOM_CONTEXT_KEY,c as PINO_LOGGER_DEFAULTS,w as formatChildLoggerContext,E as generateChildLogger,C as generateClientLogger,A as generatePlatformLogger,I as generateServerLogger,v as getBrowserLoggerContext,k as getDefaultLoggerOptions,y as getLoggerContext,U as pino,b as setBrowserLoggerContext};\n//# sourceMappingURL=index.es.js.map\n","import{IEvents as o}from\"@walletconnect/events\";import c,{EventEmitter as i}from\"events\";class n extends o{constructor(s){super(),this.opts=s,this.protocol=\"wc\",this.version=2}}class l{constructor(s,t,e){this.core=s,this.logger=t}}class h extends o{constructor(s,t){super(),this.core=s,this.logger=t,this.records=new Map}}class a{constructor(s,t){this.logger=s,this.core=t}}class g extends o{constructor(s,t){super(),this.relayer=s,this.logger=t}}class u extends o{constructor(s){super()}}class p{constructor(s,t,e,f){this.core=s,this.logger=t,this.name=e}}class I{constructor(){this.map=new Map}}class d extends o{constructor(s,t){super(),this.relayer=s,this.logger=t}}class E{constructor(s,t){this.core=s,this.logger=t}}class x extends o{constructor(s,t){super(),this.core=s,this.logger=t}}class m{constructor(s,t){this.logger=s,this.core=t}}class y{constructor(s,t,e){this.core=s,this.logger=t,this.store=e}}class v{constructor(s,t){this.projectId=s,this.logger=t}}class C{constructor(s,t,e){this.core=s,this.logger=t,this.telemetryEnabled=e}}class b extends c{constructor(){super()}}class S{constructor(s){this.opts=s,this.protocol=\"wc\",this.version=2}}class w extends i{constructor(){super()}}class M{constructor(s){this.client=s}}export{n as ICore,l as ICrypto,v as IEchoClient,M as IEngine,w as IEngineEvents,C as IEventClient,x as IExpirer,h as IJsonRpcHistory,E as IKeyChain,a as IMessageTracker,m as IPairing,g as IPublisher,u as IRelayer,S as ISignClient,b as ISignClientEvents,p as IStore,d as ISubscriber,I as ISubscriberTopicMap,y as IVerify};\n//# sourceMappingURL=index.es.js.map\n","export function alloc(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.alloc != null) {\n return globalThis.Buffer.alloc(size);\n }\n return new Uint8Array(size);\n}\nexport function allocUnsafe(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(size);\n }\n return new Uint8Array(size);\n}","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '../alloc.js';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: { decode }\n };\n}\nconst string = createCodec('utf8', 'u', buf => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, str => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', buf => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, str => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii: ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;","import bases from './util/bases.js';\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (!base) {\n throw new Error(`Unsupported encoding \"${ encoding }\"`);\n }\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');\n }\n return base.encoder.encode(array).substring(1);\n}","export const PARSE_ERROR = \"PARSE_ERROR\";\nexport const INVALID_REQUEST = \"INVALID_REQUEST\";\nexport const METHOD_NOT_FOUND = \"METHOD_NOT_FOUND\";\nexport const INVALID_PARAMS = \"INVALID_PARAMS\";\nexport const INTERNAL_ERROR = \"INTERNAL_ERROR\";\nexport const SERVER_ERROR = \"SERVER_ERROR\";\nexport const RESERVED_ERROR_CODES = [-32700, -32600, -32601, -32602, -32603];\nexport const SERVER_ERROR_CODE_RANGE = [-32000, -32099];\nexport const STANDARD_ERROR_MAP = {\n [PARSE_ERROR]: { code: -32700, message: \"Parse error\" },\n [INVALID_REQUEST]: { code: -32600, message: \"Invalid Request\" },\n [METHOD_NOT_FOUND]: { code: -32601, message: \"Method not found\" },\n [INVALID_PARAMS]: { code: -32602, message: \"Invalid params\" },\n [INTERNAL_ERROR]: { code: -32603, message: \"Internal error\" },\n [SERVER_ERROR]: { code: -32000, message: \"Server error\" },\n};\nexport const DEFAULT_ERROR = SERVER_ERROR;\n//# sourceMappingURL=constants.js.map","import { SERVER_ERROR_CODE_RANGE, RESERVED_ERROR_CODES, STANDARD_ERROR_MAP, DEFAULT_ERROR, } from \"./constants\";\nexport function isServerErrorCode(code) {\n return code <= SERVER_ERROR_CODE_RANGE[0] && code >= SERVER_ERROR_CODE_RANGE[1];\n}\nexport function isReservedErrorCode(code) {\n return RESERVED_ERROR_CODES.includes(code);\n}\nexport function isValidErrorCode(code) {\n return typeof code === \"number\";\n}\nexport function getError(type) {\n if (!Object.keys(STANDARD_ERROR_MAP).includes(type)) {\n return STANDARD_ERROR_MAP[DEFAULT_ERROR];\n }\n return STANDARD_ERROR_MAP[type];\n}\nexport function getErrorByCode(code) {\n const match = Object.values(STANDARD_ERROR_MAP).find(e => e.code === code);\n if (!match) {\n return STANDARD_ERROR_MAP[DEFAULT_ERROR];\n }\n return match;\n}\nexport function validateJsonRpcError(response) {\n if (typeof response.error.code === \"undefined\") {\n return { valid: false, error: \"Missing code for JSON-RPC error\" };\n }\n if (typeof response.error.message === \"undefined\") {\n return { valid: false, error: \"Missing message for JSON-RPC error\" };\n }\n if (!isValidErrorCode(response.error.code)) {\n return {\n valid: false,\n error: `Invalid error code type for JSON-RPC: ${response.error.code}`,\n };\n }\n if (isReservedErrorCode(response.error.code)) {\n const error = getErrorByCode(response.error.code);\n if (error.message !== STANDARD_ERROR_MAP[DEFAULT_ERROR].message &&\n response.error.message === error.message) {\n return {\n valid: false,\n error: `Invalid error code message for JSON-RPC: ${response.error.code}`,\n };\n }\n }\n return { valid: true };\n}\nexport function parseConnectionError(e, url, type) {\n return e.message.includes(\"getaddrinfo ENOTFOUND\") || e.message.includes(\"connect ECONNREFUSED\")\n ? new Error(`Unavailable ${type} RPC url at ${url}`)\n : e;\n}\n//# sourceMappingURL=error.js.map","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isBrowserCryptoAvailable = exports.getSubtleCrypto = exports.getBrowerCrypto = void 0;\nfunction getBrowerCrypto() {\n return (global === null || global === void 0 ? void 0 : global.crypto) || (global === null || global === void 0 ? void 0 : global.msCrypto) || {};\n}\nexports.getBrowerCrypto = getBrowerCrypto;\nfunction getSubtleCrypto() {\n const browserCrypto = getBrowerCrypto();\n return browserCrypto.subtle || browserCrypto.webkitSubtle;\n}\nexports.getSubtleCrypto = getSubtleCrypto;\nfunction isBrowserCryptoAvailable() {\n return !!getBrowerCrypto() && !!getSubtleCrypto();\n}\nexports.isBrowserCryptoAvailable = isBrowserCryptoAvailable;\n//# sourceMappingURL=crypto.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isBrowser = exports.isNode = exports.isReactNative = void 0;\nfunction isReactNative() {\n return (typeof document === \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n navigator.product === \"ReactNative\");\n}\nexports.isReactNative = isReactNative;\nfunction isNode() {\n return (typeof process !== \"undefined\" &&\n typeof process.versions !== \"undefined\" &&\n typeof process.versions.node !== \"undefined\");\n}\nexports.isNode = isNode;\nfunction isBrowser() {\n return !isReactNative() && !isNode();\n}\nexports.isBrowser = isBrowser;\n//# sourceMappingURL=env.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./crypto\"), exports);\ntslib_1.__exportStar(require(\"./env\"), exports);\n//# sourceMappingURL=index.js.map","import { getError, getErrorByCode, isReservedErrorCode } from \"./error\";\nimport { INTERNAL_ERROR, SERVER_ERROR } from \"./constants\";\nexport function payloadId(entropy = 3) {\n const date = Date.now() * Math.pow(10, entropy);\n const extra = Math.floor(Math.random() * Math.pow(10, entropy));\n return date + extra;\n}\nexport function getBigIntRpcId(entropy = 6) {\n return BigInt(payloadId(entropy));\n}\nexport function formatJsonRpcRequest(method, params, id) {\n return {\n id: id || payloadId(),\n jsonrpc: \"2.0\",\n method,\n params,\n };\n}\nexport function formatJsonRpcResult(id, result) {\n return {\n id,\n jsonrpc: \"2.0\",\n result,\n };\n}\nexport function formatJsonRpcError(id, error, data) {\n return {\n id,\n jsonrpc: \"2.0\",\n error: formatErrorMessage(error, data),\n };\n}\nexport function formatErrorMessage(error, data) {\n if (typeof error === \"undefined\") {\n return getError(INTERNAL_ERROR);\n }\n if (typeof error === \"string\") {\n error = Object.assign(Object.assign({}, getError(SERVER_ERROR)), { message: error });\n }\n if (typeof data !== \"undefined\") {\n error.data = data;\n }\n if (isReservedErrorCode(error.code)) {\n error = getErrorByCode(error.code);\n }\n return error;\n}\n//# sourceMappingURL=format.js.map","class e{}class o extends e{constructor(c){super()}}class n extends e{constructor(){super()}}class r extends n{constructor(c){super()}}export{n as IBaseJsonRpcProvider,e as IEvents,o as IJsonRpcConnection,r as IJsonRpcProvider};\n//# sourceMappingURL=index.es.js.map\n","const HTTP_REGEX = \"^https?:\";\nconst WS_REGEX = \"^wss?:\";\nfunction getUrlProtocol(url) {\n const matches = url.match(new RegExp(/^\\w+:/, \"gi\"));\n if (!matches || !matches.length)\n return;\n return matches[0];\n}\nfunction matchRegexProtocol(url, regex) {\n const protocol = getUrlProtocol(url);\n if (typeof protocol === \"undefined\")\n return false;\n return new RegExp(regex).test(protocol);\n}\nexport function isHttpUrl(url) {\n return matchRegexProtocol(url, HTTP_REGEX);\n}\nexport function isWsUrl(url) {\n return matchRegexProtocol(url, WS_REGEX);\n}\nexport function isLocalhostUrl(url) {\n return new RegExp(\"wss?://localhost(:d{2,5})?\").test(url);\n}\n//# sourceMappingURL=url.js.map","export function isJsonRpcPayload(payload) {\n return (typeof payload === \"object\" &&\n \"id\" in payload &&\n \"jsonrpc\" in payload &&\n payload.jsonrpc === \"2.0\");\n}\nexport function isJsonRpcRequest(payload) {\n return isJsonRpcPayload(payload) && \"method\" in payload;\n}\nexport function isJsonRpcResponse(payload) {\n return isJsonRpcPayload(payload) && (isJsonRpcResult(payload) || isJsonRpcError(payload));\n}\nexport function isJsonRpcResult(payload) {\n return \"result\" in payload;\n}\nexport function isJsonRpcError(payload) {\n return \"error\" in payload;\n}\nexport function isJsonRpcValidationInvalid(validation) {\n return \"error\" in validation && validation.valid === false;\n}\n//# sourceMappingURL=validators.js.map","import{EventEmitter as c}from\"events\";import{IJsonRpcProvider as r,formatJsonRpcRequest as h,getBigIntRpcId as a,isJsonRpcError as d,isJsonRpcResponse as v}from\"@walletconnect/jsonrpc-utils\";class o extends r{constructor(t){super(t),this.events=new c,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,e){this.events.on(t,e)}once(t,e){this.events.once(t,e)}off(t,e){this.events.off(t,e)}removeListener(t,e){this.events.removeListener(t,e)}async request(t,e){return this.requestStrict(h(t.method,t.params||[],t.id||a().toString()),e)}async requestStrict(t,e){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${t.id}`,n=>{d(n)?s(n.error):i(n.result)});try{await this.connection.send(t,e)}catch(n){s(n)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit(\"payload\",t),v(t)?this.events.emit(`${t.id}`,t):this.events.emit(\"message\",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit(\"error\",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:\"\"}`)),this.events.emit(\"disconnect\")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t==\"string\"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit(\"connect\"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on(\"payload\",t=>this.onPayload(t)),this.connection.on(\"close\",t=>this.onClose(t)),this.connection.on(\"error\",t=>this.events.emit(\"error\",t)),this.connection.on(\"register_error\",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}export{o as JsonRpcProvider,o as default};\n//# sourceMappingURL=index.es.js.map\n","import{EventEmitter as u}from\"events\";import{safeJsonStringify as p,safeJsonParse as g}from\"@walletconnect/safe-json\";import{isWsUrl as d,isReactNative as y,isLocalhostUrl as m,formatJsonRpcError as k,parseConnectionError as v}from\"@walletconnect/jsonrpc-utils\";const w=()=>typeof WebSocket<\"u\"?WebSocket:typeof global<\"u\"&&typeof global.WebSocket<\"u\"?global.WebSocket:typeof window<\"u\"&&typeof window.WebSocket<\"u\"?window.WebSocket:typeof self<\"u\"&&typeof self.WebSocket<\"u\"?self.WebSocket:require(\"ws\"),b=()=>typeof WebSocket<\"u\"||typeof global<\"u\"&&typeof global.WebSocket<\"u\"||typeof window<\"u\"&&typeof window.WebSocket<\"u\"||typeof self<\"u\"&&typeof self.WebSocket<\"u\",a=c=>c.split(\"?\")[0],h=10,S=w();class f{constructor(e){if(this.url=e,this.events=new u,this.registering=!1,!d(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<\"u\"}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)=>{if(typeof this.socket>\"u\"){t(new Error(\"Connection already closed\"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>\"u\"&&(this.socket=await this.register());try{this.socket.send(p(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!d(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount(\"register_error\")>=t||this.events.listenerCount(\"open\")>=t)&&this.events.setMaxListeners(t+1),new Promise((n,o)=>{this.events.once(\"register_error\",s=>{this.resetMaxListeners(),o(s)}),this.events.once(\"open\",()=>{if(this.resetMaxListeners(),typeof this.socket>\"u\")return o(new Error(\"WebSocket connection is missing or invalid\"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,n)=>{const o=new URLSearchParams(e).get(\"origin\"),s=y()?{headers:{origin:o}}:{rejectUnauthorized:!m(e)},i=new S(e,[],s);b()?i.onerror=r=>{const l=r;n(this.emitError(l.error))}:i.on(\"error\",r=>{n(this.emitError(r))}),i.onopen=()=>{this.onOpen(i),t(i)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),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(typeof e.data>\"u\")return;const t=typeof e.data==\"string\"?g(e.data):e.data;this.events.emit(\"payload\",t)}onError(e,t){const n=this.parseError(t),o=n.message||n.toString(),s=k(e,o);this.events.emit(\"payload\",s)}parseError(e,t=this.url){return v(e,a(t),\"WS\")}resetMaxListeners(){this.events.getMaxListeners()>h&&this.events.setMaxListeners(h)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${a(this.url)}`));return this.events.emit(\"register_error\",t),t}}export{f as WsConnection,f as default};\n//# sourceMappingURL=index.es.js.map\n","/**\n * Lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright JS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\n/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\n/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n Symbol = root.Symbol,\n Uint8Array = root.Uint8Array,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeKeys = overArg(Object.keys, Object);\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView'),\n Map = getNative(root, 'Map'),\n Promise = getNative(root, 'Promise'),\n Set = getNative(root, 'Set'),\n WeakMap = getNative(root, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\n/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\n/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\n/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(array);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\n/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\n/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = isEqual;\n","import mi,{EventEmitter as U}from\"events\";import{HEARTBEAT_EVENTS as j,HeartBeat as bi}from\"@walletconnect/heartbeat\";import fi from\"@walletconnect/keyvaluestorage\";import{generateChildLogger as E,getLoggerContext as C,pino as _i,getDefaultLoggerOptions as Ie,generatePlatformLogger as Ei}from\"@walletconnect/logger\";import{IMessageTracker as vi,IPublisher as wi,ISubscriber as Ii,IRelayer as Ti,IStore as Ci,IJsonRpcHistory as Pi,IExpirer as Si,IVerify as Ri,IEchoClient as xi,IEventClient as Oi,ICore as Ai}from\"@walletconnect/types\";import{ONE_DAY as F,SIX_HOURS as Ni,THIRTY_DAYS as ee,FIVE_SECONDS as Te,THIRTY_SECONDS as oe,toMiliseconds as w,ONE_MINUTE as ae,ONE_SECOND as q,Watch as zi,FIVE_MINUTES as he,fromMiliseconds as Ce}from\"@walletconnect/time\";import{safeJsonStringify as Li,safeJsonParse as Pe}from\"@walletconnect/safe-json\";import*as te from\"@walletconnect/relay-auth\";import{decodeJWT as Se}from\"@walletconnect/relay-auth\";import{getInternalError as d,mapToObj as Re,objToMap as xe,generateRandomBytes32 as ce,generateKeyPair as $i,deriveSymKey as ki,hashKey as Mi,validateEncoding as Ui,isTypeTwoEnvelope as Oe,encodeTypeTwoEnvelope as Fi,isTypeOneEnvelope as Ae,encrypt as Ki,validateDecoding as Bi,decodeTypeTwoEnvelope as Vi,decrypt as ji,deserialize as Ne,decodeTypeByte as qi,BASE64 as ze,BASE16 as Gi,hashMessage as le,getRelayProtocolName as ue,createExpiringPromise as K,getRelayProtocolApi as G,isUndefined as de,getSdkError as H,isValidArray as Hi,isNode as Le,getBundleId as Yi,isOnline as $e,calcExpiry as Y,formatRelayRpcUrl as Ji,subscribeToNetworkChange as Xi,isProposalStruct as Wi,isSessionStruct as Zi,TYPE_1 as Qi,formatUri as ke,parseUri as Me,createDelayedPromise as es,engineEvent as pe,isExpired as Ue,isValidParams as ge,isValidUrl as ts,isValidString as is,parseExpirerTarget as ss,formatTopicTarget as rs,formatIdTarget as ns,isBrowser as os,verifyP256Jwt as as,isTestRun as Fe,uuidv4 as Ke,formatUA as hs,getAppMetadata as cs}from\"@walletconnect/utils\";import{toString as ls}from\"uint8arrays\";import{JsonRpcProvider as us}from\"@walletconnect/jsonrpc-provider\";import{getBigIntRpcId as Be,isJsonRpcRequest as Ve,isJsonRpcResponse as je,formatJsonRpcResult as qe,formatJsonRpcRequest as Ge,formatJsonRpcError as ds,isJsonRpcResult as ps,isJsonRpcError as He}from\"@walletconnect/jsonrpc-utils\";import gs from\"@walletconnect/jsonrpc-ws-connection\";import ys from\"lodash.isequal\";import{getDocument as Ds}from\"@walletconnect/window-getters\";const ye=\"wc\",De=2,ie=\"core\",x=`${ye}@2:${ie}:`,Ye={name:ie,logger:\"error\"},Je={database:\":memory:\"},Xe=\"crypto\",me=\"client_ed25519_seed\",We=F,Ze=\"keychain\",Qe=\"0.3\",et=\"messages\",tt=\"0.3\",it=Ni,st=\"publisher\",rt=\"irn\",nt=\"error\",be=\"wss://relay.walletconnect.org\",ot=\"relayer\",v={message:\"relayer_message\",message_ack:\"relayer_message_ack\",connect:\"relayer_connect\",disconnect:\"relayer_disconnect\",error:\"relayer_error\",connection_stalled:\"relayer_connection_stalled\",transport_closed:\"relayer_transport_closed\",publish:\"relayer_publish\"},at=\"_subscription\",I={payload:\"payload\",connect:\"connect\",disconnect:\"disconnect\",error:\"error\"},ht=.1,ms={database:\":memory:\"},se=\"2.17.2\",bs=1e4,M={link_mode:\"link_mode\",relay:\"relay\"},ct=\"0.3\",lt=\"WALLETCONNECT_CLIENT_ID\",fe=\"WALLETCONNECT_LINK_MODE_APPS\",O={created:\"subscription_created\",deleted:\"subscription_deleted\",expired:\"subscription_expired\",disabled:\"subscription_disabled\",sync:\"subscription_sync\",resubscribed:\"subscription_resubscribed\"},fs=ee,ut=\"subscription\",dt=\"0.3\",pt=Te*1e3,gt=\"pairing\",yt=\"0.3\",_s=ee,B={wc_pairingDelete:{req:{ttl:F,prompt:!1,tag:1e3},res:{ttl:F,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:oe,prompt:!1,tag:1002},res:{ttl:oe,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:F,prompt:!1,tag:0},res:{ttl:F,prompt:!1,tag:0}}},V={create:\"pairing_create\",expire:\"pairing_expire\",delete:\"pairing_delete\",ping:\"pairing_ping\"},P={created:\"history_created\",updated:\"history_updated\",deleted:\"history_deleted\",sync:\"history_sync\"},Dt=\"history\",mt=\"0.3\",bt=\"expirer\",S={created:\"expirer_created\",deleted:\"expirer_deleted\",expired:\"expirer_expired\",sync:\"expirer_sync\"},ft=\"0.3\",Es=F,_t=\"verify-api\",vs=\"https://verify.walletconnect.com\",Et=\"https://verify.walletconnect.org\",J=Et,vt=`${J}/v3`,wt=[vs,Et],It=\"echo\",Tt=\"https://echo.walletconnect.com\",ws=\"event-client\",z={pairing_started:\"pairing_started\",pairing_uri_validation_success:\"pairing_uri_validation_success\",pairing_uri_not_expired:\"pairing_uri_not_expired\",store_new_pairing:\"store_new_pairing\",subscribing_pairing_topic:\"subscribing_pairing_topic\",subscribe_pairing_topic_success:\"subscribe_pairing_topic_success\",existing_pairing:\"existing_pairing\",pairing_not_expired:\"pairing_not_expired\",emit_inactive_pairing:\"emit_inactive_pairing\",emit_session_proposal:\"emit_session_proposal\",subscribing_to_pairing_topic:\"subscribing_to_pairing_topic\"},$={no_wss_connection:\"no_wss_connection\",no_internet_connection:\"no_internet_connection\",malformed_pairing_uri:\"malformed_pairing_uri\",active_pairing_already_exists:\"active_pairing_already_exists\",subscribe_pairing_topic_failure:\"subscribe_pairing_topic_failure\",pairing_expired:\"pairing_expired\",proposal_expired:\"proposal_expired\",proposal_listener_not_found:\"proposal_listener_not_found\"},Is={session_approve_started:\"session_approve_started\",proposal_not_expired:\"proposal_not_expired\",session_namespaces_validation_success:\"session_namespaces_validation_success\",create_session_topic:\"create_session_topic\",subscribing_session_topic:\"subscribing_session_topic\",subscribe_session_topic_success:\"subscribe_session_topic_success\",publishing_session_approve:\"publishing_session_approve\",session_approve_publish_success:\"session_approve_publish_success\",store_session:\"store_session\",publishing_session_settle:\"publishing_session_settle\",session_settle_publish_success:\"session_settle_publish_success\"},Ts={no_internet_connection:\"no_internet_connection\",no_wss_connection:\"no_wss_connection\",proposal_expired:\"proposal_expired\",subscribe_session_topic_failure:\"subscribe_session_topic_failure\",session_approve_publish_failure:\"session_approve_publish_failure\",session_settle_publish_failure:\"session_settle_publish_failure\",session_approve_namespace_validation_failure:\"session_approve_namespace_validation_failure\",proposal_not_found:\"proposal_not_found\"},Cs={authenticated_session_approve_started:\"authenticated_session_approve_started\",authenticated_session_not_expired:\"authenticated_session_not_expired\",chains_caip2_compliant:\"chains_caip2_compliant\",chains_evm_compliant:\"chains_evm_compliant\",create_authenticated_session_topic:\"create_authenticated_session_topic\",cacaos_verified:\"cacaos_verified\",store_authenticated_session:\"store_authenticated_session\",subscribing_authenticated_session_topic:\"subscribing_authenticated_session_topic\",subscribe_authenticated_session_topic_success:\"subscribe_authenticated_session_topic_success\",publishing_authenticated_session_approve:\"publishing_authenticated_session_approve\",authenticated_session_approve_publish_success:\"authenticated_session_approve_publish_success\"},Ps={no_internet_connection:\"no_internet_connection\",no_wss_connection:\"no_wss_connection\",missing_session_authenticate_request:\"missing_session_authenticate_request\",session_authenticate_request_expired:\"session_authenticate_request_expired\",chains_caip2_compliant_failure:\"chains_caip2_compliant_failure\",chains_evm_compliant_failure:\"chains_evm_compliant_failure\",invalid_cacao:\"invalid_cacao\",subscribe_authenticated_session_topic_failure:\"subscribe_authenticated_session_topic_failure\",authenticated_session_approve_publish_failure:\"authenticated_session_approve_publish_failure\",authenticated_session_pending_request_not_found:\"authenticated_session_pending_request_not_found\"},Ct=.1,Pt=\"event-client\",St=86400,Rt=\"https://pulse.walletconnect.org/batch\";function Ss(o,e){if(o.length>=255)throw new TypeError(\"Alphabet too long\");for(var t=new Uint8Array(256),s=0;s>>0,T=new Uint8Array(A);y!==b;){for(var N=u[y],k=0,R=A-1;(N!==0||k<_)&&R!==-1;R--,k++)N+=256*T[R]>>>0,T[R]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error(\"Non-zero carry\");_=k,y++}for(var L=A-_;L!==A&&T[L]===0;)L++;for(var Q=h.repeat(g);L>>0,A=new Uint8Array(b);u[g];){var T=t[u.charCodeAt(g)];if(T===255)return;for(var N=0,k=b-1;(T!==0||N>>0,A[k]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error(\"Non-zero carry\");y=N,g++}if(u[g]!==\" \"){for(var R=b-y;R!==b&&A[R]===0;)R++;for(var L=new Uint8Array(_+(b-R)),Q=_;R!==b;)L[Q++]=A[R++];return L}}}function m(u){var g=D(u);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:D,decode:m}}var Rs=Ss,xs=Rs;const xt=o=>{if(o instanceof Uint8Array&&o.constructor.name===\"Uint8Array\")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error(\"Unknown type, must be binary type\")},Os=o=>new TextEncoder().encode(o),As=o=>new TextDecoder().decode(o);class Ns{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error(\"Unknown type, must be binary type\")}}class zs{constructor(e,t,s){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error(\"Invalid prefix character\");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=s}decode(e){if(typeof e==\"string\"){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))}else throw Error(\"Can only multibase decode strings\")}or(e){return Ot(this,e)}}class Ls{constructor(e){this.decoders=e}or(e){return Ot(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Ot=(o,e)=>new Ls({...o.decoders||{[o.prefix]:o},...e.decoders||{[e.prefix]:e}});class $s{constructor(e,t,s,i){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=i,this.encoder=new Ns(e,t,s),this.decoder=new zs(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const re=({name:o,prefix:e,encode:t,decode:s})=>new $s(o,e,t,s),X=({prefix:o,name:e,alphabet:t})=>{const{encode:s,decode:i}=xs(t,e);return re({prefix:o,name:e,encode:s,decode:r=>xt(i(r))})},ks=(o,e,t,s)=>{const i={};for(let l=0;l=8&&(a-=8,n[c++]=255&h>>a)}if(a>=t||255&h<<8-a)throw new SyntaxError(\"Unexpected end of data\");return n},Ms=(o,e,t)=>{const s=e[e.length-1]===\"=\",i=(1<t;)n-=t,r+=e[i&a>>n];if(n&&(r+=e[i&a<re({prefix:e,name:o,encode(i){return Ms(i,s,t)},decode(i){return ks(i,s,t,o)}}),Us=re({prefix:\"\\0\",name:\"identity\",encode:o=>As(o),decode:o=>Os(o)});var Fs=Object.freeze({__proto__:null,identity:Us});const Ks=f({prefix:\"0\",name:\"base2\",alphabet:\"01\",bitsPerChar:1});var Bs=Object.freeze({__proto__:null,base2:Ks});const Vs=f({prefix:\"7\",name:\"base8\",alphabet:\"01234567\",bitsPerChar:3});var js=Object.freeze({__proto__:null,base8:Vs});const qs=X({prefix:\"9\",name:\"base10\",alphabet:\"0123456789\"});var Gs=Object.freeze({__proto__:null,base10:qs});const Hs=f({prefix:\"f\",name:\"base16\",alphabet:\"0123456789abcdef\",bitsPerChar:4}),Ys=f({prefix:\"F\",name:\"base16upper\",alphabet:\"0123456789ABCDEF\",bitsPerChar:4});var Js=Object.freeze({__proto__:null,base16:Hs,base16upper:Ys});const Xs=f({prefix:\"b\",name:\"base32\",alphabet:\"abcdefghijklmnopqrstuvwxyz234567\",bitsPerChar:5}),Ws=f({prefix:\"B\",name:\"base32upper\",alphabet:\"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\",bitsPerChar:5}),Zs=f({prefix:\"c\",name:\"base32pad\",alphabet:\"abcdefghijklmnopqrstuvwxyz234567=\",bitsPerChar:5}),Qs=f({prefix:\"C\",name:\"base32padupper\",alphabet:\"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=\",bitsPerChar:5}),er=f({prefix:\"v\",name:\"base32hex\",alphabet:\"0123456789abcdefghijklmnopqrstuv\",bitsPerChar:5}),tr=f({prefix:\"V\",name:\"base32hexupper\",alphabet:\"0123456789ABCDEFGHIJKLMNOPQRSTUV\",bitsPerChar:5}),ir=f({prefix:\"t\",name:\"base32hexpad\",alphabet:\"0123456789abcdefghijklmnopqrstuv=\",bitsPerChar:5}),sr=f({prefix:\"T\",name:\"base32hexpadupper\",alphabet:\"0123456789ABCDEFGHIJKLMNOPQRSTUV=\",bitsPerChar:5}),rr=f({prefix:\"h\",name:\"base32z\",alphabet:\"ybndrfg8ejkmcpqxot1uwisza345h769\",bitsPerChar:5});var nr=Object.freeze({__proto__:null,base32:Xs,base32upper:Ws,base32pad:Zs,base32padupper:Qs,base32hex:er,base32hexupper:tr,base32hexpad:ir,base32hexpadupper:sr,base32z:rr});const or=X({prefix:\"k\",name:\"base36\",alphabet:\"0123456789abcdefghijklmnopqrstuvwxyz\"}),ar=X({prefix:\"K\",name:\"base36upper\",alphabet:\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"});var hr=Object.freeze({__proto__:null,base36:or,base36upper:ar});const cr=X({name:\"base58btc\",prefix:\"z\",alphabet:\"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"}),lr=X({name:\"base58flickr\",prefix:\"Z\",alphabet:\"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\"});var ur=Object.freeze({__proto__:null,base58btc:cr,base58flickr:lr});const dr=f({prefix:\"m\",name:\"base64\",alphabet:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",bitsPerChar:6}),pr=f({prefix:\"M\",name:\"base64pad\",alphabet:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\",bitsPerChar:6}),gr=f({prefix:\"u\",name:\"base64url\",alphabet:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\",bitsPerChar:6}),yr=f({prefix:\"U\",name:\"base64urlpad\",alphabet:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=\",bitsPerChar:6});var Dr=Object.freeze({__proto__:null,base64:dr,base64pad:pr,base64url:gr,base64urlpad:yr});const At=Array.from(\"\\u{1F680}\\u{1FA90}\\u2604\\u{1F6F0}\\u{1F30C}\\u{1F311}\\u{1F312}\\u{1F313}\\u{1F314}\\u{1F315}\\u{1F316}\\u{1F317}\\u{1F318}\\u{1F30D}\\u{1F30F}\\u{1F30E}\\u{1F409}\\u2600\\u{1F4BB}\\u{1F5A5}\\u{1F4BE}\\u{1F4BF}\\u{1F602}\\u2764\\u{1F60D}\\u{1F923}\\u{1F60A}\\u{1F64F}\\u{1F495}\\u{1F62D}\\u{1F618}\\u{1F44D}\\u{1F605}\\u{1F44F}\\u{1F601}\\u{1F525}\\u{1F970}\\u{1F494}\\u{1F496}\\u{1F499}\\u{1F622}\\u{1F914}\\u{1F606}\\u{1F644}\\u{1F4AA}\\u{1F609}\\u263A\\u{1F44C}\\u{1F917}\\u{1F49C}\\u{1F614}\\u{1F60E}\\u{1F607}\\u{1F339}\\u{1F926}\\u{1F389}\\u{1F49E}\\u270C\\u2728\\u{1F937}\\u{1F631}\\u{1F60C}\\u{1F338}\\u{1F64C}\\u{1F60B}\\u{1F497}\\u{1F49A}\\u{1F60F}\\u{1F49B}\\u{1F642}\\u{1F493}\\u{1F929}\\u{1F604}\\u{1F600}\\u{1F5A4}\\u{1F603}\\u{1F4AF}\\u{1F648}\\u{1F447}\\u{1F3B6}\\u{1F612}\\u{1F92D}\\u2763\\u{1F61C}\\u{1F48B}\\u{1F440}\\u{1F62A}\\u{1F611}\\u{1F4A5}\\u{1F64B}\\u{1F61E}\\u{1F629}\\u{1F621}\\u{1F92A}\\u{1F44A}\\u{1F973}\\u{1F625}\\u{1F924}\\u{1F449}\\u{1F483}\\u{1F633}\\u270B\\u{1F61A}\\u{1F61D}\\u{1F634}\\u{1F31F}\\u{1F62C}\\u{1F643}\\u{1F340}\\u{1F337}\\u{1F63B}\\u{1F613}\\u2B50\\u2705\\u{1F97A}\\u{1F308}\\u{1F608}\\u{1F918}\\u{1F4A6}\\u2714\\u{1F623}\\u{1F3C3}\\u{1F490}\\u2639\\u{1F38A}\\u{1F498}\\u{1F620}\\u261D\\u{1F615}\\u{1F33A}\\u{1F382}\\u{1F33B}\\u{1F610}\\u{1F595}\\u{1F49D}\\u{1F64A}\\u{1F639}\\u{1F5E3}\\u{1F4AB}\\u{1F480}\\u{1F451}\\u{1F3B5}\\u{1F91E}\\u{1F61B}\\u{1F534}\\u{1F624}\\u{1F33C}\\u{1F62B}\\u26BD\\u{1F919}\\u2615\\u{1F3C6}\\u{1F92B}\\u{1F448}\\u{1F62E}\\u{1F646}\\u{1F37B}\\u{1F343}\\u{1F436}\\u{1F481}\\u{1F632}\\u{1F33F}\\u{1F9E1}\\u{1F381}\\u26A1\\u{1F31E}\\u{1F388}\\u274C\\u270A\\u{1F44B}\\u{1F630}\\u{1F928}\\u{1F636}\\u{1F91D}\\u{1F6B6}\\u{1F4B0}\\u{1F353}\\u{1F4A2}\\u{1F91F}\\u{1F641}\\u{1F6A8}\\u{1F4A8}\\u{1F92C}\\u2708\\u{1F380}\\u{1F37A}\\u{1F913}\\u{1F619}\\u{1F49F}\\u{1F331}\\u{1F616}\\u{1F476}\\u{1F974}\\u25B6\\u27A1\\u2753\\u{1F48E}\\u{1F4B8}\\u2B07\\u{1F628}\\u{1F31A}\\u{1F98B}\\u{1F637}\\u{1F57A}\\u26A0\\u{1F645}\\u{1F61F}\\u{1F635}\\u{1F44E}\\u{1F932}\\u{1F920}\\u{1F927}\\u{1F4CC}\\u{1F535}\\u{1F485}\\u{1F9D0}\\u{1F43E}\\u{1F352}\\u{1F617}\\u{1F911}\\u{1F30A}\\u{1F92F}\\u{1F437}\\u260E\\u{1F4A7}\\u{1F62F}\\u{1F486}\\u{1F446}\\u{1F3A4}\\u{1F647}\\u{1F351}\\u2744\\u{1F334}\\u{1F4A3}\\u{1F438}\\u{1F48C}\\u{1F4CD}\\u{1F940}\\u{1F922}\\u{1F445}\\u{1F4A1}\\u{1F4A9}\\u{1F450}\\u{1F4F8}\\u{1F47B}\\u{1F910}\\u{1F92E}\\u{1F3BC}\\u{1F975}\\u{1F6A9}\\u{1F34E}\\u{1F34A}\\u{1F47C}\\u{1F48D}\\u{1F4E3}\\u{1F942}\"),mr=At.reduce((o,e,t)=>(o[t]=e,o),[]),br=At.reduce((o,e,t)=>(o[e.codePointAt(0)]=t,o),[]);function fr(o){return o.reduce((e,t)=>(e+=mr[t],e),\"\")}function _r(o){const e=[];for(const t of o){const s=br[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Er=re({prefix:\"\\u{1F680}\",name:\"base256emoji\",encode:fr,decode:_r});var vr=Object.freeze({__proto__:null,base256emoji:Er}),wr=zt,Nt=128,Ir=127,Tr=~Ir,Cr=Math.pow(2,31);function zt(o,e,t){e=e||[],t=t||0;for(var s=t;o>=Cr;)e[t++]=o&255|Nt,o/=128;for(;o&Tr;)e[t++]=o&255|Nt,o>>>=7;return e[t]=o|0,zt.bytes=t-s+1,e}var Pr=_e,Sr=128,Lt=127;function _e(o,s){var t=0,s=s||0,i=0,r=s,n,a=o.length;do{if(r>=a)throw _e.bytes=0,new RangeError(\"Could not decode varint\");n=o[r++],t+=i<28?(n&Lt)<=Sr);return _e.bytes=r-s,t}var Rr=Math.pow(2,7),xr=Math.pow(2,14),Or=Math.pow(2,21),Ar=Math.pow(2,28),Nr=Math.pow(2,35),zr=Math.pow(2,42),Lr=Math.pow(2,49),$r=Math.pow(2,56),kr=Math.pow(2,63),Mr=function(o){return o($t.encode(o,e,t),e),Mt=o=>$t.encodingLength(o),Ee=(o,e)=>{const t=e.byteLength,s=Mt(o),i=s+Mt(t),r=new Uint8Array(i+t);return kt(o,r,0),kt(t,r,s),r.set(e,i),new Fr(o,t,e,r)};class Fr{constructor(e,t,s,i){this.code=e,this.size=t,this.digest=s,this.bytes=i}}const Ut=({name:o,code:e,encode:t})=>new Kr(o,e,t);class Kr{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Ee(this.code,t):t.then(s=>Ee(this.code,s))}else throw Error(\"Unknown type, must be binary type\")}}const Ft=o=>async e=>new Uint8Array(await crypto.subtle.digest(o,e)),Br=Ut({name:\"sha2-256\",code:18,encode:Ft(\"SHA-256\")}),Vr=Ut({name:\"sha2-512\",code:19,encode:Ft(\"SHA-512\")});var jr=Object.freeze({__proto__:null,sha256:Br,sha512:Vr});const Kt=0,qr=\"identity\",Bt=xt,Gr=o=>Ee(Kt,Bt(o)),Hr={code:Kt,name:qr,encode:Bt,digest:Gr};var Yr=Object.freeze({__proto__:null,identity:Hr});new TextEncoder,new TextDecoder;const Vt={...Fs,...Bs,...js,...Gs,...Js,...nr,...hr,...ur,...Dr,...vr};({...jr,...Yr});function Jr(o=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(o):new Uint8Array(o)}function jt(o,e,t,s){return{name:o,prefix:e,encoder:{name:o,prefix:e,encode:t},decoder:{decode:s}}}const qt=jt(\"utf8\",\"u\",o=>\"u\"+new TextDecoder(\"utf8\").decode(o),o=>new TextEncoder().encode(o.substring(1))),ve=jt(\"ascii\",\"a\",o=>{let e=\"a\";for(let t=0;t{o=o.substring(1);const e=Jr(o.length);for(let t=0;t{if(!this.initialized){const s=await this.getKeyChain();typeof s<\"u\"&&(this.keychain=s),this.initialized=!0}},this.has=s=>(this.isInitialized(),this.keychain.has(s)),this.set=async(s,i)=>{this.isInitialized(),this.keychain.set(s,i),await this.persist()},this.get=s=>{this.isInitialized();const i=this.keychain.get(s);if(typeof i>\"u\"){const{message:r}=d(\"NO_MATCHING_KEY\",`${this.name}: ${s}`);throw new Error(r)}return i},this.del=async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()},this.core=e,this.logger=E(t,this.name)}get context(){return C(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+\"//\"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Re(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<\"u\"?xe(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}}class Ht{constructor(e,t,s){this.core=e,this.logger=t,this.name=Xe,this.randomSessionIdentifier=ce(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),r=te.generateKeyPair(i);return te.encodeIss(r.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=$i();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const r=await this.getClientSeed(),n=te.generateKeyPair(r),a=this.randomSessionIdentifier,h=We;return await te.signJWT(a,i,h,n)},this.generateSharedKey=(i,r,n)=>{this.isInitialized();const a=this.getPrivateKey(i),h=ki(a,r);return this.setSymKey(h,n)},this.setSymKey=async(i,r)=>{this.isInitialized();const n=r||Mi(i);return await this.keychain.set(n,i),n},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,r,n)=>{this.isInitialized();const a=Ui(n),h=Li(r);if(Oe(a))return Fi(h,n?.encoding);if(Ae(a)){const D=a.senderPublicKey,m=a.receiverPublicKey;i=await this.generateSharedKey(D,m)}const c=this.getSymKey(i),{type:l,senderPublicKey:p}=a;return Ki({type:l,symKey:c,message:h,senderPublicKey:p,encoding:n?.encoding})},this.decode=async(i,r,n)=>{this.isInitialized();const a=Bi(r,n);if(Oe(a)){const h=Vi(r,n?.encoding);return Pe(h)}if(Ae(a)){const h=a.receiverPublicKey,c=a.senderPublicKey;i=await this.generateSharedKey(h,c)}try{const h=this.getSymKey(i),c=ji({symKey:h,encoded:r,encoding:n?.encoding});return Pe(c)}catch(h){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=(i,r=ze)=>{const n=Ne({encoded:i,encoding:r});return qi(n.type)},this.getPayloadSenderPublicKey=(i,r=ze)=>{const n=Ne({encoded:i,encoding:r});return n.senderPublicKey?ls(n.senderPublicKey,Gi):void 0},this.core=e,this.logger=E(t,this.name),this.keychain=s||new Gt(this.core,this.logger)}get context(){return C(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(me)}catch{e=ce(),await this.keychain.set(me,e)}return Wr(e,\"base16\")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}}class Yt extends vi{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=et,this.version=tt,this.initialized=!1,this.storagePrefix=x,this.init=async()=>{if(!this.initialized){this.logger.trace(\"Initialized\");try{const s=await this.getRelayerMessages();typeof s<\"u\"&&(this.messages=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:\"method\",method:\"restore\",size:this.messages.size})}catch(s){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(s)}finally{this.initialized=!0}}},this.set=async(s,i)=>{this.isInitialized();const r=le(i);let n=this.messages.get(s);return typeof n>\"u\"&&(n={}),typeof n[r]<\"u\"||(n[r]=i,this.messages.set(s,n),await this.persist()),r},this.get=s=>{this.isInitialized();let i=this.messages.get(s);return typeof i>\"u\"&&(i={}),i},this.has=(s,i)=>{this.isInitialized();const r=this.get(s),n=le(i);return typeof r[n]<\"u\"},this.del=async s=>{this.isInitialized(),this.messages.delete(s),await this.persist()},this.logger=E(e,this.name),this.core=t}get context(){return C(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+\"//\"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Re(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<\"u\"?xe(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}}class Zr extends wi{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new U,this.name=st,this.queue=new Map,this.publishTimeout=w(ae),this.failedPublishTimeout=w(q),this.needsTransportRestart=!1,this.publish=async(s,i,r)=>{var n;this.logger.debug(\"Publishing Payload\"),this.logger.trace({type:\"method\",method:\"publish\",params:{topic:s,message:i,opts:r}});const a=r?.ttl||it,h=ue(r),c=r?.prompt||!1,l=r?.tag||0,p=r?.id||Be().toString(),D={topic:s,message:i,opts:{ttl:a,relay:h,prompt:c,tag:l,id:p,attestation:r?.attestation}},m=`Failed to publish payload, please try again. id:${p} tag:${l}`,u=Date.now();let g,_=1;try{for(;g===void 0;){if(Date.now()-u>this.publishTimeout)throw new Error(m);this.logger.trace({id:p,attempts:_},`publisher.publish - attempt ${_}`),g=await await K(this.rpcPublish(s,i,a,h,c,l,p,r?.attestation).catch(y=>this.logger.warn(y)),this.publishTimeout,m),_++,g||await new Promise(y=>setTimeout(y,this.failedPublishTimeout))}this.relayer.events.emit(v.publish,D),this.logger.debug(\"Successfully Published Payload\"),this.logger.trace({type:\"method\",method:\"publish\",params:{id:p,topic:s,message:i,opts:r}})}catch(y){if(this.logger.debug(\"Failed to Publish Payload\"),this.logger.error(y),(n=r?.internal)!=null&&n.throwOnFailedPublish)throw y;this.queue.set(p,D)}},this.on=(s,i)=>{this.events.on(s,i)},this.once=(s,i)=>{this.events.once(s,i)},this.off=(s,i)=>{this.events.off(s,i)},this.removeListener=(s,i)=>{this.events.removeListener(s,i)},this.relayer=e,this.logger=E(t,this.name),this.registerEventListeners()}get context(){return C(this.logger)}rpcPublish(e,t,s,i,r,n,a,h){var c,l,p,D;const m={method:G(i.protocol).publish,params:{topic:e,message:t,ttl:s,prompt:r,tag:n,attestation:h},id:a};return de((c=m.params)==null?void 0:c.prompt)&&((l=m.params)==null||delete l.prompt),de((p=m.params)==null?void 0:p.tag)&&((D=m.params)==null||delete D.tag),this.logger.debug(\"Outgoing Relay Payload\"),this.logger.trace({type:\"message\",direction:\"outgoing\",request:m}),this.relayer.request(m)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:t,message:s,opts:i}=e;await this.publish(t,s,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(j.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(v.connection_stalled);return}this.checkQueue()}),this.relayer.on(v.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class Qr{constructor(){this.map=new Map,this.set=(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,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\"){this.map.delete(e);return}if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const i=s.filter(r=>r!==t);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var en=Object.defineProperty,tn=Object.defineProperties,sn=Object.getOwnPropertyDescriptors,Jt=Object.getOwnPropertySymbols,rn=Object.prototype.hasOwnProperty,nn=Object.prototype.propertyIsEnumerable,Xt=(o,e,t)=>e in o?en(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,W=(o,e)=>{for(var t in e||(e={}))rn.call(e,t)&&Xt(o,t,e[t]);if(Jt)for(var t of Jt(e))nn.call(e,t)&&Xt(o,t,e[t]);return o},we=(o,e)=>tn(o,sn(e));class Wt extends Ii{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new Qr,this.events=new U,this.name=ut,this.version=dt,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel=\"pending_sub_watch_label\",this.pollingInterval=20,this.storagePrefix=x,this.subscribeTimeout=w(ae),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],this.init=async()=>{this.initialized||(this.logger.trace(\"Initialized\"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId(),await this.restore()),this.initialized=!0},this.subscribe=async(s,i)=>{this.isInitialized(),this.logger.debug(\"Subscribing Topic\"),this.logger.trace({type:\"method\",method:\"subscribe\",params:{topic:s,opts:i}});try{const r=ue(i),n={topic:s,relay:r,transportType:i?.transportType};this.pending.set(s,n);const a=await this.rpcSubscribe(s,r,i);return typeof a==\"string\"&&(this.onSubscribe(a,n),this.logger.debug(\"Successfully Subscribed Topic\"),this.logger.trace({type:\"method\",method:\"subscribe\",params:{topic:s,opts:i}})),a}catch(r){throw this.logger.debug(\"Failed to Subscribe Topic\"),this.logger.error(r),r}},this.unsubscribe=async(s,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<\"u\"?await this.unsubscribeById(s,i.id,i):await this.unsubscribeByTopic(s,i)},this.isSubscribed=async s=>{if(this.topics.includes(s))return!0;const i=`${this.pendingSubscriptionWatchLabel}_${s}`;return await new Promise((r,n)=>{const a=new zi;a.start(i);const h=setInterval(()=>{!this.pending.has(s)&&this.topics.includes(s)&&(clearInterval(h),a.stop(i),r(!0)),a.elapsed(i)>=pt&&(clearInterval(h),a.stop(i),n(new Error(\"Subscription resolution timeout\")))},this.pollingInterval)}).catch(()=>!1)},this.on=(s,i)=>{this.events.on(s,i)},this.once=(s,i)=>{this.events.once(s,i)},this.off=(s,i)=>{this.events.off(s,i)},this.removeListener=(s,i)=>{this.events.removeListener(s,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=E(t,this.name),this.clientId=\"\"}get context(){return C(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 s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async i=>await this.unsubscribeById(e,i,t)))}async unsubscribeById(e,t,s){this.logger.debug(\"Unsubscribing Topic\"),this.logger.trace({type:\"method\",method:\"unsubscribe\",params:{topic:e,id:t,opts:s}});try{const i=ue(s);await this.rpcUnsubscribe(e,t,i);const r=H(\"USER_DISCONNECTED\",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug(\"Successfully Unsubscribed Topic\"),this.logger.trace({type:\"method\",method:\"unsubscribe\",params:{topic:e,id:t,opts:s}})}catch(i){throw this.logger.debug(\"Failed to Unsubscribe Topic\"),this.logger.error(i),i}}async rpcSubscribe(e,t,s){var i;s?.transportType===M.relay&&await this.restartToComplete();const r={method:G(t.protocol).subscribe,params:{topic:e}};this.logger.debug(\"Outgoing Relay Payload\"),this.logger.trace({type:\"payload\",direction:\"outgoing\",request:r});const n=(i=s?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=le(e+this.clientId);if(s?.transportType===M.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch(c=>this.logger.warn(c))},w(q)),a;const h=await K(this.relayer.request(r).catch(c=>this.logger.warn(c)),this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&n)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug(\"Outgoing Relay Subscribe Payload stalled\"),this.relayer.events.emit(v.connection_stalled),n)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:G(t.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug(\"Outgoing Relay Payload\"),this.logger.trace({type:\"payload\",direction:\"outgoing\",request:s});try{return await await K(this.relayer.request(s).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(v.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:G(t.protocol).batchFetchMessages,params:{topics:e.map(r=>r.topic)}};this.logger.debug(\"Outgoing Relay Payload\"),this.logger.trace({type:\"payload\",direction:\"outgoing\",request:s});let i;try{i=await await K(this.relayer.request(s).catch(r=>this.logger.warn(r)),this.subscribeTimeout)}catch{this.relayer.events.emit(v.connection_stalled)}return i}rpcUnsubscribe(e,t,s){const i={method:G(s.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,we(W({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,W({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),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.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,W({},t)),this.topicMap.set(t.topic,e),this.events.emit(O.created,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:s}=d(\"NO_MATCHING_KEY\",`${this.name}: ${e}`);throw new Error(s)}return t}deleteSubscription(e,t){this.logger.debug(\"Deleting subscription\"),this.logger.trace({type:\"method\",method:\"deleteSubscription\",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(O.deleted,we(W({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(O.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:t}=d(\"RESTORE_WILL_OVERRIDE\",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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);Hi(t)&&this.onBatchSubscribe(t.map((s,i)=>we(W({},e[i]),{id:s})))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(t.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(j.pulse,async()=>{await this.checkPending()}),this.events.on(O.created,async e=>{const t=O.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:\"event\",event:t,data:e}),await this.persist()}),this.events.on(O.deleted,async e=>{const t=O.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:\"event\",event:t,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen(),this.restartInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.restartInProgress||(clearInterval(t),e())},this.pollingInterval)})}}var on=Object.defineProperty,Zt=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,hn=Object.prototype.propertyIsEnumerable,Qt=(o,e,t)=>e in o?on(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,ei=(o,e)=>{for(var t in e||(e={}))an.call(e,t)&&Qt(o,t,e[t]);if(Zt)for(var t of Zt(e))hn.call(e,t)&&Qt(o,t,e[t]);return o};class ti extends Ti{constructor(e){super(e),this.protocol=\"wc\",this.version=2,this.events=new U,this.name=ot,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=[\"socket hang up\",\"stalled\",\"interrupted\"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=w(oe+q),this.request=async t=>{var s,i;this.logger.debug(\"Publishing Request Payload\");const r=t.id||Be().toString();await this.toEstablishConnection();try{const n=this.provider.request(t);this.requestsInFlight.set(r,{promise:n,request:t}),this.logger.trace({id:r,method:t.method,topic:(s=t.params)==null?void 0:s.topic},\"relayer.request - attempt to publish...\");const a=await new Promise(async(h,c)=>{const l=()=>{c(new Error(`relayer.request - publish interrupted, id: ${r}`))};this.provider.on(I.disconnect,l);const p=await n;this.provider.off(I.disconnect,l),h(p)});return this.logger.trace({id:r,method:t.method,topic:(i=t.params)==null?void 0:i.topic},\"relayer.request - published\"),a}catch(n){throw this.logger.debug(`Failed to Publish Request: ${r}`),n}finally{this.requestsInFlight.delete(r)}},this.resetPingTimeout=()=>{if(Le())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,i;(i=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t)}},this.onPayloadHandler=t=>{this.onProviderPayload(t),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.trace(\"relayer connected\"),this.startPingTimeout(),this.events.emit(v.connect)},this.onDisconnectHandler=()=>{this.logger.trace(\"relayer disconnected\"),this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.error(t),this.events.emit(v.error,t),this.logger.info(\"Fatal socket error received, closing transport\"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(I.payload,this.onPayloadHandler),this.provider.on(I.connect,this.onConnectHandler),this.provider.on(I.disconnect,this.onDisconnectHandler),this.provider.on(I.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<\"u\"&&typeof e.logger!=\"string\"?E(e.logger,this.name):_i(Ie({level:e.logger||nt})),this.messages=new Yt(this.logger,e.core),this.subscriber=new Wt(this,this.logger),this.publisher=new Zr(this,this.logger),this.relayUrl=e?.relayUrl||be,this.projectId=e.projectId,this.bundleId=Yi(),this.provider={}}async init(){if(this.logger.trace(\"Initialized\"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e)}}get context(){return C(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:M.relay})}async subscribe(e,t){var s,i,r;this.isInitialized(),t?.transportType===\"relay\"&&await this.toEstablishConnection();const n=typeof((s=t?.internal)==null?void 0:s.throwOnFailedPublish)>\"u\"?!0:(i=t?.internal)==null?void 0:i.throwOnFailedPublish;let a=((r=this.subscriber.topicMap.get(e))==null?void 0:r[0])||\"\",h;const c=l=>{l.topic===e&&(this.subscriber.off(O.created,c),h())};return await Promise.all([new Promise(l=>{h=l,this.subscriber.on(O.created,c)}),new Promise(async(l,p)=>{a=await this.subscriber.subscribe(e,ei({internal:{throwOnFailedPublish:n}},t)).catch(D=>{n&&p(D)})||a,l()})]),a}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 transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await K(this.provider.disconnect(),2e3,\"provider.disconnect()\").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(t,s)=>{const i=()=>{this.provider.off(I.disconnect,i),s(new Error(\"Connection interrupted while trying to subscribe\"))};this.provider.on(I.disconnect,i),await K(this.provider.connect(),w(ae),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(r=>{s(r)}).finally(()=>{clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),this.subscriber.start().catch(r=>{this.logger.error(r),this.onDisconnectHandler()}),this.hasExperiencedNetworkDisruption=!1,t()})}catch(t){this.logger.error(t);const s=t;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(s.message))throw t}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await $e())throw new Error(\"No internet connection detected. Please restart your network and try again.\")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace(\"Batch message events is empty. Ignoring...\");return}const t=e.sort((s,i)=>s.publishedAt-i.publishedAt);this.logger.trace(`Batch of ${t.length} message events sorted`);for(const s of t)try{await this.onMessageEvent(s)}catch(i){this.logger.warn(i)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const i=Y(he),r={topic:s,expiry:i,relay:{protocol:\"irn\"},active:!1};await this.core.pairing.pairings.set(s,r)}this.events.emit(v.message,e),await this.recordMessageEvent(e)}startPingTimeout(){var e,t,s,i,r;if(Le())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((r=(i=(s=this.provider)==null?void 0:s.connection)==null?void 0:i.socket)==null||r.once(\"ping\",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(n){this.logger.warn(n)}}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 us(new gs(Ji({sdkVersion:se,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:s}=e;await this.messages.set(t,s)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${s}`),!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,s);return i&&this.logger.debug(`Ignoring duplicate message: ${s}`),i}async onProviderPayload(e){if(this.logger.debug(\"Incoming Relay Payload\"),this.logger.trace({type:\"payload\",direction:\"incoming\",payload:e}),Ve(e)){if(!e.method.endsWith(at))return;const t=e.params,{topic:s,message:i,publishedAt:r,attestation:n}=t.data,a={topic:s,message:i,publishedAt:r,transportType:M.relay,attestation:n};this.logger.debug(\"Emitting Relayer Payload\"),this.logger.trace(ei({type:\"event\",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else je(e)&&this.events.emit(v.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(v.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=qe(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(I.payload,this.onPayloadHandler),this.provider.off(I.connect,this.onConnectHandler),this.provider.off(I.disconnect,this.onDisconnectHandler),this.provider.off(I.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await $e();Xi(async t=>{e!==t&&(e=t,t?await this.restartTransport().catch(s=>this.logger.error(s)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(v.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},w(ht))))}isInitialized(){if(!this.initialized){const{message:e}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.connected&&(clearInterval(t),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var cn=Object.defineProperty,ii=Object.getOwnPropertySymbols,ln=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,si=(o,e,t)=>e in o?cn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,ri=(o,e)=>{for(var t in e||(e={}))ln.call(e,t)&&si(o,t,e[t]);if(ii)for(var t of ii(e))un.call(e,t)&&si(o,t,e[t]);return o};class ni extends Ci{constructor(e,t,s,i=x,r=void 0){super(e,t,s,i),this.core=e,this.logger=t,this.name=s,this.map=new Map,this.version=ct,this.cached=[],this.initialized=!1,this.storagePrefix=x,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace(\"Initialized\"),await this.restore(),this.cached.forEach(n=>{this.getKey&&n!==null&&!de(n)?this.map.set(this.getKey(n),n):Wi(n)?this.map.set(n.id,n):Zi(n)&&this.map.set(n.topic,n)}),this.cached=[],this.initialized=!0)},this.set=async(n,a)=>{this.isInitialized(),this.map.has(n)?await this.update(n,a):(this.logger.debug(\"Setting value\"),this.logger.trace({type:\"method\",method:\"set\",key:n,value:a}),this.map.set(n,a),await this.persist())},this.get=n=>(this.isInitialized(),this.logger.debug(\"Getting value\"),this.logger.trace({type:\"method\",method:\"get\",key:n}),this.getData(n)),this.getAll=n=>(this.isInitialized(),n?this.values.filter(a=>Object.keys(n).every(h=>ys(a[h],n[h]))):this.values),this.update=async(n,a)=>{this.isInitialized(),this.logger.debug(\"Updating value\"),this.logger.trace({type:\"method\",method:\"update\",key:n,update:a});const h=ri(ri({},this.getData(n)),a);this.map.set(n,h),await this.persist()},this.delete=async(n,a)=>{this.isInitialized(),this.map.has(n)&&(this.logger.debug(\"Deleting value\"),this.logger.trace({type:\"method\",method:\"delete\",key:n,reason:a}),this.map.delete(n),this.addToRecentlyDeleted(n),await this.persist())},this.logger=E(t,this.name),this.storagePrefix=i,this.getKey=r}get context(){return C(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())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}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){if(this.recentlyDeleted.includes(e)){const{message:i}=d(\"MISSING_OR_INVALID\",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:s}=d(\"NO_MATCHING_KEY\",`${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}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:t}=d(\"RESTORE_WILL_OVERRIDE\",this.name);throw this.logger.error(t),new Error(t)}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}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}}class oi{constructor(e,t){this.core=e,this.logger=t,this.name=gt,this.version=yt,this.events=new mi,this.initialized=!1,this.storagePrefix=x,this.ignoredPayloadTypes=[Qi],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:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]},this.create=async s=>{this.isInitialized();const i=ce(),r=await this.core.crypto.setSymKey(i),n=Y(he),a={protocol:rt},h={topic:r,expiry:n,relay:a,active:!1,methods:s?.methods},c=ke({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:i,relay:a,expiryTimestamp:n,methods:s?.methods});return this.events.emit(V.create,h),this.core.expirer.set(r,n),await this.pairings.set(r,h),await this.core.relayer.subscribe(r,{transportType:s?.transportType}),{topic:r,uri:c}},this.pair=async s=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:s?.uri,trace:[z.pairing_started]}});this.isValidPair(s,i);const{topic:r,symKey:n,relay:a,expiryTimestamp:h,methods:c}=Me(s.uri);i.props.properties.topic=r,i.addTrace(z.pairing_uri_validation_success),i.addTrace(z.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(r)){if(l=this.pairings.get(r),i.addTrace(z.existing_pairing),l.active)throw i.setError($.active_pairing_already_exists),new Error(`Pairing already exists: ${r}. Please try again with a new connection URI.`);i.addTrace(z.pairing_not_expired)}const p=h||Y(he),D={topic:r,relay:a,expiry:p,active:!1,methods:c};this.core.expirer.set(r,p),await this.pairings.set(r,D),i.addTrace(z.store_new_pairing),s.activatePairing&&await this.activate({topic:r}),this.events.emit(V.create,D),i.addTrace(z.emit_inactive_pairing),this.core.crypto.keychain.has(r)||await this.core.crypto.setSymKey(n,r),i.addTrace(z.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError($.no_internet_connection)}try{await this.core.relayer.subscribe(r,{relay:a})}catch(m){throw i.setError($.subscribe_pairing_topic_failure),m}return i.addTrace(z.subscribe_pairing_topic_success),D},this.activate=async({topic:s})=>{this.isInitialized();const i=Y(ee);this.core.expirer.set(s,i),await this.pairings.update(s,{active:!0,expiry:i})},this.ping=async s=>{this.isInitialized(),await this.isValidPing(s);const{topic:i}=s;if(this.pairings.keys.includes(i)){const r=await this.sendRequest(i,\"wc_pairingPing\",{}),{done:n,resolve:a,reject:h}=es();this.events.once(pe(\"pairing_ping\",r),({error:c})=>{c?h(c):a()}),await n()}},this.updateExpiry=async({topic:s,expiry:i})=>{this.isInitialized(),await this.pairings.update(s,{expiry:i})},this.updateMetadata=async({topic:s,metadata:i})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:i}=s;this.pairings.keys.includes(i)&&(await this.sendRequest(i,\"wc_pairingDelete\",H(\"USER_DISCONNECTED\")),await this.deletePairing(i))},this.formatUriFromPairing=s=>{this.isInitialized();const{topic:i,relay:r,expiry:n,methods:a}=s,h=this.core.crypto.keychain.get(i);return ke({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:h,relay:r,expiryTimestamp:n,methods:a})},this.sendRequest=async(s,i,r)=>{const n=Ge(i,r),a=await this.core.crypto.encode(s,n),h=B[i].req;return this.core.history.set(s,n),this.core.relayer.publish(s,a,h),n.id},this.sendResult=async(s,i,r)=>{const n=qe(s,r),a=await this.core.crypto.encode(i,n),h=await this.core.history.get(i,s),c=B[h.request.method].res;await this.core.relayer.publish(i,a,c),await this.core.history.resolve(n)},this.sendError=async(s,i,r)=>{const n=ds(s,r),a=await this.core.crypto.encode(i,n),h=await this.core.history.get(i,s),c=B[h.request.method]?B[h.request.method].res:B.unregistered_method.res;await this.core.relayer.publish(i,a,c),await this.core.history.resolve(n)},this.deletePairing=async(s,i)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,H(\"USER_DISCONNECTED\")),this.core.crypto.deleteSymKey(s),i?Promise.resolve():this.core.expirer.del(s)])},this.cleanup=async()=>{const s=this.pairings.getAll().filter(i=>Ue(i.expiry));await Promise.all(s.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=s=>{const{topic:i,payload:r}=s;switch(r.method){case\"wc_pairingPing\":return this.onPairingPingRequest(i,r);case\"wc_pairingDelete\":return this.onPairingDeleteRequest(i,r);default:return this.onUnknownRpcMethodRequest(i,r)}},this.onRelayEventResponse=async s=>{const{topic:i,payload:r}=s,n=(await this.core.history.get(i,r.id)).request.method;switch(n){case\"wc_pairingPing\":return this.onPairingPingResponse(i,r);default:return this.onUnknownRpcMethodResponse(n)}},this.onPairingPingRequest=async(s,i)=>{const{id:r}=i;try{this.isValidPing({topic:s}),await this.sendResult(r,s,!0),this.events.emit(V.ping,{id:r,topic:s})}catch(n){await this.sendError(r,s,n),this.logger.error(n)}},this.onPairingPingResponse=(s,i)=>{const{id:r}=i;setTimeout(()=>{ps(i)?this.events.emit(pe(\"pairing_ping\",r),{}):He(i)&&this.events.emit(pe(\"pairing_ping\",r),{error:i.error})},500)},this.onPairingDeleteRequest=async(s,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(V.delete,{id:r,topic:s})}catch(n){await this.sendError(r,s,n),this.logger.error(n)}},this.onUnknownRpcMethodRequest=async(s,i)=>{const{id:r,method:n}=i;try{if(this.registeredMethods.includes(n))return;const a=H(\"WC_METHOD_UNSUPPORTED\",n);await this.sendError(r,s,a),this.logger.error(a)}catch(a){await this.sendError(r,s,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=s=>{this.registeredMethods.includes(s)||this.logger.error(H(\"WC_METHOD_UNSUPPORTED\",s))},this.isValidPair=(s,i)=>{var r;if(!ge(s)){const{message:a}=d(\"MISSING_OR_INVALID\",`pair() params: ${s}`);throw i.setError($.malformed_pairing_uri),new Error(a)}if(!ts(s.uri)){const{message:a}=d(\"MISSING_OR_INVALID\",`pair() uri: ${s.uri}`);throw i.setError($.malformed_pairing_uri),new Error(a)}const n=Me(s?.uri);if(!((r=n?.relay)!=null&&r.protocol)){const{message:a}=d(\"MISSING_OR_INVALID\",\"pair() uri#relay-protocol\");throw i.setError($.malformed_pairing_uri),new Error(a)}if(!(n!=null&&n.symKey)){const{message:a}=d(\"MISSING_OR_INVALID\",\"pair() uri#symKey\");throw i.setError($.malformed_pairing_uri),new Error(a)}if(n!=null&&n.expiryTimestamp&&w(n?.expiryTimestamp){if(!ge(s)){const{message:r}=d(\"MISSING_OR_INVALID\",`ping() params: ${s}`);throw new Error(r)}const{topic:i}=s;await this.isValidPairingTopic(i)},this.isValidDisconnect=async s=>{if(!ge(s)){const{message:r}=d(\"MISSING_OR_INVALID\",`disconnect() params: ${s}`);throw new Error(r)}const{topic:i}=s;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async s=>{if(!is(s,!1)){const{message:i}=d(\"MISSING_OR_INVALID\",`pairing topic should be a string: ${s}`);throw new Error(i)}if(!this.pairings.keys.includes(s)){const{message:i}=d(\"NO_MATCHING_KEY\",`pairing topic doesn't exist: ${s}`);throw new Error(i)}if(Ue(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:i}=d(\"EXPIRED\",`pairing topic: ${s}`);throw new Error(i)}},this.core=e,this.logger=E(t,this.name),this.pairings=new ni(this.core,this.logger,this.name,this.storagePrefix)}get context(){return C(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(v.message,async e=>{const{topic:t,message:s,transportType:i}=e;if(!this.pairings.keys.includes(t)||i===M.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))return;const r=await this.core.crypto.decode(t,s);try{Ve(r)?(this.core.history.set(t,r),this.onRelayEventRequest({topic:t,payload:r})):je(r)&&(await this.core.history.resolve(r),await this.onRelayEventResponse({topic:t,payload:r}),this.core.history.delete(t,r.id))}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(S.expired,async e=>{const{topic:t}=ss(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(V.expire,{topic:t}))})}}class ai extends Pi{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new U,this.name=Dt,this.version=mt,this.cached=[],this.initialized=!1,this.storagePrefix=x,this.init=async()=>{this.initialized||(this.logger.trace(\"Initialized\"),await this.restore(),this.cached.forEach(s=>this.records.set(s.id,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(s,i,r)=>{if(this.isInitialized(),this.logger.debug(\"Setting JSON-RPC request history record\"),this.logger.trace({type:\"method\",method:\"set\",topic:s,request:i,chainId:r}),this.records.has(i.id))return;const n={id:i.id,topic:s,request:{method:i.method,params:i.params||null},chainId:r,expiry:Y(ee)};this.records.set(n.id,n),this.persist(),this.events.emit(P.created,n)},this.resolve=async s=>{if(this.isInitialized(),this.logger.debug(\"Updating JSON-RPC response history record\"),this.logger.trace({type:\"method\",method:\"update\",response:s}),!this.records.has(s.id))return;const i=await this.getRecord(s.id);typeof i.response>\"u\"&&(i.response=He(s)?{error:s.error}:{result:s.result},this.records.set(i.id,i),this.persist(),this.events.emit(P.updated,i))},this.get=async(s,i)=>(this.isInitialized(),this.logger.debug(\"Getting record\"),this.logger.trace({type:\"method\",method:\"get\",topic:s,id:i}),await this.getRecord(i)),this.delete=(s,i)=>{this.isInitialized(),this.logger.debug(\"Deleting record\"),this.logger.trace({type:\"method\",method:\"delete\",id:i}),this.values.forEach(r=>{if(r.topic===s){if(typeof i<\"u\"&&r.id!==i)return;this.records.delete(r.id),this.events.emit(P.deleted,r)}}),this.persist()},this.exists=async(s,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===s:!1),this.on=(s,i)=>{this.events.on(s,i)},this.once=(s,i)=>{this.events.once(s,i)},this.off=(s,i)=>{this.events.off(s,i)},this.removeListener=(s,i)=>{this.events.removeListener(s,i)},this.logger=E(t,this.name)}get context(){return C(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 s={topic:t.topic,request:Ge(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),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:s}=d(\"NO_MATCHING_KEY\",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(P.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>\"u\"||!e.length)return;if(this.records.size){const{message:t}=d(\"RESTORE_WILL_OVERRIDE\",this.name);throw this.logger.error(t),new Error(t)}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(P.created,e=>{const t=P.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:\"event\",event:t,record:e})}),this.events.on(P.updated,e=>{const t=P.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:\"event\",event:t,record:e})}),this.events.on(P.deleted,e=>{const t=P.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:\"event\",event:t,record:e})}),this.core.heartbeat.on(j.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{w(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(P.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}}class hi extends Si{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new U,this.name=bt,this.version=ft,this.cached=[],this.initialized=!1,this.storagePrefix=x,this.init=async()=>{this.initialized||(this.logger.trace(\"Initialized\"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=s=>{try{const i=this.formatTarget(s);return typeof this.getExpiration(i)<\"u\"}catch{return!1}},this.set=(s,i)=>{this.isInitialized();const r=this.formatTarget(s),n={target:r,expiry:i};this.expirations.set(r,n),this.checkExpiry(r,n),this.events.emit(S.created,{target:r,expiration:n})},this.get=s=>{this.isInitialized();const i=this.formatTarget(s);return this.getExpiration(i)},this.del=s=>{if(this.isInitialized(),this.has(s)){const i=this.formatTarget(s),r=this.getExpiration(i);this.expirations.delete(i),this.events.emit(S.deleted,{target:i,expiration:r})}},this.on=(s,i)=>{this.events.on(s,i)},this.once=(s,i)=>{this.events.once(s,i)},this.off=(s,i)=>{this.events.off(s,i)},this.removeListener=(s,i)=>{this.events.removeListener(s,i)},this.logger=E(t,this.name)}get context(){return C(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(typeof e==\"string\")return rs(e);if(typeof e==\"number\")return ns(e);const{message:t}=d(\"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(S.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>\"u\"||!e.length)return;if(this.expirations.size){const{message:t}=d(\"RESTORE_WILL_OVERRIDE\",this.name);throw this.logger.error(t),new Error(t)}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:s}=d(\"NO_MATCHING_KEY\",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;w(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(S.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(j.pulse,()=>this.checkExpirations()),this.events.on(S.created,e=>{const t=S.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:\"event\",event:t,data:e}),this.persist()}),this.events.on(S.expired,e=>{const t=S.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:\"event\",event:t,data:e}),this.persist()}),this.events.on(S.deleted,e=>{const t=S.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:\"event\",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=d(\"NOT_INITIALIZED\",this.name);throw new Error(e)}}}class ci extends Ri{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,this.name=_t,this.verifyUrlV3=vt,this.storagePrefix=x,this.version=De,this.init=async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&w((i=this.publicKey)==null?void 0:i.expiresAt){if(!os()||this.isDevEnv)return;const r=window.location.origin,{id:n,decryptedId:a}=i,h=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${r}&id=${n}&decryptedId=${a}`;try{const c=Ds(),l=this.startAbortTimer(q*5),p=await new Promise((D,m)=>{const u=()=>{window.removeEventListener(\"message\",_),c.body.removeChild(g),m(\"attestation aborted\")};this.abortController.signal.addEventListener(\"abort\",u);const g=c.createElement(\"iframe\");g.src=h,g.style.display=\"none\",g.addEventListener(\"error\",u,{signal:this.abortController.signal});const _=y=>{if(y.data&&typeof y.data==\"string\")try{const b=JSON.parse(y.data);if(b.type===\"verify_attestation\"){if(Se(b.attestation).payload.id!==n)return;clearInterval(l),c.body.removeChild(g),this.abortController.signal.removeEventListener(\"abort\",u),window.removeEventListener(\"message\",_),D(b.attestation===null?\"\":b.attestation)}}catch(b){this.logger.warn(b)}};c.body.appendChild(g),window.addEventListener(\"message\",_,{signal:this.abortController.signal})});return this.logger.debug(\"jwt attestation\",p),p}catch(c){this.logger.warn(c)}return\"\"},this.resolve=async i=>{if(this.isDevEnv)return\"\";const{attestationId:r,hash:n,encryptedId:a}=i;if(r===\"\"){this.logger.debug(\"resolve: attestationId is empty, skipping\");return}if(r){if(Se(r).payload.id!==a)return;const c=await this.isValidJwtAttestation(r);if(c){if(!c.isVerified){this.logger.warn(\"resolve: jwt attestation: origin url not verified\");return}return c}}if(!n)return;const h=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(n,h)},this.fetchAttestation=async(i,r)=>{this.logger.debug(`resolving attestation: ${i} from url: ${r}`);const n=this.startAbortTimer(q*5),a=await fetch(`${r}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(n),a.status===200?await a.json():void 0},this.getVerifyUrl=i=>{let r=i||J;return wt.includes(r)||(this.logger.info(`verify url: ${r}, not included in trusted list, assigning default: ${J}`),r=J),r},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(Te),r=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await r.json()}catch(i){this.logger.warn(i)}},this.persistPublicKey=async i=>{this.logger.debug(\"persisting public key to local storage\",i),await this.store.setItem(this.storeKey,i),this.publicKey=i},this.removePublicKey=async()=>{this.logger.debug(\"removing verify v2 public key from storage\"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async i=>{const r=await this.getPublicKey();try{if(r)return this.validateAttestation(i,r)}catch(a){this.logger.error(a),this.logger.warn(\"error validating attestation\")}const n=await this.fetchAndPersistPublicKey();try{if(n)return this.validateAttestation(i,n)}catch(a){this.logger.error(a),this.logger.warn(\"error validating attestation\")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async r=>{const n=await this.fetchPublicKey();n&&(await this.persistPublicKey(n),r(n))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i},this.validateAttestation=(i,r)=>{const n=as(i,r.publicKey),a={hasExpired:w(n.exp)this.abortController.abort(),w(e))}}class li extends xi{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=It,this.registerDeviceToken=async s=>{const{clientId:i,token:r,notificationType:n,enableEncrypted:a=!1}=s,h=`${Tt}/${this.projectId}/clients`;await fetch(h,{method:\"POST\",headers:{\"Content-Type\":\"application/json\"},body:JSON.stringify({client_id:i,type:n,token:r,always_raw:a})})},this.logger=E(t,this.context)}}var dn=Object.defineProperty,ui=Object.getOwnPropertySymbols,pn=Object.prototype.hasOwnProperty,gn=Object.prototype.propertyIsEnumerable,di=(o,e,t)=>e in o?dn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,Z=(o,e)=>{for(var t in e||(e={}))pn.call(e,t)&&di(o,t,e[t]);if(ui)for(var t of ui(e))gn.call(e,t)&&di(o,t,e[t]);return o};class pi extends Oi{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,this.context=Pt,this.storagePrefix=x,this.storageVersion=Ct,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!Fe())try{const i={eventId:Ke(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:\"INIT\",type:\"\",properties:{client_id:await this.core.crypto.getClientId(),user_agent:hs(this.core.relayer.protocol,this.core.relayer.version,se)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}},this.createEvent=i=>{const{event:r=\"ERROR\",type:n=\"\",properties:{topic:a,trace:h}}=i,c=Ke(),l=this.core.projectId||\"\",p=Date.now(),D=Z({eventId:c,timestamp:p,props:{event:r,type:n,properties:{topic:a,trace:h}},bundleId:l,domain:this.getAppDomain()},this.setMethods(c));return this.telemetryEnabled&&(this.events.set(c,D),this.shouldPersist=!0),D},this.getEvent=i=>{const{eventId:r,topic:n}=i;if(r)return this.events.get(r);const a=Array.from(this.events.values()).find(h=>h.props.properties.topic===n);if(a)return Z(Z({},a),this.setMethods(a.eventId))},this.deleteEvent=i=>{const{eventId:r}=i;this.events.delete(r),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(j.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{Ce(Date.now())-Ce(i.timestamp)>St&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})},this.setMethods=i=>({addTrace:r=>this.addTrace(i,r),setError:r=>this.setError(i,r)}),this.addTrace=(i,r)=>{const n=this.events.get(i);n&&(n.props.properties.trace.push(r),this.events.set(i,n),this.shouldPersist=!0)},this.setError=(i,r)=>{const n=this.events.get(i);n&&(n.props.type=r,n.timestamp=Date.now(),this.events.set(i,n),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(r=>{this.events.set(r.eventId,Z(Z({},r),this.setMethods(r.eventId)))})}catch(i){this.logger.warn(i)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[r,n]of this.events)n.props.type&&i.push(n);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const r of i)this.events.delete(r.eventId),this.shouldPersist=!0}catch(r){this.logger.warn(r)}},this.sendEvent=async i=>{const r=this.getAppDomain()?\"\":\"&sp=desktop\";return await fetch(`${Rt}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${se}${r}`,{method:\"POST\",body:JSON.stringify(i)})},this.getAppDomain=()=>cs().url,this.logger=E(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+\"//\"+this.context}}var yn=Object.defineProperty,gi=Object.getOwnPropertySymbols,Dn=Object.prototype.hasOwnProperty,mn=Object.prototype.propertyIsEnumerable,yi=(o,e,t)=>e in o?yn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,Di=(o,e)=>{for(var t in e||(e={}))Dn.call(e,t)&&yi(o,t,e[t]);if(gi)for(var t of gi(e))mn.call(e,t)&&yi(o,t,e[t]);return o};class ne extends Ai{constructor(e){var t;super(e),this.protocol=ye,this.version=De,this.name=ie,this.events=new U,this.initialized=!1,this.on=(n,a)=>this.events.on(n,a),this.once=(n,a)=>this.events.once(n,a),this.off=(n,a)=>this.events.off(n,a),this.removeListener=(n,a)=>this.events.removeListener(n,a),this.dispatchEnvelope=({topic:n,message:a,sessionExists:h})=>{if(!n||!a)return;const c={topic:n,message:a,publishedAt:Date.now(),transportType:M.link_mode};this.relayer.onLinkMessageEvent(c,{sessionExists:h})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||be,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:\"\";const s=Ie({level:typeof e?.logger==\"string\"&&e.logger?e.logger:Ye.logger}),{logger:i,chunkLoggerController:r}=Ei({opts:s,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=r,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var n,a;(n=this.logChunkController)!=null&&n.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=E(i,this.name),this.heartbeat=new bi,this.crypto=new Ht(this,this.logger,e?.keychain),this.history=new ai(this,this.logger),this.expirer=new hi(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new fi(Di(Di({},Je),e?.storageOptions)),this.relayer=new ti({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new oi(this,this.logger),this.verify=new ci(this,this.logger,this.storage),this.echoClient=new li(this.projectId||\"\",this.logger),this.linkModeSupportedApps=[],this.eventClient=new pi(this,this.logger,e?.telemetryEnabled)}static async init(e){const t=new ne(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(lt,s),t}get context(){return C(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(fe,this.linkModeSupportedApps))}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.eventClient.init(),this.linkModeSupportedApps=await this.storage.getItem(fe)||[],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 bn=ne;export{ie as CORE_CONTEXT,Ye as CORE_DEFAULT,ye as CORE_PROTOCOL,Je as CORE_STORAGE_OPTIONS,x as CORE_STORAGE_PREFIX,De as CORE_VERSION,me as CRYPTO_CLIENT_SEED,Xe as CRYPTO_CONTEXT,We as CRYPTO_JWT_TTL,bn as Core,Ht as Crypto,It as ECHO_CONTEXT,Tt as ECHO_URL,Rt as EVENTS_CLIENT_API_URL,St as EVENTS_STORAGE_CLEANUP_INTERVAL,Pt as EVENTS_STORAGE_CONTEXT,Ct as EVENTS_STORAGE_VERSION,Ps as EVENT_CLIENT_AUTHENTICATE_ERRORS,Cs as EVENT_CLIENT_AUTHENTICATE_TRACES,ws as EVENT_CLIENT_CONTEXT,$ as EVENT_CLIENT_PAIRING_ERRORS,z as EVENT_CLIENT_PAIRING_TRACES,Ts as EVENT_CLIENT_SESSION_ERRORS,Is as EVENT_CLIENT_SESSION_TRACES,bt as EXPIRER_CONTEXT,Es as EXPIRER_DEFAULT_TTL,S as EXPIRER_EVENTS,ft as EXPIRER_STORAGE_VERSION,li as EchoClient,pi as EventClient,hi as Expirer,Dt as HISTORY_CONTEXT,P as HISTORY_EVENTS,mt as HISTORY_STORAGE_VERSION,ai as JsonRpcHistory,Ze as KEYCHAIN_CONTEXT,Qe as KEYCHAIN_STORAGE_VERSION,Gt as KeyChain,et as MESSAGES_CONTEXT,tt as MESSAGES_STORAGE_VERSION,Yt as MessageTracker,gt as PAIRING_CONTEXT,_s as PAIRING_DEFAULT_TTL,V as PAIRING_EVENTS,B as PAIRING_RPC_OPTS,yt as PAIRING_STORAGE_VERSION,pt as PENDING_SUB_RESOLUTION_TIMEOUT,st as PUBLISHER_CONTEXT,it as PUBLISHER_DEFAULT_TTL,oi as Pairing,ot as RELAYER_CONTEXT,nt as RELAYER_DEFAULT_LOGGER,rt as RELAYER_DEFAULT_PROTOCOL,be as RELAYER_DEFAULT_RELAY_URL,v as RELAYER_EVENTS,I as RELAYER_PROVIDER_EVENTS,ht as RELAYER_RECONNECT_TIMEOUT,se as RELAYER_SDK_VERSION,ms as RELAYER_STORAGE_OPTIONS,at as RELAYER_SUBSCRIBER_SUFFIX,bs as RELAYER_TRANSPORT_CUTOFF,ti as Relayer,ct as STORE_STORAGE_VERSION,ut as SUBSCRIBER_CONTEXT,fs as SUBSCRIBER_DEFAULT_TTL,O as SUBSCRIBER_EVENTS,dt as SUBSCRIBER_STORAGE_VERSION,ni as Store,Wt as Subscriber,M as TRANSPORT_TYPES,wt as TRUSTED_VERIFY_URLS,_t as VERIFY_CONTEXT,J as VERIFY_SERVER,vt as VERIFY_SERVER_V3,ci as Verify,lt as WALLETCONNECT_CLIENT_ID,fe as WALLETCONNECT_LINK_MODE_APPS,ne as default};\n//# sourceMappingURL=index.es.js.map\n","import{RELAYER_DEFAULT_PROTOCOL as Et,TRANSPORT_TYPES as f,EVENT_CLIENT_SESSION_TRACES as C,EVENT_CLIENT_SESSION_ERRORS as F,EVENT_CLIENT_AUTHENTICATE_TRACES as Q,EVENT_CLIENT_AUTHENTICATE_ERRORS as se,EVENT_CLIENT_PAIRING_ERRORS as Rt,EVENT_CLIENT_PAIRING_TRACES as St,RELAYER_EVENTS as Ue,VERIFY_SERVER as It,EXPIRER_EVENTS as ft,PAIRING_EVENTS as Ge,Store as H,Core as vt}from\"@walletconnect/core\";import{pino as qt,getDefaultLoggerOptions as Tt,generateChildLogger as Nt,getLoggerContext as Pt}from\"@walletconnect/logger\";import{IEngine as Ot,ISignClient as At}from\"@walletconnect/types\";import{getInternalError as u,calcExpiry as A,createDelayedPromise as Y,engineEvent as g,getSdkError as P,getDeepLink as bt,handleDeeplinkRedirect as Ct,isSessionCompatible as Lt,hashKey as Te,parseChainId as Ne,createEncodedRecap as xt,getRecapFromResources as Pe,mergeEncodedRecaps as Dt,TYPE_2 as Vt,BASE64URL as ie,getLinkModeURL as he,validateSignedCacao as je,getNamespacedDidChainId as Fe,getDidAddress as Qe,getMethodsFromRecap as ze,getChainsFromRecap as He,buildNamespacesFromAuth as Ye,formatMessage as Mt,BASE64 as de,hashMessage as X,isExpired as J,MemoryStore as re,isValidParams as L,isUndefined as ne,isValidRelays as kt,isValidObject as Xe,isValidRequiredNamespaces as $t,isValidNamespaces as Oe,isConformingNamespaces as Je,isValidString as k,isValidErrorReason as Kt,isValidRelay as Ut,isValidController as Gt,isValidNamespacesChainId as Be,isValidRequest as jt,isValidNamespacesRequest as Ft,isValidRequestExpiry as Qt,isValidResponse as zt,isValidEvent as Ht,isValidNamespacesEvent as Yt,getSearchParamFromURL as We,isTestRun as Xt,isReactNative as Jt,parseExpirerTarget as Bt,isValidId as Wt,TYPE_1 as Ae,getAppMetadata as Zt}from\"@walletconnect/utils\";import es,{EventEmitter as ts}from\"events\";import{THIRTY_DAYS as ss,SEVEN_DAYS as Ze,FIVE_MINUTES as b,ONE_DAY as $,ONE_HOUR as et,ONE_SECOND as is,toMiliseconds as tt}from\"@walletconnect/time\";import{payloadId as B,getBigIntRpcId as ue,isJsonRpcResult as K,isJsonRpcError as U,formatJsonRpcRequest as ge,formatJsonRpcResult as rs,formatJsonRpcError as ns,isJsonRpcRequest as os,isJsonRpcResponse as as}from\"@walletconnect/jsonrpc-utils\";const be=\"wc\",Ce=2,Le=\"client\",ye=`${be}@${Ce}:${Le}:`,we={name:Le,logger:\"error\",controller:!1,relayUrl:\"wss://relay.walletconnect.org\"},cs={session_proposal:\"session_proposal\",session_update:\"session_update\",session_extend:\"session_extend\",session_ping:\"session_ping\",session_delete:\"session_delete\",session_expire:\"session_expire\",session_request:\"session_request\",session_request_sent:\"session_request_sent\",session_event:\"session_event\",proposal_expire:\"proposal_expire\",session_authenticate:\"session_authenticate\",session_request_expire:\"session_request_expire\"},ls={database:\":memory:\"},xe=\"WALLETCONNECT_DEEPLINK_CHOICE\",ps={created:\"history_created\",updated:\"history_updated\",deleted:\"history_deleted\",sync:\"history_sync\"},hs=\"history\",ds=\"0.3\",st=\"proposal\",us=ss,it=\"Proposal expired\",rt=\"session\",z=Ze,nt=\"engine\",v={wc_sessionPropose:{req:{ttl:b,prompt:!0,tag:1100},res:{ttl:b,prompt:!1,tag:1101},reject:{ttl:b,prompt:!1,tag:1120},autoReject:{ttl:b,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:b,prompt:!1,tag:1102},res:{ttl:b,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:$,prompt:!1,tag:1104},res:{ttl:$,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:$,prompt:!1,tag:1106},res:{ttl:$,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:b,prompt:!0,tag:1108},res:{ttl:b,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:b,prompt:!0,tag:1110},res:{ttl:b,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:$,prompt:!1,tag:1112},res:{ttl:$,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:$,prompt:!1,tag:1114},res:{ttl:$,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:et,prompt:!0,tag:1116},res:{ttl:et,prompt:!1,tag:1117},reject:{ttl:b,prompt:!1,tag:1118},autoReject:{ttl:b,prompt:!1,tag:1119}}},me={min:b,max:Ze},x={idle:\"IDLE\",active:\"ACTIVE\"},ot=\"request\",at=[\"wc_sessionPropose\",\"wc_sessionRequest\",\"wc_authRequest\",\"wc_sessionAuthenticate\"],ct=\"wc\",gs=1.5,lt=\"auth\",pt=\"authKeys\",ht=\"pairingTopics\",dt=\"requests\",oe=`${ct}@${1.5}:${lt}:`,ae=`${oe}:PUB_KEY`;var ys=Object.defineProperty,ws=Object.defineProperties,ms=Object.getOwnPropertyDescriptors,ut=Object.getOwnPropertySymbols,_s=Object.prototype.hasOwnProperty,Es=Object.prototype.propertyIsEnumerable,gt=(q,o,e)=>o in q?ys(q,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):q[o]=e,I=(q,o)=>{for(var e in o||(o={}))_s.call(o,e)&>(q,e,o[e]);if(ut)for(var e of ut(o))Es.call(o,e)&>(q,e,o[e]);return q},D=(q,o)=>ws(q,ms(o));class Rs extends Ot{constructor(o){super(o),this.name=nt,this.events=new es,this.initialized=!1,this.requestQueue={state:x.idle,queue:[]},this.sessionRequestQueue={state:x.idle,queue:[]},this.requestQueueDelay=is,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(v)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},tt(this.requestQueueDelay)))},this.connect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t=D(I({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t);const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:r,sessionProperties:n,relays:a}=t;let c=s,h,p=!1;try{c&&(p=this.client.core.pairing.pairings.get(c).active)}catch(E){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),E}if(!c||!p){const{topic:E,uri:S}=await this.client.core.pairing.create();c=E,h=S}if(!c){const{message:E}=u(\"NO_MATCHING_KEY\",`connect() pairing topic: ${c}`);throw new Error(E)}const d=await this.client.core.crypto.generateKeyPair(),l=v.wc_sessionPropose.req.ttl||b,w=A(l),m=I({requiredNamespaces:i,optionalNamespaces:r,relays:a??[{protocol:Et}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:c},n&&{sessionProperties:n}),{reject:y,resolve:_,done:R}=Y(l,it);this.events.once(g(\"session_connect\"),async({error:E,session:S})=>{if(E)y(E);else if(S){S.self.publicKey=d;const M=D(I({},S),{pairingTopic:m.pairingTopic,requiredNamespaces:m.requiredNamespaces,optionalNamespaces:m.optionalNamespaces,transportType:f.relay});await this.client.session.set(S.topic,M),await this.setExpiry(S.topic,S.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:S.peer.metadata}),this.cleanupDuplicatePairings(M),_(M)}});const V=await this.sendRequest({topic:c,method:\"wc_sessionPropose\",params:m,throwOnFailedPublish:!0});return await this.setProposal(V,I({id:V},m)),{uri:h,approval:R}},this.pair=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(t){throw this.client.logger.error(\"pair() failed\"),t}},this.approve=async e=>{var t,s,i;const r=this.client.core.eventClient.createEvent({properties:{topic:(t=e?.id)==null?void 0:t.toString(),trace:[C.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(N){throw r.setError(F.no_internet_connection),N}try{await this.isValidProposalId(e?.id)}catch(N){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),r.setError(F.proposal_not_found),N}try{await this.isValidApprove(e)}catch(N){throw this.client.logger.error(\"approve() -> isValidApprove() failed\"),r.setError(F.session_approve_namespace_validation_failure),N}const{id:n,relayProtocol:a,namespaces:c,sessionProperties:h,sessionConfig:p}=e,d=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:l,proposer:w,requiredNamespaces:m,optionalNamespaces:y}=d;let _=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:l});_||(_=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:C.session_approve_started,properties:{topic:l,trace:[C.session_approve_started,C.session_namespaces_validation_success]}}));const R=await this.client.core.crypto.generateKeyPair(),V=w.publicKey,E=await this.client.core.crypto.generateSharedKey(R,V),S=I(I({relay:{protocol:a??\"irn\"},namespaces:c,controller:{publicKey:R,metadata:this.client.metadata},expiry:A(z)},h&&{sessionProperties:h}),p&&{sessionConfig:p}),M=f.relay;_.addTrace(C.subscribing_session_topic);try{await this.client.core.relayer.subscribe(E,{transportType:M})}catch(N){throw _.setError(F.subscribe_session_topic_failure),N}_.addTrace(C.subscribe_session_topic_success);const W=D(I({},S),{topic:E,requiredNamespaces:m,optionalNamespaces:y,pairingTopic:l,acknowledged:!1,self:S.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:R,transportType:f.relay});await this.client.session.set(E,W),_.addTrace(C.store_session);try{_.addTrace(C.publishing_session_settle),await this.sendRequest({topic:E,method:\"wc_sessionSettle\",params:S,throwOnFailedPublish:!0}).catch(N=>{throw _?.setError(F.session_settle_publish_failure),N}),_.addTrace(C.session_settle_publish_success),_.addTrace(C.publishing_session_approve),await this.sendResult({id:n,topic:l,result:{relay:{protocol:a??\"irn\"},responderPublicKey:R},throwOnFailedPublish:!0}).catch(N=>{throw _?.setError(F.session_approve_publish_failure),N}),_.addTrace(C.session_approve_publish_success)}catch(N){throw this.client.logger.error(N),this.client.session.delete(E,P(\"USER_DISCONNECTED\")),await this.client.core.relayer.unsubscribe(E),N}return this.client.core.eventClient.deleteEvent({eventId:_.eventId}),await this.client.core.pairing.updateMetadata({topic:l,metadata:w.metadata}),await this.client.proposal.delete(n,P(\"USER_DISCONNECTED\")),await this.client.core.pairing.activate({topic:l}),await this.setExpiry(E,A(z)),{topic:E,acknowledged:()=>Promise.resolve(this.client.session.get(E))}},this.reject=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(r){throw this.client.logger.error(\"reject() -> isValidReject() failed\"),r}const{id:t,reason:s}=e;let i;try{i=this.client.proposal.get(t).pairingTopic}catch(r){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),r}i&&(await this.sendError({id:t,topic:i,error:s,rpcOpts:v.wc_sessionPropose.reject}),await this.client.proposal.delete(t,P(\"USER_DISCONNECTED\")))},this.update=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(p){throw this.client.logger.error(\"update() -> isValidUpdate() failed\"),p}const{topic:t,namespaces:s}=e,{done:i,resolve:r,reject:n}=Y(),a=B(),c=ue().toString(),h=this.client.session.get(t).namespaces;return this.events.once(g(\"session_update\",a),({error:p})=>{p?n(p):r()}),await this.client.session.update(t,{namespaces:s}),await this.sendRequest({topic:t,method:\"wc_sessionUpdate\",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(p=>{this.client.logger.error(p),this.client.session.update(t,{namespaces:h}),n(p)}),{acknowledged:i}},this.extend=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(a){throw this.client.logger.error(\"extend() -> isValidExtend() failed\"),a}const{topic:t}=e,s=B(),{done:i,resolve:r,reject:n}=Y();return this.events.once(g(\"session_extend\",s),({error:a})=>{a?n(a):r()}),await this.setExpiry(t,A(z)),this.sendRequest({topic:t,method:\"wc_sessionExtend\",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(a=>{n(a)}),{acknowledged:i}},this.request=async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(w){throw this.client.logger.error(\"request() -> isValidRequest() failed\"),w}const{chainId:t,request:s,topic:i,expiry:r=v.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(i);n?.transportType===f.relay&&await this.confirmOnlineStateOrThrow();const a=B(),c=ue().toString(),{done:h,resolve:p,reject:d}=Y(r,\"Request expired. Please try again.\");this.events.once(g(\"session_request\",a),({error:w,result:m})=>{w?d(w):p(m)});const l=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);return l?(await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:i,method:\"wc_sessionRequest\",params:{request:D(I({},s),{expiryTimestamp:A(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0,appLink:l}).catch(w=>d(w)),this.client.events.emit(\"session_request_sent\",{topic:i,request:s,chainId:t,id:a}),await h()):await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:i,method:\"wc_sessionRequest\",params:{request:D(I({},s),{expiryTimestamp:A(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0}).catch(m=>d(m)),this.client.events.emit(\"session_request_sent\",{topic:i,request:s,chainId:t,id:a}),w()}),new Promise(async w=>{var m;if(!((m=n.sessionConfig)!=null&&m.disableDeepLink)){const y=await bt(this.client.core.storage,xe);await Ct({id:a,topic:i,wcDeepLink:y})}w()}),h()]).then(w=>w[2])},this.respond=async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:i}=s,r=this.client.session.get(t);r.transportType===f.relay&&await this.confirmOnlineStateOrThrow();const n=this.getAppLinkIfEnabled(r.peer.metadata,r.transportType);K(s)?await this.sendResult({id:i,topic:t,result:s.result,throwOnFailedPublish:!0,appLink:n}):U(s)&&await this.sendError({id:i,topic:t,error:s.error,appLink:n}),this.cleanupAfterResponse(e)},this.ping=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(s){throw this.client.logger.error(\"ping() -> isValidPing() failed\"),s}const{topic:t}=e;if(this.client.session.keys.includes(t)){const s=B(),i=ue().toString(),{done:r,resolve:n,reject:a}=Y();this.events.once(g(\"session_ping\",s),({error:c})=>{c?a(c):n()}),await Promise.all([this.sendRequest({topic:t,method:\"wc_sessionPing\",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),r()])}else this.client.core.pairing.pairings.keys.includes(t)&&await this.client.core.pairing.ping({topic:t})},this.emit=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:s,chainId:i}=e,r=ue().toString();await this.sendRequest({topic:t,method:\"wc_sessionEvent\",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:r})},this.disconnect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:\"wc_sessionDelete\",params:P(\"USER_DISCONNECTED\"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(t))await this.client.core.pairing.disconnect({topic:t});else{const{message:s}=u(\"MISMATCHED_TOPIC\",`Session or pairing topic not found: ${t}`);throw new Error(s)}},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>Lt(t,e))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(e,t)=>{var s;this.isInitialized(),this.isValidAuthenticate(e);const i=t&&this.client.core.linkModeSupportedApps.includes(t)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),r=i?f.link_mode:f.relay;r===f.relay&&await this.confirmOnlineStateOrThrow();const{chains:n,statement:a=\"\",uri:c,domain:h,nonce:p,type:d,exp:l,nbf:w,methods:m=[],expiry:y}=e,_=[...e.resources||[]],{topic:R,uri:V}=await this.client.core.pairing.create({methods:[\"wc_sessionAuthenticate\"],transportType:r});this.client.logger.info({message:\"Generated new pairing\",pairing:{topic:R,uri:V}});const E=await this.client.core.crypto.generateKeyPair(),S=Te(E);if(await Promise.all([this.client.auth.authKeys.set(ae,{responseTopic:S,publicKey:E}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:R})]),await this.client.core.relayer.subscribe(S,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${R}`),m.length>0){const{namespace:O}=Ne(n[0]);let T=xt(O,\"request\",m);Pe(_)&&(T=Dt(T,_.pop())),_.push(T)}const M=y&&y>v.wc_sessionAuthenticate.req.ttl?y:v.wc_sessionAuthenticate.req.ttl,W={authPayload:{type:d??\"caip122\",chains:n,statement:a,aud:c,domain:h,version:\"1\",nonce:p,iat:new Date().toISOString(),exp:l,nbf:w,resources:_},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:A(M)},N={eip155:{chains:n,methods:[...new Set([\"personal_sign\",...m])],events:[\"chainChanged\",\"accountsChanged\"]}},De={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:\"irn\"}],pairingTopic:R,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:A(v.wc_sessionPropose.req.ttl)},{done:wt,resolve:Ve,reject:Ee}=Y(M,\"Request expired\"),ce=async({error:O,session:T})=>{if(this.events.off(g(\"session_request\",G),Re),O)Ee(O);else if(T){T.self.publicKey=E,await this.client.session.set(T.topic,T),await this.setExpiry(T.topic,T.expiry),R&&await this.client.core.pairing.updateMetadata({topic:R,metadata:T.peer.metadata});const le=this.client.session.get(T.topic);await this.deleteProposal(Z),Ve({session:le})}},Re=async O=>{var T,le,Me;if(await this.deletePendingAuthRequest(G,{message:\"fulfilled\",code:0}),O.error){const te=P(\"WC_METHOD_UNSUPPORTED\",\"wc_sessionAuthenticate\");return O.error.code===te.code?void 0:(this.events.off(g(\"session_connect\"),ce),Ee(O.error.message))}await this.deleteProposal(Z),this.events.off(g(\"session_connect\"),ce);const{cacaos:ke,responder:j}=O.result,Ie=[],$e=[];for(const te of ke){await je({cacao:te,projectId:this.client.core.projectId})||(this.client.logger.error(te,\"Signature verification failed\"),Ee(P(\"SESSION_SETTLEMENT_FAILED\",\"Signature verification failed\")));const{p:fe}=te,ve=Pe(fe.resources),Ke=[Fe(fe.iss)],mt=Qe(fe.iss);if(ve){const qe=ze(ve),_t=He(ve);Ie.push(...qe),Ke.push(..._t)}for(const qe of Ke)$e.push(`${qe}:${mt}`)}const ee=await this.client.core.crypto.generateSharedKey(E,j.publicKey);let pe;Ie.length>0&&(pe={topic:ee,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:j,controller:j.publicKey,expiry:A(z),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:\"irn\"},pairingTopic:R,namespaces:Ye([...new Set(Ie)],[...new Set($e)]),transportType:r},await this.client.core.relayer.subscribe(ee,{transportType:r}),await this.client.session.set(ee,pe),R&&await this.client.core.pairing.updateMetadata({topic:R,metadata:j.metadata}),pe=this.client.session.get(ee)),(T=this.client.metadata.redirect)!=null&&T.linkMode&&(le=j.metadata.redirect)!=null&&le.linkMode&&(Me=j.metadata.redirect)!=null&&Me.universal&&t&&(this.client.core.addLinkModeSupportedApp(j.metadata.redirect.universal),this.client.session.update(ee,{transportType:f.link_mode})),Ve({auths:ke,session:pe})},G=B(),Z=B();this.events.once(g(\"session_connect\"),ce),this.events.once(g(\"session_request\",G),Re);let Se;try{if(i){const O=ge(\"wc_sessionAuthenticate\",W,G);this.client.core.history.set(R,O);const T=await this.client.core.crypto.encode(\"\",O,{type:Vt,encoding:ie});Se=he(t,R,T)}else await Promise.all([this.sendRequest({topic:R,method:\"wc_sessionAuthenticate\",params:W,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:G}),this.sendRequest({topic:R,method:\"wc_sessionPropose\",params:De,expiry:v.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:Z})])}catch(O){throw this.events.off(g(\"session_connect\"),ce),this.events.off(g(\"session_request\",G),Re),O}return await this.setProposal(Z,I({id:Z},De)),await this.setAuthRequest(G,{request:D(I({},W),{verifyContext:{}}),pairingTopic:R,transportType:r}),{uri:Se??V,response:wt}},this.approveSessionAuthenticate=async e=>{const{id:t,auths:s}=e,i=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[Q.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(se.no_internet_connection),y}const r=this.getPendingAuthRequest(t);if(!r)throw i.setError(se.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${t}`);const n=r.transportType||f.relay;n===f.relay&&await this.confirmOnlineStateOrThrow();const a=r.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),h=Te(a),p={type:Ae,receiverPublicKey:a,senderPublicKey:c},d=[],l=[];for(const y of s){if(!await je({cacao:y,projectId:this.client.core.projectId})){i.setError(se.invalid_cacao);const S=P(\"SESSION_SETTLEMENT_FAILED\",\"Signature verification failed\");throw await this.sendError({id:t,topic:h,error:S,encodeOpts:p}),new Error(S.message)}i.addTrace(Q.cacaos_verified);const{p:_}=y,R=Pe(_.resources),V=[Fe(_.iss)],E=Qe(_.iss);if(R){const S=ze(R),M=He(R);d.push(...S),V.push(...M)}for(const S of V)l.push(`${S}:${E}`)}const w=await this.client.core.crypto.generateSharedKey(c,a);i.addTrace(Q.create_authenticated_session_topic);let m;if(d?.length>0){m={topic:w,acknowledged:!0,self:{publicKey:c,metadata:this.client.metadata},peer:{publicKey:a,metadata:r.requester.metadata},controller:a,expiry:A(z),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:\"irn\"},pairingTopic:r.pairingTopic,namespaces:Ye([...new Set(d)],[...new Set(l)]),transportType:n},i.addTrace(Q.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:n})}catch(y){throw i.setError(se.subscribe_authenticated_session_topic_failure),y}i.addTrace(Q.subscribe_authenticated_session_topic_success),await this.client.session.set(w,m),i.addTrace(Q.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}i.addTrace(Q.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:t,result:{cacaos:s,responder:{publicKey:c,metadata:this.client.metadata}},encodeOpts:p,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(r.requester.metadata,n)})}catch(y){throw i.setError(se.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(t,{message:\"fulfilled\",code:0}),await this.client.core.pairing.activate({topic:r.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:m}},this.rejectSessionAuthenticate=async e=>{this.isInitialized();const{id:t,reason:s}=e,i=this.getPendingAuthRequest(t);if(!i)throw new Error(`Could not find pending auth request with id ${t}`);i.transportType===f.relay&&await this.confirmOnlineStateOrThrow();const r=i.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),a=Te(r),c={type:Ae,receiverPublicKey:r,senderPublicKey:n};await this.sendError({id:t,topic:a,error:s,encodeOpts:c,rpcOpts:v.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(t,{message:\"rejected\",code:0}),await this.client.proposal.delete(t,P(\"USER_DISCONNECTED\"))},this.formatAuthMessage=e=>{this.isInitialized();const{request:t,iss:s}=e;return Mt(t,s)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}},50)},this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>{var r,n;return((r=i.peerMetadata)==null?void 0:r.url)&&((n=i.peerMetadata)==null?void 0:n.url)===e.peer.metadata.url&&i.topic&&i.topic!==t.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info(\"Duplicate pairings clean up finished\")}catch(t){this.client.logger.error(t)}},this.deleteSession=async e=>{var t;const{topic:s,expirerHasDeleted:i=!1,emitEvent:r=!0,id:n=0}=e,{self:a}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,P(\"USER_DISCONNECTED\")),this.addToRecentlyDeleted(s,\"session\"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(xe).catch(c=>this.client.logger.warn(c)),this.getPendingSessionRequests().forEach(c=>{c.topic===s&&this.deletePendingSessionRequest(c.id,P(\"USER_DISCONNECTED\"))}),s===((t=this.sessionRequestQueue.queue[0])==null?void 0:t.topic)&&(this.sessionRequestQueue.state=x.idle),r&&this.client.events.emit(\"session_delete\",{id:n,topic:s})},this.deleteProposal=async(e,t)=>{if(t)try{const s=this.client.proposal.get(e),i=this.client.core.eventClient.getEvent({topic:s.pairingTopic});i?.setError(F.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(e,P(\"USER_DISCONNECTED\")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,\"proposal\")},this.deletePendingSessionRequest=async(e,t,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,\"request\"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==e),s&&(this.sessionRequestQueue.state=x.idle,this.client.events.emit(\"session_request_expire\",{id:e}))},this.deletePendingAuthRequest=async(e,t,s=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))},this.setProposal=async(e,t)=>{this.client.core.expirer.set(e,A(v.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)},this.setAuthRequest=async(e,t)=>{const{request:s,pairingTopic:i,transportType:r=f.relay}=t;this.client.core.expirer.set(e,s.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:e,pairingTopic:i,verifyContext:s.verifyContext,transportType:r})},this.setPendingSessionRequest=async e=>{const{id:t,topic:s,params:i,verifyContext:r}=e,n=i.request.expiryTimestamp||A(v.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:s,params:i,verifyContext:r})},this.sendRequest=async e=>{const{topic:t,method:s,params:i,expiry:r,relayRpcId:n,clientRpcId:a,throwOnFailedPublish:c,appLink:h}=e,p=ge(s,i,a);let d;const l=!!h;try{const y=l?ie:de;d=await this.client.core.crypto.encode(t,p,{encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),y}let w;if(at.includes(s)){const y=X(JSON.stringify(p)),_=X(d);w=await this.client.core.verify.register({id:_,decryptedId:y})}const m=v[s].req;if(m.attestation=w,r&&(m.ttl=r),n&&(m.id=n),this.client.core.history.set(t,p),l){const y=he(h,t,d);await global.Linking.openURL(y,this.client.name)}else{const y=v[s].req;r&&(y.ttl=r),n&&(y.id=n),c?(y.internal=D(I({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,d,y)):this.client.core.relayer.publish(t,d,y).catch(_=>this.client.logger.error(_))}return p.id},this.sendResult=async e=>{const{id:t,topic:s,result:i,throwOnFailedPublish:r,encodeOpts:n,appLink:a}=e,c=rs(t,i);let h;const p=a&&typeof(global==null?void 0:global.Linking)<\"u\";try{const l=p?ie:de;h=await this.client.core.crypto.encode(s,c,D(I({},n||{}),{encoding:l}))}catch(l){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),l}let d;try{d=await this.client.core.history.get(s,t)}catch(l){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${t}) failed`),l}if(p){const l=he(a,s,h);await global.Linking.openURL(l,this.client.name)}else{const l=v[d.request.method].res;r?(l.internal=D(I({},l.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,h,l)):this.client.core.relayer.publish(s,h,l).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(c)},this.sendError=async e=>{const{id:t,topic:s,error:i,encodeOpts:r,rpcOpts:n,appLink:a}=e,c=ns(t,i);let h;const p=a&&typeof(global==null?void 0:global.Linking)<\"u\";try{const l=p?ie:de;h=await this.client.core.crypto.encode(s,c,D(I({},r||{}),{encoding:l}))}catch(l){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),l}let d;try{d=await this.client.core.history.get(s,t)}catch(l){throw this.client.logger.error(`sendError() -> history.get(${s}, ${t}) failed`),l}if(p){const l=he(a,s,h);await global.Linking.openURL(l,this.client.name)}else{const l=n||v[d.request.method].res;this.client.core.relayer.publish(s,h,l)}await this.client.core.history.resolve(c)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach(s=>{let i=!1;J(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&e.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{J(s.expiryTimestamp)&&t.push(s.id)}),await Promise.all([...e.map(s=>this.deleteSession({topic:s})),...t.map(s=>this.deleteProposal(s))])},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===x.active){this.client.logger.info(\"Request queue already active, skipping...\");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=x.active;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(t){this.client.logger.warn(t)}}this.requestQueue.state=x.idle},this.processRequest=async e=>{const{topic:t,payload:s,attestation:i,transportType:r,encryptedId:n}=e,a=s.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:a}))switch(a){case\"wc_sessionPropose\":return await this.onSessionProposeRequest({topic:t,payload:s,attestation:i,encryptedId:n});case\"wc_sessionSettle\":return await this.onSessionSettleRequest(t,s);case\"wc_sessionUpdate\":return await this.onSessionUpdateRequest(t,s);case\"wc_sessionExtend\":return await this.onSessionExtendRequest(t,s);case\"wc_sessionPing\":return await this.onSessionPingRequest(t,s);case\"wc_sessionDelete\":return await this.onSessionDeleteRequest(t,s);case\"wc_sessionRequest\":return await this.onSessionRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});case\"wc_sessionEvent\":return await this.onSessionEventRequest(t,s);case\"wc_sessionAuthenticate\":return await this.onSessionAuthenticateRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${a}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:s,transportType:i}=e,r=(await this.client.core.history.get(t,s.id)).request.method;switch(r){case\"wc_sessionPropose\":return this.onSessionProposeResponse(t,s,i);case\"wc_sessionSettle\":return this.onSessionSettleResponse(t,s);case\"wc_sessionUpdate\":return this.onSessionUpdateResponse(t,s);case\"wc_sessionExtend\":return this.onSessionExtendResponse(t,s);case\"wc_sessionPing\":return this.onSessionPingResponse(t,s);case\"wc_sessionRequest\":return this.onSessionRequestResponse(t,s);case\"wc_sessionAuthenticate\":return this.onSessionAuthenticateResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:s}=u(\"MISSING_OR_INVALID\",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)},this.shouldIgnorePairingRequest=e=>{const{topic:t,requestMethod:s}=e,i=this.expectedPairingMethodMap.get(t);return!i||i.includes(s)?!1:!!(i.includes(\"wc_sessionAuthenticate\")&&this.client.events.listenerCount(\"session_authenticate\")>0)},this.onSessionProposeRequest=async e=>{const{topic:t,payload:s,attestation:i,encryptedId:r}=e,{params:n,id:a}=s;try{const c=this.client.core.eventClient.getEvent({topic:t});this.isValidConnect(I({},s.params));const h=n.expiryTimestamp||A(v.wc_sessionPropose.req.ttl),p=I({id:a,pairingTopic:t,expiryTimestamp:h},n);await this.setProposal(a,p);const d=await this.getVerifyContext({attestationId:i,hash:X(JSON.stringify(s)),encryptedId:r,metadata:p.proposer.metadata});this.client.events.listenerCount(\"session_proposal\")===0&&(console.warn(\"No listener for session_proposal event\"),c?.setError(Rt.proposal_listener_not_found)),c?.addTrace(St.emit_session_proposal),this.client.events.emit(\"session_proposal\",{id:a,params:p,verifyContext:d})}catch(c){await this.sendError({id:a,topic:t,error:c,rpcOpts:v.wc_sessionPropose.autoReject}),this.client.logger.error(c)}},this.onSessionProposeResponse=async(e,t,s)=>{const{id:i}=t;if(K(t)){const{result:r}=t;this.client.logger.trace({type:\"method\",method:\"onSessionProposeResponse\",result:r});const n=this.client.proposal.get(i);this.client.logger.trace({type:\"method\",method:\"onSessionProposeResponse\",proposal:n});const a=n.proposer.publicKey;this.client.logger.trace({type:\"method\",method:\"onSessionProposeResponse\",selfPublicKey:a});const c=r.responderPublicKey;this.client.logger.trace({type:\"method\",method:\"onSessionProposeResponse\",peerPublicKey:c});const h=await this.client.core.crypto.generateSharedKey(a,c);this.client.logger.trace({type:\"method\",method:\"onSessionProposeResponse\",sessionTopic:h});const p=await this.client.core.relayer.subscribe(h,{transportType:s});this.client.logger.trace({type:\"method\",method:\"onSessionProposeResponse\",subscriptionId:p}),await this.client.core.pairing.activate({topic:e})}else if(U(t)){await this.client.proposal.delete(i,P(\"USER_DISCONNECTED\"));const r=g(\"session_connect\");if(this.events.listenerCount(r)===0)throw new Error(`emitting ${r} without any listeners, 954`);this.events.emit(g(\"session_connect\"),{error:t.error})}},this.onSessionSettleRequest=async(e,t)=>{const{id:s,params:i}=t;try{this.isValidSessionSettleRequest(i);const{relay:r,controller:n,expiry:a,namespaces:c,sessionProperties:h,sessionConfig:p}=t.params,d=D(I(I({topic:e,relay:r,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:\"\",requiredNamespaces:{},optionalNamespaces:{},controller:n.publicKey,self:{publicKey:\"\",metadata:this.client.metadata},peer:{publicKey:n.publicKey,metadata:n.metadata}},h&&{sessionProperties:h}),p&&{sessionConfig:p}),{transportType:f.relay}),l=g(\"session_connect\");if(this.events.listenerCount(l)===0)throw new Error(`emitting ${l} without any listeners 997`);this.events.emit(g(\"session_connect\"),{session:d}),await this.sendResult({id:t.id,topic:e,result:!0,throwOnFailedPublish:!0})}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}},this.onSessionSettleResponse=async(e,t)=>{const{id:s}=t;K(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(g(\"session_approve\",s),{})):U(t)&&(await this.client.session.delete(e,P(\"USER_DISCONNECTED\")),this.events.emit(g(\"session_approve\",s),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:s,id:i}=t;try{const r=`${e}_session_update`,n=re.get(r);if(n&&this.isRequestOutOfSync(n,i)){this.client.logger.info(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:e,error:P(\"INVALID_UPDATE_REQUEST\")});return}this.isValidUpdate(I({topic:e},s));try{re.set(r,i),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0})}catch(a){throw re.delete(r),a}this.client.events.emit(\"session_update\",{id:i,topic:e,params:s})}catch(r){await this.sendError({id:i,topic:e,error:r}),this.client.logger.error(r)}},this.isRequestOutOfSync=(e,t)=>parseInt(t.toString().slice(0,-3))<=parseInt(e.toString().slice(0,-3)),this.onSessionUpdateResponse=(e,t)=>{const{id:s}=t,i=g(\"session_update\",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);K(t)?this.events.emit(g(\"session_update\",s),{}):U(t)&&this.events.emit(g(\"session_update\",s),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,A(z)),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit(\"session_extend\",{id:s,topic:e})}catch(i){await this.sendError({id:s,topic:e,error:i}),this.client.logger.error(i)}},this.onSessionExtendResponse=(e,t)=>{const{id:s}=t,i=g(\"session_extend\",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);K(t)?this.events.emit(g(\"session_extend\",s),{}):U(t)&&this.events.emit(g(\"session_extend\",s),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit(\"session_ping\",{id:s,topic:e})}catch(i){await this.sendError({id:s,topic:e,error:i}),this.client.logger.error(i)}},this.onSessionPingResponse=(e,t)=>{const{id:s}=t,i=g(\"session_ping\",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);setTimeout(()=>{K(t)?this.events.emit(g(\"session_ping\",s),{}):U(t)&&this.events.emit(g(\"session_ping\",s),{error:t.error})},500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),Promise.all([new Promise(i=>{this.client.core.relayer.once(Ue.publish,async()=>{i(await this.deleteSession({topic:e,id:s}))})}),this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:P(\"USER_DISCONNECTED\")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}},this.onSessionRequest=async e=>{var t,s,i;const{topic:r,payload:n,attestation:a,encryptedId:c,transportType:h}=e,{id:p,params:d}=n;try{await this.isValidRequest(I({topic:r},d));const l=this.client.session.get(r),w=await this.getVerifyContext({attestationId:a,hash:X(JSON.stringify(ge(\"wc_sessionRequest\",d,p))),encryptedId:c,metadata:l.peer.metadata,transportType:h}),m={id:p,topic:r,params:d,verifyContext:w};await this.setPendingSessionRequest(m),h===f.link_mode&&(t=l.peer.metadata.redirect)!=null&&t.universal&&this.client.core.addLinkModeSupportedApp((s=l.peer.metadata.redirect)==null?void 0:s.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(l){await this.sendError({id:p,topic:r,error:l}),this.client.logger.error(l)}},this.onSessionRequestResponse=(e,t)=>{const{id:s}=t,i=g(\"session_request\",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);K(t)?this.events.emit(g(\"session_request\",s),{result:t.result}):U(t)&&this.events.emit(g(\"session_request\",s),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:s,params:i}=t;try{const r=`${e}_session_event_${i.event.name}`,n=re.get(r);if(n&&this.isRequestOutOfSync(n,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(I({topic:e},i)),this.client.events.emit(\"session_event\",{id:s,topic:e,params:i}),re.set(r,s)}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}},this.onSessionAuthenticateResponse=(e,t)=>{const{id:s}=t;this.client.logger.trace({type:\"method\",method:\"onSessionAuthenticateResponse\",topic:e,payload:t}),K(t)?this.events.emit(g(\"session_request\",s),{result:t.result}):U(t)&&this.events.emit(g(\"session_request\",s),{error:t.error})},this.onSessionAuthenticateRequest=async e=>{var t;const{topic:s,payload:i,attestation:r,encryptedId:n,transportType:a}=e;try{const{requester:c,authPayload:h,expiryTimestamp:p}=i.params,d=await this.getVerifyContext({attestationId:r,hash:X(JSON.stringify(i)),encryptedId:n,metadata:c.metadata,transportType:a}),l={requester:c,pairingTopic:s,id:i.id,authPayload:h,verifyContext:d,expiryTimestamp:p};await this.setAuthRequest(i.id,{request:l,pairingTopic:s,transportType:a}),a===f.link_mode&&(t=c.metadata.redirect)!=null&&t.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit(\"session_authenticate\",{topic:s,params:i.params,id:i.id,verifyContext:d})}catch(c){this.client.logger.error(c);const h=i.params.requester.publicKey,p=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(i.params.requester.metadata,a),l={type:Ae,receiverPublicKey:h,senderPublicKey:p};await this.sendError({id:i.id,topic:s,error:c,encodeOpts:l,rpcOpts:v.wc_sessionAuthenticate.autoReject,appLink:d})}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:\"fulfilled\",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=x.idle,this.processSessionRequestQueue()},tt(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:e,error:t})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===e&&i.request.method===\"wc_sessionRequest\").forEach(i=>{const r=i.request.id,n=g(\"session_request\",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);this.events.emit(g(\"session_request\",i.request.id),{error:t})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===x.active){this.client.logger.info(\"session request queue is already active.\");return}const e=this.sessionRequestQueue.queue[0];if(!e){this.client.logger.info(\"session request queue is empty.\");return}try{this.sessionRequestQueue.state=x.active,this.emitSessionRequest(e)}catch(t){this.client.logger.error(t)}},this.emitSessionRequest=e=>{this.client.events.emit(\"session_request\",e)},this.onPairingCreated=e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find(s=>s.pairingTopic===e.topic);t&&this.onSessionProposeRequest({topic:e.topic,payload:ge(\"wc_sessionPropose\",{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties},t.id)})},this.isValidConnect=async e=>{if(!L(e)){const{message:a}=u(\"MISSING_OR_INVALID\",`connect() params: ${JSON.stringify(e)}`);throw new Error(a)}const{pairingTopic:t,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:r,relays:n}=e;if(ne(t)||await this.isValidPairingTopic(t),!kt(n,!0)){const{message:a}=u(\"MISSING_OR_INVALID\",`connect() relays: ${n}`);throw new Error(a)}!ne(s)&&Xe(s)!==0&&this.validateNamespaces(s,\"requiredNamespaces\"),!ne(i)&&Xe(i)!==0&&this.validateNamespaces(i,\"optionalNamespaces\"),ne(r)||this.validateSessionProps(r,\"sessionProperties\")},this.validateNamespaces=(e,t)=>{const s=$t(e,\"connect()\",t);if(s)throw new Error(s.message)},this.isValidApprove=async e=>{if(!L(e))throw new Error(u(\"MISSING_OR_INVALID\",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:i,sessionProperties:r}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const n=this.client.proposal.get(t),a=Oe(s,\"approve()\");if(a)throw new Error(a.message);const c=Je(n.requiredNamespaces,s,\"approve()\");if(c)throw new Error(c.message);if(!k(i,!0)){const{message:h}=u(\"MISSING_OR_INVALID\",`approve() relayProtocol: ${i}`);throw new Error(h)}ne(r)||this.validateSessionProps(r,\"sessionProperties\")},this.isValidReject=async e=>{if(!L(e)){const{message:i}=u(\"MISSING_OR_INVALID\",`reject() params: ${e}`);throw new Error(i)}const{id:t,reason:s}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!Kt(s)){const{message:i}=u(\"MISSING_OR_INVALID\",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}},this.isValidSessionSettleRequest=e=>{if(!L(e)){const{message:c}=u(\"MISSING_OR_INVALID\",`onSessionSettleRequest() params: ${e}`);throw new Error(c)}const{relay:t,controller:s,namespaces:i,expiry:r}=e;if(!Ut(t)){const{message:c}=u(\"MISSING_OR_INVALID\",\"onSessionSettleRequest() relay protocol should be a string\");throw new Error(c)}const n=Gt(s,\"onSessionSettleRequest()\");if(n)throw new Error(n.message);const a=Oe(i,\"onSessionSettleRequest()\");if(a)throw new Error(a.message);if(J(r)){const{message:c}=u(\"EXPIRED\",\"onSessionSettleRequest()\");throw new Error(c)}},this.isValidUpdate=async e=>{if(!L(e)){const{message:a}=u(\"MISSING_OR_INVALID\",`update() params: ${e}`);throw new Error(a)}const{topic:t,namespaces:s}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const i=this.client.session.get(t),r=Oe(s,\"update()\");if(r)throw new Error(r.message);const n=Je(i.requiredNamespaces,s,\"update()\");if(n)throw new Error(n.message)},this.isValidExtend=async e=>{if(!L(e)){const{message:s}=u(\"MISSING_OR_INVALID\",`extend() params: ${e}`);throw new Error(s)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!L(e)){const{message:a}=u(\"MISSING_OR_INVALID\",`request() params: ${e}`);throw new Error(a)}const{topic:t,request:s,chainId:i,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!Be(n,i)){const{message:a}=u(\"MISSING_OR_INVALID\",`request() chainId: ${i}`);throw new Error(a)}if(!jt(s)){const{message:a}=u(\"MISSING_OR_INVALID\",`request() ${JSON.stringify(s)}`);throw new Error(a)}if(!Ft(n,i,s.method)){const{message:a}=u(\"MISSING_OR_INVALID\",`request() method: ${s.method}`);throw new Error(a)}if(r&&!Qt(r,me)){const{message:a}=u(\"MISSING_OR_INVALID\",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${me.min} and ${me.max}`);throw new Error(a)}},this.isValidRespond=async e=>{var t;if(!L(e)){const{message:r}=u(\"MISSING_OR_INVALID\",`respond() params: ${e}`);throw new Error(r)}const{topic:s,response:i}=e;try{await this.isValidSessionTopic(s)}catch(r){throw(t=e?.response)!=null&&t.id&&this.cleanupAfterResponse(e),r}if(!zt(i)){const{message:r}=u(\"MISSING_OR_INVALID\",`respond() response: ${JSON.stringify(i)}`);throw new Error(r)}},this.isValidPing=async e=>{if(!L(e)){const{message:s}=u(\"MISSING_OR_INVALID\",`ping() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!L(e)){const{message:n}=u(\"MISSING_OR_INVALID\",`emit() params: ${e}`);throw new Error(n)}const{topic:t,event:s,chainId:i}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!Be(r,i)){const{message:n}=u(\"MISSING_OR_INVALID\",`emit() chainId: ${i}`);throw new Error(n)}if(!Ht(s)){const{message:n}=u(\"MISSING_OR_INVALID\",`emit() event: ${JSON.stringify(s)}`);throw new Error(n)}if(!Yt(r,i,s.name)){const{message:n}=u(\"MISSING_OR_INVALID\",`emit() event: ${JSON.stringify(s)}`);throw new Error(n)}},this.isValidDisconnect=async e=>{if(!L(e)){const{message:s}=u(\"MISSING_OR_INVALID\",`disconnect() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidAuthenticate=e=>{const{chains:t,uri:s,domain:i,nonce:r}=e;if(!Array.isArray(t)||t.length===0)throw new Error(\"chains is required and must be a non-empty array\");if(!k(s,!1))throw new Error(\"uri is required parameter\");if(!k(i,!1))throw new Error(\"domain is required parameter\");if(!k(r,!1))throw new Error(\"nonce is required parameter\");if([...new Set(t.map(a=>Ne(a).namespace))].length>1)throw new Error(\"Multi-namespace requests are not supported. Please request single namespace only.\");const{namespace:n}=Ne(t[0]);if(n!==\"eip155\")throw new Error(\"Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.\")},this.getVerifyContext=async e=>{const{attestationId:t,hash:s,encryptedId:i,metadata:r,transportType:n}=e,a={verified:{verifyUrl:r.verifyUrl||It,validation:\"UNKNOWN\",origin:r.url||\"\"}};try{if(n===f.link_mode){const h=this.getAppLinkIfEnabled(r,n);return a.verified.validation=h&&new URL(h).origin===new URL(r.url).origin?\"VALID\":\"INVALID\",a}const c=await this.client.core.verify.resolve({attestationId:t,hash:s,encryptedId:i,verifyUrl:r.verifyUrl});c&&(a.verified.origin=c.origin,a.verified.isScam=c.isScam,a.verified.validation=c.origin===new URL(r.url).origin?\"VALID\":\"INVALID\")}catch(c){this.client.logger.warn(c)}return this.client.logger.debug(`Verify context: ${JSON.stringify(a)}`),a},this.validateSessionProps=(e,t)=>{Object.values(e).forEach(s=>{if(!k(s,!1)){const{message:i}=u(\"MISSING_OR_INVALID\",`${t} must be in Record format. Received: ${JSON.stringify(s)}`);throw new Error(i)}})},this.getPendingAuthRequest=e=>{const t=this.client.auth.requests.get(e);return typeof t==\"object\"?t:void 0},this.addToRecentlyDeleted=(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const i=this.recentlyDeletedLimit/2;for(const r of this.recentlyDeletedMap.keys()){if(s++>=i)break;this.recentlyDeletedMap.delete(r)}}},this.checkRecentlyDeleted=e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=u(\"MISSING_OR_INVALID\",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}},this.isLinkModeEnabled=(e,t)=>{var s,i,r,n,a,c,h,p,d;return!e||t!==f.link_mode?!1:((i=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:i.linkMode)===!0&&((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.universal)!==void 0&&((c=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:c.universal)!==\"\"&&((h=e?.redirect)==null?void 0:h.universal)!==void 0&&((p=e?.redirect)==null?void 0:p.universal)!==\"\"&&((d=e?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof(global==null?void 0:global.Linking)<\"u\"},this.getAppLinkIfEnabled=(e,t)=>{var s;return this.isLinkModeEnabled(e,t)?(s=e?.redirect)==null?void 0:s.universal:void 0},this.handleLinkModeMessage=({url:e})=>{if(!e||!e.includes(\"wc_ev\")||!e.includes(\"topic\"))return;const t=We(e,\"topic\")||\"\",s=decodeURIComponent(We(e,\"wc_ev\")||\"\"),i=this.client.session.keys.includes(t);i&&this.client.session.update(t,{transportType:f.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:i})},this.registerLinkModeListeners=async()=>{var e;if(Xt()||Jt()&&(e=this.client.metadata.redirect)!=null&&e.linkMode){const t=global==null?void 0:global.Linking;if(typeof t<\"u\"){t.addEventListener(\"url\",this.handleLinkModeMessage,this.client.name);const s=await t.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}}isInitialized(){if(!this.initialized){const{message:o}=u(\"NOT_INITIALIZED\",this.name);throw new Error(o)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ue.message,o=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(o):this.onRelayMessage(o)})}async onRelayMessage(o){const{topic:e,message:t,attestation:s,transportType:i}=o,{publicKey:r}=this.client.auth.authKeys.keys.includes(ae)?this.client.auth.authKeys.get(ae):{responseTopic:void 0,publicKey:void 0},n=await this.client.core.crypto.decode(e,t,{receiverPublicKey:r,encoding:i===f.link_mode?ie:de});try{os(n)?(this.client.core.history.set(e,n),this.onRelayEventRequest({topic:e,payload:n,attestation:s,transportType:i,encryptedId:X(t)})):as(n)?(await this.client.core.history.resolve(n),await this.onRelayEventResponse({topic:e,payload:n,transportType:i}),this.client.core.history.delete(e,n.id)):this.onRelayEventUnknownPayload({topic:e,payload:n,transportType:i})}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ft.expired,async o=>{const{topic:e,id:t}=Bt(o.target);if(t&&this.client.pendingRequest.keys.includes(t))return await this.deletePendingSessionRequest(t,u(\"EXPIRED\"),!0);if(t&&this.client.auth.requests.keys.includes(t))return await this.deletePendingAuthRequest(t,u(\"EXPIRED\"),!0);e?this.client.session.keys.includes(e)&&(await this.deleteSession({topic:e,expirerHasDeleted:!0}),this.client.events.emit(\"session_expire\",{topic:e})):t&&(await this.deleteProposal(t,!0),this.client.events.emit(\"proposal_expire\",{id:t}))})}registerPairingEvents(){this.client.core.pairing.events.on(Ge.create,o=>this.onPairingCreated(o)),this.client.core.pairing.events.on(Ge.delete,o=>{this.addToRecentlyDeleted(o.topic,\"pairing\")})}isValidPairingTopic(o){if(!k(o,!1)){const{message:e}=u(\"MISSING_OR_INVALID\",`pairing topic should be a string: ${o}`);throw new Error(e)}if(!this.client.core.pairing.pairings.keys.includes(o)){const{message:e}=u(\"NO_MATCHING_KEY\",`pairing topic doesn't exist: ${o}`);throw new Error(e)}if(J(this.client.core.pairing.pairings.get(o).expiry)){const{message:e}=u(\"EXPIRED\",`pairing topic: ${o}`);throw new Error(e)}}async isValidSessionTopic(o){if(!k(o,!1)){const{message:e}=u(\"MISSING_OR_INVALID\",`session topic should be a string: ${o}`);throw new Error(e)}if(this.checkRecentlyDeleted(o),!this.client.session.keys.includes(o)){const{message:e}=u(\"NO_MATCHING_KEY\",`session topic doesn't exist: ${o}`);throw new Error(e)}if(J(this.client.session.get(o).expiry)){await this.deleteSession({topic:o});const{message:e}=u(\"EXPIRED\",`session topic: ${o}`);throw new Error(e)}if(!this.client.core.crypto.keychain.has(o)){const{message:e}=u(\"MISSING_OR_INVALID\",`session topic does not exist in keychain: ${o}`);throw await this.deleteSession({topic:o}),new Error(e)}}async isValidSessionOrPairingTopic(o){if(this.checkRecentlyDeleted(o),this.client.session.keys.includes(o))await this.isValidSessionTopic(o);else if(this.client.core.pairing.pairings.keys.includes(o))this.isValidPairingTopic(o);else if(k(o,!1)){const{message:e}=u(\"NO_MATCHING_KEY\",`session or pairing topic doesn't exist: ${o}`);throw new Error(e)}else{const{message:e}=u(\"MISSING_OR_INVALID\",`session or pairing topic should be a string: ${o}`);throw new Error(e)}}async isValidProposalId(o){if(!Wt(o)){const{message:e}=u(\"MISSING_OR_INVALID\",`proposal id should be a number: ${o}`);throw new Error(e)}if(!this.client.proposal.keys.includes(o)){const{message:e}=u(\"NO_MATCHING_KEY\",`proposal id doesn't exist: ${o}`);throw new Error(e)}if(J(this.client.proposal.get(o).expiryTimestamp)){await this.deleteProposal(o);const{message:e}=u(\"EXPIRED\",`proposal id: ${o}`);throw new Error(e)}}}class Ss extends H{constructor(o,e){super(o,e,st,ye),this.core=o,this.logger=e}}class yt extends H{constructor(o,e){super(o,e,rt,ye),this.core=o,this.logger=e}}class Is extends H{constructor(o,e){super(o,e,ot,ye,t=>t.id),this.core=o,this.logger=e}}class fs extends H{constructor(o,e){super(o,e,pt,oe,()=>ae),this.core=o,this.logger=e}}class vs extends H{constructor(o,e){super(o,e,ht,oe),this.core=o,this.logger=e}}class qs extends H{constructor(o,e){super(o,e,dt,oe,t=>t.id),this.core=o,this.logger=e}}class Ts{constructor(o,e){this.core=o,this.logger=e,this.authKeys=new fs(this.core,this.logger),this.pairingTopics=new vs(this.core,this.logger),this.requests=new qs(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class _e extends At{constructor(o){super(o),this.protocol=be,this.version=Ce,this.name=we.name,this.events=new ts,this.on=(t,s)=>this.events.on(t,s),this.once=(t,s)=>this.events.once(t,s),this.off=(t,s)=>this.events.off(t,s),this.removeListener=(t,s)=>this.events.removeListener(t,s),this.removeAllListeners=t=>this.events.removeAllListeners(t),this.connect=async t=>{try{return await this.engine.connect(t)}catch(s){throw this.logger.error(s.message),s}},this.pair=async t=>{try{return await this.engine.pair(t)}catch(s){throw this.logger.error(s.message),s}},this.approve=async t=>{try{return await this.engine.approve(t)}catch(s){throw this.logger.error(s.message),s}},this.reject=async t=>{try{return await this.engine.reject(t)}catch(s){throw this.logger.error(s.message),s}},this.update=async t=>{try{return await this.engine.update(t)}catch(s){throw this.logger.error(s.message),s}},this.extend=async t=>{try{return await this.engine.extend(t)}catch(s){throw this.logger.error(s.message),s}},this.request=async t=>{try{return await this.engine.request(t)}catch(s){throw this.logger.error(s.message),s}},this.respond=async t=>{try{return await this.engine.respond(t)}catch(s){throw this.logger.error(s.message),s}},this.ping=async t=>{try{return await this.engine.ping(t)}catch(s){throw this.logger.error(s.message),s}},this.emit=async t=>{try{return await this.engine.emit(t)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async t=>{try{return await this.engine.disconnect(t)}catch(s){throw this.logger.error(s.message),s}},this.find=t=>{try{return this.engine.find(t)}catch(s){throw this.logger.error(s.message),s}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(t){throw this.logger.error(t.message),t}},this.authenticate=async(t,s)=>{try{return await this.engine.authenticate(t,s)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=t=>{try{return this.engine.formatAuthMessage(t)}catch(s){throw this.logger.error(s.message),s}},this.approveSessionAuthenticate=async t=>{try{return await this.engine.approveSessionAuthenticate(t)}catch(s){throw this.logger.error(s.message),s}},this.rejectSessionAuthenticate=async t=>{try{return await this.engine.rejectSessionAuthenticate(t)}catch(s){throw this.logger.error(s.message),s}},this.name=o?.name||we.name,this.metadata=o?.metadata||Zt(),this.signConfig=o?.signConfig;const e=typeof o?.logger<\"u\"&&typeof o?.logger!=\"string\"?o.logger:qt(Tt({level:o?.logger||we.logger}));this.core=o?.core||new vt(o),this.logger=Nt(e,this.name),this.session=new yt(this.core,this.logger),this.proposal=new Ss(this.core,this.logger),this.pendingRequest=new Is(this.core,this.logger),this.engine=new Rs(this),this.auth=new Ts(this.core,this.logger)}static async init(o){const e=new _e(o);return await e.initialize(),e}get context(){return Pt(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.auth.init(),await this.engine.init(),this.logger.info(\"SignClient Initialization Success\"),this.engine.processRelayMessageCache()}catch(o){throw this.logger.info(\"SignClient Initialization Failure\"),this.logger.error(o.message),o}}}const Ns=yt,Ps=_e;export{lt as AUTH_CONTEXT,pt as AUTH_KEYS_CONTEXT,ht as AUTH_PAIRING_TOPIC_CONTEXT,ct as AUTH_PROTOCOL,ae as AUTH_PUBLIC_KEY_NAME,dt as AUTH_REQUEST_CONTEXT,oe as AUTH_STORAGE_PREFIX,gs as AUTH_VERSION,nt as ENGINE_CONTEXT,x as ENGINE_QUEUE_STATES,v as ENGINE_RPC_OPTS,hs as HISTORY_CONTEXT,ps as HISTORY_EVENTS,ds as HISTORY_STORAGE_VERSION,at as METHODS_TO_VERIFY,st as PROPOSAL_CONTEXT,us as PROPOSAL_EXPIRY,it as PROPOSAL_EXPIRY_MESSAGE,ot as REQUEST_CONTEXT,rt as SESSION_CONTEXT,z as SESSION_EXPIRY,me as SESSION_REQUEST_EXPIRY_BOUNDARIES,Le as SIGN_CLIENT_CONTEXT,we as SIGN_CLIENT_DEFAULT,cs as SIGN_CLIENT_EVENTS,be as SIGN_CLIENT_PROTOCOL,ls as SIGN_CLIENT_STORAGE_OPTIONS,ye as SIGN_CLIENT_STORAGE_PREFIX,Ce as SIGN_CLIENT_VERSION,Ns as SessionStore,Ps as SignClient,xe as WALLETCONNECT_DEEPLINK_CHOICE,_e as default};\n//# sourceMappingURL=index.es.js.map\n","/**\n * @license\n * Lodash \n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '4.17.21';\n\n /** Used as the size to enable large array optimizations. */\n var LARGE_ARRAY_SIZE = 200;\n\n /** Error message constants. */\n var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n FUNC_ERROR_TEXT = 'Expected a function',\n INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';\n\n /** Used to stand-in for `undefined` hash values. */\n var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n /** Used as the maximum memoize cache size. */\n var MAX_MEMOIZE_SIZE = 500;\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** Used to compose bitmasks for cloning. */\n var CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n /** Used to compose bitmasks for value comparisons. */\n var COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n /** Used to compose bitmasks for function metadata. */\n var WRAP_BIND_FLAG = 1,\n WRAP_BIND_KEY_FLAG = 2,\n WRAP_CURRY_BOUND_FLAG = 4,\n WRAP_CURRY_FLAG = 8,\n WRAP_CURRY_RIGHT_FLAG = 16,\n WRAP_PARTIAL_FLAG = 32,\n WRAP_PARTIAL_RIGHT_FLAG = 64,\n WRAP_ARY_FLAG = 128,\n WRAP_REARG_FLAG = 256,\n WRAP_FLIP_FLAG = 512;\n\n /** Used as default options for `_.truncate`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect hot functions by number of calls within a span of milliseconds. */\n var HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 1,\n LAZY_MAP_FLAG = 2,\n LAZY_WHILE_FLAG = 3;\n\n /** Used as references for various `Number` constants. */\n var INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = 4294967295,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used to associate wrap methods with their bit flags. */\n var wrapFlags = [\n ['ary', WRAP_ARY_FLAG],\n ['bind', WRAP_BIND_FLAG],\n ['bindKey', WRAP_BIND_KEY_FLAG],\n ['curry', WRAP_CURRY_FLAG],\n ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n ['flip', WRAP_FLIP_FLAG],\n ['partial', WRAP_PARTIAL_FLAG],\n ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n ['rearg', WRAP_REARG_FLAG]\n ];\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n domExcTag = '[object DOMException]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]',\n weakSetTag = '[object WeakSet]';\n\n var arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n /** Used to match empty string literals in compiled template source. */\n var reEmptyStringLeading = /\\b__p \\+= '';/g,\n reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n /** Used to match HTML entities and HTML characters. */\n var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,\n reUnescapedHtml = /[&<>\"']/g,\n reHasEscapedHtml = RegExp(reEscapedHtml.source),\n reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n /** Used to match template delimiters. */\n var reEscape = /<%-([\\s\\S]+?)%>/g,\n reEvaluate = /<%([\\s\\S]+?)%>/g,\n reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n /** Used to match property names within property paths. */\n var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/,\n rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n /**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\n var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n reHasRegExpChar = RegExp(reRegExpChar.source);\n\n /** Used to match leading whitespace. */\n var reTrimStart = /^\\s+/;\n\n /** Used to match a single whitespace character. */\n var reWhitespace = /\\s/;\n\n /** Used to match wrap detail comments. */\n var reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n reSplitDetails = /,? & /;\n\n /** Used to match words composed of alphanumeric characters. */\n var reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n /**\n * Used to validate the `validate` option in `_.template` variable.\n *\n * Forbids characters which could potentially change the meaning of the function argument definition:\n * - \"(),\" (modification of function parameters)\n * - \"=\" (default value)\n * - \"[]{}\" (destructuring of function parameters)\n * - \"/\" (beginning of a comment)\n * - whitespace\n */\n var reForbiddenIdentifierChars = /[()=,{}\\[\\]\\/\\s]/;\n\n /** Used to match backslashes in property paths. */\n var reEscapeChar = /\\\\(\\\\)?/g;\n\n /**\n * Used to match\n * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).\n */\n var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n /** Used to match `RegExp` flags from their coerced string values. */\n var reFlags = /\\w*$/;\n\n /** Used to detect bad signed hexadecimal string values. */\n var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n /** Used to detect binary string values. */\n var reIsBinary = /^0b[01]+$/i;\n\n /** Used to detect host constructors (Safari). */\n var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n /** Used to detect octal string values. */\n var reIsOctal = /^0o[0-7]+$/i;\n\n /** Used to detect unsigned integer values. */\n var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n /** Used to match Latin Unicode letters (excluding mathematical operators). */\n var reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n /** Used to ensure capturing order of template delimiters. */\n var reNoMatch = /($^)/;\n\n /** Used to match unescaped characters in compiled string literals. */\n var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n /** Used to compose unicode character classes. */\n var rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n /** Used to compose unicode capture groups. */\n var rsApos = \"['\\u2019]\",\n rsAstral = '[' + rsAstralRange + ']',\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n /** Used to compose unicode regexes. */\n var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n /** Used to match apostrophes. */\n var reApos = RegExp(rsApos, 'g');\n\n /**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\n var reComboMark = RegExp(rsCombo, 'g');\n\n /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\n var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n /** Used to match complex or compound words. */\n var reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n ].join('|'), 'g');\n\n /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\n var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n /** Used to detect strings that need a more robust regexp to match words. */\n var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n /** Used to assign default `context` object properties. */\n var contextProps = [\n 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',\n 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',\n 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',\n 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'\n ];\n\n /** Used to make template sourceURLs easier to identify. */\n var templateCounter = -1;\n\n /** Used to identify `toStringTag` values of typed arrays. */\n var typedArrayTags = {};\n typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n typedArrayTags[uint32Tag] = true;\n typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n typedArrayTags[errorTag] = typedArrayTags[funcTag] =\n typedArrayTags[mapTag] = typedArrayTags[numberTag] =\n typedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n typedArrayTags[setTag] = typedArrayTags[stringTag] =\n typedArrayTags[weakMapTag] = false;\n\n /** Used to identify `toStringTag` values supported by `_.clone`. */\n var cloneableTags = {};\n cloneableTags[argsTag] = cloneableTags[arrayTag] =\n cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\n cloneableTags[boolTag] = cloneableTags[dateTag] =\n cloneableTags[float32Tag] = cloneableTags[float64Tag] =\n cloneableTags[int8Tag] = cloneableTags[int16Tag] =\n cloneableTags[int32Tag] = cloneableTags[mapTag] =\n cloneableTags[numberTag] = cloneableTags[objectTag] =\n cloneableTags[regexpTag] = cloneableTags[setTag] =\n cloneableTags[stringTag] = cloneableTags[symbolTag] =\n cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n cloneableTags[errorTag] = cloneableTags[funcTag] =\n cloneableTags[weakMapTag] = false;\n\n /** Used to map Latin Unicode letters to basic Latin letters. */\n var deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n };\n\n /** Used to map characters to HTML entities. */\n var htmlEscapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n };\n\n /** Used to map HTML entities to characters. */\n var htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\"\n };\n\n /** Used to escape characters for inclusion in compiled string literals. */\n var stringEscapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n '\\n': 'n',\n '\\r': 'r',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n /** Built-in method references without a dependency on `root`. */\n var freeParseFloat = parseFloat,\n freeParseInt = parseInt;\n\n /** Detect free variable `global` from Node.js. */\n var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n /** Detect free variable `self`. */\n var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n /** Used as a reference to the global object. */\n var root = freeGlobal || freeSelf || Function('return this')();\n\n /** Detect free variable `exports`. */\n var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n /** Detect free variable `module`. */\n var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n /** Detect the popular CommonJS extension `module.exports`. */\n var moduleExports = freeModule && freeModule.exports === freeExports;\n\n /** Detect free variable `process` from Node.js. */\n var freeProcess = moduleExports && freeGlobal.process;\n\n /** Used to access faster Node.js helpers. */\n var nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n }());\n\n /* Node.js helper references. */\n var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,\n nodeIsDate = nodeUtil && nodeUtil.isDate,\n nodeIsMap = nodeUtil && nodeUtil.isMap,\n nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,\n nodeIsSet = nodeUtil && nodeUtil.isSet,\n nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\n function apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n }\n\n /**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function arrayAggregator(array, setter, iteratee, accumulator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n var value = array[index];\n setter(accumulator, value, iteratee(value), array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEachRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEachRight(array, iteratee) {\n var length = array == null ? 0 : array.length;\n\n while (length--) {\n if (iteratee(array[length], length, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.every` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\n function arrayEvery(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n }\n\n /**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n }\n\n /**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\n function arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n }\n\n /**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.reduceRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the last element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduceRight(array, iteratee, accumulator, initAccum) {\n var length = array == null ? 0 : array.length;\n if (initAccum && length) {\n accumulator = array[--length];\n }\n while (length--) {\n accumulator = iteratee(accumulator, array[length], length, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets the size of an ASCII `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n var asciiSize = baseProperty('length');\n\n /**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function asciiToArray(string) {\n return string.split('');\n }\n\n /**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function asciiWords(string) {\n return string.match(reAsciiWord) || [];\n }\n\n /**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\n function baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n }\n\n /**\n * This function is like `baseIndexOf` except that it accepts a comparator.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOfWith(array, value, fromIndex, comparator) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (comparator(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\n function baseIsNaN(value) {\n return value !== value;\n }\n\n /**\n * The base implementation of `_.mean` and `_.meanBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the mean.\n */\n function baseMean(array, iteratee) {\n var length = array == null ? 0 : array.length;\n return length ? (baseSum(array, iteratee) / length) : NAN;\n }\n\n /**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\n function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\n function baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\n function baseSum(array, iteratee) {\n var result,\n index = -1,\n length = array.length;\n\n while (++index < length) {\n var current = iteratee(array[index]);\n if (current !== undefined) {\n result = result === undefined ? current : (result + current);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\n function baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array\n * of key-value pairs for `object` corresponding to the property names of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the key-value pairs.\n */\n function baseToPairs(object, props) {\n return arrayMap(props, function(key) {\n return [key, object[key]];\n });\n }\n\n /**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\n function baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n }\n\n /**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\n function baseUnary(func) {\n return function(value) {\n return func(value);\n };\n }\n\n /**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\n function baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n }\n\n /**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function cacheHas(cache, key) {\n return cache.has(key);\n }\n\n /**\n * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the first unmatched string symbol.\n */\n function charsStartIndex(strSymbols, chrSymbols) {\n var index = -1,\n length = strSymbols.length;\n\n while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the last unmatched string symbol.\n */\n function charsEndIndex(strSymbols, chrSymbols) {\n var index = strSymbols.length;\n\n while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\n function countHolders(array, placeholder) {\n var length = array.length,\n result = 0;\n\n while (length--) {\n if (array[length] === placeholder) {\n ++result;\n }\n }\n return result;\n }\n\n /**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\n var deburrLetter = basePropertyOf(deburredLetters);\n\n /**\n * Used by `_.escape` to convert characters to HTML entities.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n var escapeHtmlChar = basePropertyOf(htmlEscapes);\n\n /**\n * Used by `_.template` to escape characters for inclusion in compiled string literals.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeStringChar(chr) {\n return '\\\\' + stringEscapes[chr];\n }\n\n /**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function getValue(object, key) {\n return object == null ? undefined : object[key];\n }\n\n /**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\n function hasUnicode(string) {\n return reHasUnicode.test(string);\n }\n\n /**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\n function hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n }\n\n /**\n * Converts `iterator` to an array.\n *\n * @private\n * @param {Object} iterator The iterator to convert.\n * @returns {Array} Returns the converted array.\n */\n function iteratorToArray(iterator) {\n var data,\n result = [];\n\n while (!(data = iterator.next()).done) {\n result.push(data.value);\n }\n return result;\n }\n\n /**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\n function mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n }\n\n /**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\n function overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n }\n\n /**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\n function replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value === placeholder || value === PLACEHOLDER) {\n array[index] = PLACEHOLDER;\n result[resIndex++] = index;\n }\n }\n return result;\n }\n\n /**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\n function setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n }\n\n /**\n * Converts `set` to its value-value pairs.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the value-value pairs.\n */\n function setToPairs(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = [value, value];\n });\n return result;\n }\n\n /**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * A specialized version of `_.lastIndexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictLastIndexOf(array, value, fromIndex) {\n var index = fromIndex + 1;\n while (index--) {\n if (array[index] === value) {\n return index;\n }\n }\n return index;\n }\n\n /**\n * Gets the number of symbols in `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the string size.\n */\n function stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n }\n\n /**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\n function trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n }\n\n /**\n * Used by `_.unescape` to convert HTML entities to characters.\n *\n * @private\n * @param {string} chr The matched character to unescape.\n * @returns {string} Returns the unescaped character.\n */\n var unescapeHtmlChar = basePropertyOf(htmlUnescapes);\n\n /**\n * Gets the size of a Unicode `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n function unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n }\n\n /**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function unicodeToArray(string) {\n return string.match(reUnicode) || [];\n }\n\n /**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n }\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * Create a new pristine `lodash` function using the `context` object.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Util\n * @param {Object} [context=root] The context object.\n * @returns {Function} Returns a new `lodash` function.\n * @example\n *\n * _.mixin({ 'foo': _.constant('foo') });\n *\n * var lodash = _.runInContext();\n * lodash.mixin({ 'bar': lodash.constant('bar') });\n *\n * _.isFunction(_.foo);\n * // => true\n * _.isFunction(_.bar);\n * // => false\n *\n * lodash.isFunction(lodash.foo);\n * // => false\n * lodash.isFunction(lodash.bar);\n * // => true\n *\n * // Create a suped-up `defer` in Node.js.\n * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n */\n var runInContext = (function runInContext(context) {\n context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));\n\n /** Built-in constructor references. */\n var Array = context.Array,\n Date = context.Date,\n Error = context.Error,\n Function = context.Function,\n Math = context.Math,\n Object = context.Object,\n RegExp = context.RegExp,\n String = context.String,\n TypeError = context.TypeError;\n\n /** Used for built-in method references. */\n var arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n /** Used to detect overreaching core-js shims. */\n var coreJsData = context['__core-js_shared__'];\n\n /** Used to resolve the decompiled source of functions. */\n var funcToString = funcProto.toString;\n\n /** Used to check objects for own properties. */\n var hasOwnProperty = objectProto.hasOwnProperty;\n\n /** Used to generate unique IDs. */\n var idCounter = 0;\n\n /** Used to detect methods masquerading as native. */\n var maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n }());\n\n /**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\n var nativeObjectToString = objectProto.toString;\n\n /** Used to infer the `Object` constructor. */\n var objectCtorString = funcToString.call(Object);\n\n /** Used to restore the original `_` reference in `_.noConflict`. */\n var oldDash = root._;\n\n /** Used to detect if a method is native. */\n var reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n );\n\n /** Built-in value references. */\n var Buffer = moduleExports ? context.Buffer : undefined,\n Symbol = context.Symbol,\n Uint8Array = context.Uint8Array,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,\n symIterator = Symbol ? Symbol.iterator : undefined,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n var defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n }());\n\n /** Mocked built-ins. */\n var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,\n ctxNow = Date && Date.now !== root.Date.now && Date.now,\n ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;\n\n /* Built-in method references for those with the same name as other `lodash` methods. */\n var nativeCeil = Math.ceil,\n nativeFloor = Math.floor,\n nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeIsFinite = context.isFinite,\n nativeJoin = arrayProto.join,\n nativeKeys = overArg(Object.keys, Object),\n nativeMax = Math.max,\n nativeMin = Math.min,\n nativeNow = Date.now,\n nativeParseInt = context.parseInt,\n nativeRandom = Math.random,\n nativeReverse = arrayProto.reverse;\n\n /* Built-in method references that are verified to be native. */\n var DataView = getNative(context, 'DataView'),\n Map = getNative(context, 'Map'),\n Promise = getNative(context, 'Promise'),\n Set = getNative(context, 'Set'),\n WeakMap = getNative(context, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n /** Used to store function metadata. */\n var metaMap = WeakMap && new WeakMap;\n\n /** Used to lookup unminified function names. */\n var realNames = {};\n\n /** Used to detect maps, sets, and weakmaps. */\n var dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n /** Used to convert symbols to primitives and strings. */\n var symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object which wraps `value` to enable implicit method\n * chain sequences. Methods that operate on and return arrays, collections,\n * and functions can be chained together. Methods that retrieve a single value\n * or may return a primitive value will automatically end the chain sequence\n * and return the unwrapped value. Otherwise, the value must be unwrapped\n * with `_#value`.\n *\n * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n * enabled using `_.chain`.\n *\n * The execution of chained methods is lazy, that is, it's deferred until\n * `_#value` is implicitly or explicitly called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion.\n * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n * the creation of intermediate arrays and can greatly reduce the number of\n * iteratee executions. Sections of a chain sequence qualify for shortcut\n * fusion if the section is applied to an array and iteratees accept only\n * one argument. The heuristic for whether a section qualifies for shortcut\n * fusion is subject to change.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers have `Array` and `String` methods.\n *\n * The wrapper `Array` methods are:\n * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n *\n * The wrapper `String` methods are:\n * `replace` and `split`\n *\n * The wrapper methods that support shortcut fusion are:\n * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n * `zipObject`, `zipObjectDeep`, and `zipWith`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n * `upperFirst`, `value`, and `words`\n *\n * @name _\n * @constructor\n * @category Seq\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // Returns an unwrapped value.\n * wrapped.reduce(_.add);\n * // => 6\n *\n * // Returns a wrapped value.\n * var squares = wrapped.map(square);\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\n function lodash(value) {\n if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n if (value instanceof LodashWrapper) {\n return value;\n }\n if (hasOwnProperty.call(value, '__wrapped__')) {\n return wrapperClone(value);\n }\n }\n return new LodashWrapper(value);\n }\n\n /**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\n var baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n }());\n\n /**\n * The function whose prototype chain sequence wrappers inherit from.\n *\n * @private\n */\n function baseLodash() {\n // No operation performed.\n }\n\n /**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable explicit method chain sequences.\n */\n function LodashWrapper(value, chainAll) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__chain__ = !!chainAll;\n this.__index__ = 0;\n this.__values__ = undefined;\n }\n\n /**\n * By default, the template delimiters used by lodash are like those in\n * embedded Ruby (ERB) as well as ES2015 template strings. Change the\n * following template settings to use alternative delimiters.\n *\n * @static\n * @memberOf _\n * @type {Object}\n */\n lodash.templateSettings = {\n\n /**\n * Used to detect `data` property values to be HTML-escaped.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'escape': reEscape,\n\n /**\n * Used to detect code to be evaluated.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'evaluate': reEvaluate,\n\n /**\n * Used to detect `data` property values to inject.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'interpolate': reInterpolate,\n\n /**\n * Used to reference the data object in the template text.\n *\n * @memberOf _.templateSettings\n * @type {string}\n */\n 'variable': '',\n\n /**\n * Used to import variables into the compiled template.\n *\n * @memberOf _.templateSettings\n * @type {Object}\n */\n 'imports': {\n\n /**\n * A reference to the `lodash` function.\n *\n * @memberOf _.templateSettings.imports\n * @type {Function}\n */\n '_': lodash\n }\n };\n\n // Ensure wrappers are instances of `baseLodash`.\n lodash.prototype = baseLodash.prototype;\n lodash.prototype.constructor = lodash;\n\n LodashWrapper.prototype = baseCreate(baseLodash.prototype);\n LodashWrapper.prototype.constructor = LodashWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @constructor\n * @param {*} value The value to wrap.\n */\n function LazyWrapper(value) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__dir__ = 1;\n this.__filtered__ = false;\n this.__iteratees__ = [];\n this.__takeCount__ = MAX_ARRAY_LENGTH;\n this.__views__ = [];\n }\n\n /**\n * Creates a clone of the lazy wrapper object.\n *\n * @private\n * @name clone\n * @memberOf LazyWrapper\n * @returns {Object} Returns the cloned `LazyWrapper` object.\n */\n function lazyClone() {\n var result = new LazyWrapper(this.__wrapped__);\n result.__actions__ = copyArray(this.__actions__);\n result.__dir__ = this.__dir__;\n result.__filtered__ = this.__filtered__;\n result.__iteratees__ = copyArray(this.__iteratees__);\n result.__takeCount__ = this.__takeCount__;\n result.__views__ = copyArray(this.__views__);\n return result;\n }\n\n /**\n * Reverses the direction of lazy iteration.\n *\n * @private\n * @name reverse\n * @memberOf LazyWrapper\n * @returns {Object} Returns the new reversed `LazyWrapper` object.\n */\n function lazyReverse() {\n if (this.__filtered__) {\n var result = new LazyWrapper(this);\n result.__dir__ = -1;\n result.__filtered__ = true;\n } else {\n result = this.clone();\n result.__dir__ *= -1;\n }\n return result;\n }\n\n /**\n * Extracts the unwrapped value from its lazy wrapper.\n *\n * @private\n * @name value\n * @memberOf LazyWrapper\n * @returns {*} Returns the unwrapped value.\n */\n function lazyValue() {\n var array = this.__wrapped__.value(),\n dir = this.__dir__,\n isArr = isArray(array),\n isRight = dir < 0,\n arrLength = isArr ? array.length : 0,\n view = getView(0, arrLength, this.__views__),\n start = view.start,\n end = view.end,\n length = end - start,\n index = isRight ? end : (start - 1),\n iteratees = this.__iteratees__,\n iterLength = iteratees.length,\n resIndex = 0,\n takeCount = nativeMin(length, this.__takeCount__);\n\n if (!isArr || (!isRight && arrLength == length && takeCount == length)) {\n return baseWrapperValue(array, this.__actions__);\n }\n var result = [];\n\n outer:\n while (length-- && resIndex < takeCount) {\n index += dir;\n\n var iterIndex = -1,\n value = array[index];\n\n while (++iterIndex < iterLength) {\n var data = iteratees[iterIndex],\n iteratee = data.iteratee,\n type = data.type,\n computed = iteratee(value);\n\n if (type == LAZY_MAP_FLAG) {\n value = computed;\n } else if (!computed) {\n if (type == LAZY_FILTER_FLAG) {\n continue outer;\n } else {\n break outer;\n }\n }\n }\n result[resIndex++] = value;\n }\n return result;\n }\n\n // Ensure `LazyWrapper` is an instance of `baseLodash`.\n LazyWrapper.prototype = baseCreate(baseLodash.prototype);\n LazyWrapper.prototype.constructor = LazyWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\n function hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n }\n\n /**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n }\n\n /**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\n function hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n }\n\n // Add methods to `Hash`.\n Hash.prototype.clear = hashClear;\n Hash.prototype['delete'] = hashDelete;\n Hash.prototype.get = hashGet;\n Hash.prototype.has = hashHas;\n Hash.prototype.set = hashSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n function listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n }\n\n /**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n }\n\n /**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n }\n\n /**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\n function listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n }\n\n // Add methods to `ListCache`.\n ListCache.prototype.clear = listCacheClear;\n ListCache.prototype['delete'] = listCacheDelete;\n ListCache.prototype.get = listCacheGet;\n ListCache.prototype.has = listCacheHas;\n ListCache.prototype.set = listCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\n function mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n }\n\n /**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function mapCacheGet(key) {\n return getMapData(this, key).get(key);\n }\n\n /**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function mapCacheHas(key) {\n return getMapData(this, key).has(key);\n }\n\n /**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\n function mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n }\n\n // Add methods to `MapCache`.\n MapCache.prototype.clear = mapCacheClear;\n MapCache.prototype['delete'] = mapCacheDelete;\n MapCache.prototype.get = mapCacheGet;\n MapCache.prototype.has = mapCacheHas;\n MapCache.prototype.set = mapCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\n function SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n }\n\n /**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\n function setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n }\n\n /**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\n function setCacheHas(value) {\n return this.__data__.has(value);\n }\n\n // Add methods to `SetCache`.\n SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\n SetCache.prototype.has = setCacheHas;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n }\n\n /**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\n function stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n }\n\n /**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function stackGet(key) {\n return this.__data__.get(key);\n }\n\n /**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function stackHas(key) {\n return this.__data__.has(key);\n }\n\n /**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\n function stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n }\n\n // Add methods to `Stack`.\n Stack.prototype.clear = stackClear;\n Stack.prototype['delete'] = stackDelete;\n Stack.prototype.get = stackGet;\n Stack.prototype.has = stackHas;\n Stack.prototype.set = stackSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\n function arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.sample` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @returns {*} Returns the random element.\n */\n function arraySample(array) {\n var length = array.length;\n return length ? array[baseRandom(0, length - 1)] : undefined;\n }\n\n /**\n * A specialized version of `_.sampleSize` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function arraySampleSize(array, n) {\n return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));\n }\n\n /**\n * A specialized version of `_.shuffle` for arrays.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function arrayShuffle(array) {\n return shuffleSelf(copyArray(array));\n }\n\n /**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n }\n\n /**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseAggregator(collection, setter, iteratee, accumulator) {\n baseEach(collection, function(value, key, collection) {\n setter(accumulator, value, iteratee(value), collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n }\n\n /**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n }\n\n /**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n }\n\n /**\n * The base implementation of `_.at` without support for individual paths.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {string[]} paths The property paths to pick.\n * @returns {Array} Returns the picked elements.\n */\n function baseAt(object, paths) {\n var index = -1,\n length = paths.length,\n result = Array(length),\n skip = object == null;\n\n while (++index < length) {\n result[index] = skip ? undefined : get(object, paths[index]);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.clamp` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n */\n function baseClamp(number, lower, upper) {\n if (number === number) {\n if (upper !== undefined) {\n number = number <= upper ? number : upper;\n }\n if (lower !== undefined) {\n number = number >= lower ? number : lower;\n }\n }\n return number;\n }\n\n /**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\n function baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n }\n\n /**\n * The base implementation of `_.conforms` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property predicates to conform to.\n * @returns {Function} Returns the new spec function.\n */\n function baseConforms(source) {\n var props = keys(source);\n return function(object) {\n return baseConformsTo(object, source, props);\n };\n }\n\n /**\n * The base implementation of `_.conformsTo` which accepts `props` to check.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n */\n function baseConformsTo(object, source, props) {\n var length = props.length;\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (length--) {\n var key = props[length],\n predicate = source[key],\n value = object[key];\n\n if ((value === undefined && !(key in object)) || !predicate(value)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.delay` and `_.defer` which accepts `args`\n * to provide to `func`.\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {Array} args The arguments to provide to `func`.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n function baseDelay(func, wait, args) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return setTimeout(function() { func.apply(undefined, args); }, wait);\n }\n\n /**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\n function baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEach = createBaseEach(baseForOwn);\n\n /**\n * The base implementation of `_.forEachRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEachRight = createBaseEach(baseForOwnRight, true);\n\n /**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\n function baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n }\n\n /**\n * The base implementation of methods like `_.max` and `_.min` which accepts a\n * `comparator` to determine the extremum value.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The iteratee invoked per iteration.\n * @param {Function} comparator The comparator used to compare values.\n * @returns {*} Returns the extremum value.\n */\n function baseExtremum(array, iteratee, comparator) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n var value = array[index],\n current = iteratee(value);\n\n if (current != null && (computed === undefined\n ? (current === current && !isSymbol(current))\n : comparator(current, computed)\n )) {\n var computed = current,\n result = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.fill` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function baseFill(array, value, start, end) {\n var length = array.length;\n\n start = toInteger(start);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (end === undefined || end > length) ? length : toInteger(end);\n if (end < 0) {\n end += length;\n }\n end = start > end ? 0 : toLength(end);\n while (start < end) {\n array[start++] = value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.filter` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function(value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\n function baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseFor = createBaseFor();\n\n /**\n * This function is like `baseFor` except that it iterates over properties\n * in the opposite order.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseForRight = createBaseFor(true);\n\n /**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.forOwnRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwnRight(object, iteratee) {\n return object && baseForRight(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.functions` which creates an array of\n * `object` function property names filtered from `props`.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The property names to filter.\n * @returns {Array} Returns the function names.\n */\n function baseFunctions(object, props) {\n return arrayFilter(props, function(key) {\n return isFunction(object[key]);\n });\n }\n\n /**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\n function baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n }\n\n /**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n }\n\n /**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n function baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n }\n\n /**\n * The base implementation of `_.gt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n */\n function baseGt(value, other) {\n return value > other;\n }\n\n /**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n }\n\n /**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHasIn(object, key) {\n return object != null && key in Object(object);\n }\n\n /**\n * The base implementation of `_.inRange` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to check.\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n */\n function baseInRange(number, start, end) {\n return number >= nativeMin(start, end) && number < nativeMax(start, end);\n }\n\n /**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of shared values.\n */\n function baseIntersection(arrays, iteratee, comparator) {\n var includes = comparator ? arrayIncludesWith : arrayIncludes,\n length = arrays[0].length,\n othLength = arrays.length,\n othIndex = othLength,\n caches = Array(othLength),\n maxLength = Infinity,\n result = [];\n\n while (othIndex--) {\n var array = arrays[othIndex];\n if (othIndex && iteratee) {\n array = arrayMap(array, baseUnary(iteratee));\n }\n maxLength = nativeMin(array.length, maxLength);\n caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n ? new SetCache(othIndex && array)\n : undefined;\n }\n array = arrays[0];\n\n var index = -1,\n seen = caches[0];\n\n outer:\n while (++index < length && result.length < maxLength) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (!(seen\n ? cacheHas(seen, computed)\n : includes(result, computed, comparator)\n )) {\n othIndex = othLength;\n while (--othIndex) {\n var cache = caches[othIndex];\n if (!(cache\n ? cacheHas(cache, computed)\n : includes(arrays[othIndex], computed, comparator))\n ) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.invert` and `_.invertBy` which inverts\n * `object` with values transformed by `iteratee` and set by `setter`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform values.\n * @param {Object} accumulator The initial inverted object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseInverter(object, setter, iteratee, accumulator) {\n baseForOwn(object, function(value, key, object) {\n setter(accumulator, iteratee(value), key, object);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.invoke` without support for individual\n * method arguments.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {Array} args The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n */\n function baseInvoke(object, path, args) {\n path = castPath(path, object);\n object = parent(object, path);\n var func = object == null ? object : object[toKey(last(path))];\n return func == null ? undefined : apply(func, object, args);\n }\n\n /**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\n function baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n }\n\n /**\n * The base implementation of `_.isArrayBuffer` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n */\n function baseIsArrayBuffer(value) {\n return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;\n }\n\n /**\n * The base implementation of `_.isDate` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n */\n function baseIsDate(value) {\n return isObjectLike(value) && baseGetTag(value) == dateTag;\n }\n\n /**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\n function baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n }\n\n /**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n }\n\n /**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\n function baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n }\n\n /**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\n function baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\n function baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n }\n\n /**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\n function baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n }\n\n /**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\n function baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n }\n\n /**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\n function baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n }\n\n /**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\n function baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n }\n\n /**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.lt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n */\n function baseLt(value, other) {\n return value < other;\n }\n\n /**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n }\n\n /**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n }\n\n /**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n }\n\n /**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n }\n\n /**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n }\n\n /**\n * The base implementation of `_.nth` which doesn't coerce arguments.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {number} n The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n */\n function baseNth(array, n) {\n var length = array.length;\n if (!length) {\n return;\n }\n n += n < 0 ? length : 0;\n return isIndex(n, length) ? array[n] : undefined;\n }\n\n /**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\n function baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n }\n\n /**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\n function basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n }\n\n /**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\n function basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n }\n\n /**\n * The base implementation of `_.pullAllBy` without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n */\n function basePullAll(array, values, iteratee, comparator) {\n var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n index = -1,\n length = values.length,\n seen = array;\n\n if (array === values) {\n values = copyArray(values);\n }\n if (iteratee) {\n seen = arrayMap(array, baseUnary(iteratee));\n }\n while (++index < length) {\n var fromIndex = 0,\n value = values[index],\n computed = iteratee ? iteratee(value) : value;\n\n while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n if (seen !== array) {\n splice.call(seen, fromIndex, 1);\n }\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.pullAt` without support for individual\n * indexes or capturing the removed elements.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {number[]} indexes The indexes of elements to remove.\n * @returns {Array} Returns `array`.\n */\n function basePullAt(array, indexes) {\n var length = array ? indexes.length : 0,\n lastIndex = length - 1;\n\n while (length--) {\n var index = indexes[length];\n if (length == lastIndex || index !== previous) {\n var previous = index;\n if (isIndex(index)) {\n splice.call(array, index, 1);\n } else {\n baseUnset(array, index);\n }\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.random` without support for returning\n * floating-point numbers.\n *\n * @private\n * @param {number} lower The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the random number.\n */\n function baseRandom(lower, upper) {\n return lower + nativeFloor(nativeRandom() * (upper - lower + 1));\n }\n\n /**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\n function baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n }\n\n /**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\n function baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n }\n\n /**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\n function baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n }\n\n /**\n * The base implementation of `_.sample`.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n */\n function baseSample(collection) {\n return arraySample(values(collection));\n }\n\n /**\n * The base implementation of `_.sampleSize` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function baseSampleSize(collection, n) {\n var array = values(collection);\n return shuffleSelf(array, baseClamp(n, 0, array.length));\n }\n\n /**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n }\n\n /**\n * The base implementation of `setData` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var baseSetData = !metaMap ? identity : function(func, data) {\n metaMap.set(func, data);\n return func;\n };\n\n /**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n };\n\n /**\n * The base implementation of `_.shuffle`.\n *\n * @private\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function baseShuffle(collection) {\n return shuffleSelf(values(collection));\n }\n\n /**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n }\n\n /**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function(value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which\n * performs a binary search of `array` to determine the index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, retHighest) {\n var low = 0,\n high = array == null ? low : array.length;\n\n if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = array[mid];\n\n if (computed !== null && !isSymbol(computed) &&\n (retHighest ? (computed <= value) : (computed < value))) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n return baseSortedIndexBy(array, value, identity, retHighest);\n }\n\n /**\n * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`\n * which invokes `iteratee` for `value` and each element of `array` to compute\n * their sort ranking. The iteratee is invoked with one argument; (value).\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iteratee The iteratee invoked per element.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndexBy(array, value, iteratee, retHighest) {\n var low = 0,\n high = array == null ? 0 : array.length;\n if (high === 0) {\n return 0;\n }\n\n value = iteratee(value);\n var valIsNaN = value !== value,\n valIsNull = value === null,\n valIsSymbol = isSymbol(value),\n valIsUndefined = value === undefined;\n\n while (low < high) {\n var mid = nativeFloor((low + high) / 2),\n computed = iteratee(array[mid]),\n othIsDefined = computed !== undefined,\n othIsNull = computed === null,\n othIsReflexive = computed === computed,\n othIsSymbol = isSymbol(computed);\n\n if (valIsNaN) {\n var setLow = retHighest || othIsReflexive;\n } else if (valIsUndefined) {\n setLow = othIsReflexive && (retHighest || othIsDefined);\n } else if (valIsNull) {\n setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);\n } else if (valIsSymbol) {\n setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);\n } else if (othIsNull || othIsSymbol) {\n setLow = false;\n } else {\n setLow = retHighest ? (computed <= value) : (computed < value);\n }\n if (setLow) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return nativeMin(high, MAX_ARRAY_INDEX);\n }\n\n /**\n * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseSortedUniq(array, iteratee) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n if (!index || !eq(computed, seen)) {\n var seen = computed;\n result[resIndex++] = value === 0 ? 0 : value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toNumber` which doesn't ensure correct\n * conversions of binary, hexadecimal, or octal string values.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n */\n function baseToNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n return +value;\n }\n\n /**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\n function baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\n function baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n }\n\n /**\n * The base implementation of `_.update`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to update.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseUpdate(object, path, updater, customizer) {\n return baseSet(object, path, updater(baseGet(object, path)), customizer);\n }\n\n /**\n * The base implementation of methods like `_.dropWhile` and `_.takeWhile`\n * without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {Function} predicate The function invoked per iteration.\n * @param {boolean} [isDrop] Specify dropping elements instead of taking them.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseWhile(array, predicate, isDrop, fromRight) {\n var length = array.length,\n index = fromRight ? length : -1;\n\n while ((fromRight ? index-- : ++index < length) &&\n predicate(array[index], index, array)) {}\n\n return isDrop\n ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))\n : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));\n }\n\n /**\n * The base implementation of `wrapperValue` which returns the result of\n * performing a sequence of actions on the unwrapped `value`, where each\n * successive action is supplied the return value of the previous.\n *\n * @private\n * @param {*} value The unwrapped value.\n * @param {Array} actions Actions to perform to resolve the unwrapped value.\n * @returns {*} Returns the resolved value.\n */\n function baseWrapperValue(value, actions) {\n var result = value;\n if (result instanceof LazyWrapper) {\n result = result.value();\n }\n return arrayReduce(actions, function(result, action) {\n return action.func.apply(action.thisArg, arrayPush([result], action.args));\n }, result);\n }\n\n /**\n * The base implementation of methods like `_.xor`, without support for\n * iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of values.\n */\n function baseXor(arrays, iteratee, comparator) {\n var length = arrays.length;\n if (length < 2) {\n return length ? baseUniq(arrays[0]) : [];\n }\n var index = -1,\n result = Array(length);\n\n while (++index < length) {\n var array = arrays[index],\n othIndex = -1;\n\n while (++othIndex < length) {\n if (othIndex != index) {\n result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);\n }\n }\n }\n return baseUniq(baseFlatten(result, 1), iteratee, comparator);\n }\n\n /**\n * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n *\n * @private\n * @param {Array} props The property identifiers.\n * @param {Array} values The property values.\n * @param {Function} assignFunc The function to assign values.\n * @returns {Object} Returns the new object.\n */\n function baseZipObject(props, values, assignFunc) {\n var index = -1,\n length = props.length,\n valsLength = values.length,\n result = {};\n\n while (++index < length) {\n var value = index < valsLength ? values[index] : undefined;\n assignFunc(result, props[index], value);\n }\n return result;\n }\n\n /**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\n function castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n }\n\n /**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\n function castFunction(value) {\n return typeof value == 'function' ? value : identity;\n }\n\n /**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\n function castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n }\n\n /**\n * A `baseRest` alias which can be replaced with `identity` by module\n * replacement plugins.\n *\n * @private\n * @type {Function}\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n var castRest = baseRest;\n\n /**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\n function castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n }\n\n /**\n * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).\n *\n * @private\n * @param {number|Object} id The timer id or timeout object of the timer to clear.\n */\n var clearTimeout = ctxClearTimeout || function(id) {\n return root.clearTimeout(id);\n };\n\n /**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\n function cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n }\n\n /**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\n function cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n }\n\n /**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\n function cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n }\n\n /**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\n function cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n }\n\n /**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\n function cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n }\n\n /**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\n function cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n }\n\n /**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\n function compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n }\n\n /**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\n function compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n }\n\n /**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgs(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersLength = holders.length,\n leftIndex = -1,\n leftLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(leftLength + rangeLength),\n isUncurried = !isCurried;\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n }\n while (rangeLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgsRight(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersIndex = -1,\n holdersLength = holders.length,\n rightIndex = -1,\n rightLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(rangeLength + rightLength),\n isUncurried = !isCurried;\n\n while (++argsIndex < rangeLength) {\n result[argsIndex] = args[argsIndex];\n }\n var offset = argsIndex;\n while (++rightIndex < rightLength) {\n result[offset + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[offset + holders[holdersIndex]] = args[argsIndex++];\n }\n }\n return result;\n }\n\n /**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\n function copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n }\n\n /**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\n function copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n }\n\n /**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n }\n\n /**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n }\n\n /**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\n function createAggregator(setter, initializer) {\n return function(collection, iteratee) {\n var func = isArray(collection) ? arrayAggregator : baseAggregator,\n accumulator = initializer ? initializer() : {};\n\n return func(collection, setter, getIteratee(iteratee, 2), accumulator);\n };\n }\n\n /**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\n function createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n }\n\n /**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n }\n\n /**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createBind(func, bitmask, thisArg) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return fn.apply(isBind ? thisArg : this, arguments);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\n function createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n }\n\n /**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\n function createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n }\n\n /**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCtor(Ctor) {\n return function() {\n // Use a `switch` statement to work with class constructors. See\n // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n // for more details.\n var args = arguments;\n switch (args.length) {\n case 0: return new Ctor;\n case 1: return new Ctor(args[0]);\n case 2: return new Ctor(args[0], args[1]);\n case 3: return new Ctor(args[0], args[1], args[2]);\n case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n }\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, args);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n }\n\n /**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCurry(func, bitmask, arity) {\n var Ctor = createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length,\n placeholder = getHolder(wrapper);\n\n while (index--) {\n args[index] = arguments[index];\n }\n var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n ? []\n : replaceHolders(args, placeholder);\n\n length -= holders.length;\n if (length < arity) {\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, undefined,\n args, holders, undefined, undefined, arity - length);\n }\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return apply(fn, this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\n function createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = getIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n }\n\n /**\n * Creates a `_.flow` or `_.flowRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new flow function.\n */\n function createFlow(fromRight) {\n return flatRest(function(funcs) {\n var length = funcs.length,\n index = length,\n prereq = LodashWrapper.prototype.thru;\n\n if (fromRight) {\n funcs.reverse();\n }\n while (index--) {\n var func = funcs[index];\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n var wrapper = new LodashWrapper([], true);\n }\n }\n index = wrapper ? index : length;\n while (++index < length) {\n func = funcs[index];\n\n var funcName = getFuncName(func),\n data = funcName == 'wrapper' ? getData(func) : undefined;\n\n if (data && isLaziable(data[0]) &&\n data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n !data[4].length && data[9] == 1\n ) {\n wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n } else {\n wrapper = (func.length == 1 && isLaziable(func))\n ? wrapper[funcName]()\n : wrapper.thru(func);\n }\n }\n return function() {\n var args = arguments,\n value = args[0];\n\n if (wrapper && args.length == 1 && isArray(value)) {\n return wrapper.plant(value).value();\n }\n var index = 0,\n result = length ? funcs[index].apply(this, args) : value;\n\n while (++index < length) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n });\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n * to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & WRAP_ARY_FLAG,\n isBind = bitmask & WRAP_BIND_FLAG,\n isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n isFlip = bitmask & WRAP_FLIP_FLAG,\n Ctor = isBindKey ? undefined : createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length;\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (isCurried) {\n var placeholder = getHolder(wrapper),\n holdersCount = countHolders(args, placeholder);\n }\n if (partials) {\n args = composeArgs(args, partials, holders, isCurried);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n }\n length -= holdersCount;\n if (isCurried && length < arity) {\n var newHolders = replaceHolders(args, placeholder);\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n args, newHolders, argPos, ary, arity - length\n );\n }\n var thisBinding = isBind ? thisArg : this,\n fn = isBindKey ? thisBinding[func] : func;\n\n length = args.length;\n if (argPos) {\n args = reorder(args, argPos);\n } else if (isFlip && length > 1) {\n args.reverse();\n }\n if (isAry && ary < length) {\n args.length = ary;\n }\n if (this && this !== root && this instanceof wrapper) {\n fn = Ctor || createCtor(fn);\n }\n return fn.apply(thisBinding, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.invertBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} toIteratee The function to resolve iteratees.\n * @returns {Function} Returns the new inverter function.\n */\n function createInverter(setter, toIteratee) {\n return function(object, iteratee) {\n return baseInverter(object, setter, toIteratee(iteratee), {});\n };\n }\n\n /**\n * Creates a function that performs a mathematical operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @param {number} [defaultValue] The value used for `undefined` arguments.\n * @returns {Function} Returns the new mathematical operation function.\n */\n function createMathOperation(operator, defaultValue) {\n return function(value, other) {\n var result;\n if (value === undefined && other === undefined) {\n return defaultValue;\n }\n if (value !== undefined) {\n result = value;\n }\n if (other !== undefined) {\n if (result === undefined) {\n return other;\n }\n if (typeof value == 'string' || typeof other == 'string') {\n value = baseToString(value);\n other = baseToString(other);\n } else {\n value = baseToNumber(value);\n other = baseToNumber(other);\n }\n result = operator(value, other);\n }\n return result;\n };\n }\n\n /**\n * Creates a function like `_.over`.\n *\n * @private\n * @param {Function} arrayFunc The function to iterate over iteratees.\n * @returns {Function} Returns the new over function.\n */\n function createOver(arrayFunc) {\n return flatRest(function(iteratees) {\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n return baseRest(function(args) {\n var thisArg = this;\n return arrayFunc(iteratees, function(iteratee) {\n return apply(iteratee, thisArg, args);\n });\n });\n });\n }\n\n /**\n * Creates the padding for `string` based on `length`. The `chars` string\n * is truncated if the number of characters exceeds `length`.\n *\n * @private\n * @param {number} length The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padding for `string`.\n */\n function createPadding(length, chars) {\n chars = chars === undefined ? ' ' : baseToString(chars);\n\n var charsLength = chars.length;\n if (charsLength < 2) {\n return charsLength ? baseRepeat(chars, length) : chars;\n }\n var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n return hasUnicode(chars)\n ? castSlice(stringToArray(result), 0, length).join('')\n : result.slice(0, length);\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n * the new function.\n * @returns {Function} Returns the new wrapped function.\n */\n function createPartial(func, bitmask, thisArg, partials) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(leftLength + argsLength),\n fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return apply(fn, isBind ? thisArg : this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\n function createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n }\n\n /**\n * Creates a function that performs a relational operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @returns {Function} Returns the new relational operation function.\n */\n function createRelationalOperation(operator) {\n return function(value, other) {\n if (!(typeof value == 'string' && typeof other == 'string')) {\n value = toNumber(value);\n other = toNumber(other);\n }\n return operator(value, other);\n };\n }\n\n /**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n var isCurry = bitmask & WRAP_CURRY_FLAG,\n newHolders = isCurry ? holders : undefined,\n newHoldersRight = isCurry ? undefined : holders,\n newPartials = isCurry ? partials : undefined,\n newPartialsRight = isCurry ? undefined : partials;\n\n bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n }\n var newData = [\n func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n newHoldersRight, argPos, ary, arity\n ];\n\n var result = wrapFunc.apply(undefined, newData);\n if (isLaziable(func)) {\n setData(result, newData);\n }\n result.placeholder = placeholder;\n return setWrapToString(result, func, bitmask);\n }\n\n /**\n * Creates a function like `_.round`.\n *\n * @private\n * @param {string} methodName The name of the `Math` method to use when rounding.\n * @returns {Function} Returns the new round function.\n */\n function createRound(methodName) {\n var func = Math[methodName];\n return function(number, precision) {\n number = toNumber(number);\n precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n if (precision && nativeIsFinite(number)) {\n // Shift with exponential notation to avoid floating-point issues.\n // See [MDN](https://mdn.io/round#Examples) for more details.\n var pair = (toString(number) + 'e').split('e'),\n value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n pair = (toString(value) + 'e').split('e');\n return +(pair[0] + 'e' + (+pair[1] - precision));\n }\n return func(number);\n };\n }\n\n /**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\n var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n };\n\n /**\n * Creates a `_.toPairs` or `_.toPairsIn` function.\n *\n * @private\n * @param {Function} keysFunc The function to get the keys of a given object.\n * @returns {Function} Returns the new pairs function.\n */\n function createToPairs(keysFunc) {\n return function(object) {\n var tag = getTag(object);\n if (tag == mapTag) {\n return mapToArray(object);\n }\n if (tag == setTag) {\n return setToPairs(object);\n }\n return baseToPairs(object, keysFunc(object));\n };\n }\n\n /**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * 512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n partials = holders = undefined;\n }\n ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n arity = arity === undefined ? arity : toInteger(arity);\n length -= holders ? holders.length : 0;\n\n if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = undefined;\n }\n var data = isBindKey ? undefined : getData(func);\n\n var newData = [\n func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n argPos, ary, arity\n ];\n\n if (data) {\n mergeData(newData, data);\n }\n func = newData[0];\n bitmask = newData[1];\n thisArg = newData[2];\n partials = newData[3];\n holders = newData[4];\n arity = newData[9] = newData[9] === undefined\n ? (isBindKey ? 0 : func.length)\n : nativeMax(newData[9] - length, 0);\n\n if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n }\n if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n var result = createBind(func, bitmask, thisArg);\n } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n result = createCurry(func, bitmask, arity);\n } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n result = createPartial(func, bitmask, thisArg, partials);\n } else {\n result = createHybrid.apply(undefined, newData);\n }\n var setter = data ? baseSetData : setData;\n return setWrapToString(setter(result, newData), func, bitmask);\n }\n\n /**\n * Used by `_.defaults` to customize its `_.assignIn` use to assign properties\n * of source objects to the destination object for all destination properties\n * that resolve to `undefined`.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to assign.\n * @param {Object} object The parent object of `objValue`.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsAssignIn(objValue, srcValue, key, object) {\n if (objValue === undefined ||\n (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n return srcValue;\n }\n return objValue;\n }\n\n /**\n * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n * objects into destination objects that are passed thru.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to merge.\n * @param {Object} object The parent object of `objValue`.\n * @param {Object} source The parent object of `srcValue`.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n if (isObject(objValue) && isObject(srcValue)) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, objValue);\n baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n stack['delete'](srcValue);\n }\n return objValue;\n }\n\n /**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\n function customOmitClone(value) {\n return isPlainObject(value) ? undefined : value;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\n function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n function flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n }\n\n /**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n }\n\n /**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n }\n\n /**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\n var getData = !metaMap ? noop : function(func) {\n return metaMap.get(func);\n };\n\n /**\n * Gets the name of `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {string} Returns the function name.\n */\n function getFuncName(func) {\n var result = (func.name + ''),\n array = realNames[result],\n length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n while (length--) {\n var data = array[length],\n otherFunc = data.func;\n if (otherFunc == null || otherFunc == func) {\n return data.name;\n }\n }\n return result;\n }\n\n /**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\n function getHolder(func) {\n var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;\n return object.placeholder;\n }\n\n /**\n * Gets the appropriate \"iteratee\" function. If `_.iteratee` is customized,\n * this function returns the custom method, otherwise it returns `baseIteratee`.\n * If arguments are provided, the chosen function is invoked with them and\n * its result is returned.\n *\n * @private\n * @param {*} [value] The value to convert to an iteratee.\n * @param {number} [arity] The arity of the created iteratee.\n * @returns {Function} Returns the chosen function or its result.\n */\n function getIteratee() {\n var result = lodash.iteratee || iteratee;\n result = result === iteratee ? baseIteratee : result;\n return arguments.length ? result(arguments[0], arguments[1]) : result;\n }\n\n /**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\n function getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n }\n\n /**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\n function getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n }\n\n /**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\n function getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n }\n\n /**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\n function getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n }\n\n /**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n };\n\n /**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n };\n\n /**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n var getTag = baseGetTag;\n\n // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\n if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n }\n\n /**\n * Gets the view, applying any `transforms` to the `start` and `end` positions.\n *\n * @private\n * @param {number} start The start of the view.\n * @param {number} end The end of the view.\n * @param {Array} transforms The transformations to apply to the view.\n * @returns {Object} Returns an object containing the `start` and `end`\n * positions of the view.\n */\n function getView(start, end, transforms) {\n var index = -1,\n length = transforms.length;\n\n while (++index < length) {\n var data = transforms[index],\n size = data.size;\n\n switch (data.type) {\n case 'drop': start += size; break;\n case 'dropRight': end -= size; break;\n case 'take': end = nativeMin(end, start + size); break;\n case 'takeRight': start = nativeMax(start, end - size); break;\n }\n }\n return { 'start': start, 'end': end };\n }\n\n /**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\n function getWrapDetails(source) {\n var match = source.match(reWrapDetails);\n return match ? match[1].split(reSplitDetails) : [];\n }\n\n /**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\n function hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n }\n\n /**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\n function initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n }\n\n /**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n }\n\n /**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n }\n\n /**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\n function insertWrapDetails(source, details) {\n var length = details.length;\n if (!length) {\n return source;\n }\n var lastIndex = length - 1;\n details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n details = details.join(length > 2 ? ', ' : ' ');\n return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n }\n\n /**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\n function isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n }\n\n /**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\n function isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n }\n\n /**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\n function isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n }\n\n /**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\n function isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n }\n\n /**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\n function isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n }\n\n /**\n * Checks if `func` has a lazy counterpart.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n * else `false`.\n */\n function isLaziable(func) {\n var funcName = getFuncName(func),\n other = lodash[funcName];\n\n if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n return false;\n }\n if (func === other) {\n return true;\n }\n var data = getData(other);\n return !!data && func === data[0];\n }\n\n /**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\n function isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n }\n\n /**\n * Checks if `func` is capable of being masked.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `func` is maskable, else `false`.\n */\n var isMaskable = coreJsData ? isFunction : stubFalse;\n\n /**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\n function isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n }\n\n /**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\n function isStrictComparable(value) {\n return value === value && !isObject(value);\n }\n\n /**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n }\n\n /**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\n function memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n }\n\n /**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers used to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and\n * `_.rearg` modify function arguments, making the order in which they are\n * executed important, preventing the merging of metadata. However, we make\n * an exception for a safe combined case where curried functions have `_.ary`\n * and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\n function mergeData(data, source) {\n var bitmask = data[1],\n srcBitmask = source[1],\n newBitmask = bitmask | srcBitmask,\n isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n var isCombo =\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n // Exit early if metadata can't be merged.\n if (!(isCommon || isCombo)) {\n return data;\n }\n // Use source `thisArg` if available.\n if (srcBitmask & WRAP_BIND_FLAG) {\n data[2] = source[2];\n // Set when currying a bound function.\n newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n }\n // Compose partial arguments.\n var value = source[3];\n if (value) {\n var partials = data[3];\n data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n }\n // Compose partial right arguments.\n value = source[5];\n if (value) {\n partials = data[5];\n data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n }\n // Use source `argPos` if available.\n value = source[7];\n if (value) {\n data[7] = value;\n }\n // Use source `ary` if it's smaller.\n if (srcBitmask & WRAP_ARY_FLAG) {\n data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n }\n // Use source `arity` if one is not provided.\n if (data[9] == null) {\n data[9] = source[9];\n }\n // Use source `func` and merge bitmasks.\n data[0] = source[0];\n data[1] = newBitmask;\n\n return data;\n }\n\n /**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\n function objectToString(value) {\n return nativeObjectToString.call(value);\n }\n\n /**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\n function overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n }\n\n /**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\n function parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n }\n\n /**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\n function reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = copyArray(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n }\n\n /**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n }\n\n /**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity\n * function to avoid garbage collection pauses in V8. See\n * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var setData = shortOut(baseSetData);\n\n /**\n * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n var setTimeout = ctxSetTimeout || function(func, wait) {\n return root.setTimeout(func, wait);\n };\n\n /**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var setToString = shortOut(baseSetToString);\n\n /**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\n function setWrapToString(wrapper, reference, bitmask) {\n var source = (reference + '');\n return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n }\n\n /**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\n function shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n }\n\n /**\n * A specialized version of `_.shuffle` which mutates and sets the size of `array`.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @param {number} [size=array.length] The size of `array`.\n * @returns {Array} Returns `array`.\n */\n function shuffleSelf(array, size) {\n var index = -1,\n length = array.length,\n lastIndex = length - 1;\n\n size = size === undefined ? length : size;\n while (++index < size) {\n var rand = baseRandom(index, lastIndex),\n value = array[rand];\n\n array[rand] = array[index];\n array[index] = value;\n }\n array.length = size;\n return array;\n }\n\n /**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\n var stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n });\n\n /**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\n function toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\n function toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n }\n\n /**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\n function updateWrapDetails(details, bitmask) {\n arrayEach(wrapFlags, function(pair) {\n var value = '_.' + pair[0];\n if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n details.push(value);\n }\n });\n return details.sort();\n }\n\n /**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\n function wrapperClone(wrapper) {\n if (wrapper instanceof LazyWrapper) {\n return wrapper.clone();\n }\n var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n result.__actions__ = copyArray(wrapper.__actions__);\n result.__index__ = wrapper.__index__;\n result.__values__ = wrapper.__values__;\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements split into groups the length of `size`.\n * If `array` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the new array of chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\n function chunk(array, size, guard) {\n if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n size = 1;\n } else {\n size = nativeMax(toInteger(size), 0);\n }\n var length = array == null ? 0 : array.length;\n if (!length || size < 1) {\n return [];\n }\n var index = 0,\n resIndex = 0,\n result = Array(nativeCeil(length / size));\n\n while (index < length) {\n result[resIndex++] = baseSlice(array, index, (index += size));\n }\n return result;\n }\n\n /**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\n function compact(array) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * Creates a new array concatenating `array` with any additional arrays\n * and/or values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to concatenate.\n * @param {...*} [values] The values to concatenate.\n * @returns {Array} Returns the new concatenated array.\n * @example\n *\n * var array = [1];\n * var other = _.concat(array, 2, [3], [[4]]);\n *\n * console.log(other);\n * // => [1, 2, 3, [4]]\n *\n * console.log(array);\n * // => [1]\n */\n function concat() {\n var length = arguments.length;\n if (!length) {\n return [];\n }\n var args = Array(length - 1),\n array = arguments[0],\n index = length;\n\n while (index--) {\n args[index - 1] = arguments[index];\n }\n return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n }\n\n /**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\n var difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `iteratee` which\n * is invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * **Note:** Unlike `_.pullAllBy`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var differenceBy = baseRest(function(array, values) {\n var iteratee = last(values);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `comparator`\n * which is invoked to compare elements of `array` to `values`. The order and\n * references of result values are determined by the first array. The comparator\n * is invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.pullAllWith`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n *\n * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }]\n */\n var differenceWith = baseRest(function(array, values) {\n var comparator = last(values);\n if (isArrayLikeObject(comparator)) {\n comparator = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)\n : [];\n });\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function drop(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function dropRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the end.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.dropRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropRightWhile(users, ['active', false]);\n * // => objects for ['barney']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropRightWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the beginning.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.dropWhile(users, function(o) { return !o.active; });\n * // => objects for ['pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropWhile(users, ['active', false]);\n * // => objects for ['pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true)\n : [];\n }\n\n /**\n * Fills elements of `array` with `value` from `start` up to, but not\n * including, `end`.\n *\n * **Note:** This method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Array\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.fill(array, 'a');\n * console.log(array);\n * // => ['a', 'a', 'a']\n *\n * _.fill(Array(3), 2);\n * // => [2, 2, 2]\n *\n * _.fill([4, 6, 8, 10], '*', 1, 3);\n * // => [4, '*', '*', 10]\n */\n function fill(array, value, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n start = 0;\n end = length;\n }\n return baseFill(array, value, start, end);\n }\n\n /**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\n function findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index);\n }\n\n /**\n * This method is like `_.findIndex` except that it iterates over elements\n * of `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });\n * // => 2\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n * // => 0\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastIndex(users, ['active', false]);\n * // => 2\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastIndex(users, 'active');\n * // => 0\n */\n function findLastIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length - 1;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = fromIndex < 0\n ? nativeMax(length + index, 0)\n : nativeMin(index, length - 1);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index, true);\n }\n\n /**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\n function flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n }\n\n /**\n * Recursively flattens `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, [3, [4]], 5]]);\n * // => [1, 2, 3, 4, 5]\n */\n function flattenDeep(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, INFINITY) : [];\n }\n\n /**\n * Recursively flatten `array` up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * var array = [1, [2, [3, [4]], 5]];\n *\n * _.flattenDepth(array, 1);\n * // => [1, 2, [3, [4]], 5]\n *\n * _.flattenDepth(array, 2);\n * // => [1, 2, 3, [4], 5]\n */\n function flattenDepth(array, depth) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(array, depth);\n }\n\n /**\n * The inverse of `_.toPairs`; this method returns an object composed\n * from key-value `pairs`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} pairs The key-value pairs.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.fromPairs([['a', 1], ['b', 2]]);\n * // => { 'a': 1, 'b': 2 }\n */\n function fromPairs(pairs) {\n var index = -1,\n length = pairs == null ? 0 : pairs.length,\n result = {};\n\n while (++index < length) {\n var pair = pairs[index];\n result[pair[0]] = pair[1];\n }\n return result;\n }\n\n /**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias first\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.head([1, 2, 3]);\n * // => 1\n *\n * _.head([]);\n * // => undefined\n */\n function head(array) {\n return (array && array.length) ? array[0] : undefined;\n }\n\n /**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. If `fromIndex` is negative, it's used as the\n * offset from the end of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // Search from the `fromIndex`.\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n */\n function indexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseIndexOf(array, value, index);\n }\n\n /**\n * Gets all but the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.initial([1, 2, 3]);\n * // => [1, 2]\n */\n function initial(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 0, -1) : [];\n }\n\n /**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\n var intersection = baseRest(function(arrays) {\n var mapped = arrayMap(arrays, castArrayLikeObject);\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped)\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `iteratee`\n * which is invoked for each element of each `arrays` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [2.1]\n *\n * // The `_.property` iteratee shorthand.\n * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }]\n */\n var intersectionBy = baseRest(function(arrays) {\n var iteratee = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n if (iteratee === last(mapped)) {\n iteratee = undefined;\n } else {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\n var intersectionWith = baseRest(function(arrays) {\n var comparator = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n comparator = typeof comparator == 'function' ? comparator : undefined;\n if (comparator) {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, undefined, comparator)\n : [];\n });\n\n /**\n * Converts all elements in `array` into a string separated by `separator`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to convert.\n * @param {string} [separator=','] The element separator.\n * @returns {string} Returns the joined string.\n * @example\n *\n * _.join(['a', 'b', 'c'], '~');\n * // => 'a~b~c'\n */\n function join(array, separator) {\n return array == null ? '' : nativeJoin.call(array, separator);\n }\n\n /**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\n function last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n }\n\n /**\n * This method is like `_.indexOf` except that it iterates over elements of\n * `array` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.lastIndexOf([1, 2, 1, 2], 2);\n * // => 3\n *\n * // Search from the `fromIndex`.\n * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n * // => 1\n */\n function lastIndexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);\n }\n return value === value\n ? strictLastIndexOf(array, value, index)\n : baseFindIndex(array, baseIsNaN, index, true);\n }\n\n /**\n * Gets the element at index `n` of `array`. If `n` is negative, the nth\n * element from the end is returned.\n *\n * @static\n * @memberOf _\n * @since 4.11.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=0] The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n *\n * _.nth(array, 1);\n * // => 'b'\n *\n * _.nth(array, -2);\n * // => 'c';\n */\n function nth(array, n) {\n return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;\n }\n\n /**\n * Removes all given values from `array` using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`\n * to remove elements from an array by predicate.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...*} [values] The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pull(array, 'a', 'c');\n * console.log(array);\n * // => ['b', 'b']\n */\n var pull = baseRest(pullAll);\n\n /**\n * This method is like `_.pull` except that it accepts an array of values to remove.\n *\n * **Note:** Unlike `_.difference`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pullAll(array, ['a', 'c']);\n * console.log(array);\n * // => ['b', 'b']\n */\n function pullAll(array, values) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values)\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `iteratee` which is\n * invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The iteratee is invoked with one argument: (value).\n *\n * **Note:** Unlike `_.differenceBy`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];\n *\n * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');\n * console.log(array);\n * // => [{ 'x': 2 }]\n */\n function pullAllBy(array, values, iteratee) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, getIteratee(iteratee, 2))\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `comparator` which\n * is invoked to compare elements of `array` to `values`. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.differenceWith`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];\n *\n * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);\n * console.log(array);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]\n */\n function pullAllWith(array, values, comparator) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, undefined, comparator)\n : array;\n }\n\n /**\n * Removes elements from `array` corresponding to `indexes` and returns an\n * array of removed elements.\n *\n * **Note:** Unlike `_.at`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...(number|number[])} [indexes] The indexes of elements to remove.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n * var pulled = _.pullAt(array, [1, 3]);\n *\n * console.log(array);\n * // => ['a', 'c']\n *\n * console.log(pulled);\n * // => ['b', 'd']\n */\n var pullAt = flatRest(function(array, indexes) {\n var length = array == null ? 0 : array.length,\n result = baseAt(array, indexes);\n\n basePullAt(array, arrayMap(indexes, function(index) {\n return isIndex(index, length) ? +index : index;\n }).sort(compareAscending));\n\n return result;\n });\n\n /**\n * Removes all elements from `array` that `predicate` returns truthy for\n * and returns an array of the removed elements. The predicate is invoked\n * with three arguments: (value, index, array).\n *\n * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`\n * to pull elements from an array by value.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [1, 2, 3, 4];\n * var evens = _.remove(array, function(n) {\n * return n % 2 == 0;\n * });\n *\n * console.log(array);\n * // => [1, 3]\n *\n * console.log(evens);\n * // => [2, 4]\n */\n function remove(array, predicate) {\n var result = [];\n if (!(array && array.length)) {\n return result;\n }\n var index = -1,\n indexes = [],\n length = array.length;\n\n predicate = getIteratee(predicate, 3);\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result.push(value);\n indexes.push(index);\n }\n }\n basePullAt(array, indexes);\n return result;\n }\n\n /**\n * Reverses `array` so that the first element becomes the last, the second\n * element becomes the second to last, and so on.\n *\n * **Note:** This method mutates `array` and is based on\n * [`Array#reverse`](https://mdn.io/Array/reverse).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.reverse(array);\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function reverse(array) {\n return array == null ? array : nativeReverse.call(array);\n }\n\n /**\n * Creates a slice of `array` from `start` up to, but not including, `end`.\n *\n * **Note:** This method is used instead of\n * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are\n * returned.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function slice(array, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n start = 0;\n end = length;\n }\n else {\n start = start == null ? 0 : toInteger(start);\n end = end === undefined ? length : toInteger(end);\n }\n return baseSlice(array, start, end);\n }\n\n /**\n * Uses a binary search to determine the lowest index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedIndex([30, 50], 40);\n * // => 1\n */\n function sortedIndex(array, value) {\n return baseSortedIndex(array, value);\n }\n\n /**\n * This method is like `_.sortedIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedIndexBy(objects, { 'x': 4 }, 'x');\n * // => 0\n */\n function sortedIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));\n }\n\n /**\n * This method is like `_.indexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedIndexOf([4, 5, 5, 5, 6], 5);\n * // => 1\n */\n function sortedIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value);\n if (index < length && eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.sortedIndex` except that it returns the highest\n * index at which `value` should be inserted into `array` in order to\n * maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedLastIndex([4, 5, 5, 5, 6], 5);\n * // => 4\n */\n function sortedLastIndex(array, value) {\n return baseSortedIndex(array, value, true);\n }\n\n /**\n * This method is like `_.sortedLastIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 1\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');\n * // => 1\n */\n function sortedLastIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);\n }\n\n /**\n * This method is like `_.lastIndexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);\n * // => 3\n */\n function sortedLastIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value, true) - 1;\n if (eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.uniq` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniq([1, 1, 2]);\n * // => [1, 2]\n */\n function sortedUniq(array) {\n return (array && array.length)\n ? baseSortedUniq(array)\n : [];\n }\n\n /**\n * This method is like `_.uniqBy` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);\n * // => [1.1, 2.3]\n */\n function sortedUniqBy(array, iteratee) {\n return (array && array.length)\n ? baseSortedUniq(array, getIteratee(iteratee, 2))\n : [];\n }\n\n /**\n * Gets all but the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.tail([1, 2, 3]);\n * // => [2, 3]\n */\n function tail(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 1, length) : [];\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\n function take(array, n, guard) {\n if (!(array && array.length)) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRight([1, 2, 3]);\n * // => [3]\n *\n * _.takeRight([1, 2, 3], 2);\n * // => [2, 3]\n *\n * _.takeRight([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.takeRight([1, 2, 3], 0);\n * // => []\n */\n function takeRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the end. Elements are\n * taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.takeRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeRightWhile(users, ['active', false]);\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeRightWhile(users, 'active');\n * // => []\n */\n function takeRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), false, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` with elements taken from the beginning. Elements\n * are taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.takeWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeWhile(users, ['active', false]);\n * // => objects for ['barney', 'fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeWhile(users, 'active');\n * // => []\n */\n function takeWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3))\n : [];\n }\n\n /**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\n var union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n });\n\n /**\n * This method is like `_.union` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which uniqueness is computed. Result values are chosen from the first\n * array in which the value occurs. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.unionBy([2.1], [1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n var unionBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.union` except that it accepts `comparator` which\n * is invoked to compare elements of `arrays`. Result values are chosen from\n * the first array in which the value occurs. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.unionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var unionWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);\n });\n\n /**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\n function uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * uniqueness is computed. The order of result values is determined by the\n * order they occur in the array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n function uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\n function uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n }\n\n /**\n * This method is like `_.zip` except that it accepts an array of grouped\n * elements and creates an array regrouping the elements to their pre-zip\n * configuration.\n *\n * @static\n * @memberOf _\n * @since 1.2.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n *\n * _.unzip(zipped);\n * // => [['a', 'b'], [1, 2], [true, false]]\n */\n function unzip(array) {\n if (!(array && array.length)) {\n return [];\n }\n var length = 0;\n array = arrayFilter(array, function(group) {\n if (isArrayLikeObject(group)) {\n length = nativeMax(group.length, length);\n return true;\n }\n });\n return baseTimes(length, function(index) {\n return arrayMap(array, baseProperty(index));\n });\n }\n\n /**\n * This method is like `_.unzip` except that it accepts `iteratee` to specify\n * how regrouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * regrouped values.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip([1, 2], [10, 20], [100, 200]);\n * // => [[1, 10, 100], [2, 20, 200]]\n *\n * _.unzipWith(zipped, _.add);\n * // => [3, 30, 300]\n */\n function unzipWith(array, iteratee) {\n if (!(array && array.length)) {\n return [];\n }\n var result = unzip(array);\n if (iteratee == null) {\n return result;\n }\n return arrayMap(result, function(group) {\n return apply(iteratee, undefined, group);\n });\n }\n\n /**\n * Creates an array excluding all given values using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.pull`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.xor\n * @example\n *\n * _.without([2, 1, 2, 3], 1, 2);\n * // => [3]\n */\n var without = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, values)\n : [];\n });\n\n /**\n * Creates an array of unique values that is the\n * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)\n * of the given arrays. The order of result values is determined by the order\n * they occur in the arrays.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.without\n * @example\n *\n * _.xor([2, 1], [2, 3]);\n * // => [1, 3]\n */\n var xor = baseRest(function(arrays) {\n return baseXor(arrayFilter(arrays, isArrayLikeObject));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which by which they're compared. The order of result values is determined\n * by the order they occur in the arrays. The iteratee is invoked with one\n * argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2, 3.4]\n *\n * // The `_.property` iteratee shorthand.\n * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var xorBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `comparator` which is\n * invoked to compare elements of `arrays`. The order of result values is\n * determined by the order they occur in the arrays. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.xorWith(objects, others, _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var xorWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);\n });\n\n /**\n * Creates an array of grouped elements, the first of which contains the\n * first elements of the given arrays, the second of which contains the\n * second elements of the given arrays, and so on.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n */\n var zip = baseRest(unzip);\n\n /**\n * This method is like `_.fromPairs` except that it accepts two arrays,\n * one of property identifiers and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 0.4.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['a', 'b'], [1, 2]);\n * // => { 'a': 1, 'b': 2 }\n */\n function zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n }\n\n /**\n * This method is like `_.zipObject` except that it supports property paths.\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);\n * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }\n */\n function zipObjectDeep(props, values) {\n return baseZipObject(props || [], values || [], baseSet);\n }\n\n /**\n * This method is like `_.zip` except that it accepts `iteratee` to specify\n * how grouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * grouped values.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {\n * return a + b + c;\n * });\n * // => [111, 222]\n */\n var zipWith = baseRest(function(arrays) {\n var length = arrays.length,\n iteratee = length > 1 ? arrays[length - 1] : undefined;\n\n iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;\n return unzipWith(arrays, iteratee);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` wrapper instance that wraps `value` with explicit method\n * chain sequences enabled. The result of such sequences must be unwrapped\n * with `_#value`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Seq\n * @param {*} value The value to wrap.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'pebbles', 'age': 1 }\n * ];\n *\n * var youngest = _\n * .chain(users)\n * .sortBy('age')\n * .map(function(o) {\n * return o.user + ' is ' + o.age;\n * })\n * .head()\n * .value();\n * // => 'pebbles is 1'\n */\n function chain(value) {\n var result = lodash(value);\n result.__chain__ = true;\n return result;\n }\n\n /**\n * This method invokes `interceptor` and returns `value`. The interceptor\n * is invoked with one argument; (value). The purpose of this method is to\n * \"tap into\" a method chain sequence in order to modify intermediate results.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns `value`.\n * @example\n *\n * _([1, 2, 3])\n * .tap(function(array) {\n * // Mutate input array.\n * array.pop();\n * })\n * .reverse()\n * .value();\n * // => [2, 1]\n */\n function tap(value, interceptor) {\n interceptor(value);\n return value;\n }\n\n /**\n * This method is like `_.tap` except that it returns the result of `interceptor`.\n * The purpose of this method is to \"pass thru\" values replacing intermediate\n * results in a method chain sequence.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns the result of `interceptor`.\n * @example\n *\n * _(' abc ')\n * .chain()\n * .trim()\n * .thru(function(value) {\n * return [value];\n * })\n * .value();\n * // => ['abc']\n */\n function thru(value, interceptor) {\n return interceptor(value);\n }\n\n /**\n * This method is the wrapper version of `_.at`.\n *\n * @name at\n * @memberOf _\n * @since 1.0.0\n * @category Seq\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _(object).at(['a[0].b.c', 'a[1]']).value();\n * // => [3, 4]\n */\n var wrapperAt = flatRest(function(paths) {\n var length = paths.length,\n start = length ? paths[0] : 0,\n value = this.__wrapped__,\n interceptor = function(object) { return baseAt(object, paths); };\n\n if (length > 1 || this.__actions__.length ||\n !(value instanceof LazyWrapper) || !isIndex(start)) {\n return this.thru(interceptor);\n }\n value = value.slice(start, +start + (length ? 1 : 0));\n value.__actions__.push({\n 'func': thru,\n 'args': [interceptor],\n 'thisArg': undefined\n });\n return new LodashWrapper(value, this.__chain__).thru(function(array) {\n if (length && !array.length) {\n array.push(undefined);\n }\n return array;\n });\n });\n\n /**\n * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.\n *\n * @name chain\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * // A sequence without explicit chaining.\n * _(users).head();\n * // => { 'user': 'barney', 'age': 36 }\n *\n * // A sequence with explicit chaining.\n * _(users)\n * .chain()\n * .head()\n * .pick('user')\n * .value();\n * // => { 'user': 'barney' }\n */\n function wrapperChain() {\n return chain(this);\n }\n\n /**\n * Executes the chain sequence and returns the wrapped result.\n *\n * @name commit\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapped = _(array).push(3);\n *\n * console.log(array);\n * // => [1, 2]\n *\n * wrapped = wrapped.commit();\n * console.log(array);\n * // => [1, 2, 3]\n *\n * wrapped.last();\n * // => 3\n *\n * console.log(array);\n * // => [1, 2, 3]\n */\n function wrapperCommit() {\n return new LodashWrapper(this.value(), this.__chain__);\n }\n\n /**\n * Gets the next value on a wrapped object following the\n * [iterator protocol](https://mdn.io/iteration_protocols#iterator).\n *\n * @name next\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the next iterator value.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 1 }\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 2 }\n *\n * wrapped.next();\n * // => { 'done': true, 'value': undefined }\n */\n function wrapperNext() {\n if (this.__values__ === undefined) {\n this.__values__ = toArray(this.value());\n }\n var done = this.__index__ >= this.__values__.length,\n value = done ? undefined : this.__values__[this.__index__++];\n\n return { 'done': done, 'value': value };\n }\n\n /**\n * Enables the wrapper to be iterable.\n *\n * @name Symbol.iterator\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the wrapper object.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped[Symbol.iterator]() === wrapped;\n * // => true\n *\n * Array.from(wrapped);\n * // => [1, 2]\n */\n function wrapperToIterator() {\n return this;\n }\n\n /**\n * Creates a clone of the chain sequence planting `value` as the wrapped value.\n *\n * @name plant\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @param {*} value The value to plant.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2]).map(square);\n * var other = wrapped.plant([3, 4]);\n *\n * other.value();\n * // => [9, 16]\n *\n * wrapped.value();\n * // => [1, 4]\n */\n function wrapperPlant(value) {\n var result,\n parent = this;\n\n while (parent instanceof baseLodash) {\n var clone = wrapperClone(parent);\n clone.__index__ = 0;\n clone.__values__ = undefined;\n if (result) {\n previous.__wrapped__ = clone;\n } else {\n result = clone;\n }\n var previous = clone;\n parent = parent.__wrapped__;\n }\n previous.__wrapped__ = value;\n return result;\n }\n\n /**\n * This method is the wrapper version of `_.reverse`.\n *\n * **Note:** This method mutates the wrapped array.\n *\n * @name reverse\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _(array).reverse().value()\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function wrapperReverse() {\n var value = this.__wrapped__;\n if (value instanceof LazyWrapper) {\n var wrapped = value;\n if (this.__actions__.length) {\n wrapped = new LazyWrapper(this);\n }\n wrapped = wrapped.reverse();\n wrapped.__actions__.push({\n 'func': thru,\n 'args': [reverse],\n 'thisArg': undefined\n });\n return new LodashWrapper(wrapped, this.__chain__);\n }\n return this.thru(reverse);\n }\n\n /**\n * Executes the chain sequence to resolve the unwrapped value.\n *\n * @name value\n * @memberOf _\n * @since 0.1.0\n * @alias toJSON, valueOf\n * @category Seq\n * @returns {*} Returns the resolved unwrapped value.\n * @example\n *\n * _([1, 2, 3]).value();\n * // => [1, 2, 3]\n */\n function wrapperValue() {\n return baseWrapperValue(this.__wrapped__, this.__actions__);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the number of times the key was returned by `iteratee`. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.countBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': 1, '6': 2 }\n *\n * // The `_.property` iteratee shorthand.\n * _.countBy(['one', 'two', 'three'], 'length');\n * // => { '3': 2, '5': 1 }\n */\n var countBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n ++result[key];\n } else {\n baseAssignValue(result, key, 1);\n }\n });\n\n /**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\n function every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\n function filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\n var find = createFind(findIndex);\n\n /**\n * This method is like `_.find` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=collection.length-1] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * _.findLast([1, 2, 3, 4], function(n) {\n * return n % 2 == 1;\n * });\n * // => 3\n */\n var findLast = createFind(findLastIndex);\n\n /**\n * Creates a flattened array of values by running each element in `collection`\n * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n * with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [n, n];\n * }\n *\n * _.flatMap([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDeep([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMapDeep(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), INFINITY);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDepth([1, 2], duplicate, 2);\n * // => [[1, 1], [2, 2]]\n */\n function flatMapDepth(collection, iteratee, depth) {\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(map(collection, iteratee), depth);\n }\n\n /**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forEach` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @alias eachRight\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEach\n * @example\n *\n * _.forEachRight([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `2` then `1`.\n */\n function forEachRight(collection, iteratee) {\n var func = isArray(collection) ? arrayEachRight : baseEachRight;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\n var groupBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n baseAssignValue(result, key, [value]);\n }\n });\n\n /**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\n function includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n }\n\n /**\n * Invokes the method at `path` of each element in `collection`, returning\n * an array of the results of each invoked method. Any additional arguments\n * are provided to each invoked method. If `path` is a function, it's invoked\n * for, and `this` bound to, each element in `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array|Function|string} path The path of the method to invoke or\n * the function invoked per iteration.\n * @param {...*} [args] The arguments to invoke each method with.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');\n * // => [[1, 5, 7], [1, 2, 3]]\n *\n * _.invokeMap([123, 456], String.prototype.split, '');\n * // => [['1', '2', '3'], ['4', '5', '6']]\n */\n var invokeMap = baseRest(function(collection, path, args) {\n var index = -1,\n isFunc = typeof path == 'function',\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value) {\n result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);\n });\n return result;\n });\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the last element responsible for generating the key. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var array = [\n * { 'dir': 'left', 'code': 97 },\n * { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.keyBy(array, function(o) {\n * return String.fromCharCode(o.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.keyBy(array, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n */\n var keyBy = createAggregator(function(result, value, key) {\n baseAssignValue(result, key, value);\n });\n\n /**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\n function map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.sortBy` except that it allows specifying the sort\n * orders of the iteratees to sort by. If `orders` is unspecified, all values\n * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n * descending or \"asc\" for ascending sort order of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @param {string[]} [orders] The sort orders of `iteratees`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 34 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'barney', 'age': 36 }\n * ];\n *\n * // Sort by `user` in ascending order and by `age` in descending order.\n * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n */\n function orderBy(collection, iteratees, orders, guard) {\n if (collection == null) {\n return [];\n }\n if (!isArray(iteratees)) {\n iteratees = iteratees == null ? [] : [iteratees];\n }\n orders = guard ? undefined : orders;\n if (!isArray(orders)) {\n orders = orders == null ? [] : [orders];\n }\n return baseOrderBy(collection, iteratees, orders);\n }\n\n /**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, the second of which\n * contains elements `predicate` returns falsey for. The predicate is\n * invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true },\n * { 'user': 'pebbles', 'age': 1, 'active': false }\n * ];\n *\n * _.partition(users, function(o) { return o.active; });\n * // => objects for [['fred'], ['barney', 'pebbles']]\n *\n * // The `_.matches` iteratee shorthand.\n * _.partition(users, { 'age': 1, 'active': false });\n * // => objects for [['pebbles'], ['barney', 'fred']]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.partition(users, ['active', false]);\n * // => objects for [['barney', 'pebbles'], ['fred']]\n *\n * // The `_.property` iteratee shorthand.\n * _.partition(users, 'active');\n * // => objects for [['fred'], ['barney', 'pebbles']]\n */\n var partition = createAggregator(function(result, value, key) {\n result[key ? 0 : 1].push(value);\n }, function() { return [[], []]; });\n\n /**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\n function reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n }\n\n /**\n * This method is like `_.reduce` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduce\n * @example\n *\n * var array = [[0, 1], [2, 3], [4, 5]];\n *\n * _.reduceRight(array, function(flattened, other) {\n * return flattened.concat(other);\n * }, []);\n * // => [4, 5, 2, 3, 0, 1]\n */\n function reduceRight(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduceRight : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);\n }\n\n /**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.filter\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * _.reject(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.reject(users, { 'age': 40, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.reject(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.reject(users, 'active');\n * // => objects for ['barney']\n */\n function reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(getIteratee(predicate, 3)));\n }\n\n /**\n * Gets a random element from `collection`.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n * @example\n *\n * _.sample([1, 2, 3, 4]);\n * // => 2\n */\n function sample(collection) {\n var func = isArray(collection) ? arraySample : baseSample;\n return func(collection);\n }\n\n /**\n * Gets `n` random elements at unique keys from `collection` up to the\n * size of `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @param {number} [n=1] The number of elements to sample.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the random elements.\n * @example\n *\n * _.sampleSize([1, 2, 3], 2);\n * // => [3, 1]\n *\n * _.sampleSize([1, 2, 3], 4);\n * // => [2, 3, 1]\n */\n function sampleSize(collection, n, guard) {\n if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n var func = isArray(collection) ? arraySampleSize : baseSampleSize;\n return func(collection, n);\n }\n\n /**\n * Creates an array of shuffled values, using a version of the\n * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n * @example\n *\n * _.shuffle([1, 2, 3, 4]);\n * // => [4, 1, 3, 2]\n */\n function shuffle(collection) {\n var func = isArray(collection) ? arrayShuffle : baseShuffle;\n return func(collection);\n }\n\n /**\n * Gets the size of `collection` by returning its length for array-like\n * values or the number of own enumerable string keyed properties for objects.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @returns {number} Returns the collection size.\n * @example\n *\n * _.size([1, 2, 3]);\n * // => 3\n *\n * _.size({ 'a': 1, 'b': 2 });\n * // => 2\n *\n * _.size('pebbles');\n * // => 7\n */\n function size(collection) {\n if (collection == null) {\n return 0;\n }\n if (isArrayLike(collection)) {\n return isString(collection) ? stringSize(collection) : collection.length;\n }\n var tag = getTag(collection);\n if (tag == mapTag || tag == setTag) {\n return collection.size;\n }\n return baseKeys(collection).length;\n }\n\n /**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\n function some(collection, predicate, guard) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\n var sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\n var now = ctxNow || function() {\n return root.Date.now();\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * The opposite of `_.before`; this method creates a function that invokes\n * `func` once it's called `n` or more times.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {number} n The number of calls before `func` is invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var saves = ['profile', 'settings'];\n *\n * var done = _.after(saves.length, function() {\n * console.log('done saving!');\n * });\n *\n * _.forEach(saves, function(type) {\n * asyncSave({ 'type': type, 'complete': done });\n * });\n * // => Logs 'done saving!' after the two async saves have completed.\n */\n function after(n, func) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n < 1) {\n return func.apply(this, arguments);\n }\n };\n }\n\n /**\n * Creates a function that invokes `func`, with up to `n` arguments,\n * ignoring any additional arguments.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\n function ary(func, n, guard) {\n n = guard ? undefined : n;\n n = (func && n == null) ? func.length : n;\n return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n }\n\n /**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it's called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery(element).on('click', _.before(5, addContactToList));\n * // => Allows adding up to 4 contacts to the list.\n */\n function before(n, func) {\n var result;\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n > 0) {\n result = func.apply(this, arguments);\n }\n if (n <= 1) {\n func = undefined;\n }\n return result;\n };\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of `thisArg`\n * and `partials` prepended to the arguments it receives.\n *\n * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for partially applied arguments.\n *\n * **Note:** Unlike native `Function#bind`, this method doesn't set the \"length\"\n * property of bound functions.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * function greet(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n *\n * var object = { 'user': 'fred' };\n *\n * var bound = _.bind(greet, object, 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bind(greet, object, _, '!');\n * bound('hi');\n * // => 'hi fred!'\n */\n var bind = baseRest(function(func, thisArg, partials) {\n var bitmask = WRAP_BIND_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bind));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(func, bitmask, thisArg, partials, holders);\n });\n\n /**\n * Creates a function that invokes the method at `object[key]` with `partials`\n * prepended to the arguments it receives.\n *\n * This method differs from `_.bind` by allowing bound functions to reference\n * methods that may be redefined or don't yet exist. See\n * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)\n * for more details.\n *\n * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Function\n * @param {Object} object The object to invoke the method on.\n * @param {string} key The key of the method.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var object = {\n * 'user': 'fred',\n * 'greet': function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n * };\n *\n * var bound = _.bindKey(object, 'greet', 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * object.greet = function(greeting, punctuation) {\n * return greeting + 'ya ' + this.user + punctuation;\n * };\n *\n * bound('!');\n * // => 'hiya fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bindKey(object, 'greet', _, '!');\n * bound('hi');\n * // => 'hiya fred!'\n */\n var bindKey = baseRest(function(object, key, partials) {\n var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bindKey));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(key, bitmask, object, partials, holders);\n });\n\n /**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\n function curry(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curry.placeholder;\n return result;\n }\n\n /**\n * This method is like `_.curry` except that arguments are applied to `func`\n * in the manner of `_.partialRight` instead of `_.partial`.\n *\n * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curryRight(abc);\n *\n * curried(3)(2)(1);\n * // => [1, 2, 3]\n *\n * curried(2, 3)(1);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(3)(1, _)(2);\n * // => [1, 2, 3]\n */\n function curryRight(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curryRight.placeholder;\n return result;\n }\n\n /**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\n function debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n }\n\n /**\n * Defers invoking the `func` until the current call stack has cleared. Any\n * additional arguments are provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to defer.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function(text) {\n * console.log(text);\n * }, 'deferred');\n * // => Logs 'deferred' after one millisecond.\n */\n var defer = baseRest(function(func, args) {\n return baseDelay(func, 1, args);\n });\n\n /**\n * Invokes `func` after `wait` milliseconds. Any additional arguments are\n * provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.delay(function(text) {\n * console.log(text);\n * }, 1000, 'later');\n * // => Logs 'later' after one second.\n */\n var delay = baseRest(function(func, wait, args) {\n return baseDelay(func, toNumber(wait) || 0, args);\n });\n\n /**\n * Creates a function that invokes `func` with arguments reversed.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to flip arguments for.\n * @returns {Function} Returns the new flipped function.\n * @example\n *\n * var flipped = _.flip(function() {\n * return _.toArray(arguments);\n * });\n *\n * flipped('a', 'b', 'c', 'd');\n * // => ['d', 'c', 'b', 'a']\n */\n function flip(func) {\n return createWrap(func, WRAP_FLIP_FLAG);\n }\n\n /**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\n function memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n }\n\n // Expose `MapCache`.\n memoize.Cache = MapCache;\n\n /**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\n function negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n }\n\n /**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first invocation. The `func` is\n * invoked with the `this` binding and arguments of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // => `createApplication` is invoked once\n */\n function once(func) {\n return before(2, func);\n }\n\n /**\n * Creates a function that invokes `func` with its arguments transformed.\n *\n * @static\n * @since 4.0.0\n * @memberOf _\n * @category Function\n * @param {Function} func The function to wrap.\n * @param {...(Function|Function[])} [transforms=[_.identity]]\n * The argument transforms.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function doubled(n) {\n * return n * 2;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var func = _.overArgs(function(x, y) {\n * return [x, y];\n * }, [square, doubled]);\n *\n * func(9, 3);\n * // => [81, 6]\n *\n * func(10, 5);\n * // => [100, 10]\n */\n var overArgs = castRest(function(func, transforms) {\n transforms = (transforms.length == 1 && isArray(transforms[0]))\n ? arrayMap(transforms[0], baseUnary(getIteratee()))\n : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));\n\n var funcsLength = transforms.length;\n return baseRest(function(args) {\n var index = -1,\n length = nativeMin(args.length, funcsLength);\n\n while (++index < length) {\n args[index] = transforms[index].call(this, args[index]);\n }\n return apply(func, this, args);\n });\n });\n\n /**\n * Creates a function that invokes `func` with `partials` prepended to the\n * arguments it receives. This method is like `_.bind` except it does **not**\n * alter the `this` binding.\n *\n * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 0.2.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var sayHelloTo = _.partial(greet, 'hello');\n * sayHelloTo('fred');\n * // => 'hello fred'\n *\n * // Partially applied with placeholders.\n * var greetFred = _.partial(greet, _, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n */\n var partial = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partial));\n return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);\n });\n\n /**\n * This method is like `_.partial` except that partially applied arguments\n * are appended to the arguments it receives.\n *\n * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var greetFred = _.partialRight(greet, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n *\n * // Partially applied with placeholders.\n * var sayHelloTo = _.partialRight(greet, 'hello', _);\n * sayHelloTo('fred');\n * // => 'hello fred'\n */\n var partialRight = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partialRight));\n return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);\n });\n\n /**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified `indexes` where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n * return [a, b, c];\n * }, [2, 0, 1]);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n */\n var rearg = flatRest(function(func, indexes) {\n return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n });\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * created function and arguments from `start` and beyond provided as\n * an array.\n *\n * **Note:** This method is based on the\n * [rest parameter](https://mdn.io/rest_parameters).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.rest(function(what, names) {\n * return what + ' ' + _.initial(names).join(', ') +\n * (_.size(names) > 1 ? ', & ' : '') + _.last(names);\n * });\n *\n * say('hello', 'fred', 'barney', 'pebbles');\n * // => 'hello fred, barney, & pebbles'\n */\n function rest(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start === undefined ? start : toInteger(start);\n return baseRest(func, start);\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * create function and an array of arguments much like\n * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).\n *\n * **Note:** This method is based on the\n * [spread operator](https://mdn.io/spread_operator).\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Function\n * @param {Function} func The function to spread arguments over.\n * @param {number} [start=0] The start position of the spread.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.spread(function(who, what) {\n * return who + ' says ' + what;\n * });\n *\n * say(['fred', 'hello']);\n * // => 'fred says hello'\n *\n * var numbers = Promise.all([\n * Promise.resolve(40),\n * Promise.resolve(36)\n * ]);\n *\n * numbers.then(_.spread(function(x, y) {\n * return x + y;\n * }));\n * // => a Promise of 76\n */\n function spread(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start == null ? 0 : nativeMax(toInteger(start), 0);\n return baseRest(function(args) {\n var array = args[start],\n otherArgs = castSlice(args, 0, start);\n\n if (array) {\n arrayPush(otherArgs, array);\n }\n return apply(func, this, otherArgs);\n });\n }\n\n /**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\n function throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n }\n\n /**\n * Creates a function that accepts up to one argument, ignoring any\n * additional arguments.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.unary(parseInt));\n * // => [6, 8, 10]\n */\n function unary(func) {\n return ary(func, 1);\n }\n\n /**\n * Creates a function that provides `value` to `wrapper` as its first\n * argument. Any additional arguments provided to the function are appended\n * to those provided to the `wrapper`. The wrapper is invoked with the `this`\n * binding of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {*} value The value to wrap.\n * @param {Function} [wrapper=identity] The wrapper function.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var p = _.wrap(_.escape, function(func, text) {\n * return '

' + func(text) + '

';\n * });\n *\n * p('fred, barney, & pebbles');\n * // => '

fred, barney, & pebbles

'\n */\n function wrap(value, wrapper) {\n return partial(castFunction(wrapper), value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Casts `value` as an array if it's not one.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Lang\n * @param {*} value The value to inspect.\n * @returns {Array} Returns the cast array.\n * @example\n *\n * _.castArray(1);\n * // => [1]\n *\n * _.castArray({ 'a': 1 });\n * // => [{ 'a': 1 }]\n *\n * _.castArray('abc');\n * // => ['abc']\n *\n * _.castArray(null);\n * // => [null]\n *\n * _.castArray(undefined);\n * // => [undefined]\n *\n * _.castArray();\n * // => []\n *\n * var array = [1, 2, 3];\n * console.log(_.castArray(array) === array);\n * // => true\n */\n function castArray() {\n if (!arguments.length) {\n return [];\n }\n var value = arguments[0];\n return isArray(value) ? value : [value];\n }\n\n /**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\n function clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.clone` except that it accepts `customizer` which\n * is invoked to produce the cloned value. If `customizer` returns `undefined`,\n * cloning is handled by the method instead. The `customizer` is invoked with\n * up to four arguments; (value [, index|key, object, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeepWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(false);\n * }\n * }\n *\n * var el = _.cloneWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 0\n */\n function cloneWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\n function cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.cloneWith` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the deep cloned value.\n * @see _.cloneWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(true);\n * }\n * }\n *\n * var el = _.cloneDeepWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 20\n */\n function cloneDeepWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * Checks if `object` conforms to `source` by invoking the predicate\n * properties of `source` with the corresponding property values of `object`.\n *\n * **Note:** This method is equivalent to `_.conforms` when `source` is\n * partially applied.\n *\n * @static\n * @memberOf _\n * @since 4.14.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 1; } });\n * // => true\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 2; } });\n * // => false\n */\n function conformsTo(object, source) {\n return source == null || baseConformsTo(object, source, keys(source));\n }\n\n /**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\n function eq(value, other) {\n return value === other || (value !== value && other !== other);\n }\n\n /**\n * Checks if `value` is greater than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n * @see _.lt\n * @example\n *\n * _.gt(3, 1);\n * // => true\n *\n * _.gt(3, 3);\n * // => false\n *\n * _.gt(1, 3);\n * // => false\n */\n var gt = createRelationalOperation(baseGt);\n\n /**\n * Checks if `value` is greater than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than or equal to\n * `other`, else `false`.\n * @see _.lte\n * @example\n *\n * _.gte(3, 1);\n * // => true\n *\n * _.gte(3, 3);\n * // => true\n *\n * _.gte(1, 3);\n * // => false\n */\n var gte = createRelationalOperation(function(value, other) {\n return value >= other;\n });\n\n /**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\n var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n };\n\n /**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\n var isArray = Array.isArray;\n\n /**\n * Checks if `value` is classified as an `ArrayBuffer` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n * @example\n *\n * _.isArrayBuffer(new ArrayBuffer(2));\n * // => true\n *\n * _.isArrayBuffer(new Array(2));\n * // => false\n */\n var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;\n\n /**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\n function isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n }\n\n /**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\n function isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n }\n\n /**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\n function isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n }\n\n /**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\n var isBuffer = nativeIsBuffer || stubFalse;\n\n /**\n * Checks if `value` is classified as a `Date` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n * @example\n *\n * _.isDate(new Date);\n * // => true\n *\n * _.isDate('Mon April 23 2012');\n * // => false\n */\n var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;\n\n /**\n * Checks if `value` is likely a DOM element.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.\n * @example\n *\n * _.isElement(document.body);\n * // => true\n *\n * _.isElement('');\n * // => false\n */\n function isElement(value) {\n return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);\n }\n\n /**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\n function isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\n function isEqual(value, other) {\n return baseIsEqual(value, other);\n }\n\n /**\n * This method is like `_.isEqual` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with up to\n * six arguments: (objValue, othValue [, index|key, object, other, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, othValue) {\n * if (isGreeting(objValue) && isGreeting(othValue)) {\n * return true;\n * }\n * }\n *\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqualWith(array, other, customizer);\n * // => true\n */\n function isEqualWith(value, other, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n var result = customizer ? customizer(value, other) : undefined;\n return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n }\n\n /**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\n function isError(value) {\n if (!isObjectLike(value)) {\n return false;\n }\n var tag = baseGetTag(value);\n return tag == errorTag || tag == domExcTag ||\n (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n }\n\n /**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on\n * [`Number.isFinite`](https://mdn.io/Number/isFinite).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n * @example\n *\n * _.isFinite(3);\n * // => true\n *\n * _.isFinite(Number.MIN_VALUE);\n * // => true\n *\n * _.isFinite(Infinity);\n * // => false\n *\n * _.isFinite('3');\n * // => false\n */\n function isFinite(value) {\n return typeof value == 'number' && nativeIsFinite(value);\n }\n\n /**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\n function isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n }\n\n /**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\n function isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n }\n\n /**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\n function isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\n function isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n }\n\n /**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\n function isObjectLike(value) {\n return value != null && typeof value == 'object';\n }\n\n /**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\n var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\n /**\n * Performs a partial deep comparison between `object` and `source` to\n * determine if `object` contains equivalent property values.\n *\n * **Note:** This method is equivalent to `_.matches` when `source` is\n * partially applied.\n *\n * Partial comparisons will match empty array and empty object `source`\n * values against any array or object value, respectively. See `_.isEqual`\n * for a list of supported value comparisons.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.isMatch(object, { 'b': 2 });\n * // => true\n *\n * _.isMatch(object, { 'b': 1 });\n * // => false\n */\n function isMatch(object, source) {\n return object === source || baseIsMatch(object, source, getMatchData(source));\n }\n\n /**\n * This method is like `_.isMatch` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with five\n * arguments: (objValue, srcValue, index|key, object, source).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, srcValue) {\n * if (isGreeting(objValue) && isGreeting(srcValue)) {\n * return true;\n * }\n * }\n *\n * var object = { 'greeting': 'hello' };\n * var source = { 'greeting': 'hi' };\n *\n * _.isMatchWith(object, source, customizer);\n * // => true\n */\n function isMatchWith(object, source, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseIsMatch(object, source, getMatchData(source), customizer);\n }\n\n /**\n * Checks if `value` is `NaN`.\n *\n * **Note:** This method is based on\n * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as\n * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for\n * `undefined` and other non-number values.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n * @example\n *\n * _.isNaN(NaN);\n * // => true\n *\n * _.isNaN(new Number(NaN));\n * // => true\n *\n * isNaN(undefined);\n * // => true\n *\n * _.isNaN(undefined);\n * // => false\n */\n function isNaN(value) {\n // An `NaN` primitive is the only value that is not equal to itself.\n // Perform the `toStringTag` check first to avoid errors with some\n // ActiveX objects in IE.\n return isNumber(value) && value != +value;\n }\n\n /**\n * Checks if `value` is a pristine native function.\n *\n * **Note:** This method can't reliably detect native functions in the presence\n * of the core-js package because core-js circumvents this kind of detection.\n * Despite multiple requests, the core-js maintainer has made it clear: any\n * attempt to fix the detection will be obstructed. As a result, we're left\n * with little choice but to throw an error. Unfortunately, this also affects\n * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),\n * which rely on core-js.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n * @example\n *\n * _.isNative(Array.prototype.push);\n * // => true\n *\n * _.isNative(_);\n * // => false\n */\n function isNative(value) {\n if (isMaskable(value)) {\n throw new Error(CORE_ERROR_TEXT);\n }\n return baseIsNative(value);\n }\n\n /**\n * Checks if `value` is `null`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\n function isNull(value) {\n return value === null;\n }\n\n /**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\n function isNil(value) {\n return value == null;\n }\n\n /**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n * classified as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a number, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\n function isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n }\n\n /**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\n function isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n }\n\n /**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\n var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\n /**\n * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754\n * double precision number which isn't the result of a rounded unsafe integer.\n *\n * **Note:** This method is based on\n * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.\n * @example\n *\n * _.isSafeInteger(3);\n * // => true\n *\n * _.isSafeInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isSafeInteger(Infinity);\n * // => false\n *\n * _.isSafeInteger('3');\n * // => false\n */\n function isSafeInteger(value) {\n return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\n var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\n /**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\n function isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n }\n\n /**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\n function isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n }\n\n /**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\n var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n /**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\n function isUndefined(value) {\n return value === undefined;\n }\n\n /**\n * Checks if `value` is classified as a `WeakMap` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.\n * @example\n *\n * _.isWeakMap(new WeakMap);\n * // => true\n *\n * _.isWeakMap(new Map);\n * // => false\n */\n function isWeakMap(value) {\n return isObjectLike(value) && getTag(value) == weakMapTag;\n }\n\n /**\n * Checks if `value` is classified as a `WeakSet` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.\n * @example\n *\n * _.isWeakSet(new WeakSet);\n * // => true\n *\n * _.isWeakSet(new Set);\n * // => false\n */\n function isWeakSet(value) {\n return isObjectLike(value) && baseGetTag(value) == weakSetTag;\n }\n\n /**\n * Checks if `value` is less than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n * @see _.gt\n * @example\n *\n * _.lt(1, 3);\n * // => true\n *\n * _.lt(3, 3);\n * // => false\n *\n * _.lt(3, 1);\n * // => false\n */\n var lt = createRelationalOperation(baseLt);\n\n /**\n * Checks if `value` is less than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than or equal to\n * `other`, else `false`.\n * @see _.gte\n * @example\n *\n * _.lte(1, 3);\n * // => true\n *\n * _.lte(3, 3);\n * // => true\n *\n * _.lte(3, 1);\n * // => false\n */\n var lte = createRelationalOperation(function(value, other) {\n return value <= other;\n });\n\n /**\n * Converts `value` to an array.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Array} Returns the converted array.\n * @example\n *\n * _.toArray({ 'a': 1, 'b': 2 });\n * // => [1, 2]\n *\n * _.toArray('abc');\n * // => ['a', 'b', 'c']\n *\n * _.toArray(1);\n * // => []\n *\n * _.toArray(null);\n * // => []\n */\n function toArray(value) {\n if (!value) {\n return [];\n }\n if (isArrayLike(value)) {\n return isString(value) ? stringToArray(value) : copyArray(value);\n }\n if (symIterator && value[symIterator]) {\n return iteratorToArray(value[symIterator]());\n }\n var tag = getTag(value),\n func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);\n\n return func(value);\n }\n\n /**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\n function toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n }\n\n /**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\n function toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n }\n\n /**\n * Converts `value` to an integer suitable for use as the length of an\n * array-like object.\n *\n * **Note:** This method is based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toLength(3.2);\n * // => 3\n *\n * _.toLength(Number.MIN_VALUE);\n * // => 0\n *\n * _.toLength(Infinity);\n * // => 4294967295\n *\n * _.toLength('3.2');\n * // => 3\n */\n function toLength(value) {\n return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;\n }\n\n /**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\n function toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n }\n\n /**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\n function toPlainObject(value) {\n return copyObject(value, keysIn(value));\n }\n\n /**\n * Converts `value` to a safe integer. A safe integer can be compared and\n * represented correctly.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toSafeInteger(3.2);\n * // => 3\n *\n * _.toSafeInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toSafeInteger(Infinity);\n * // => 9007199254740991\n *\n * _.toSafeInteger('3.2');\n * // => 3\n */\n function toSafeInteger(value) {\n return value\n ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)\n : (value === 0 ? value : 0);\n }\n\n /**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\n function toString(value) {\n return value == null ? '' : baseToString(value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Assigns own enumerable string keyed properties of source objects to the\n * destination object. Source objects are applied from left to right.\n * Subsequent sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object` and is loosely based on\n * [`Object.assign`](https://mdn.io/Object/assign).\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assignIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assign({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'c': 3 }\n */\n var assign = createAssigner(function(object, source) {\n if (isPrototype(source) || isArrayLike(source)) {\n copyObject(source, keys(source), object);\n return;\n }\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n assignValue(object, key, source[key]);\n }\n }\n });\n\n /**\n * This method is like `_.assign` except that it iterates over own and\n * inherited source properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extend\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assign\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assignIn({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }\n */\n var assignIn = createAssigner(function(object, source) {\n copyObject(source, keysIn(source), object);\n });\n\n /**\n * This method is like `_.assignIn` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extendWith\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignInWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keysIn(source), object, customizer);\n });\n\n /**\n * This method is like `_.assign` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignInWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keys(source), object, customizer);\n });\n\n /**\n * Creates an array of values corresponding to `paths` of `object`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Array} Returns the picked values.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _.at(object, ['a[0].b.c', 'a[1]']);\n * // => [3, 4]\n */\n var at = flatRest(baseAt);\n\n /**\n * Creates an object that inherits from the `prototype` object. If a\n * `properties` object is given, its own enumerable string keyed properties\n * are assigned to the created object.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Object\n * @param {Object} prototype The object to inherit from.\n * @param {Object} [properties] The properties to assign to the object.\n * @returns {Object} Returns the new object.\n * @example\n *\n * function Shape() {\n * this.x = 0;\n * this.y = 0;\n * }\n *\n * function Circle() {\n * Shape.call(this);\n * }\n *\n * Circle.prototype = _.create(Shape.prototype, {\n * 'constructor': Circle\n * });\n *\n * var circle = new Circle;\n * circle instanceof Circle;\n * // => true\n *\n * circle instanceof Shape;\n * // => true\n */\n function create(prototype, properties) {\n var result = baseCreate(prototype);\n return properties == null ? result : baseAssign(result, properties);\n }\n\n /**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n });\n\n /**\n * This method is like `_.defaults` except that it recursively assigns\n * default properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaults\n * @example\n *\n * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n * // => { 'a': { 'b': 2, 'c': 3 } }\n */\n var defaultsDeep = baseRest(function(args) {\n args.push(undefined, customDefaultsMerge);\n return apply(mergeWith, undefined, args);\n });\n\n /**\n * This method is like `_.find` except that it returns the key of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findKey(users, function(o) { return o.age < 40; });\n * // => 'barney' (iteration order is not guaranteed)\n *\n * // The `_.matches` iteratee shorthand.\n * _.findKey(users, { 'age': 1, 'active': true });\n * // => 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findKey(users, 'active');\n * // => 'barney'\n */\n function findKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);\n }\n\n /**\n * This method is like `_.findKey` except that it iterates over elements of\n * a collection in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findLastKey(users, function(o) { return o.age < 40; });\n * // => returns 'pebbles' assuming `_.findKey` returns 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastKey(users, { 'age': 36, 'active': true });\n * // => 'barney'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastKey(users, 'active');\n * // => 'pebbles'\n */\n function findLastKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);\n }\n\n /**\n * Iterates over own and inherited enumerable string keyed properties of an\n * object and invokes `iteratee` for each property. The iteratee is invoked\n * with three arguments: (value, key, object). Iteratee functions may exit\n * iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forInRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forIn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).\n */\n function forIn(object, iteratee) {\n return object == null\n ? object\n : baseFor(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * This method is like `_.forIn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forInRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.\n */\n function forInRight(object, iteratee) {\n return object == null\n ? object\n : baseForRight(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * Iterates over own enumerable string keyed properties of an object and\n * invokes `iteratee` for each property. The iteratee is invoked with three\n * arguments: (value, key, object). Iteratee functions may exit iteration\n * early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwnRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forOwn(object, iteratee) {\n return object && baseForOwn(object, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forOwn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwnRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.\n */\n function forOwnRight(object, iteratee) {\n return object && baseForOwnRight(object, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an array of function property names from own enumerable properties\n * of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functionsIn\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functions(new Foo);\n * // => ['a', 'b']\n */\n function functions(object) {\n return object == null ? [] : baseFunctions(object, keys(object));\n }\n\n /**\n * Creates an array of function property names from own and inherited\n * enumerable properties of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functions\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functionsIn(new Foo);\n * // => ['a', 'b', 'c']\n */\n function functionsIn(object) {\n return object == null ? [] : baseFunctions(object, keysIn(object));\n }\n\n /**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\n function get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n }\n\n /**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\n function has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n }\n\n /**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\n function hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n */\n var invoke = baseRest(baseInvoke);\n\n /**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\n function keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n }\n\n /**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\n function keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n }\n\n /**\n * The opposite of `_.mapValues`; this method creates an object with the\n * same values as `object` and keys generated by running each own enumerable\n * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n * with three arguments: (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapValues\n * @example\n *\n * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n * return key + value;\n * });\n * // => { 'a1': 1, 'b2': 2 }\n */\n function mapKeys(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, iteratee(value, key, object), value);\n });\n return result;\n }\n\n /**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\n function mapValues(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n }\n\n /**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\n var merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n });\n\n /**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\n var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n });\n\n /**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\n var omit = flatRest(function(object, paths) {\n var result = {};\n if (object == null) {\n return result;\n }\n var isDeep = false;\n paths = arrayMap(paths, function(path) {\n path = castPath(path, object);\n isDeep || (isDeep = path.length > 1);\n return path;\n });\n copyObject(object, getAllKeysIn(object), result);\n if (isDeep) {\n result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n }\n var length = paths.length;\n while (length--) {\n baseUnset(result, paths[length]);\n }\n return result;\n });\n\n /**\n * The opposite of `_.pickBy`; this method creates an object composed of\n * the own and inherited enumerable string keyed properties of `object` that\n * `predicate` doesn't return truthy for. The predicate is invoked with two\n * arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omitBy(object, _.isNumber);\n * // => { 'b': '2' }\n */\n function omitBy(object, predicate) {\n return pickBy(object, negate(getIteratee(predicate)));\n }\n\n /**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\n var pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n });\n\n /**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\n function pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = getIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n }\n\n /**\n * This method is like `_.get` except that if the resolved value is a\n * function it's invoked with the `this` binding of its parent object and\n * its result is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to resolve.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };\n *\n * _.result(object, 'a[0].b.c1');\n * // => 3\n *\n * _.result(object, 'a[0].b.c2');\n * // => 4\n *\n * _.result(object, 'a[0].b.c3', 'default');\n * // => 'default'\n *\n * _.result(object, 'a[0].b.c3', _.constant('default'));\n * // => 'default'\n */\n function result(object, path, defaultValue) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length;\n\n // Ensure the loop is entered when path is empty.\n if (!length) {\n length = 1;\n object = undefined;\n }\n while (++index < length) {\n var value = object == null ? undefined : object[toKey(path[index])];\n if (value === undefined) {\n index = length;\n value = defaultValue;\n }\n object = isFunction(value) ? value.call(object) : value;\n }\n return object;\n }\n\n /**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\n function set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n }\n\n /**\n * This method is like `_.set` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.setWith(object, '[0][1]', 'a', Object);\n * // => { '0': { '1': 'a' } }\n */\n function setWith(object, path, value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseSet(object, path, value, customizer);\n }\n\n /**\n * Creates an array of own enumerable string keyed-value pairs for `object`\n * which can be consumed by `_.fromPairs`. If `object` is a map or set, its\n * entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entries\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairs(new Foo);\n * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)\n */\n var toPairs = createToPairs(keys);\n\n /**\n * Creates an array of own and inherited enumerable string keyed-value pairs\n * for `object` which can be consumed by `_.fromPairs`. If `object` is a map\n * or set, its entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entriesIn\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairsIn(new Foo);\n * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)\n */\n var toPairsIn = createToPairs(keysIn);\n\n /**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own\n * enumerable string keyed properties thru `iteratee`, with each invocation\n * potentially mutating the `accumulator` object. If `accumulator` is not\n * provided, a new object with the same `[[Prototype]]` will be used. The\n * iteratee is invoked with four arguments: (accumulator, value, key, object).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * }, []);\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\n function transform(object, iteratee, accumulator) {\n var isArr = isArray(object),\n isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n iteratee = getIteratee(iteratee, 4);\n if (accumulator == null) {\n var Ctor = object && object.constructor;\n if (isArrLike) {\n accumulator = isArr ? new Ctor : [];\n }\n else if (isObject(object)) {\n accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n }\n else {\n accumulator = {};\n }\n }\n (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n }\n\n /**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\n function unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n }\n\n /**\n * This method is like `_.set` except that accepts `updater` to produce the\n * value to set. Use `_.updateWith` to customize `path` creation. The `updater`\n * is invoked with one argument: (value).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.update(object, 'a[0].b.c', function(n) { return n * n; });\n * console.log(object.a[0].b.c);\n * // => 9\n *\n * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });\n * console.log(object.x[0].y.z);\n * // => 0\n */\n function update(object, path, updater) {\n return object == null ? object : baseUpdate(object, path, castFunction(updater));\n }\n\n /**\n * This method is like `_.update` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.updateWith(object, '[0][1]', _.constant('a'), Object);\n * // => { '0': { '1': 'a' } }\n */\n function updateWith(object, path, updater, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);\n }\n\n /**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\n function values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n }\n\n /**\n * Creates an array of the own and inherited enumerable string keyed property\n * values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.valuesIn(new Foo);\n * // => [1, 2, 3] (iteration order is not guaranteed)\n */\n function valuesIn(object) {\n return object == null ? [] : baseValues(object, keysIn(object));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\n function clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n }\n\n /**\n * Checks if `n` is between `start` and up to, but not including, `end`. If\n * `end` is not specified, it's set to `start` with `start` then set to `0`.\n * If `start` is greater than `end` the params are swapped to support\n * negative ranges.\n *\n * @static\n * @memberOf _\n * @since 3.3.0\n * @category Number\n * @param {number} number The number to check.\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n * @see _.range, _.rangeRight\n * @example\n *\n * _.inRange(3, 2, 4);\n * // => true\n *\n * _.inRange(4, 8);\n * // => true\n *\n * _.inRange(4, 2);\n * // => false\n *\n * _.inRange(2, 2);\n * // => false\n *\n * _.inRange(1.2, 2);\n * // => true\n *\n * _.inRange(5.2, 4);\n * // => false\n *\n * _.inRange(-3, -2, -6);\n * // => true\n */\n function inRange(number, start, end) {\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n number = toNumber(number);\n return baseInRange(number, start, end);\n }\n\n /**\n * Produces a random number between the inclusive `lower` and `upper` bounds.\n * If only one argument is provided a number between `0` and the given number\n * is returned. If `floating` is `true`, or either `lower` or `upper` are\n * floats, a floating-point number is returned instead of an integer.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Number\n * @param {number} [lower=0] The lower bound.\n * @param {number} [upper=1] The upper bound.\n * @param {boolean} [floating] Specify returning a floating-point number.\n * @returns {number} Returns the random number.\n * @example\n *\n * _.random(0, 5);\n * // => an integer between 0 and 5\n *\n * _.random(5);\n * // => also an integer between 0 and 5\n *\n * _.random(5, true);\n * // => a floating-point number between 0 and 5\n *\n * _.random(1.2, 5.2);\n * // => a floating-point number between 1.2 and 5.2\n */\n function random(lower, upper, floating) {\n if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {\n upper = floating = undefined;\n }\n if (floating === undefined) {\n if (typeof upper == 'boolean') {\n floating = upper;\n upper = undefined;\n }\n else if (typeof lower == 'boolean') {\n floating = lower;\n lower = undefined;\n }\n }\n if (lower === undefined && upper === undefined) {\n lower = 0;\n upper = 1;\n }\n else {\n lower = toFinite(lower);\n if (upper === undefined) {\n upper = lower;\n lower = 0;\n } else {\n upper = toFinite(upper);\n }\n }\n if (lower > upper) {\n var temp = lower;\n lower = upper;\n upper = temp;\n }\n if (floating || lower % 1 || upper % 1) {\n var rand = nativeRandom();\n return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);\n }\n return baseRandom(lower, upper);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\n var camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n });\n\n /**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\n function capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n }\n\n /**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\n function deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n }\n\n /**\n * Checks if `string` ends with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=string.length] The position to search up to.\n * @returns {boolean} Returns `true` if `string` ends with `target`,\n * else `false`.\n * @example\n *\n * _.endsWith('abc', 'c');\n * // => true\n *\n * _.endsWith('abc', 'b');\n * // => false\n *\n * _.endsWith('abc', 'b', 2);\n * // => true\n */\n function endsWith(string, target, position) {\n string = toString(string);\n target = baseToString(target);\n\n var length = string.length;\n position = position === undefined\n ? length\n : baseClamp(toInteger(position), 0, length);\n\n var end = position;\n position -= target.length;\n return position >= 0 && string.slice(position, end) == target;\n }\n\n /**\n * Converts the characters \"&\", \"<\", \">\", '\"', and \"'\" in `string` to their\n * corresponding HTML entities.\n *\n * **Note:** No other characters are escaped. To escape additional\n * characters use a third-party library like [_he_](https://mths.be/he).\n *\n * Though the \">\" character is escaped for symmetry, characters like\n * \">\" and \"/\" don't need escaping in HTML and have no special meaning\n * unless they're part of a tag or unquoted attribute value. See\n * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n * (under \"semi-related fun fact\") for more details.\n *\n * When working with HTML you should always\n * [quote attribute values](http://wonko.com/post/html-escaping) to reduce\n * XSS vectors.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escape('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function escape(string) {\n string = toString(string);\n return (string && reHasUnescapedHtml.test(string))\n ? string.replace(reUnescapedHtml, escapeHtmlChar)\n : string;\n }\n\n /**\n * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\n function escapeRegExp(string) {\n string = toString(string);\n return (string && reHasRegExpChar.test(string))\n ? string.replace(reRegExpChar, '\\\\$&')\n : string;\n }\n\n /**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\n var kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n });\n\n /**\n * Converts `string`, as space separated words, to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the lower cased string.\n * @example\n *\n * _.lowerCase('--Foo-Bar--');\n * // => 'foo bar'\n *\n * _.lowerCase('fooBar');\n * // => 'foo bar'\n *\n * _.lowerCase('__FOO_BAR__');\n * // => 'foo bar'\n */\n var lowerCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + word.toLowerCase();\n });\n\n /**\n * Converts the first character of `string` to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.lowerFirst('Fred');\n * // => 'fred'\n *\n * _.lowerFirst('FRED');\n * // => 'fRED'\n */\n var lowerFirst = createCaseFirst('toLowerCase');\n\n /**\n * Pads `string` on the left and right sides if it's shorter than `length`.\n * Padding characters are truncated if they can't be evenly divided by `length`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.pad('abc', 8);\n * // => ' abc '\n *\n * _.pad('abc', 8, '_-');\n * // => '_-abc_-_'\n *\n * _.pad('abc', 3);\n * // => 'abc'\n */\n function pad(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n if (!length || strLength >= length) {\n return string;\n }\n var mid = (length - strLength) / 2;\n return (\n createPadding(nativeFloor(mid), chars) +\n string +\n createPadding(nativeCeil(mid), chars)\n );\n }\n\n /**\n * Pads `string` on the right side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padEnd('abc', 6);\n * // => 'abc '\n *\n * _.padEnd('abc', 6, '_-');\n * // => 'abc_-_'\n *\n * _.padEnd('abc', 3);\n * // => 'abc'\n */\n function padEnd(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (string + createPadding(length - strLength, chars))\n : string;\n }\n\n /**\n * Pads `string` on the left side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padStart('abc', 6);\n * // => ' abc'\n *\n * _.padStart('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padStart('abc', 3);\n * // => 'abc'\n */\n function padStart(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (createPadding(length - strLength, chars) + string)\n : string;\n }\n\n /**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\n function parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n }\n\n /**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=1] The number of times to repeat the string.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\n function repeat(string, n, guard) {\n if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n return baseRepeat(toString(string), n);\n }\n\n /**\n * Replaces matches for `pattern` in `string` with `replacement`.\n *\n * **Note:** This method is based on\n * [`String#replace`](https://mdn.io/String/replace).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to modify.\n * @param {RegExp|string} pattern The pattern to replace.\n * @param {Function|string} replacement The match replacement.\n * @returns {string} Returns the modified string.\n * @example\n *\n * _.replace('Hi Fred', 'Fred', 'Barney');\n * // => 'Hi Barney'\n */\n function replace() {\n var args = arguments,\n string = toString(args[0]);\n\n return args.length < 3 ? string : string.replace(args[1], args[2]);\n }\n\n /**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\n var snakeCase = createCompounder(function(result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n });\n\n /**\n * Splits `string` by `separator`.\n *\n * **Note:** This method is based on\n * [`String#split`](https://mdn.io/String/split).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to split.\n * @param {RegExp|string} separator The separator pattern to split by.\n * @param {number} [limit] The length to truncate results to.\n * @returns {Array} Returns the string segments.\n * @example\n *\n * _.split('a-b-c', '-', 2);\n * // => ['a', 'b']\n */\n function split(string, separator, limit) {\n if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n separator = limit = undefined;\n }\n limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n if (!limit) {\n return [];\n }\n string = toString(string);\n if (string && (\n typeof separator == 'string' ||\n (separator != null && !isRegExp(separator))\n )) {\n separator = baseToString(separator);\n if (!separator && hasUnicode(string)) {\n return castSlice(stringToArray(string), 0, limit);\n }\n }\n return string.split(separator, limit);\n }\n\n /**\n * Converts `string` to\n * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n *\n * @static\n * @memberOf _\n * @since 3.1.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar--');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__FOO_BAR__');\n * // => 'FOO BAR'\n */\n var startCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + upperFirst(word);\n });\n\n /**\n * Checks if `string` starts with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=0] The position to search from.\n * @returns {boolean} Returns `true` if `string` starts with `target`,\n * else `false`.\n * @example\n *\n * _.startsWith('abc', 'a');\n * // => true\n *\n * _.startsWith('abc', 'b');\n * // => false\n *\n * _.startsWith('abc', 'b', 1);\n * // => true\n */\n function startsWith(string, target, position) {\n string = toString(string);\n position = position == null\n ? 0\n : baseClamp(toInteger(position), 0, string.length);\n\n target = baseToString(target);\n return string.slice(position, position + target.length) == target;\n }\n\n /**\n * Creates a compiled template function that can interpolate data properties\n * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n * properties may be accessed as free variables in the template. If a setting\n * object is given, it takes precedence over `_.templateSettings` values.\n *\n * **Note:** In the development build `_.template` utilizes\n * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n * for easier debugging.\n *\n * For more information on precompiling templates see\n * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n *\n * For more information on Chrome extension sandboxes see\n * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The template string.\n * @param {Object} [options={}] The options object.\n * @param {RegExp} [options.escape=_.templateSettings.escape]\n * The HTML \"escape\" delimiter.\n * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]\n * The \"evaluate\" delimiter.\n * @param {Object} [options.imports=_.templateSettings.imports]\n * An object to import into the template as free variables.\n * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]\n * The \"interpolate\" delimiter.\n * @param {string} [options.sourceURL='lodash.templateSources[n]']\n * The sourceURL of the compiled template.\n * @param {string} [options.variable='obj']\n * The data object variable name.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the compiled template function.\n * @example\n *\n * // Use the \"interpolate\" delimiter to create a compiled template.\n * var compiled = _.template('hello <%= user %>!');\n * compiled({ 'user': 'fred' });\n * // => 'hello fred!'\n *\n * // Use the HTML \"escape\" delimiter to escape data property values.\n * var compiled = _.template('<%- value %>');\n * compiled({ 'value': '