wallaby-cash 3.15.0 → 3.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,13 +1,13 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./r/oci-3T3HuAKO.cjs"),t=require("bip39"),r=require("uuid"),s=require("loglevel"),a=require("crypto-js"),n=require("jwt-decode"),i=require("@simplewebauthn/browser"),o=require("js-base64"),c=require("scale-ts"),d=e=>e&&"object"==typeof e&&"default"in e?e:{default:e};function l(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const h=l(t),p=d(s),u=l(i);var y,f,g,w,m,v,S,_,A,E,b,I,P,T,k,C,x,K,O,N,R,D,L,U,B,q;exports.PasskeyChallengeType=void 0,(y=exports.PasskeyChallengeType||(exports.PasskeyChallengeType={})).REGISTRATION="webauthn.create",y.AUTHENTICATION="webauthn.get",exports.PublicKeyCredentialAlgorithm=void 0,(f=exports.PublicKeyCredentialAlgorithm||(exports.PublicKeyCredentialAlgorithm={}))[f.RS256=-257]="RS256",f[f.ES256=-7]="ES256",exports.TransportEnum=void 0,(g=exports.TransportEnum||(exports.TransportEnum={})).Usb="usb",g.Nfc="nfc",g.Ble="ble",g.Internal="internal",g.Hybrid="hybrid";class V extends Error{constructor(e){var t;const{message:r,statusCode:s,errorCode:a,kind:n,data:i,cause:o,onError:c}=e;super(r),this.name="WallabyError",this.status=s,this.errorCode=a,this.kind=null!=n?n:V.inferKind(s,a),this.cause=o,this.onError=c,this.data=i,Object.setPrototypeOf(this,new.target.prototype),null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,new.target)}static isWallabyError(e){return e instanceof V}static inferKind(e,t){return 0===e?"network":"device_storage_unsupported"===t||(null==t?void 0:t.startsWith("sdk_"))?"sdk":"api"}toJSON(){return{name:this.name,message:this.message,kind:this.kind,status:this.status,errorCode:this.errorCode,data:this.data}}}exports.UserAssetSource=void 0,(w=exports.UserAssetSource||(exports.UserAssetSource={})).Merchant="merchant",w.User="user",w.republic="republic",exports.AssetConfigStatus=void 0,(m=exports.AssetConfigStatus||(exports.AssetConfigStatus={})).Active="active",m.Inactive="inactive",exports.AssetType=void 0,(v=exports.AssetType||(exports.AssetType={})).Coin="COIN",v.Token="TOKEN",exports.OwnershipType=void 0,(S=exports.OwnershipType||(exports.OwnershipType={})).SingleOwner="SINGLE_OWNER",S.MultiSig="MULTI_SIG",exports.TokenStandard=void 0,(_=exports.TokenStandard||(exports.TokenStandard={})).Erc20="ERC_20",_.Erc1404="ERC_1404",_.Arc20="ARC_20",_.Arc1404="ARC_1404",_.Mrc20="MRC_20",_.Bep20="BEP_20",_.AlgoStandard="ALGO_STANDARD",_.AlgoApp="ALGO_APP",_.TokenFactory="TOKEN_FACTORY",_.SeiErc20="SEI_ERC_20",_.AptFA="APT_FUNGIBLE_ASSET",exports.AddressType=void 0,(A=exports.AddressType||(exports.AddressType={})).Segwit="SEGWIT",A.Legacy="LEGACY",A.Default="DEFAULT",exports.BlockchainStatus=void 0,(E=exports.BlockchainStatus||(exports.BlockchainStatus={})).Up="UP",E.Down="DOWN",exports.BlockchainSlip44=void 0,(b=exports.BlockchainSlip44||(exports.BlockchainSlip44={}))[b.BTC=0]="BTC",b[b.ETH=60]="ETH",b[b.ALGO=283]="ALGO",b[b.AVAX=9e3]="AVAX",b[b.MATIC=966]="MATIC",b[b.BSC=519]="BSC",b[b.BASE=8453]="BASE",b[b.SUI=784]="SUI",b[b.INJ=2525]="INJ",b[b.SEI=19000118]="SEI",b[b.APT=637]="APT",b[b.HBAR=3030]="HBAR",b[b.POLYX=595]="POLYX",exports.BlockchainName=void 0,(I=exports.BlockchainName||(exports.BlockchainName={})).Algorand="ALGORAND",I.Aptos="APTOS",I.Avalanche="AVALANCHE",I.Base="BASE",I.Bitcoin="BITCOIN",I.Bsc="BSC",I.Canton="CANTON",I.Ethereum="ETHEREUM",I.Hedera="HEDERA",I.Injective="INJECTIVE",I.Polygon="POLYGON",I.Polymesh="POLYMESH",I.Sei="SEI",I.Sui="SUI",I.Solana="SOLANA",exports.RequestMethod=void 0,(P=exports.RequestMethod||(exports.RequestMethod={})).Post="POST",P.Get="GET",P.Put="PUT",P.Delete="DELETE",exports.ApiKeyStatus=void 0,(T=exports.ApiKeyStatus||(exports.ApiKeyStatus={})).Active="active",T.Inactive="inactive",exports.TransactionEntryType=void 0,(k=exports.TransactionEntryType||(exports.TransactionEntryType={})).INCOMING="INCOMING",k.OUTGOING="OUTGOING",k.UNKNOWN="UNKNOWN",exports.KeyTypeName=void 0,(C=exports.KeyTypeName||(exports.KeyTypeName={})).WallabyShare="wallaby_share",C.OwnerMainDeviceShare="owner_main_device_share",C.OwnerBackupDeviceShare="owner_backup_device_share",exports.SeedPhraseType=void 0,(x=exports.SeedPhraseType||(exports.SeedPhraseType={})).Standard="standard",x.Algorand="algorand",exports.WalletAddressTypeName=void 0,(K=exports.WalletAddressTypeName||(exports.WalletAddressTypeName={})).BTC_MAINNET_SEGWIT="BTC:MAINNET:SEGWIT",K.BTC_MAINNET_LEGACY="BTC:MAINNET:LEGACY",K.BTC_TESTNET_SEGWIT="BTC:TESTNET:SEGWIT",K.BTC_TESTNET_LEGACY="BTC:TESTNET:LEGACY",K.ETH="ETH:ALL:DEFAULT",K.ALGO="ALGO:ALL:DEFAULT",K.SUI="SUI:ALL:DEFAULT",K.INJ="INJ:ALL:DEFAULT",K.APT="APT:ALL:DEFAULT",K.POLYX="POLYX:ALL:DEFAULT",K.BSC="BSC:ALL:DEFAULT",K.AVAX="AVAX:ALL:DEFAULT",K.MATIC="MATIC:ALL:DEFAULT",K.BASE="BASE:ALL:DEFAULT",K.SEI="SEI:ALL:DEFAULT",K.HBAR="HBAR:ALL:DEFAULT",K.CC="CC:ALL:DEFAULT",exports.ReturnWalletOption=void 0,(O=exports.ReturnWalletOption||(exports.ReturnWalletOption={})).ReturnOnlyEncryptedShares="RETURN_ONLY_ENCRYPTED_SHARES",O.ReturnOnlyEncryptedSeedPhrase="RETURN_ONLY_ENCRYPTED_SEED_PHRASE",O.ReturnBothEncryptedSharesAndSeed="RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED",exports.WalletOwnershipType=void 0,(N=exports.WalletOwnershipType||(exports.WalletOwnershipType={})).SingleOwner="SINGLE_OWNER",N.MultiOwner="MULTI_OWNER",exports.AuthType=void 0,(R=exports.AuthType||(exports.AuthType={})).Password="password",R.Passkey="passkey",exports.LocalStorageItems=void 0,(D=exports.LocalStorageItems||(exports.LocalStorageItems={})).AccessToken="access-token",D.RefreshToken="refresh-token",D.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",D.EncryptedKeyShares="encrypted-key-shares",D.PrimaryDeviceKeyShare="primary-device-key-share",D.BackupDeviceKeyShare="backup-device-key-share",D.EncryptedShare="encrypted-share",D.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",D.EncryptedDevicePrivateKey="encrypted-private-key",D.ClientAuthPublicKey="client-auth-pub-key",D.ClientAuthToken="republic-jwt",D.PasskeyCredential="pass-key-credential",D.Blob="blob",exports.LegacyKeyNames=void 0,(L=exports.LegacyKeyNames||(exports.LegacyKeyNames={})).EncryptedPrivateKey="encryptedPrivateKey",L.WallabyAuthPubKey="wallabyAuthPubKey",L.EncryptedAlgorandSeed="encryptedAlgorandSeed",L.EncryptedSeed="encryptedSeed",L.ClientAuthToken="republic_jwt",L.AccessToken="accessToken",exports.V1KeyNames=void 0,(U=exports.V1KeyNames||(exports.V1KeyNames={})).AccessToken="access-token",U.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",U.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",U.EncryptedDevicePrivateKey="encrypted-private-key",U.ClientAuthPublicKey="client-auth-pub-key",U.WallabyAuthPubKey="wallaby-auth-pub-key",U.ClientAuthToken="republic-jwt",exports.V2KeyNames=void 0,(B=exports.V2KeyNames||(exports.V2KeyNames={})).AccessToken="access-token",B.RefreshToken="refresh-token",B.BackupDeviceKeyShare="backup-device-key-share",B.ClientAuthPublicKey="client-auth-pub-key",B.ClientAuthToken="republic-jwt",B.EncryptedDevicePrivateKey="encrypted-private-key",B.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",B.PasskeyCredential="pass-key-credential",B.PrimaryDeviceKeyShare="primary-device-key-share",B.WallabyAuthPubKey="wallaby-auth-pub-key",B.MigrationVersion="wsdk_migrated_with_version",B.LastMigratedAt="wsdk_last_migrated_at",B.PasswordResetAttempts="wsdk_password_reset_attempts",B.MigrationAttempts="wsdk_migration_attempts",B.CredentialConversionInProgress="credential-conversion-in-progress",B.PendingCommit="pending-commit",B.LegacySeedClaimedWalletId="wsdk_legacy_seed_claimed_wallet_id",exports.ErrorResponseCodes=void 0,(q=exports.ErrorResponseCodes||(exports.ErrorResponseCodes={})).unknown_error="unknown_error",q.internal_server_error="internal_server_error",q.request_payload_missing="request_payload_missing",q.request_payload_wrong_format="request_payload_wrong_format",q.auth_api_key_invalid="auth_api_key_invalid",q.auth_api_key_not_active="auth_api_key_not_active",q.auth_api_key_pub_key_not_set="auth_api_key_pub_key_not_set",q.auth_api_key_pub_key_already_in_use="auth_api_key_pub_key_already_in_use",q.auth_api_key_not_provided="auth_api_key_not_provided",q.auth_api_key_not_found="auth_api_key_not_found",q.auth_origin_not_allowed="auth_origin_not_allowed",q.auth_api_jwt_invalid="auth_api_jwt_invalid",q.auth_api_jwt_not_active="auth_api_jwt_not_active",q.auth_api_jwt_not_provided="auth_api_jwt_not_provided",q.auth_api_jwt_expired="auth_api_jwt_expired",q.auth_api_unauthorized="auth_api_unauthorized",q.auth_client_jwt_invalid="auth_client_jwt_invalid",q.auth_client_jwt_missing_external_id_payload="auth_client_jwt_missing_external_id_payload",q.auth_client_jwt_missing_exp_payload="auth_client_jwt_missing_exp_payload",q.auth_client_jwt_external_id_not_match="auth_client_jwt_external_id_not_match",q.auth_client_jwt_expired="auth_client_jwt_expired",q.auth_client_jwt_not_provided="auth_client_jwt_not_provided",q.auth_client_jwt_invalid_auth_type="auth_client_jwt_invalid_auth_type",q.auth_client_jwt_invalid_passkey="auth_client_jwt_invalid_passkey",q.auth_client_pub_key_and_message_not_match="auth_client_pub_key_and_message_not_match",q.auth_client_pub_key_and_message_expired="auth_client_pub_key_and_message_expired",q.auth_client_pub_key_and_message_signature_failed="auth_client_pub_key_and_message_signature_failed",q.auth_client_pub_key_not_found="auth_client_pub_key_not_found",q.auth_client_pub_key_already_registered="auth_client_pub_key_already_registered",q.auth_user_not_allowed_to_perform_the_action="auth_user_not_allowed_to_perform_the_action",q.auth_upside_signature_not_provided="auth_upside_signature_not_provided",q.auth_upside_signature_invalid="auth_upside_signature_invalid",q.auth_upside_wrong_base64_signature="auth_upside_wrong_base64_signature",q.multisig_participant_not_found="multisig_participant_not_found",q.wallet_not_found="wallet_not_found",q.wallet_recovery_seed_mismatch="wallet_recovery_seed_mismatch",q.wallet_address_not_found="wallet_address_not_found",q.wallet_address_generation_failed="wallet_address_generation_failed",q.invalid_public_key="invalid_public_key",q.canton_registration_daily_limit_exceeded="canton_registration_daily_limit_exceeded",q.asset_not_found="asset_not_found",q.seedphrase_could_not_be_decrypted="seedphrase_could_not_be_decrypted",q.invalid_seed_phrase="invalid_seed_phrase",q.user_already_exists="user_already_exists",q.user_not_found="user_not_found",q.otp_code_invalid="otp_code_invalid",q.otp_code_expired="otp_code_expired",q.merchant_not_found="merchant_not_found",q.swap_provider_not_found="swap_provider_not_found",q.swap_chain_not_supported="swap_chain_not_supported",q.swap_asset_not_supported="swap_asset_not_supported",q.swap_quote_executing="swap_quote_executing",q.swap_quote_in_progress="swap_quote_in_progress",q.swap_quote_completed="swap_quote_completed",q.swap_quote_failed="swap_quote_failed",q.swap_quote_abandoned="swap_quote_abandoned",q.swap_quote_execution_failed="swap_quote_execution_failed",q.swap_quote_invalid="swap_quote_invalid",q.feature_not_enabled="feature_not_enabled",q.insufficient_balance="insufficient_balance",q.transaction_failed="transaction_failed",q.invalid_number_of_signatures="invalid_number_of_signatures",q.invalid_signature="invalid_signature",q.chain_adapter_not_found="chain_adapter_not_found",q.chain_not_found="chain_not_found",q.invalid_address="invalid_address",q.auth_refresh_token_not_found="auth_refresh_token_not_found",q.auth_refresh_token_expired="auth_refresh_token_expired",q.auth_refresh_token_reuse_detected="auth_refresh_token_reuse_detected",q.sdk_jwt_invalid="sdk_jwt_invalid",q.sdk_jwt_expired="sdk_jwt_expired",q.sdk_unknown_error="sdk_unknown_error",q.sdk_too_many_requests="sdk_too_many_requests",q.sdk_seed_phrase_decryption_failed="sdk_seed_phrase_decryption_failed",q.sdk_key_shares_not_found="sdk_key_shares_not_found",q.sdk_key_share_decryption_failed="sdk_key_share_decryption_failed",q.sdk_seed_phrase_not_found="sdk_seed_phrase_not_found",q.sdk_private_key_decryption_failed="sdk_private_key_decryption_failed",q.sdk_private_key_not_found="sdk_private_key_not_found",q.sdk_device_key_missing_with_existing_data="sdk_device_key_missing_with_existing_data",q.sdk_refresh_token_missing="sdk_refresh_token_missing",q.sdk_missing_parameter="sdk_missing_parameter",q.sdk_invalid_parameter="sdk_invalid_parameter",q.sdk_invalid_response="sdk_invalid_response",q.sdk_wrong_password="sdk_wrong_password",q.sdk_no_valid_seed_option="sdk_no_valid_seed_option",q.sdk_ambiguous_legacy_migration_data="sdk_ambiguous_legacy_migration_data",q.sdk_passkey_prf_not_available="sdk_passkey_prf_not_available",q.sdk_passkey_challenge_unavailable="sdk_passkey_challenge_unavailable",q.sdk_passkey_authentication_failed="sdk_passkey_authentication_failed",q.sdk_passkey_registration_failed="sdk_passkey_registration_failed";const M={error:"UnknownError",message:"An unknown error occurred"},W={error:"IOSVersionNotSupportedError",message:"Passkeys are not supported on this device. iOS 15 and above is required to use Passkeys"},F={error:"AndroidVersionNotSupportedError",message:"Passkeys are not supported on this device. Android 9 and above is required to use Passkeys"},G={error:"RequestFailed",message:"The request failed. No Credentials were returned."},j={error:"UserCancelled",message:"The user cancelled the request."},H={error:"InvalidChallenge",message:"The provided challenge was invalid"},$={error:"InvalidUserId",message:"The provided userId was invalid"},Y={error:"BadConfiguration",message:"Your app is not properly configured. Refer to the docs for help."},z={error:"NoCredentials",message:"No viable credential is available for the user."},J={error:"Interrupted",message:"The operation was interrupted and may be retried."},X={error:"TimedOut",message:"The operation timed out."},Z={error:"ERROR_CEREMONY_ABORTED",message:"User did not complete the request in time."},Q={error:"ERROR_INVALID_DOMAIN",message:"Invalid domain."},ee={error:"ERROR_INVALID_RP_ID",message:"Invalid Relying Party ID."},te={error:"ERROR_INVALID_USER_ID_LENGTH",message:"Invalid user ID length."},re={error:"ERROR_MALFORMED_PUBKEYCREDPARAMS",message:"Malformed public key credential parameters."},se={error:"ERROR_AUTHENTICATOR_GENERAL_ERROR",message:"Authenticator encountered a general error."},ae={error:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",message:"Authenticator does not support discoverable credentials."},ne={error:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",message:"Authenticator does not support user verification."},ie={error:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",message:"Authenticator was previously registered."},oe={error:"InvalidStateError",message:"The authenticator was previously registered"},ce={error:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",message:"Authenticator does not support any of the provided public key credential parameters algorithms."},de={error:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",message:"User verification failed during auto-registration."},le={error:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",message:"An error occurred. See the cause property for more details."},he=[M,W,F,G,j,H,$,Y,z,J,X,Z,Q,ee,te,re,se,ae,ne,ie,ce,de,le];let pe=!1;"undefined"!=typeof window&&window.localStorage&&(pe="true"===window.localStorage.getItem("wsdk:enable_logging")),pe&&p.default.setLevel("trace");const ue=p.default;var ye,fe=("undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}).performance||{};fe.now||fe.mozNow||fe.msNow||fe.oNow||fe.webkitNow;const ge=null!==(ye={env:{}}.env.NODE_ENV)&&void 0!==ye?ye:"development",we="testnet",me="9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe75d907fe6db9e4c";exports.PublicKeyCredentialAlgorithm.RS256,exports.PublicKeyCredentialAlgorithm.ES256;const ve="undefined"!=typeof window&&"undefined"!=typeof document,Se={platform:"web",isNative:!ve,isWeb:ve},_e="3.15.0",Ae="x-sdk-version",Ee=`wallaby-cash/${_e}`,be=e=>e.replace(/:/g,"_"),Ie="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Pe(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Te(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./r/oci-3T3HuAKO.cjs"),t=require("bip39"),r=require("uuid"),s=require("loglevel"),a=require("crypto-js"),n=require("jwt-decode"),i=require("@simplewebauthn/browser"),o=require("js-base64"),c=require("scale-ts"),d=e=>e&&"object"==typeof e&&"default"in e?e:{default:e};function l(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const h=l(t),u=d(s),p=l(i);var y,f,g,w,m,v,S,_,A,E,b,I,P,T,k,C,x,K,O,N,R,D,L,U,B,q;exports.PasskeyChallengeType=void 0,(y=exports.PasskeyChallengeType||(exports.PasskeyChallengeType={})).REGISTRATION="webauthn.create",y.AUTHENTICATION="webauthn.get",exports.PublicKeyCredentialAlgorithm=void 0,(f=exports.PublicKeyCredentialAlgorithm||(exports.PublicKeyCredentialAlgorithm={}))[f.RS256=-257]="RS256",f[f.ES256=-7]="ES256",exports.TransportEnum=void 0,(g=exports.TransportEnum||(exports.TransportEnum={})).Usb="usb",g.Nfc="nfc",g.Ble="ble",g.Internal="internal",g.Hybrid="hybrid";class V extends Error{constructor(e){var t;const{message:r,statusCode:s,errorCode:a,kind:n,data:i,cause:o,onError:c}=e;super(r),this.name="WallabyError",this.status=s,this.errorCode=a,this.kind=null!=n?n:V.inferKind(s,a),this.cause=o,this.onError=c,this.data=i,Object.setPrototypeOf(this,new.target.prototype),null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,new.target)}static isWallabyError(e){return e instanceof V}static inferKind(e,t){return 0===e?"network":"device_storage_unsupported"===t||(null==t?void 0:t.startsWith("sdk_"))?"sdk":"api"}toJSON(){return{name:this.name,message:this.message,kind:this.kind,status:this.status,errorCode:this.errorCode,data:this.data}}}exports.UserAssetSource=void 0,(w=exports.UserAssetSource||(exports.UserAssetSource={})).Merchant="merchant",w.User="user",w.republic="republic",exports.AssetConfigStatus=void 0,(m=exports.AssetConfigStatus||(exports.AssetConfigStatus={})).Active="active",m.Inactive="inactive",exports.AssetType=void 0,(v=exports.AssetType||(exports.AssetType={})).Coin="COIN",v.Token="TOKEN",exports.OwnershipType=void 0,(S=exports.OwnershipType||(exports.OwnershipType={})).SingleOwner="SINGLE_OWNER",S.MultiSig="MULTI_SIG",exports.TokenStandard=void 0,(_=exports.TokenStandard||(exports.TokenStandard={})).Erc20="ERC_20",_.Erc1404="ERC_1404",_.Arc20="ARC_20",_.Arc1404="ARC_1404",_.Mrc20="MRC_20",_.Bep20="BEP_20",_.AlgoStandard="ALGO_STANDARD",_.AlgoApp="ALGO_APP",_.TokenFactory="TOKEN_FACTORY",_.SeiErc20="SEI_ERC_20",_.AptFA="APT_FUNGIBLE_ASSET",exports.AddressType=void 0,(A=exports.AddressType||(exports.AddressType={})).Segwit="SEGWIT",A.Legacy="LEGACY",A.Default="DEFAULT",exports.BlockchainStatus=void 0,(E=exports.BlockchainStatus||(exports.BlockchainStatus={})).Up="UP",E.Down="DOWN",exports.BlockchainSlip44=void 0,(b=exports.BlockchainSlip44||(exports.BlockchainSlip44={}))[b.BTC=0]="BTC",b[b.ETH=60]="ETH",b[b.ALGO=283]="ALGO",b[b.AVAX=9e3]="AVAX",b[b.MATIC=966]="MATIC",b[b.BSC=519]="BSC",b[b.BASE=8453]="BASE",b[b.SUI=784]="SUI",b[b.INJ=2525]="INJ",b[b.SEI=19000118]="SEI",b[b.APT=637]="APT",b[b.HBAR=3030]="HBAR",b[b.POLYX=595]="POLYX",exports.BlockchainName=void 0,(I=exports.BlockchainName||(exports.BlockchainName={})).Algorand="ALGORAND",I.Aptos="APTOS",I.Avalanche="AVALANCHE",I.Base="BASE",I.Bitcoin="BITCOIN",I.Bsc="BSC",I.Canton="CANTON",I.Ethereum="ETHEREUM",I.Hedera="HEDERA",I.Injective="INJECTIVE",I.Polygon="POLYGON",I.Polymesh="POLYMESH",I.Sei="SEI",I.Sui="SUI",I.Solana="SOLANA",exports.RequestMethod=void 0,(P=exports.RequestMethod||(exports.RequestMethod={})).Post="POST",P.Get="GET",P.Put="PUT",P.Delete="DELETE",exports.ApiKeyStatus=void 0,(T=exports.ApiKeyStatus||(exports.ApiKeyStatus={})).Active="active",T.Inactive="inactive",exports.TransactionEntryType=void 0,(k=exports.TransactionEntryType||(exports.TransactionEntryType={})).INCOMING="INCOMING",k.OUTGOING="OUTGOING",k.UNKNOWN="UNKNOWN",exports.KeyTypeName=void 0,(C=exports.KeyTypeName||(exports.KeyTypeName={})).WallabyShare="wallaby_share",C.OwnerMainDeviceShare="owner_main_device_share",C.OwnerBackupDeviceShare="owner_backup_device_share",exports.SeedPhraseType=void 0,(x=exports.SeedPhraseType||(exports.SeedPhraseType={})).Standard="standard",x.Algorand="algorand",exports.WalletAddressTypeName=void 0,(K=exports.WalletAddressTypeName||(exports.WalletAddressTypeName={})).BTC_MAINNET_SEGWIT="BTC:MAINNET:SEGWIT",K.BTC_MAINNET_LEGACY="BTC:MAINNET:LEGACY",K.BTC_TESTNET_SEGWIT="BTC:TESTNET:SEGWIT",K.BTC_TESTNET_LEGACY="BTC:TESTNET:LEGACY",K.ETH="ETH:ALL:DEFAULT",K.ALGO="ALGO:ALL:DEFAULT",K.SUI="SUI:ALL:DEFAULT",K.INJ="INJ:ALL:DEFAULT",K.APT="APT:ALL:DEFAULT",K.POLYX="POLYX:ALL:DEFAULT",K.BSC="BSC:ALL:DEFAULT",K.AVAX="AVAX:ALL:DEFAULT",K.MATIC="MATIC:ALL:DEFAULT",K.BASE="BASE:ALL:DEFAULT",K.SEI="SEI:ALL:DEFAULT",K.HBAR="HBAR:ALL:DEFAULT",K.CC="CC:ALL:DEFAULT",exports.ReturnWalletOption=void 0,(O=exports.ReturnWalletOption||(exports.ReturnWalletOption={})).ReturnOnlyEncryptedShares="RETURN_ONLY_ENCRYPTED_SHARES",O.ReturnOnlyEncryptedSeedPhrase="RETURN_ONLY_ENCRYPTED_SEED_PHRASE",O.ReturnBothEncryptedSharesAndSeed="RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED",exports.WalletOwnershipType=void 0,(N=exports.WalletOwnershipType||(exports.WalletOwnershipType={})).SingleOwner="SINGLE_OWNER",N.MultiOwner="MULTI_OWNER",exports.AuthType=void 0,(R=exports.AuthType||(exports.AuthType={})).Password="password",R.Passkey="passkey",exports.LocalStorageItems=void 0,(D=exports.LocalStorageItems||(exports.LocalStorageItems={})).AccessToken="access-token",D.RefreshToken="refresh-token",D.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",D.EncryptedKeyShares="encrypted-key-shares",D.PrimaryDeviceKeyShare="primary-device-key-share",D.BackupDeviceKeyShare="backup-device-key-share",D.EncryptedShare="encrypted-share",D.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",D.EncryptedDevicePrivateKey="encrypted-private-key",D.ClientAuthPublicKey="client-auth-pub-key",D.ClientAuthToken="republic-jwt",D.PasskeyCredential="pass-key-credential",D.Blob="blob",exports.LegacyKeyNames=void 0,(L=exports.LegacyKeyNames||(exports.LegacyKeyNames={})).EncryptedPrivateKey="encryptedPrivateKey",L.WallabyAuthPubKey="wallabyAuthPubKey",L.EncryptedAlgorandSeed="encryptedAlgorandSeed",L.EncryptedSeed="encryptedSeed",L.ClientAuthToken="republic_jwt",L.AccessToken="accessToken",exports.V1KeyNames=void 0,(U=exports.V1KeyNames||(exports.V1KeyNames={})).AccessToken="access-token",U.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",U.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",U.EncryptedDevicePrivateKey="encrypted-private-key",U.ClientAuthPublicKey="client-auth-pub-key",U.WallabyAuthPubKey="wallaby-auth-pub-key",U.ClientAuthToken="republic-jwt",exports.V2KeyNames=void 0,(B=exports.V2KeyNames||(exports.V2KeyNames={})).AccessToken="access-token",B.RefreshToken="refresh-token",B.BackupDeviceKeyShare="backup-device-key-share",B.ClientAuthPublicKey="client-auth-pub-key",B.ClientAuthToken="republic-jwt",B.EncryptedDevicePrivateKey="encrypted-private-key",B.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",B.PasskeyCredential="pass-key-credential",B.PrimaryDeviceKeyShare="primary-device-key-share",B.WallabyAuthPubKey="wallaby-auth-pub-key",B.MigrationVersion="wsdk_migrated_with_version",B.LastMigratedAt="wsdk_last_migrated_at",B.PasswordResetAttempts="wsdk_password_reset_attempts",B.MigrationAttempts="wsdk_migration_attempts",B.CredentialConversionInProgress="credential-conversion-in-progress",B.PendingCommit="pending-commit",B.LegacySeedClaimedWalletId="wsdk_legacy_seed_claimed_wallet_id",exports.ErrorResponseCodes=void 0,(q=exports.ErrorResponseCodes||(exports.ErrorResponseCodes={})).unknown_error="unknown_error",q.internal_server_error="internal_server_error",q.request_payload_missing="request_payload_missing",q.request_payload_wrong_format="request_payload_wrong_format",q.auth_api_key_invalid="auth_api_key_invalid",q.auth_api_key_not_active="auth_api_key_not_active",q.auth_api_key_pub_key_not_set="auth_api_key_pub_key_not_set",q.auth_api_key_pub_key_already_in_use="auth_api_key_pub_key_already_in_use",q.auth_api_key_not_provided="auth_api_key_not_provided",q.auth_api_key_not_found="auth_api_key_not_found",q.auth_origin_not_allowed="auth_origin_not_allowed",q.auth_api_jwt_invalid="auth_api_jwt_invalid",q.auth_api_jwt_not_active="auth_api_jwt_not_active",q.auth_api_jwt_not_provided="auth_api_jwt_not_provided",q.auth_api_jwt_expired="auth_api_jwt_expired",q.auth_api_unauthorized="auth_api_unauthorized",q.auth_client_jwt_invalid="auth_client_jwt_invalid",q.auth_client_jwt_missing_external_id_payload="auth_client_jwt_missing_external_id_payload",q.auth_client_jwt_missing_exp_payload="auth_client_jwt_missing_exp_payload",q.auth_client_jwt_external_id_not_match="auth_client_jwt_external_id_not_match",q.auth_client_jwt_expired="auth_client_jwt_expired",q.auth_client_jwt_not_provided="auth_client_jwt_not_provided",q.auth_client_jwt_invalid_auth_type="auth_client_jwt_invalid_auth_type",q.auth_client_jwt_invalid_passkey="auth_client_jwt_invalid_passkey",q.auth_client_pub_key_and_message_not_match="auth_client_pub_key_and_message_not_match",q.auth_client_pub_key_and_message_expired="auth_client_pub_key_and_message_expired",q.auth_client_pub_key_and_message_signature_failed="auth_client_pub_key_and_message_signature_failed",q.auth_client_pub_key_not_found="auth_client_pub_key_not_found",q.auth_client_pub_key_already_registered="auth_client_pub_key_already_registered",q.auth_user_not_allowed_to_perform_the_action="auth_user_not_allowed_to_perform_the_action",q.auth_upside_signature_not_provided="auth_upside_signature_not_provided",q.auth_upside_signature_invalid="auth_upside_signature_invalid",q.auth_upside_wrong_base64_signature="auth_upside_wrong_base64_signature",q.multisig_participant_not_found="multisig_participant_not_found",q.wallet_not_found="wallet_not_found",q.wallet_recovery_seed_mismatch="wallet_recovery_seed_mismatch",q.wallet_address_not_found="wallet_address_not_found",q.wallet_address_generation_failed="wallet_address_generation_failed",q.invalid_public_key="invalid_public_key",q.canton_registration_daily_limit_exceeded="canton_registration_daily_limit_exceeded",q.asset_not_found="asset_not_found",q.seedphrase_could_not_be_decrypted="seedphrase_could_not_be_decrypted",q.invalid_seed_phrase="invalid_seed_phrase",q.user_already_exists="user_already_exists",q.user_not_found="user_not_found",q.otp_code_invalid="otp_code_invalid",q.otp_code_expired="otp_code_expired",q.merchant_not_found="merchant_not_found",q.swap_provider_not_found="swap_provider_not_found",q.swap_chain_not_supported="swap_chain_not_supported",q.swap_asset_not_supported="swap_asset_not_supported",q.swap_quote_executing="swap_quote_executing",q.swap_quote_in_progress="swap_quote_in_progress",q.swap_quote_completed="swap_quote_completed",q.swap_quote_failed="swap_quote_failed",q.swap_quote_abandoned="swap_quote_abandoned",q.swap_quote_execution_failed="swap_quote_execution_failed",q.swap_quote_invalid="swap_quote_invalid",q.feature_not_enabled="feature_not_enabled",q.insufficient_balance="insufficient_balance",q.transaction_failed="transaction_failed",q.invalid_number_of_signatures="invalid_number_of_signatures",q.invalid_signature="invalid_signature",q.chain_adapter_not_found="chain_adapter_not_found",q.chain_not_found="chain_not_found",q.invalid_address="invalid_address",q.auth_refresh_token_not_found="auth_refresh_token_not_found",q.auth_refresh_token_expired="auth_refresh_token_expired",q.auth_refresh_token_reuse_detected="auth_refresh_token_reuse_detected",q.sdk_jwt_invalid="sdk_jwt_invalid",q.sdk_jwt_expired="sdk_jwt_expired",q.sdk_unknown_error="sdk_unknown_error",q.sdk_too_many_requests="sdk_too_many_requests",q.sdk_seed_phrase_decryption_failed="sdk_seed_phrase_decryption_failed",q.sdk_key_shares_not_found="sdk_key_shares_not_found",q.sdk_key_share_decryption_failed="sdk_key_share_decryption_failed",q.sdk_seed_phrase_not_found="sdk_seed_phrase_not_found",q.sdk_private_key_decryption_failed="sdk_private_key_decryption_failed",q.sdk_private_key_not_found="sdk_private_key_not_found",q.sdk_device_key_missing_with_existing_data="sdk_device_key_missing_with_existing_data",q.sdk_refresh_token_missing="sdk_refresh_token_missing",q.sdk_missing_parameter="sdk_missing_parameter",q.sdk_invalid_parameter="sdk_invalid_parameter",q.sdk_invalid_response="sdk_invalid_response",q.sdk_wrong_password="sdk_wrong_password",q.sdk_no_valid_seed_option="sdk_no_valid_seed_option",q.sdk_ambiguous_legacy_migration_data="sdk_ambiguous_legacy_migration_data",q.sdk_passkey_prf_not_available="sdk_passkey_prf_not_available",q.sdk_passkey_challenge_unavailable="sdk_passkey_challenge_unavailable",q.sdk_passkey_authentication_failed="sdk_passkey_authentication_failed",q.sdk_passkey_registration_failed="sdk_passkey_registration_failed";const M={error:"UnknownError",message:"An unknown error occurred"},W={error:"IOSVersionNotSupportedError",message:"Passkeys are not supported on this device. iOS 15 and above is required to use Passkeys"},F={error:"AndroidVersionNotSupportedError",message:"Passkeys are not supported on this device. Android 9 and above is required to use Passkeys"},G={error:"RequestFailed",message:"The request failed. No Credentials were returned."},j={error:"UserCancelled",message:"The user cancelled the request."},H={error:"InvalidChallenge",message:"The provided challenge was invalid"},$={error:"InvalidUserId",message:"The provided userId was invalid"},Y={error:"BadConfiguration",message:"Your app is not properly configured. Refer to the docs for help."},z={error:"NoCredentials",message:"No viable credential is available for the user."},J={error:"Interrupted",message:"The operation was interrupted and may be retried."},X={error:"TimedOut",message:"The operation timed out."},Z={error:"ERROR_CEREMONY_ABORTED",message:"User did not complete the request in time."},Q={error:"ERROR_INVALID_DOMAIN",message:"Invalid domain."},ee={error:"ERROR_INVALID_RP_ID",message:"Invalid Relying Party ID."},te={error:"ERROR_INVALID_USER_ID_LENGTH",message:"Invalid user ID length."},re={error:"ERROR_MALFORMED_PUBKEYCREDPARAMS",message:"Malformed public key credential parameters."},se={error:"ERROR_AUTHENTICATOR_GENERAL_ERROR",message:"Authenticator encountered a general error."},ae={error:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",message:"Authenticator does not support discoverable credentials."},ne={error:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",message:"Authenticator does not support user verification."},ie={error:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",message:"Authenticator was previously registered."},oe={error:"InvalidStateError",message:"The authenticator was previously registered"},ce={error:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",message:"Authenticator does not support any of the provided public key credential parameters algorithms."},de={error:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",message:"User verification failed during auto-registration."},le={error:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",message:"An error occurred. See the cause property for more details."},he=[M,W,F,G,j,H,$,Y,z,J,X,Z,Q,ee,te,re,se,ae,ne,ie,ce,de,le];let ue=!1;"undefined"!=typeof window&&window.localStorage&&(ue="true"===window.localStorage.getItem("wsdk:enable_logging")),ue&&u.default.setLevel("trace");const pe=u.default;var ye,fe=("undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}).performance||{};fe.now||fe.mozNow||fe.msNow||fe.oNow||fe.webkitNow;const ge=null!==(ye={env:{}}.env.NODE_ENV)&&void 0!==ye?ye:"development",we="testnet",me="9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe75d907fe6db9e4c";exports.PublicKeyCredentialAlgorithm.RS256,exports.PublicKeyCredentialAlgorithm.ES256;const ve="undefined"!=typeof window&&"undefined"!=typeof document,Se={platform:"web",isNative:!ve,isWeb:ve},_e="3.15.1",Ae="x-sdk-version",Ee=`wallaby-cash/${_e}`,be=e=>e.replace(/:/g,"_"),Ie="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Pe(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Te(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
2
2
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3
3
  var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ke(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Pe(e.outputLen),Pe(e.blockLen)}function Ce(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function xe(e,t){Te(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ke(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Oe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ne(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Re(e,t){return e<<32-t|e>>>t}const De=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Le(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Ue=De?e=>e:e=>Le(e);const Be=De?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Le(e[t]);return e},qe=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Ve=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Me(e){if(Te(e),qe)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Ve[e[r]];return t}const We=48,Fe=57,Ge=65,je=70,He=97,$e=102;function Ye(e){return e>=We&&e<=Fe?e-We:e>=Ge&&e<=je?e-(Ge-10):e>=He&&e<=$e?e-(He-10):void 0}function ze(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Je(e){return"string"==typeof e&&(e=ze(e)),Te(e),e}function Xe(e){return"string"==typeof e&&(e=ze(e)),Te(e),e}class Ze{}function Qe(e){const t=t=>e().update(Je(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function et(e){const t=(t,r)=>e(r).update(Je(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}function tt(e=32){if(Ie&&"function"==typeof Ie.getRandomValues)return Ie.getRandomValues(new Uint8Array(e));if(Ie&&"function"==typeof Ie.randomBytes)return Uint8Array.from(Ie.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function rt(e){return tt(e)}
4
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const st=BigInt(0),at=BigInt(1);function nt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function it(e){if(!nt(e))throw new Error("Uint8Array expected")}function ot(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function ct(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function dt(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?st:BigInt("0x"+e)}const lt="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,ht=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function pt(e){if(it(e),lt)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=ht[e[r]];return t}const ut=48,yt=57,ft=65,gt=70,wt=97,mt=102;function vt(e){return e>=ut&&e<=yt?e-ut:e>=ft&&e<=gt?e-(ft-10):e>=wt&&e<=mt?e-(wt-10):void 0}function St(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(lt)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){const r=vt(e.charCodeAt(a)),n=vt(e.charCodeAt(a+1));if(void 0===r||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[t]=16*r+n}return s}function _t(e){return dt(pt(e))}function At(e){return it(e),dt(pt(Uint8Array.from(e).reverse()))}function Et(e,t){return St(e.toString(16).padStart(2*t,"0"))}function bt(e,t){return Et(e,t).reverse()}function It(e,t,r){let s;if("string"==typeof t)try{s=St(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!nt(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const a=s.length;if("number"==typeof r&&a!==r)throw new Error(e+" of length "+r+" expected, got "+a);return s}function Pt(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];it(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const a=e[t];r.set(a,s),s+=a.length}return r}const Tt=e=>"bigint"==typeof e&&st<=e;function kt(e,t,r){return Tt(e)&&Tt(t)&&Tt(r)&&t<=e&&e<r}function Ct(e,t,r,s){if(!kt(t,r,s))throw new Error("expected valid "+e+": "+r+" <= n < "+s+", got "+t)}const xt=e=>(at<<BigInt(e))-at,Kt=e=>new Uint8Array(e),Ot=e=>Uint8Array.from(e);const Nt={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||nt(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Rt(e,t,r={}){const s=(t,r,s)=>{const a=Nt[r];if("function"!=typeof a)throw new Error("invalid validator function");const n=e[t];if(!(s&&void 0===n||a(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+r+", got "+n)};for(const[e,r]of Object.entries(t))s(e,r,!1);for(const[e,t]of Object.entries(r))s(e,t,!0);return e}function Dt(e){const t=new WeakMap;return(r,...s)=>{const a=t.get(r);if(void 0!==a)return a;const n=e(r,...s);return t.set(r,n),n}}const Lt=Te;function Ut(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(qe)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){const r=Ye(e.charCodeAt(a)),n=Ye(e.charCodeAt(a+1));if(void 0===r||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[t]=16*r+n}return s}(e.startsWith("0x")?e.substring(2):e)}function Bt(e){return t=>(Lt(t),e(t))}const qt=e=>{if("string"!=typeof e)throw new Error("[stripHexPrefix] input must be type 'string', received "+typeof e);return(e=>{if("string"!=typeof e)throw new Error("[isHexPrefixed] input must be type 'string', received type "+typeof e);return"0"===e[0]&&"x"===e[1]})(e)?e.slice(2):e},Vt=e=>e.startsWith("0x")?e:"0x"+e,Mt=e=>{let t=e;return 64===Ut(e).length&&(t="04"+e),t.substring(2)},Wt=e=>{const t=e.reduce(((e,t)=>e+t.byteLength),0),r=new Uint8Array(t);let s=0;return e.forEach((e=>{r.set(e,s),s+=e.byteLength})),r},Ft=e=>{if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);const t=[];for(let r=0;r<e.length;r++){const s=e.codePointAt(r);if(!s)throw new Error("Invalid code point");s<128?t.push(s):s<2048?t.push(192|s>>6,128|63&s):s<65536?t.push(224|s>>12,128|s>>6&63,128|63&s):(r++,t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s))}return new Uint8Array(t)};function Gt(e,t,r){return e&t^e&r^t&r}class jt extends Ze{constructor(e,t,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ne(this.buffer)}update(e){Ce(this),Te(e=Je(e));const{view:t,buffer:r,blockLen:s}=this,a=e.length;for(let n=0;n<a;){const i=Math.min(s-this.pos,a-n);if(i!==s)r.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=Ne(e);for(;s<=a-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ce(this),xe(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:a}=this;let{pos:n}=this;t[n++]=128,Oe(this.buffer.subarray(n)),this.padOffset>s-n&&(this.process(r,0),n=0);for(let e=n;e<s;e++)t[e]=0;!function(e,t,r,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,s);const a=BigInt(32),n=BigInt(4294967295),i=Number(r>>a&n),o=Number(r&n),c=s?4:0,d=s?0:4;e.setUint32(t+c,i,s),e.setUint32(t+d,o,s)}(r,s-8,BigInt(8*this.length),a),this.process(r,0);const i=Ne(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,d=this.get();if(c>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)i.setUint32(4*e,d[e],a)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:a,destroyed:n,pos:i}=this;return e.destroyed=n,e.finished=a,e.length=s,e.pos=i,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Ht=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$t=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Yt=BigInt(2**32-1),zt=BigInt(32);function Jt(e,t=!1){return t?{h:Number(e&Yt),l:Number(e>>zt&Yt)}:{h:0|Number(e>>zt&Yt),l:0|Number(e&Yt)}}function Xt(e,t=!1){const r=e.length;let s=new Uint32Array(r),a=new Uint32Array(r);for(let n=0;n<r;n++){const{h:r,l:i}=Jt(e[n],t);[s[n],a[n]]=[r,i]}return[s,a]}const Zt=(e,t,r)=>e>>>r,Qt=(e,t,r)=>e<<32-r|t>>>r,er=(e,t,r)=>e>>>r|t<<32-r,tr=(e,t,r)=>e<<32-r|t>>>r,rr=(e,t,r)=>e<<64-r|t>>>r-32,sr=(e,t,r)=>e>>>r-32|t<<64-r;function ar(e,t,r,s){const a=(t>>>0)+(s>>>0);return{h:e+r+(a/2**32|0)|0,l:0|a}}const nr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),ir=(e,t,r,s)=>t+r+s+(e/2**32|0)|0,or=(e,t,r,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),cr=(e,t,r,s,a)=>t+r+s+a+(e/2**32|0)|0,dr=(e,t,r,s,a)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0)+(a>>>0),lr=(e,t,r,s,a,n)=>t+r+s+a+n+(e/2**32|0)|0,hr=Uint32Array.from([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]),pr=new Uint32Array(64);class ur extends jt{constructor(e=32){super(64,e,8,!1),this.A=0|Ht[0],this.B=0|Ht[1],this.C=0|Ht[2],this.D=0|Ht[3],this.E=0|Ht[4],this.F=0|Ht[5],this.G=0|Ht[6],this.H=0|Ht[7]}get(){const{A:e,B:t,C:r,D:s,E:a,F:n,G:i,H:o}=this;return[e,t,r,s,a,n,i,o]}set(e,t,r,s,a,n,i,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|s,this.E=0|a,this.F=0|n,this.G=0|i,this.H=0|o}process(e,t){for(let r=0;r<16;r++,t+=4)pr[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=pr[e-15],r=pr[e-2],s=Re(t,7)^Re(t,18)^t>>>3,a=Re(r,17)^Re(r,19)^r>>>10;pr[e]=a+pr[e-7]+s+pr[e-16]|0}let{A:r,B:s,C:a,D:n,E:i,F:o,G:c,H:d}=this;for(let e=0;e<64;e++){const t=d+(Re(i,6)^Re(i,11)^Re(i,25))+((l=i)&o^~l&c)+hr[e]+pr[e]|0,h=(Re(r,2)^Re(r,13)^Re(r,22))+Gt(r,s,a)|0;d=c,c=o,o=i,i=n+t|0,n=a,a=s,s=r,r=t+h|0}var l;r=r+this.A|0,s=s+this.B|0,a=a+this.C|0,n=n+this.D|0,i=i+this.E|0,o=o+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,s,a,n,i,o,c,d)}roundClean(){Oe(pr)}destroy(){this.set(0,0,0,0,0,0,0,0),Oe(this.buffer)}}const yr=(()=>Xt(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),fr=(()=>yr[0])(),gr=(()=>yr[1])(),wr=new Uint32Array(80),mr=new Uint32Array(80);class vr extends jt{constructor(e=64){super(128,e,16,!1),this.Ah=0|$t[0],this.Al=0|$t[1],this.Bh=0|$t[2],this.Bl=0|$t[3],this.Ch=0|$t[4],this.Cl=0|$t[5],this.Dh=0|$t[6],this.Dl=0|$t[7],this.Eh=0|$t[8],this.El=0|$t[9],this.Fh=0|$t[10],this.Fl=0|$t[11],this.Gh=0|$t[12],this.Gl=0|$t[13],this.Hh=0|$t[14],this.Hl=0|$t[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:s,Ch:a,Cl:n,Dh:i,Dl:o,Eh:c,El:d,Fh:l,Fl:h,Gh:p,Gl:u,Hh:y,Hl:f}=this;return[e,t,r,s,a,n,i,o,c,d,l,h,p,u,y,f]}set(e,t,r,s,a,n,i,o,c,d,l,h,p,u,y,f){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|s,this.Ch=0|a,this.Cl=0|n,this.Dh=0|i,this.Dl=0|o,this.Eh=0|c,this.El=0|d,this.Fh=0|l,this.Fl=0|h,this.Gh=0|p,this.Gl=0|u,this.Hh=0|y,this.Hl=0|f}process(e,t){for(let r=0;r<16;r++,t+=4)wr[r]=e.getUint32(t),mr[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|wr[e-15],r=0|mr[e-15],s=er(t,r,1)^er(t,r,8)^Zt(t,0,7),a=tr(t,r,1)^tr(t,r,8)^Qt(t,r,7),n=0|wr[e-2],i=0|mr[e-2],o=er(n,i,19)^rr(n,i,61)^Zt(n,0,6),c=tr(n,i,19)^sr(n,i,61)^Qt(n,i,6),d=or(a,c,mr[e-7],mr[e-16]),l=cr(d,s,o,wr[e-7],wr[e-16]);wr[e]=0|l,mr[e]=0|d}let{Ah:r,Al:s,Bh:a,Bl:n,Ch:i,Cl:o,Dh:c,Dl:d,Eh:l,El:h,Fh:p,Fl:u,Gh:y,Gl:f,Hh:g,Hl:w}=this;for(let e=0;e<80;e++){const t=er(l,h,14)^er(l,h,18)^rr(l,h,41),m=tr(l,h,14)^tr(l,h,18)^sr(l,h,41),v=l&p^~l&y,S=dr(w,m,h&u^~h&f,gr[e],mr[e]),_=lr(S,g,t,v,fr[e],wr[e]),A=0|S,E=er(r,s,28)^rr(r,s,34)^rr(r,s,39),b=tr(r,s,28)^sr(r,s,34)^sr(r,s,39),I=r&a^r&i^a&i,P=s&n^s&o^n&o;g=0|y,w=0|f,y=0|p,f=0|u,p=0|l,u=0|h,({h:l,l:h}=ar(0|c,0|d,0|_,0|A)),c=0|i,d=0|o,i=0|a,o=0|n,a=0|r,n=0|s;const T=nr(A,b,P);r=ir(T,_,E,I),s=0|T}({h:r,l:s}=ar(0|this.Ah,0|this.Al,0|r,0|s)),({h:a,l:n}=ar(0|this.Bh,0|this.Bl,0|a,0|n)),({h:i,l:o}=ar(0|this.Ch,0|this.Cl,0|i,0|o)),({h:c,l:d}=ar(0|this.Dh,0|this.Dl,0|c,0|d)),({h:l,l:h}=ar(0|this.Eh,0|this.El,0|l,0|h)),({h:p,l:u}=ar(0|this.Fh,0|this.Fl,0|p,0|u)),({h:y,l:f}=ar(0|this.Gh,0|this.Gl,0|y,0|f)),({h:g,l:w}=ar(0|this.Hh,0|this.Hl,0|g,0|w)),this.set(r,s,a,n,i,o,c,d,l,h,p,u,y,f,g,w)}roundClean(){Oe(wr,mr)}destroy(){Oe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Sr=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class _r extends vr{constructor(){super(32),this.Ah=0|Sr[0],this.Al=0|Sr[1],this.Bh=0|Sr[2],this.Bl=0|Sr[3],this.Ch=0|Sr[4],this.Cl=0|Sr[5],this.Dh=0|Sr[6],this.Dl=0|Sr[7],this.Eh=0|Sr[8],this.El=0|Sr[9],this.Fh=0|Sr[10],this.Fl=0|Sr[11],this.Gh=0|Sr[12],this.Gl=0|Sr[13],this.Hh=0|Sr[14],this.Hl=0|Sr[15]}}const Ar=Qe((()=>new ur)),Er=Qe((()=>new vr)),br=Qe((()=>new _r));class Ir extends Ze{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ke(e);const r=Je(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,a=new Uint8Array(s);a.set(r.length>s?e.create().update(r).digest():r);for(let e=0;e<a.length;e++)a[e]^=54;this.iHash.update(a),this.oHash=e.create();for(let e=0;e<a.length;e++)a[e]^=106;this.oHash.update(a),Oe(a)}update(e){return Ce(this),this.iHash.update(e),this}digestInto(e){Ce(this),Te(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:a,blockLen:n,outputLen:i}=this;return e.finished=s,e.destroyed=a,e.blockLen=n,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Pr=(e,t,r)=>new Ir(e,t).update(r).digest();Pr.create=(e,t)=>new Ir(e,t)
4
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const st=BigInt(0),at=BigInt(1);function nt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function it(e){if(!nt(e))throw new Error("Uint8Array expected")}function ot(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function ct(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function dt(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?st:BigInt("0x"+e)}const lt="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,ht=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function ut(e){if(it(e),lt)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=ht[e[r]];return t}const pt=48,yt=57,ft=65,gt=70,wt=97,mt=102;function vt(e){return e>=pt&&e<=yt?e-pt:e>=ft&&e<=gt?e-(ft-10):e>=wt&&e<=mt?e-(wt-10):void 0}function St(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(lt)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){const r=vt(e.charCodeAt(a)),n=vt(e.charCodeAt(a+1));if(void 0===r||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[t]=16*r+n}return s}function _t(e){return dt(ut(e))}function At(e){return it(e),dt(ut(Uint8Array.from(e).reverse()))}function Et(e,t){return St(e.toString(16).padStart(2*t,"0"))}function bt(e,t){return Et(e,t).reverse()}function It(e,t,r){let s;if("string"==typeof t)try{s=St(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!nt(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const a=s.length;if("number"==typeof r&&a!==r)throw new Error(e+" of length "+r+" expected, got "+a);return s}function Pt(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];it(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const a=e[t];r.set(a,s),s+=a.length}return r}const Tt=e=>"bigint"==typeof e&&st<=e;function kt(e,t,r){return Tt(e)&&Tt(t)&&Tt(r)&&t<=e&&e<r}function Ct(e,t,r,s){if(!kt(t,r,s))throw new Error("expected valid "+e+": "+r+" <= n < "+s+", got "+t)}const xt=e=>(at<<BigInt(e))-at,Kt=e=>new Uint8Array(e),Ot=e=>Uint8Array.from(e);const Nt={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||nt(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Rt(e,t,r={}){const s=(t,r,s)=>{const a=Nt[r];if("function"!=typeof a)throw new Error("invalid validator function");const n=e[t];if(!(s&&void 0===n||a(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+r+", got "+n)};for(const[e,r]of Object.entries(t))s(e,r,!1);for(const[e,t]of Object.entries(r))s(e,t,!0);return e}function Dt(e){const t=new WeakMap;return(r,...s)=>{const a=t.get(r);if(void 0!==a)return a;const n=e(r,...s);return t.set(r,n),n}}const Lt=Te;function Ut(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(qe)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){const r=Ye(e.charCodeAt(a)),n=Ye(e.charCodeAt(a+1));if(void 0===r||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[t]=16*r+n}return s}(e.startsWith("0x")?e.substring(2):e)}function Bt(e){return t=>(Lt(t),e(t))}const qt=e=>{if("string"!=typeof e)throw new Error("[stripHexPrefix] input must be type 'string', received "+typeof e);return(e=>{if("string"!=typeof e)throw new Error("[isHexPrefixed] input must be type 'string', received type "+typeof e);return"0"===e[0]&&"x"===e[1]})(e)?e.slice(2):e},Vt=e=>e.startsWith("0x")?e:"0x"+e,Mt=e=>{let t=e;return 64===Ut(e).length&&(t="04"+e),t.substring(2)},Wt=e=>{const t=e.reduce(((e,t)=>e+t.byteLength),0),r=new Uint8Array(t);let s=0;return e.forEach((e=>{r.set(e,s),s+=e.byteLength})),r},Ft=e=>{if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);const t=[];for(let r=0;r<e.length;r++){const s=e.codePointAt(r);if(!s)throw new Error("Invalid code point");s<128?t.push(s):s<2048?t.push(192|s>>6,128|63&s):s<65536?t.push(224|s>>12,128|s>>6&63,128|63&s):(r++,t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s))}return new Uint8Array(t)};function Gt(e,t,r){return e&t^e&r^t&r}class jt extends Ze{constructor(e,t,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ne(this.buffer)}update(e){Ce(this),Te(e=Je(e));const{view:t,buffer:r,blockLen:s}=this,a=e.length;for(let n=0;n<a;){const i=Math.min(s-this.pos,a-n);if(i!==s)r.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=Ne(e);for(;s<=a-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ce(this),xe(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:a}=this;let{pos:n}=this;t[n++]=128,Oe(this.buffer.subarray(n)),this.padOffset>s-n&&(this.process(r,0),n=0);for(let e=n;e<s;e++)t[e]=0;!function(e,t,r,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,s);const a=BigInt(32),n=BigInt(4294967295),i=Number(r>>a&n),o=Number(r&n),c=s?4:0,d=s?0:4;e.setUint32(t+c,i,s),e.setUint32(t+d,o,s)}(r,s-8,BigInt(8*this.length),a),this.process(r,0);const i=Ne(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,d=this.get();if(c>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)i.setUint32(4*e,d[e],a)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:a,destroyed:n,pos:i}=this;return e.destroyed=n,e.finished=a,e.length=s,e.pos=i,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Ht=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$t=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Yt=BigInt(2**32-1),zt=BigInt(32);function Jt(e,t=!1){return t?{h:Number(e&Yt),l:Number(e>>zt&Yt)}:{h:0|Number(e>>zt&Yt),l:0|Number(e&Yt)}}function Xt(e,t=!1){const r=e.length;let s=new Uint32Array(r),a=new Uint32Array(r);for(let n=0;n<r;n++){const{h:r,l:i}=Jt(e[n],t);[s[n],a[n]]=[r,i]}return[s,a]}const Zt=(e,t,r)=>e>>>r,Qt=(e,t,r)=>e<<32-r|t>>>r,er=(e,t,r)=>e>>>r|t<<32-r,tr=(e,t,r)=>e<<32-r|t>>>r,rr=(e,t,r)=>e<<64-r|t>>>r-32,sr=(e,t,r)=>e>>>r-32|t<<64-r;function ar(e,t,r,s){const a=(t>>>0)+(s>>>0);return{h:e+r+(a/2**32|0)|0,l:0|a}}const nr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),ir=(e,t,r,s)=>t+r+s+(e/2**32|0)|0,or=(e,t,r,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),cr=(e,t,r,s,a)=>t+r+s+a+(e/2**32|0)|0,dr=(e,t,r,s,a)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0)+(a>>>0),lr=(e,t,r,s,a,n)=>t+r+s+a+n+(e/2**32|0)|0,hr=Uint32Array.from([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]),ur=new Uint32Array(64);class pr extends jt{constructor(e=32){super(64,e,8,!1),this.A=0|Ht[0],this.B=0|Ht[1],this.C=0|Ht[2],this.D=0|Ht[3],this.E=0|Ht[4],this.F=0|Ht[5],this.G=0|Ht[6],this.H=0|Ht[7]}get(){const{A:e,B:t,C:r,D:s,E:a,F:n,G:i,H:o}=this;return[e,t,r,s,a,n,i,o]}set(e,t,r,s,a,n,i,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|s,this.E=0|a,this.F=0|n,this.G=0|i,this.H=0|o}process(e,t){for(let r=0;r<16;r++,t+=4)ur[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=ur[e-15],r=ur[e-2],s=Re(t,7)^Re(t,18)^t>>>3,a=Re(r,17)^Re(r,19)^r>>>10;ur[e]=a+ur[e-7]+s+ur[e-16]|0}let{A:r,B:s,C:a,D:n,E:i,F:o,G:c,H:d}=this;for(let e=0;e<64;e++){const t=d+(Re(i,6)^Re(i,11)^Re(i,25))+((l=i)&o^~l&c)+hr[e]+ur[e]|0,h=(Re(r,2)^Re(r,13)^Re(r,22))+Gt(r,s,a)|0;d=c,c=o,o=i,i=n+t|0,n=a,a=s,s=r,r=t+h|0}var l;r=r+this.A|0,s=s+this.B|0,a=a+this.C|0,n=n+this.D|0,i=i+this.E|0,o=o+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,s,a,n,i,o,c,d)}roundClean(){Oe(ur)}destroy(){this.set(0,0,0,0,0,0,0,0),Oe(this.buffer)}}const yr=(()=>Xt(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),fr=(()=>yr[0])(),gr=(()=>yr[1])(),wr=new Uint32Array(80),mr=new Uint32Array(80);class vr extends jt{constructor(e=64){super(128,e,16,!1),this.Ah=0|$t[0],this.Al=0|$t[1],this.Bh=0|$t[2],this.Bl=0|$t[3],this.Ch=0|$t[4],this.Cl=0|$t[5],this.Dh=0|$t[6],this.Dl=0|$t[7],this.Eh=0|$t[8],this.El=0|$t[9],this.Fh=0|$t[10],this.Fl=0|$t[11],this.Gh=0|$t[12],this.Gl=0|$t[13],this.Hh=0|$t[14],this.Hl=0|$t[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:s,Ch:a,Cl:n,Dh:i,Dl:o,Eh:c,El:d,Fh:l,Fl:h,Gh:u,Gl:p,Hh:y,Hl:f}=this;return[e,t,r,s,a,n,i,o,c,d,l,h,u,p,y,f]}set(e,t,r,s,a,n,i,o,c,d,l,h,u,p,y,f){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|s,this.Ch=0|a,this.Cl=0|n,this.Dh=0|i,this.Dl=0|o,this.Eh=0|c,this.El=0|d,this.Fh=0|l,this.Fl=0|h,this.Gh=0|u,this.Gl=0|p,this.Hh=0|y,this.Hl=0|f}process(e,t){for(let r=0;r<16;r++,t+=4)wr[r]=e.getUint32(t),mr[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|wr[e-15],r=0|mr[e-15],s=er(t,r,1)^er(t,r,8)^Zt(t,0,7),a=tr(t,r,1)^tr(t,r,8)^Qt(t,r,7),n=0|wr[e-2],i=0|mr[e-2],o=er(n,i,19)^rr(n,i,61)^Zt(n,0,6),c=tr(n,i,19)^sr(n,i,61)^Qt(n,i,6),d=or(a,c,mr[e-7],mr[e-16]),l=cr(d,s,o,wr[e-7],wr[e-16]);wr[e]=0|l,mr[e]=0|d}let{Ah:r,Al:s,Bh:a,Bl:n,Ch:i,Cl:o,Dh:c,Dl:d,Eh:l,El:h,Fh:u,Fl:p,Gh:y,Gl:f,Hh:g,Hl:w}=this;for(let e=0;e<80;e++){const t=er(l,h,14)^er(l,h,18)^rr(l,h,41),m=tr(l,h,14)^tr(l,h,18)^sr(l,h,41),v=l&u^~l&y,S=dr(w,m,h&p^~h&f,gr[e],mr[e]),_=lr(S,g,t,v,fr[e],wr[e]),A=0|S,E=er(r,s,28)^rr(r,s,34)^rr(r,s,39),b=tr(r,s,28)^sr(r,s,34)^sr(r,s,39),I=r&a^r&i^a&i,P=s&n^s&o^n&o;g=0|y,w=0|f,y=0|u,f=0|p,u=0|l,p=0|h,({h:l,l:h}=ar(0|c,0|d,0|_,0|A)),c=0|i,d=0|o,i=0|a,o=0|n,a=0|r,n=0|s;const T=nr(A,b,P);r=ir(T,_,E,I),s=0|T}({h:r,l:s}=ar(0|this.Ah,0|this.Al,0|r,0|s)),({h:a,l:n}=ar(0|this.Bh,0|this.Bl,0|a,0|n)),({h:i,l:o}=ar(0|this.Ch,0|this.Cl,0|i,0|o)),({h:c,l:d}=ar(0|this.Dh,0|this.Dl,0|c,0|d)),({h:l,l:h}=ar(0|this.Eh,0|this.El,0|l,0|h)),({h:u,l:p}=ar(0|this.Fh,0|this.Fl,0|u,0|p)),({h:y,l:f}=ar(0|this.Gh,0|this.Gl,0|y,0|f)),({h:g,l:w}=ar(0|this.Hh,0|this.Hl,0|g,0|w)),this.set(r,s,a,n,i,o,c,d,l,h,u,p,y,f,g,w)}roundClean(){Oe(wr,mr)}destroy(){Oe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Sr=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class _r extends vr{constructor(){super(32),this.Ah=0|Sr[0],this.Al=0|Sr[1],this.Bh=0|Sr[2],this.Bl=0|Sr[3],this.Ch=0|Sr[4],this.Cl=0|Sr[5],this.Dh=0|Sr[6],this.Dl=0|Sr[7],this.Eh=0|Sr[8],this.El=0|Sr[9],this.Fh=0|Sr[10],this.Fl=0|Sr[11],this.Gh=0|Sr[12],this.Gl=0|Sr[13],this.Hh=0|Sr[14],this.Hl=0|Sr[15]}}const Ar=Qe((()=>new pr)),Er=Qe((()=>new vr)),br=Qe((()=>new _r));class Ir extends Ze{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ke(e);const r=Je(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,a=new Uint8Array(s);a.set(r.length>s?e.create().update(r).digest():r);for(let e=0;e<a.length;e++)a[e]^=54;this.iHash.update(a),this.oHash=e.create();for(let e=0;e<a.length;e++)a[e]^=106;this.oHash.update(a),Oe(a)}update(e){return Ce(this),this.iHash.update(e),this}digestInto(e){Ce(this),Te(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:a,blockLen:n,outputLen:i}=this;return e.finished=s,e.destroyed=a,e.blockLen=n,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Pr=(e,t,r)=>new Ir(e,t).update(r).digest();Pr.create=(e,t)=>new Ir(e,t)
5
5
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const Tr=BigInt(0),kr=BigInt(1),Cr=BigInt(2),xr=BigInt(3),Kr=BigInt(4),Or=BigInt(5),Nr=BigInt(8);function Rr(e,t){const r=e%t;return r>=Tr?r:t+r}function Dr(e,t,r){let s=e;for(;t-- >Tr;)s*=s,s%=r;return s}function Lr(e,t){if(e===Tr)throw new Error("invert: expected non-zero number");if(t<=Tr)throw new Error("invert: expected positive modulus, got "+t);let r=Rr(e,t),s=t,a=Tr,n=kr;for(;r!==Tr;){const e=s%r,t=a-n*(s/r);s=r,r=e,a=n,n=t}if(s!==kr)throw new Error("invert: does not exist");return Rr(a,t)}function Ur(e){return e%Kr===xr?function(t,r){const s=(e+kr)/Kr,a=t.pow(r,s);if(!t.eql(t.sqr(a),r))throw new Error("Cannot find square root");return a}:e%Nr===Or?function(t,r){const s=t.mul(r,Cr),a=(e-Or)/Nr,n=t.pow(s,a),i=t.mul(r,n),o=t.mul(t.mul(i,Cr),n),c=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(c),r))throw new Error("Cannot find square root");return c}:function(e){let t=e-kr,r=0;for(;t%Cr===Tr;)t/=Cr,r++;let s=Cr;const a=Wr(e);for(;s<e&&Vr(a,s);)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r){const t=(e+kr)/Kr;return function(e,r){const s=e.pow(r,t);if(!e.eql(e.sqr(s),r))throw new Error("Cannot find square root");return s}}const n=(t+kr)/Cr;return function(e,a){if(!Vr(e,a))throw new Error("Cannot find square root");let i=r,o=e.pow(e.mul(e.ONE,s),t),c=e.pow(a,n),d=e.pow(a,t);for(;!e.eql(d,e.ONE);){if(e.eql(d,e.ZERO))return e.ZERO;let t=1;for(let r=e.sqr(d);t<i&&!e.eql(r,e.ONE);t++)r=e.sqr(r);const r=e.pow(o,kr<<BigInt(i-t-1));o=e.sqr(r),c=e.mul(c,r),d=e.mul(d,o),i=t}return c}}(e)}const Br=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qr(e,t,r=!1){const s=new Array(t.length).fill(r?e.ZERO:void 0),a=t.reduce(((t,r,a)=>e.is0(r)?t:(s[a]=t,e.mul(t,r))),e.ONE),n=e.inv(a);return t.reduceRight(((t,r,a)=>e.is0(r)?t:(s[a]=e.mul(t,s[a]),e.mul(t,r))),n),s}function Vr(e,t){const r=function(e,t){const r=(e.ORDER-kr)/Cr,s=e.pow(t,r),a=e.eql(s,e.ONE),n=e.eql(s,e.ZERO),i=e.eql(s,e.neg(e.ONE));if(!a&&!n&&!i)throw new Error("Cannot find square root: probably non-prime P");return a?1:n?0:-1}(e,t);return 0===r||1===r}function Mr(e,t){void 0!==t&&Pe(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function Wr(e,t,r=!1,s={}){if(e<=Tr)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:a,nByteLength:n}=Mr(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i;const o=Object.freeze({ORDER:e,isLE:r,BITS:a,BYTES:n,MASK:xt(a),ZERO:Tr,ONE:kr,create:t=>Rr(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Tr<=t&&t<e},is0:e=>e===Tr,isOdd:e=>(e&kr)===kr,neg:t=>Rr(-t,e),eql:(e,t)=>e===t,sqr:t=>Rr(t*t,e),add:(t,r)=>Rr(t+r,e),sub:(t,r)=>Rr(t-r,e),mul:(t,r)=>Rr(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Tr)throw new Error("invalid exponent, negatives unsupported");if(r===Tr)return e.ONE;if(r===kr)return t;let s=e.ONE,a=t;for(;r>Tr;)r&kr&&(s=e.mul(s,a)),a=e.sqr(a),r>>=kr;return s}(o,e,t),div:(t,r)=>Rr(t*Lr(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Lr(t,e),sqrt:s.sqrt||(t=>(i||(i=Ur(e)),i(o,t))),toBytes:e=>r?bt(e,n):Et(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return r?At(e):_t(e)},invertBatch:e=>qr(o,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(o)}function Fr(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Gr(e){const t=Fr(e);return t+Math.ceil(t/2)}
6
6
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7
7
  const jr=BigInt(0),Hr=BigInt(1);function $r(e,t){const r=t.negate();return e?r:t}function Yr(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function zr(e,t){Yr(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:xt(e),maxNumber:r,shiftBy:BigInt(e)}}function Jr(e,t,r){const{windowSize:s,mask:a,maxNumber:n,shiftBy:i}=r;let o=Number(e&a),c=e>>i;o>s&&(o-=n,c+=Hr);const d=t*s;return{nextN:c,offset:d+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:d}}const Xr=new WeakMap,Zr=new WeakMap;function Qr(e){return Zr.get(e)||1}function es(e,t,r,s){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)}))}(s,t),r.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const a=e.ZERO,n=function(e){let t;for(t=0;e>st;e>>=at,t+=1);return t}(BigInt(r.length)),i=n>12?n-3:n>4?n-2:n?2:1,o=xt(i),c=new Array(Number(o)+1).fill(a);let d=a;for(let e=Math.floor((t.BITS-1)/i)*i;e>=0;e-=i){c.fill(a);for(let t=0;t<s.length;t++){const a=s[t],n=Number(a>>BigInt(e)&o);c[n]=c[n].add(r[t])}let t=a;for(let e=c.length-1,r=a;e>0;e--)r=r.add(c[e]),t=t.add(r);if(d=d.add(t),0!==e)for(let e=0;e<i;e++)d=d.double()}return d}function ts(e){return Rt(e.Fp,Br.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),Rt(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Mr(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}
8
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function rs(e){void 0!==e.lowS&&ot("lowS",e.lowS),void 0!==e.prehash&&ot("prehash",e.prehash)}class ss extends Error{constructor(e=""){super(e)}}const as={Err:ss,_tlv:{encode:(e,t)=>{const{Err:r}=as;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const s=t.length/2,a=ct(s);if(a.length/2&128)throw new r("tlv.encode: long form length too big");const n=s>127?ct(a.length/2|128):"";return ct(e)+n+a+t},decode(e,t){const{Err:r}=as;let s=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new r("tlv.decode: wrong tlv");const a=t[s++];let n=0;if(!!(128&a)){const e=127&a;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const i=t.subarray(s,s+e);if(i.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===i[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of i)n=n<<8|e;if(s+=e,n<128)throw new r("tlv.decode(long): not minimal encoding")}else n=a;const i=t.subarray(s,s+n);if(i.length!==n)throw new r("tlv.decode: wrong value length");return{v:i,l:t.subarray(s+n)}}},_int:{encode(e){const{Err:t}=as;if(e<ns)throw new t("integer: negative integers are not allowed");let r=ct(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=as;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return _t(e)}},toSig(e){const{Err:t,_int:r,_tlv:s}=as,a=It("signature",e),{v:n,l:i}=s.decode(48,a);if(i.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:c}=s.decode(2,n),{v:d,l:l}=s.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(o),s:r.decode(d)}},hexFromSig(e){const{_tlv:t,_int:r}=as,s=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,s)}},ns=BigInt(0),is=BigInt(1);BigInt(2);const os=BigInt(3);function cs(e){const t=function(e){const t=ts(e);Rt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:s,a:a}=t;if(r){if(!s.eql(a,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if("object"!=typeof r||"bigint"!=typeof r.beta||"function"!=typeof r.splitScalar)throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,s=Wr(t.n,t.nBitLength),a=t.toBytes||((e,t,s)=>{const a=t.toAffine();return Pt(Uint8Array.from([4]),r.toBytes(a.x),r.toBytes(a.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function i(e){const{a:s,b:a}=t,n=r.sqr(e),i=r.mul(n,e);return r.add(r.add(i,r.mul(e,s)),a)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(e){const{allowedPrivateKeyLengths:r,nByteLength:s,wrapPrivateKey:a,n:n}=t;if(r&&"bigint"!=typeof e){if(nt(e)&&(e=pt(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*s,"0")}let i;try{i="bigint"==typeof e?e:_t(It("private key",e,s))}catch(t){throw new Error("invalid private key, expected hex or "+s+" bytes, got "+typeof e)}return a&&(i=Rr(i,n)),Ct("private key",i,is,n),i}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const d=Dt(((e,t)=>{const{px:s,py:a,pz:n}=e;if(r.eql(n,r.ONE))return{x:s,y:a};const i=e.is0();null==t&&(t=i?r.ONE:r.inv(n));const o=r.mul(s,t),c=r.mul(a,t),d=r.mul(n,t);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(d,r.ONE))throw new Error("invZ was invalid");return{x:o,y:c}})),l=Dt((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:s,y:a}=e.toAffine();if(!r.isValid(s)||!r.isValid(a))throw new Error("bad point: x or y not FE");const n=r.sqr(a),o=i(s);if(!r.eql(n,o))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class h{constructor(e,t,s){if(null==e||!r.isValid(e))throw new Error("x required");if(null==t||!r.isValid(t)||r.is0(t))throw new Error("y required");if(null==s||!r.isValid(s))throw new Error("z required");this.px=e,this.py=t,this.pz=s,Object.freeze(this)}static fromAffine(e){const{x:t,y:s}=e||{};if(!e||!r.isValid(t)||!r.isValid(s))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const a=e=>r.eql(e,r.ZERO);return a(t)&&a(s)?h.ZERO:new h(t,s,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=qr(r,e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(n(It("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(o(e))}static msm(e,t){return es(h,s,e,t)}_setWindowSize(e){u.setWindowSize(this,e)}assertValidity(){l(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:s,pz:a}=this,{px:n,py:i,pz:o}=e,d=r.eql(r.mul(t,o),r.mul(n,a)),l=r.eql(r.mul(s,o),r.mul(i,a));return d&&l}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:s}=t,a=r.mul(s,os),{px:n,py:i,pz:o}=this;let c=r.ZERO,d=r.ZERO,l=r.ZERO,p=r.mul(n,n),u=r.mul(i,i),y=r.mul(o,o),f=r.mul(n,i);return f=r.add(f,f),l=r.mul(n,o),l=r.add(l,l),c=r.mul(e,l),d=r.mul(a,y),d=r.add(c,d),c=r.sub(u,d),d=r.add(u,d),d=r.mul(c,d),c=r.mul(f,c),l=r.mul(a,l),y=r.mul(e,y),f=r.sub(p,y),f=r.mul(e,f),f=r.add(f,l),l=r.add(p,p),p=r.add(l,p),p=r.add(p,y),p=r.mul(p,f),d=r.add(d,p),y=r.mul(i,o),y=r.add(y,y),p=r.mul(y,f),c=r.sub(c,p),l=r.mul(y,u),l=r.add(l,l),l=r.add(l,l),new h(c,d,l)}add(e){c(e);const{px:s,py:a,pz:n}=this,{px:i,py:o,pz:d}=e;let l=r.ZERO,p=r.ZERO,u=r.ZERO;const y=t.a,f=r.mul(t.b,os);let g=r.mul(s,i),w=r.mul(a,o),m=r.mul(n,d),v=r.add(s,a),S=r.add(i,o);v=r.mul(v,S),S=r.add(g,w),v=r.sub(v,S),S=r.add(s,n);let _=r.add(i,d);return S=r.mul(S,_),_=r.add(g,m),S=r.sub(S,_),_=r.add(a,n),l=r.add(o,d),_=r.mul(_,l),l=r.add(w,m),_=r.sub(_,l),u=r.mul(y,S),l=r.mul(f,m),u=r.add(l,u),l=r.sub(w,u),u=r.add(w,u),p=r.mul(l,u),w=r.add(g,g),w=r.add(w,g),m=r.mul(y,m),S=r.mul(f,S),w=r.add(w,m),m=r.sub(g,m),m=r.mul(y,m),S=r.add(S,m),g=r.mul(w,S),p=r.add(p,g),g=r.mul(_,S),l=r.mul(v,l),l=r.sub(l,g),g=r.mul(v,w),u=r.mul(_,u),u=r.add(u,g),new h(l,p,u)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return u.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){const{endo:s,n:a}=t;Ct("scalar",e,ns,a);const n=h.ZERO;if(e===ns)return n;if(this.is0()||e===is)return this;if(!s||u.hasPrecomputes(this))return u.wNAFCachedUnsafe(this,e,h.normalizeZ);let{k1neg:i,k1:o,k2neg:c,k2:d}=s.splitScalar(e),l=n,p=n,y=this;for(;o>ns||d>ns;)o&is&&(l=l.add(y)),d&is&&(p=p.add(y)),y=y.double(),o>>=is,d>>=is;return i&&(l=l.negate()),c&&(p=p.negate()),p=new h(r.mul(p.px,s.beta),p.py,p.pz),l.add(p)}multiply(e){const{endo:s,n:a}=t;let n,i;if(Ct("scalar",e,is,a),s){const{k1neg:t,k1:a,k2neg:o,k2:c}=s.splitScalar(e);let{p:d,f:l}=this.wNAF(a),{p:p,f:y}=this.wNAF(c);d=u.constTimeNegate(t,d),p=u.constTimeNegate(o,p),p=new h(r.mul(p.px,s.beta),p.py,p.pz),n=d.add(p),i=l.add(y)}else{const{p:t,f:r}=this.wNAF(e);n=t,i=r}return h.normalizeZ([n,i])[0]}multiplyAndAddUnsafe(e,t,r){const s=h.BASE,a=(e,t)=>t!==ns&&t!==is&&e.equals(s)?e.multiply(t):e.multiplyUnsafe(t),n=a(this,t).add(a(e,r));return n.is0()?void 0:n}toAffine(e){return d(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===is)return!0;if(r)return r(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===is?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return ot("isCompressed",e),this.assertValidity(),a(h,this,e)}toHex(e=!0){return ot("isCompressed",e),pt(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const p=t.nBitLength,u=(y=h,f=t.endo?Math.ceil(p/2):p,{constTimeNegate:$r,hasPrecomputes:e=>1!==Qr(e),unsafeLadder(e,t,r=y.ZERO){let s=e;for(;t>jr;)t&Hr&&(r=r.add(s)),s=s.double(),t>>=Hr;return r},precomputeWindow(e,t){const{windows:r,windowSize:s}=zr(t,f),a=[];let n=e,i=n;for(let e=0;e<r;e++){i=n,a.push(i);for(let e=1;e<s;e++)i=i.add(n),a.push(i);n=i.double()}return a},wNAF(e,t,r){let s=y.ZERO,a=y.BASE;const n=zr(e,f);for(let e=0;e<n.windows;e++){const{nextN:i,offset:o,isZero:c,isNeg:d,isNegF:l,offsetF:h}=Jr(r,e,n);r=i,c?a=a.add($r(l,t[h])):s=s.add($r(d,t[o]))}return{p:s,f:a}},wNAFUnsafe(e,t,r,s=y.ZERO){const a=zr(e,f);for(let e=0;e<a.windows&&r!==jr;e++){const{nextN:n,offset:i,isZero:o,isNeg:c}=Jr(r,e,a);if(r=n,!o){const e=t[i];s=s.add(c?e.negate():e)}}return s},getPrecomputes(e,t,r){let s=Xr.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&Xr.set(t,r(s))),s},wNAFCached(e,t,r){const s=Qr(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)},wNAFCachedUnsafe(e,t,r,s){const a=Qr(e);return 1===a?this.unsafeLadder(e,t,s):this.wNAFUnsafe(a,this.getPrecomputes(a,e,r),t,s)},setWindowSize(e,t){Yr(t,f),Zr.set(e,t),Xr.delete(e)}});var y,f;return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:o,weierstrassEquation:i,isWithinCurveOrder:function(e){return kt(e,is,t.n)}}}function ds(e){const t=function(e){const t=ts(e);return Rt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n:s}=t,a=r.BYTES+1,n=2*r.BYTES+1;function i(e){return Rr(e,s)}function o(e){return Lr(e,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:h}=cs({...t,toBytes(e,t,s){const a=t.toAffine(),n=r.toBytes(a.x),i=Pt;return ot("isCompressed",s),s?i(Uint8Array.from([t.hasEvenY()?2:3]),n):i(Uint8Array.from([4]),n,r.toBytes(a.y))},fromBytes(e){const t=e.length,s=e[0],i=e.subarray(1);if(t!==a||2!==s&&3!==s){if(t===n&&4===s){return{x:r.fromBytes(i.subarray(0,r.BYTES)),y:r.fromBytes(i.subarray(r.BYTES,2*r.BYTES))}}throw new Error("invalid Point, expected length of "+a+", or uncompressed "+n+", got "+t)}{const e=_t(i);if(!kt(e,is,r.ORDER))throw new Error("Point is not on curve");const t=l(e);let a;try{a=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~s)!==((a&is)===is)&&(a=r.neg(a)),{x:e,y:a}}}}),p=e=>pt(Et(e,t.nByteLength));function u(e){return e>s>>is}const y=(e,t,r)=>_t(e.slice(t,r));class f{constructor(e,t,r){Ct("r",e,is,s),Ct("s",t,is,s),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromCompact(e){const r=t.nByteLength;return e=It("compactSignature",e,2*r),new f(y(e,0,r),y(e,r,2*r))}static fromDER(e){const{r:t,s:r}=as.toSig(It("DER",e));return new f(t,r)}assertValidity(){}addRecoveryBit(e){return new f(this.r,this.s,e)}recoverPublicKey(e){const{r:s,s:a,recovery:n}=this,d=v(It("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const l=2===n||3===n?s+t.n:s;if(l>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&n?"03":"02",u=c.fromHex(h+p(l)),y=o(l),f=i(-d*y),g=i(a*y),w=c.BASE.multiplyAndAddUnsafe(u,f,g);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return St(this.toDERHex())}toDERHex(){return as.hexFromSig(this)}toCompactRawBytes(){return St(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const g={isValidPrivateKey(e){try{return d(e),!0}catch(e){return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const e=Gr(t.n);return function(e,t,r=!1){const s=e.length,a=Fr(t),n=Gr(t);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const i=Rr(r?At(e):_t(e),t-kr)+kr;return r?bt(i,a):Et(i,a)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function w(e){const t=nt(e),r="string"==typeof e,s=(t||r)&&e.length;return t?s===a||s===n:r?s===2*a||s===2*n:e instanceof c}const m=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const r=_t(e),s=8*e.length-t.nBitLength;return s>0?r>>BigInt(s):r},v=t.bits2int_modN||function(e){return i(m(e))},S=xt(t.nBitLength);function _(e){return Ct("num < 2^"+t.nBitLength,e,ns,S),Et(e,t.nByteLength)}function A(e,s,a=E){if(["recovered","canonical"].some((e=>e in a)))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:l}=t;let{lowS:p,prehash:y,extraEntropy:g}=a;null==p&&(p=!0),e=It("msgHash",e),rs(a),y&&(e=It("prehashed msgHash",n(e)));const w=v(e),S=d(s),A=[_(S),_(w)];if(null!=g&&!1!==g){const e=!0===g?l(r.BYTES):g;A.push(It("extraEntropy",e))}const b=Pt(...A),I=w;return{seed:b,k2sig:function(e){const t=m(e);if(!h(t))return;const r=o(t),s=c.BASE.multiply(t).toAffine(),a=i(s.x);if(a===ns)return;const n=i(r*i(I+a*S));if(n===ns)return;let d=(s.x===a?0:2)|Number(s.y&is),l=n;return p&&u(n)&&(l=function(e){return u(e)?i(-e):e}(n),d^=1),new f(a,l,d)}}}const E={lowS:t.lowS,prehash:!1},b={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(w(e))throw new Error("first arg must be private key");if(!w(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(d(e)).toRawBytes(r)},sign:function(e,r,s=E){const{seed:a,k2sig:n}=A(e,r,s),i=t,o=function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let s=Kt(e),a=Kt(e),n=0;const i=()=>{s.fill(1),a.fill(0),n=0},o=(...e)=>r(a,s,...e),c=(e=Kt(0))=>{a=o(Ot([0]),e),s=o(),0!==e.length&&(a=o(Ot([1]),e),s=o())},d=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){s=o();const t=s.slice();r.push(t),e+=s.length}return Pt(...r)};return(e,t)=>{let r;for(i(),c(e);!(r=t(d()));)c();return i(),r}}(i.hash.outputLen,i.nByteLength,i.hmac);return o(a,n)},verify:function(e,r,s,a=b){const n=e;r=It("msgHash",r),s=It("publicKey",s);const{lowS:d,prehash:l,format:h}=a;if(rs(a),"strict"in a)throw new Error("options.strict was renamed to lowS");if(void 0!==h&&"compact"!==h&&"der"!==h)throw new Error("format must be compact or der");const p="string"==typeof n||nt(n),u=!p&&!h&&"object"==typeof n&&null!==n&&"bigint"==typeof n.r&&"bigint"==typeof n.s;if(!p&&!u)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let y,g;try{if(u&&(y=new f(n.r,n.s)),p){try{"compact"!==h&&(y=f.fromDER(n))}catch(e){if(!(e instanceof as.Err))throw e}y||"der"===h||(y=f.fromCompact(n))}g=c.fromHex(s)}catch(e){return!1}if(!y)return!1;if(d&&y.hasHighS())return!1;l&&(r=t.hash(r));const{r:w,s:m}=y,S=v(r),_=o(m),A=i(S*_),E=i(w*_),I=c.BASE.multiplyAndAddUnsafe(g,A,E)?.toAffine();return!!I&&i(I.x)===w},ProjectivePoint:c,Signature:f,utils:g}}
8
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function rs(e){void 0!==e.lowS&&ot("lowS",e.lowS),void 0!==e.prehash&&ot("prehash",e.prehash)}class ss extends Error{constructor(e=""){super(e)}}const as={Err:ss,_tlv:{encode:(e,t)=>{const{Err:r}=as;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const s=t.length/2,a=ct(s);if(a.length/2&128)throw new r("tlv.encode: long form length too big");const n=s>127?ct(a.length/2|128):"";return ct(e)+n+a+t},decode(e,t){const{Err:r}=as;let s=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new r("tlv.decode: wrong tlv");const a=t[s++];let n=0;if(!!(128&a)){const e=127&a;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const i=t.subarray(s,s+e);if(i.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===i[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of i)n=n<<8|e;if(s+=e,n<128)throw new r("tlv.decode(long): not minimal encoding")}else n=a;const i=t.subarray(s,s+n);if(i.length!==n)throw new r("tlv.decode: wrong value length");return{v:i,l:t.subarray(s+n)}}},_int:{encode(e){const{Err:t}=as;if(e<ns)throw new t("integer: negative integers are not allowed");let r=ct(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=as;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return _t(e)}},toSig(e){const{Err:t,_int:r,_tlv:s}=as,a=It("signature",e),{v:n,l:i}=s.decode(48,a);if(i.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:c}=s.decode(2,n),{v:d,l:l}=s.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(o),s:r.decode(d)}},hexFromSig(e){const{_tlv:t,_int:r}=as,s=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,s)}},ns=BigInt(0),is=BigInt(1);BigInt(2);const os=BigInt(3);function cs(e){const t=function(e){const t=ts(e);Rt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:s,a:a}=t;if(r){if(!s.eql(a,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if("object"!=typeof r||"bigint"!=typeof r.beta||"function"!=typeof r.splitScalar)throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,s=Wr(t.n,t.nBitLength),a=t.toBytes||((e,t,s)=>{const a=t.toAffine();return Pt(Uint8Array.from([4]),r.toBytes(a.x),r.toBytes(a.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function i(e){const{a:s,b:a}=t,n=r.sqr(e),i=r.mul(n,e);return r.add(r.add(i,r.mul(e,s)),a)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(e){const{allowedPrivateKeyLengths:r,nByteLength:s,wrapPrivateKey:a,n:n}=t;if(r&&"bigint"!=typeof e){if(nt(e)&&(e=ut(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*s,"0")}let i;try{i="bigint"==typeof e?e:_t(It("private key",e,s))}catch(t){throw new Error("invalid private key, expected hex or "+s+" bytes, got "+typeof e)}return a&&(i=Rr(i,n)),Ct("private key",i,is,n),i}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const d=Dt(((e,t)=>{const{px:s,py:a,pz:n}=e;if(r.eql(n,r.ONE))return{x:s,y:a};const i=e.is0();null==t&&(t=i?r.ONE:r.inv(n));const o=r.mul(s,t),c=r.mul(a,t),d=r.mul(n,t);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(d,r.ONE))throw new Error("invZ was invalid");return{x:o,y:c}})),l=Dt((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:s,y:a}=e.toAffine();if(!r.isValid(s)||!r.isValid(a))throw new Error("bad point: x or y not FE");const n=r.sqr(a),o=i(s);if(!r.eql(n,o))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class h{constructor(e,t,s){if(null==e||!r.isValid(e))throw new Error("x required");if(null==t||!r.isValid(t)||r.is0(t))throw new Error("y required");if(null==s||!r.isValid(s))throw new Error("z required");this.px=e,this.py=t,this.pz=s,Object.freeze(this)}static fromAffine(e){const{x:t,y:s}=e||{};if(!e||!r.isValid(t)||!r.isValid(s))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const a=e=>r.eql(e,r.ZERO);return a(t)&&a(s)?h.ZERO:new h(t,s,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=qr(r,e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(n(It("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(o(e))}static msm(e,t){return es(h,s,e,t)}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){l(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:s,pz:a}=this,{px:n,py:i,pz:o}=e,d=r.eql(r.mul(t,o),r.mul(n,a)),l=r.eql(r.mul(s,o),r.mul(i,a));return d&&l}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:s}=t,a=r.mul(s,os),{px:n,py:i,pz:o}=this;let c=r.ZERO,d=r.ZERO,l=r.ZERO,u=r.mul(n,n),p=r.mul(i,i),y=r.mul(o,o),f=r.mul(n,i);return f=r.add(f,f),l=r.mul(n,o),l=r.add(l,l),c=r.mul(e,l),d=r.mul(a,y),d=r.add(c,d),c=r.sub(p,d),d=r.add(p,d),d=r.mul(c,d),c=r.mul(f,c),l=r.mul(a,l),y=r.mul(e,y),f=r.sub(u,y),f=r.mul(e,f),f=r.add(f,l),l=r.add(u,u),u=r.add(l,u),u=r.add(u,y),u=r.mul(u,f),d=r.add(d,u),y=r.mul(i,o),y=r.add(y,y),u=r.mul(y,f),c=r.sub(c,u),l=r.mul(y,p),l=r.add(l,l),l=r.add(l,l),new h(c,d,l)}add(e){c(e);const{px:s,py:a,pz:n}=this,{px:i,py:o,pz:d}=e;let l=r.ZERO,u=r.ZERO,p=r.ZERO;const y=t.a,f=r.mul(t.b,os);let g=r.mul(s,i),w=r.mul(a,o),m=r.mul(n,d),v=r.add(s,a),S=r.add(i,o);v=r.mul(v,S),S=r.add(g,w),v=r.sub(v,S),S=r.add(s,n);let _=r.add(i,d);return S=r.mul(S,_),_=r.add(g,m),S=r.sub(S,_),_=r.add(a,n),l=r.add(o,d),_=r.mul(_,l),l=r.add(w,m),_=r.sub(_,l),p=r.mul(y,S),l=r.mul(f,m),p=r.add(l,p),l=r.sub(w,p),p=r.add(w,p),u=r.mul(l,p),w=r.add(g,g),w=r.add(w,g),m=r.mul(y,m),S=r.mul(f,S),w=r.add(w,m),m=r.sub(g,m),m=r.mul(y,m),S=r.add(S,m),g=r.mul(w,S),u=r.add(u,g),g=r.mul(_,S),l=r.mul(v,l),l=r.sub(l,g),g=r.mul(v,w),p=r.mul(_,p),p=r.add(p,g),new h(l,u,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){const{endo:s,n:a}=t;Ct("scalar",e,ns,a);const n=h.ZERO;if(e===ns)return n;if(this.is0()||e===is)return this;if(!s||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,e,h.normalizeZ);let{k1neg:i,k1:o,k2neg:c,k2:d}=s.splitScalar(e),l=n,u=n,y=this;for(;o>ns||d>ns;)o&is&&(l=l.add(y)),d&is&&(u=u.add(y)),y=y.double(),o>>=is,d>>=is;return i&&(l=l.negate()),c&&(u=u.negate()),u=new h(r.mul(u.px,s.beta),u.py,u.pz),l.add(u)}multiply(e){const{endo:s,n:a}=t;let n,i;if(Ct("scalar",e,is,a),s){const{k1neg:t,k1:a,k2neg:o,k2:c}=s.splitScalar(e);let{p:d,f:l}=this.wNAF(a),{p:u,f:y}=this.wNAF(c);d=p.constTimeNegate(t,d),u=p.constTimeNegate(o,u),u=new h(r.mul(u.px,s.beta),u.py,u.pz),n=d.add(u),i=l.add(y)}else{const{p:t,f:r}=this.wNAF(e);n=t,i=r}return h.normalizeZ([n,i])[0]}multiplyAndAddUnsafe(e,t,r){const s=h.BASE,a=(e,t)=>t!==ns&&t!==is&&e.equals(s)?e.multiply(t):e.multiplyUnsafe(t),n=a(this,t).add(a(e,r));return n.is0()?void 0:n}toAffine(e){return d(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===is)return!0;if(r)return r(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===is?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return ot("isCompressed",e),this.assertValidity(),a(h,this,e)}toHex(e=!0){return ot("isCompressed",e),ut(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const u=t.nBitLength,p=(y=h,f=t.endo?Math.ceil(u/2):u,{constTimeNegate:$r,hasPrecomputes:e=>1!==Qr(e),unsafeLadder(e,t,r=y.ZERO){let s=e;for(;t>jr;)t&Hr&&(r=r.add(s)),s=s.double(),t>>=Hr;return r},precomputeWindow(e,t){const{windows:r,windowSize:s}=zr(t,f),a=[];let n=e,i=n;for(let e=0;e<r;e++){i=n,a.push(i);for(let e=1;e<s;e++)i=i.add(n),a.push(i);n=i.double()}return a},wNAF(e,t,r){let s=y.ZERO,a=y.BASE;const n=zr(e,f);for(let e=0;e<n.windows;e++){const{nextN:i,offset:o,isZero:c,isNeg:d,isNegF:l,offsetF:h}=Jr(r,e,n);r=i,c?a=a.add($r(l,t[h])):s=s.add($r(d,t[o]))}return{p:s,f:a}},wNAFUnsafe(e,t,r,s=y.ZERO){const a=zr(e,f);for(let e=0;e<a.windows&&r!==jr;e++){const{nextN:n,offset:i,isZero:o,isNeg:c}=Jr(r,e,a);if(r=n,!o){const e=t[i];s=s.add(c?e.negate():e)}}return s},getPrecomputes(e,t,r){let s=Xr.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&Xr.set(t,r(s))),s},wNAFCached(e,t,r){const s=Qr(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)},wNAFCachedUnsafe(e,t,r,s){const a=Qr(e);return 1===a?this.unsafeLadder(e,t,s):this.wNAFUnsafe(a,this.getPrecomputes(a,e,r),t,s)},setWindowSize(e,t){Yr(t,f),Zr.set(e,t),Xr.delete(e)}});var y,f;return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:o,weierstrassEquation:i,isWithinCurveOrder:function(e){return kt(e,is,t.n)}}}function ds(e){const t=function(e){const t=ts(e);return Rt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n:s}=t,a=r.BYTES+1,n=2*r.BYTES+1;function i(e){return Rr(e,s)}function o(e){return Lr(e,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:h}=cs({...t,toBytes(e,t,s){const a=t.toAffine(),n=r.toBytes(a.x),i=Pt;return ot("isCompressed",s),s?i(Uint8Array.from([t.hasEvenY()?2:3]),n):i(Uint8Array.from([4]),n,r.toBytes(a.y))},fromBytes(e){const t=e.length,s=e[0],i=e.subarray(1);if(t!==a||2!==s&&3!==s){if(t===n&&4===s){return{x:r.fromBytes(i.subarray(0,r.BYTES)),y:r.fromBytes(i.subarray(r.BYTES,2*r.BYTES))}}throw new Error("invalid Point, expected length of "+a+", or uncompressed "+n+", got "+t)}{const e=_t(i);if(!kt(e,is,r.ORDER))throw new Error("Point is not on curve");const t=l(e);let a;try{a=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~s)!==((a&is)===is)&&(a=r.neg(a)),{x:e,y:a}}}}),u=e=>ut(Et(e,t.nByteLength));function p(e){return e>s>>is}const y=(e,t,r)=>_t(e.slice(t,r));class f{constructor(e,t,r){Ct("r",e,is,s),Ct("s",t,is,s),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromCompact(e){const r=t.nByteLength;return e=It("compactSignature",e,2*r),new f(y(e,0,r),y(e,r,2*r))}static fromDER(e){const{r:t,s:r}=as.toSig(It("DER",e));return new f(t,r)}assertValidity(){}addRecoveryBit(e){return new f(this.r,this.s,e)}recoverPublicKey(e){const{r:s,s:a,recovery:n}=this,d=v(It("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const l=2===n||3===n?s+t.n:s;if(l>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&n?"03":"02",p=c.fromHex(h+u(l)),y=o(l),f=i(-d*y),g=i(a*y),w=c.BASE.multiplyAndAddUnsafe(p,f,g);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return St(this.toDERHex())}toDERHex(){return as.hexFromSig(this)}toCompactRawBytes(){return St(this.toCompactHex())}toCompactHex(){return u(this.r)+u(this.s)}}const g={isValidPrivateKey(e){try{return d(e),!0}catch(e){return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const e=Gr(t.n);return function(e,t,r=!1){const s=e.length,a=Fr(t),n=Gr(t);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const i=Rr(r?At(e):_t(e),t-kr)+kr;return r?bt(i,a):Et(i,a)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function w(e){const t=nt(e),r="string"==typeof e,s=(t||r)&&e.length;return t?s===a||s===n:r?s===2*a||s===2*n:e instanceof c}const m=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const r=_t(e),s=8*e.length-t.nBitLength;return s>0?r>>BigInt(s):r},v=t.bits2int_modN||function(e){return i(m(e))},S=xt(t.nBitLength);function _(e){return Ct("num < 2^"+t.nBitLength,e,ns,S),Et(e,t.nByteLength)}function A(e,s,a=E){if(["recovered","canonical"].some((e=>e in a)))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:l}=t;let{lowS:u,prehash:y,extraEntropy:g}=a;null==u&&(u=!0),e=It("msgHash",e),rs(a),y&&(e=It("prehashed msgHash",n(e)));const w=v(e),S=d(s),A=[_(S),_(w)];if(null!=g&&!1!==g){const e=!0===g?l(r.BYTES):g;A.push(It("extraEntropy",e))}const b=Pt(...A),I=w;return{seed:b,k2sig:function(e){const t=m(e);if(!h(t))return;const r=o(t),s=c.BASE.multiply(t).toAffine(),a=i(s.x);if(a===ns)return;const n=i(r*i(I+a*S));if(n===ns)return;let d=(s.x===a?0:2)|Number(s.y&is),l=n;return u&&p(n)&&(l=function(e){return p(e)?i(-e):e}(n),d^=1),new f(a,l,d)}}}const E={lowS:t.lowS,prehash:!1},b={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(w(e))throw new Error("first arg must be private key");if(!w(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(d(e)).toRawBytes(r)},sign:function(e,r,s=E){const{seed:a,k2sig:n}=A(e,r,s),i=t,o=function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let s=Kt(e),a=Kt(e),n=0;const i=()=>{s.fill(1),a.fill(0),n=0},o=(...e)=>r(a,s,...e),c=(e=Kt(0))=>{a=o(Ot([0]),e),s=o(),0!==e.length&&(a=o(Ot([1]),e),s=o())},d=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){s=o();const t=s.slice();r.push(t),e+=s.length}return Pt(...r)};return(e,t)=>{let r;for(i(),c(e);!(r=t(d()));)c();return i(),r}}(i.hash.outputLen,i.nByteLength,i.hmac);return o(a,n)},verify:function(e,r,s,a=b){const n=e;r=It("msgHash",r),s=It("publicKey",s);const{lowS:d,prehash:l,format:h}=a;if(rs(a),"strict"in a)throw new Error("options.strict was renamed to lowS");if(void 0!==h&&"compact"!==h&&"der"!==h)throw new Error("format must be compact or der");const u="string"==typeof n||nt(n),p=!u&&!h&&"object"==typeof n&&null!==n&&"bigint"==typeof n.r&&"bigint"==typeof n.s;if(!u&&!p)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let y,g;try{if(p&&(y=new f(n.r,n.s)),u){try{"compact"!==h&&(y=f.fromDER(n))}catch(e){if(!(e instanceof as.Err))throw e}y||"der"===h||(y=f.fromCompact(n))}g=c.fromHex(s)}catch(e){return!1}if(!y)return!1;if(d&&y.hasHighS())return!1;l&&(r=t.hash(r));const{r:w,s:m}=y,S=v(r),_=o(m),A=i(S*_),E=i(w*_),I=c.BASE.multiplyAndAddUnsafe(g,A,E)?.toAffine();return!!I&&i(I.x)===w},ProjectivePoint:c,Signature:f,utils:g}}
9
9
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ls(e){return{hash:e,hmac:(t,...r)=>Pr(e,t,function(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];Te(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const a=e[t];r.set(a,s),s+=a.length}return r}(...r)),randomBytes:tt}}BigInt(4);
10
10
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
- const hs=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ps=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),us=BigInt(1),ys=BigInt(2),fs=(e,t)=>(e+t/ys)/t;const gs=Wr(hs,void 0,void 0,{sqrt:function(e){const t=hs,r=BigInt(3),s=BigInt(6),a=BigInt(11),n=BigInt(22),i=BigInt(23),o=BigInt(44),c=BigInt(88),d=e*e*e%t,l=d*d*e%t,h=Dr(l,r,t)*l%t,p=Dr(h,r,t)*l%t,u=Dr(p,ys,t)*d%t,y=Dr(u,a,t)*u%t,f=Dr(y,n,t)*y%t,g=Dr(f,o,t)*f%t,w=Dr(g,c,t)*g%t,m=Dr(w,o,t)*f%t,v=Dr(m,r,t)*l%t,S=Dr(v,i,t)*y%t,_=Dr(S,s,t)*d%t,A=Dr(_,ys,t);if(!gs.eql(gs.sqr(A),e))throw new Error("Cannot find square root");return A}}),ws=function(e,t){const r=t=>ds({...e,...ls(t)});return{...r(t),create:r}}({a:BigInt(0),b:BigInt(7),Fp:gs,n:ps,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=ps,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),s=-us*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=r,i=BigInt("0x100000000000000000000000000000000"),o=fs(n*e,t),c=fs(-s*e,t);let d=Rr(e-o*r-c*a,t),l=Rr(-o*s-c*n,t);const h=d>i,p=l>i;if(h&&(d=t-d),p&&(l=t-l),d>i||l>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:d,k2neg:p,k2:l}}}},Ar);BigInt(0),ws.ProjectivePoint;const ms=e=>{const t=qt(e),r=ws.getPublicKey(t),s=ws.ProjectivePoint.fromHex(r);return Mt(Me(s.toRawBytes(!1)))},vs=BigInt(0),Ss=BigInt(1),_s=BigInt(2),As=BigInt(7),Es=BigInt(256),bs=BigInt(113),Is=[],Ps=[],Ts=[];for(let e=0,t=Ss,r=1,s=0;e<24;e++){[r,s]=[s,(2*r+3*s)%5],Is.push(2*(5*s+r)),Ps.push((e+1)*(e+2)/2%64);let a=vs;for(let e=0;e<7;e++)t=(t<<Ss^(t>>As)*bs)%Es,t&_s&&(a^=Ss<<(Ss<<BigInt(e))-Ss);Ts.push(a)}const ks=Xt(Ts,!0),Cs=ks[0],xs=ks[1],Ks=(e,t,r)=>r>32?((e,t,r)=>t<<r-32|e>>>64-r)(e,t,r):((e,t,r)=>e<<r|t>>>32-r)(e,t,r),Os=(e,t,r)=>r>32?((e,t,r)=>e<<r-32|t>>>64-r)(e,t,r):((e,t,r)=>t<<r|e>>>32-r)(e,t,r);class Ns extends Ze{constructor(e,t,r,s=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=a,Pe(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ke(this.state)}clone(){return this._cloneInto()}keccak(){Be(this.state32),function(e,t=24){const r=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const s=(t+8)%10,a=(t+2)%10,n=r[a],i=r[a+1],o=Ks(n,i,1)^r[s],c=Os(n,i,1)^r[s+1];for(let r=0;r<50;r+=10)e[t+r]^=o,e[t+r+1]^=c}let t=e[2],a=e[3];for(let r=0;r<24;r++){const s=Ps[r],n=Ks(t,a,s),i=Os(t,a,s),o=Is[r];t=e[o],a=e[o+1],e[o]=n,e[o+1]=i}for(let t=0;t<50;t+=10){for(let s=0;s<10;s++)r[s]=e[t+s];for(let s=0;s<10;s++)e[t+s]^=~r[(s+2)%10]&r[(s+4)%10]}e[0]^=Cs[s],e[1]^=xs[s]}Oe(r)}(this.state32,this.rounds),Be(this.state32),this.posOut=0,this.pos=0}update(e){Ce(this),Te(e=Je(e));const{blockLen:t,state:r}=this,s=e.length;for(let a=0;a<s;){const n=Math.min(t-this.pos,s-a);for(let t=0;t<n;t++)r[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:s}=this;e[r]^=t,128&t&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Ce(this,!1),Te(e),this.finish();const t=this.state,{blockLen:r}=this;for(let s=0,a=e.length;s<a;){this.posOut>=r&&this.keccak();const n=Math.min(r-this.posOut,a-s);e.set(t.subarray(this.posOut,this.posOut+n),s),this.posOut+=n,s+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Pe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(xe(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Oe(this.state)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:s,rounds:a,enableXOF:n}=this;return e||(e=new Ns(t,r,s,n,a)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=r,e.outputLen=s,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Rs=(()=>{return e=1,t=136,r=32,Qe((()=>new Ns(t,e,r)));var e,t,r})(),Ds=(()=>{const e=Bt(Rs);return e.create=Rs.create,e})(),Ls=e=>{const t=(e=>{if(e){if(!(e instanceof Uint8Array)||e.length<32)throw new Error("entropy must be a Uint8Array of at least 32 bytes");const t=new Set(e);if(t.size<Math.min(8,e.length/4))throw new Error(`entropy is too repetitive (only ${t.size} unique byte values)`);const r=Ds(e);return Vt(Me(r))}{const e=Ds(Wt([rt(32),rt(32)])),t=Wt([Wt([rt(32),e]),rt(32)]),r=Ds(t);return Vt(Me(r))}})(e),r=ms(t);return{privateKey:t,publicKey:qt(r)}},Us=(e,t)=>{const r=Vt(t);if(66!==r.length||("string"!=typeof(s=r)||!s.match(/^0x[0-9A-Fa-f]+$/)))throw new Error("Can only sign hashes, given: "+t);var s;const a=ws.sign(Ut(qt(t)),Ut(qt(e))),n=1===a.recovery?"1c":"1b";return"0x"+a.toCompactHex()+n},Bs=(e,t)=>Pr(Ar,e,t),qs=Bt(Er);function Vs(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
11
+ const hs=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),us=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ps=BigInt(1),ys=BigInt(2),fs=(e,t)=>(e+t/ys)/t;const gs=Wr(hs,void 0,void 0,{sqrt:function(e){const t=hs,r=BigInt(3),s=BigInt(6),a=BigInt(11),n=BigInt(22),i=BigInt(23),o=BigInt(44),c=BigInt(88),d=e*e*e%t,l=d*d*e%t,h=Dr(l,r,t)*l%t,u=Dr(h,r,t)*l%t,p=Dr(u,ys,t)*d%t,y=Dr(p,a,t)*p%t,f=Dr(y,n,t)*y%t,g=Dr(f,o,t)*f%t,w=Dr(g,c,t)*g%t,m=Dr(w,o,t)*f%t,v=Dr(m,r,t)*l%t,S=Dr(v,i,t)*y%t,_=Dr(S,s,t)*d%t,A=Dr(_,ys,t);if(!gs.eql(gs.sqr(A),e))throw new Error("Cannot find square root");return A}}),ws=function(e,t){const r=t=>ds({...e,...ls(t)});return{...r(t),create:r}}({a:BigInt(0),b:BigInt(7),Fp:gs,n:us,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=us,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),s=-ps*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=r,i=BigInt("0x100000000000000000000000000000000"),o=fs(n*e,t),c=fs(-s*e,t);let d=Rr(e-o*r-c*a,t),l=Rr(-o*s-c*n,t);const h=d>i,u=l>i;if(h&&(d=t-d),u&&(l=t-l),d>i||l>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:d,k2neg:u,k2:l}}}},Ar);BigInt(0),ws.ProjectivePoint;const ms=e=>{const t=qt(e),r=ws.getPublicKey(t),s=ws.ProjectivePoint.fromHex(r);return Mt(Me(s.toRawBytes(!1)))},vs=BigInt(0),Ss=BigInt(1),_s=BigInt(2),As=BigInt(7),Es=BigInt(256),bs=BigInt(113),Is=[],Ps=[],Ts=[];for(let e=0,t=Ss,r=1,s=0;e<24;e++){[r,s]=[s,(2*r+3*s)%5],Is.push(2*(5*s+r)),Ps.push((e+1)*(e+2)/2%64);let a=vs;for(let e=0;e<7;e++)t=(t<<Ss^(t>>As)*bs)%Es,t&_s&&(a^=Ss<<(Ss<<BigInt(e))-Ss);Ts.push(a)}const ks=Xt(Ts,!0),Cs=ks[0],xs=ks[1],Ks=(e,t,r)=>r>32?((e,t,r)=>t<<r-32|e>>>64-r)(e,t,r):((e,t,r)=>e<<r|t>>>32-r)(e,t,r),Os=(e,t,r)=>r>32?((e,t,r)=>e<<r-32|t>>>64-r)(e,t,r):((e,t,r)=>t<<r|e>>>32-r)(e,t,r);class Ns extends Ze{constructor(e,t,r,s=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=a,Pe(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ke(this.state)}clone(){return this._cloneInto()}keccak(){Be(this.state32),function(e,t=24){const r=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const s=(t+8)%10,a=(t+2)%10,n=r[a],i=r[a+1],o=Ks(n,i,1)^r[s],c=Os(n,i,1)^r[s+1];for(let r=0;r<50;r+=10)e[t+r]^=o,e[t+r+1]^=c}let t=e[2],a=e[3];for(let r=0;r<24;r++){const s=Ps[r],n=Ks(t,a,s),i=Os(t,a,s),o=Is[r];t=e[o],a=e[o+1],e[o]=n,e[o+1]=i}for(let t=0;t<50;t+=10){for(let s=0;s<10;s++)r[s]=e[t+s];for(let s=0;s<10;s++)e[t+s]^=~r[(s+2)%10]&r[(s+4)%10]}e[0]^=Cs[s],e[1]^=xs[s]}Oe(r)}(this.state32,this.rounds),Be(this.state32),this.posOut=0,this.pos=0}update(e){Ce(this),Te(e=Je(e));const{blockLen:t,state:r}=this,s=e.length;for(let a=0;a<s;){const n=Math.min(t-this.pos,s-a);for(let t=0;t<n;t++)r[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:s}=this;e[r]^=t,128&t&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Ce(this,!1),Te(e),this.finish();const t=this.state,{blockLen:r}=this;for(let s=0,a=e.length;s<a;){this.posOut>=r&&this.keccak();const n=Math.min(r-this.posOut,a-s);e.set(t.subarray(this.posOut,this.posOut+n),s),this.posOut+=n,s+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Pe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(xe(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Oe(this.state)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:s,rounds:a,enableXOF:n}=this;return e||(e=new Ns(t,r,s,n,a)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=r,e.outputLen=s,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Rs=(()=>{return e=1,t=136,r=32,Qe((()=>new Ns(t,e,r)));var e,t,r})(),Ds=(()=>{const e=Bt(Rs);return e.create=Rs.create,e})(),Ls=e=>{const t=(e=>{if(e){if(!(e instanceof Uint8Array)||e.length<32)throw new Error("entropy must be a Uint8Array of at least 32 bytes");const t=new Set(e);if(t.size<Math.min(8,e.length/4))throw new Error(`entropy is too repetitive (only ${t.size} unique byte values)`);const r=Ds(e);return Vt(Me(r))}{const e=Ds(Wt([rt(32),rt(32)])),t=Wt([Wt([rt(32),e]),rt(32)]),r=Ds(t);return Vt(Me(r))}})(e),r=ms(t);return{privateKey:t,publicKey:qt(r)}},Us=(e,t)=>{const r=Vt(t);if(66!==r.length||("string"!=typeof(s=r)||!s.match(/^0x[0-9A-Fa-f]+$/)))throw new Error("Can only sign hashes, given: "+t);var s;const a=ws.sign(Ut(qt(t)),Ut(qt(e))),n=1===a.recovery?"1c":"1b";return"0x"+a.toCompactHex()+n},Bs=(e,t)=>Pr(Ar,e,t),qs=Bt(Er);function Vs(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
12
12
  /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
13
- var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ms(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ws(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Fs=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Gs(e,t){if(s=t,(r=e).buffer===s.buffer&&r.byteOffset<s.byteOffset+s.byteLength&&s.byteOffset<r.byteOffset+r.byteLength&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported");var r,s}const js=(e,t)=>{function r(r,...s){if(Vs(r),!Fs)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=s[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?Vs(t):Vs(t,e.nonceLength)}const a=e.tagLength;a&&void 0!==s[1]&&Vs(s[1]);const n=t(r,...s),i=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Vs(t)}};let o=!1;const c={encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Vs(e),i(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(Vs(e),a&&e.length<a)throw new Error("invalid ciphertext length: smaller than tagLength="+a);return i(n.decrypt.length,t),n.decrypt(e,t)}};return c}return Object.assign(r,e),r};function Hs(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!$s(t))throw new Error("invalid output, must be aligned");return t}function $s(e){return e.byteOffset%4==0}function Ys(e){return Uint8Array.from(e)}const zs=16;function Js(e){return e<<1^283&-(e>>7)}function Xs(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Js(e);return r}const Zs=(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Js(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let s=e[255-r];s|=s<<8,t[e[r]]=255&(s^s>>4^s>>5^s>>6^s>>7^99)}return Ws(e),t})(),Qs=Zs.map(((e,t)=>Zs.indexOf(t))),ea=e=>e<<8|e>>>24;function ta(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map(((r,s)=>t(e[s]))),s=r.map(ea),a=s.map(ea),n=a.map(ea),i=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let d=0;d<256;d++){const l=256*t+d;i[l]=r[t]^s[d],o[l]=a[t]^n[d],c[l]=e[t]<<8|e[d]}return{sbox:e,sbox2:c,T0:r,T1:s,T2:a,T3:n,T01:i,T23:o}}const ra=ta(Zs,(e=>Xs(e,3)<<24|e<<16|e<<8|Xs(e,2))),sa=ta(Qs,(e=>Xs(e,11)<<24|Xs(e,13)<<16|Xs(e,9)<<8|Xs(e,14))),aa=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Js(r))e[t]=r;return e})();function na(e){Vs(e);const t=e.length;if(![16,24,32].includes(t))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+t);const{sbox2:r}=ra,s=[];$s(e)||s.push(e=Ys(e));const a=Ms(e),n=a.length,i=e=>oa(r,e,e,e,e),o=new Uint32Array(t+28);o.set(a);for(let e=n;e<o.length;e++){let t=o[e-1];e%n==0?t=i((c=t)<<24|c>>>8)^aa[e/n-1]:n>6&&e%n==4&&(t=i(t)),o[e]=o[e-n]^t}var c;return Ws(...s),o}function ia(e,t,r,s,a,n){return e[r<<8&65280|s>>>8&255]^t[a>>>8&65280|n>>>24&255]}function oa(e,t,r,s,a){return e[255&t|65280&r]|e[s>>>16&255|a>>>16&65280]<<16}function ca(e,t,r,s,a){const{sbox2:n,T01:i,T23:o}=ra;let c=0;t^=e[c++],r^=e[c++],s^=e[c++],a^=e[c++];const d=e.length/4-2;for(let n=0;n<d;n++){const n=e[c++]^ia(i,o,t,r,s,a),d=e[c++]^ia(i,o,r,s,a,t),l=e[c++]^ia(i,o,s,a,t,r),h=e[c++]^ia(i,o,a,t,r,s);t=n,r=d,s=l,a=h}return{s0:e[c++]^oa(n,t,r,s,a),s1:e[c++]^oa(n,r,s,a,t),s2:e[c++]^oa(n,s,a,t,r),s3:e[c++]^oa(n,a,t,r,s)}}function da(e,t,r,s,a){const{sbox2:n,T01:i,T23:o}=sa;let c=0;t^=e[c++],r^=e[c++],s^=e[c++],a^=e[c++];const d=e.length/4-2;for(let n=0;n<d;n++){const n=e[c++]^ia(i,o,t,a,s,r),d=e[c++]^ia(i,o,r,t,a,s),l=e[c++]^ia(i,o,s,r,t,a),h=e[c++]^ia(i,o,a,s,r,t);t=n,r=d,s=l,a=h}return{s0:e[c++]^oa(n,t,a,s,r),s1:e[c++]^oa(n,r,t,a,s),s2:e[c++]^oa(n,s,r,t,a),s3:e[c++]^oa(n,a,s,r,t)}}function la(e,t,r,s){Vs(t,zs),Vs(r);const a=r.length;Gs(r,s=Hs(a,s));const n=t,i=Ms(n);let{s0:o,s1:c,s2:d,s3:l}=ca(e,i[0],i[1],i[2],i[3]);const h=Ms(r),p=Ms(s);for(let t=0;t+4<=h.length;t+=4){p[t+0]=h[t+0]^o,p[t+1]=h[t+1]^c,p[t+2]=h[t+2]^d,p[t+3]=h[t+3]^l;let r=1;for(let e=n.length-1;e>=0;e--)r=r+(255&n[e])|0,n[e]=255&r,r>>>=8;({s0:o,s1:c,s2:d,s3:l}=ca(e,i[0],i[1],i[2],i[3]))}const u=zs*Math.floor(h.length/4);if(u<a){const e=new Uint32Array([o,c,d,l]),t=(y=e,new Uint8Array(y.buffer,y.byteOffset,y.byteLength));for(let e=u,n=0;e<a;e++,n++)s[e]=r[e]^t[n];Ws(e)}var y;return s}const ha=js({blockSize:16,nonceLength:16},(function(e,t){function r(r,s){if(Vs(r),void 0!==s&&(Vs(s),!$s(s)))throw new Error("unaligned destination");const a=na(e),n=Ys(t),i=[a,n];$s(r)||i.push(r=Ys(r));const o=la(a,n,r,s);return Ws(...i),o}return{encrypt:(e,t)=>r(e,t),decrypt:(e,t)=>r(e,t)}}));const pa=js({blockSize:16,nonceLength:16},(function(e,t,r={}){const s=!r.disablePadding;return{encrypt(r,a){const n=na(e),{b:i,o:o,out:c}=function(e,t,r){Vs(e);let s=e.length;const a=s%zs;if(!t&&0!==a)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");$s(e)||(e=Ys(e));const n=Ms(e);if(t){let e=zs-a;e||(e=zs),s+=e}return Gs(e,r=Hs(s,r)),{b:n,o:Ms(r),out:r}}(r,s,a);let d=t;const l=[n];$s(d)||l.push(d=Ys(d));const h=Ms(d);let p=h[0],u=h[1],y=h[2],f=h[3],g=0;for(;g+4<=i.length;)p^=i[g+0],u^=i[g+1],y^=i[g+2],f^=i[g+3],({s0:p,s1:u,s2:y,s3:f}=ca(n,p,u,y,f)),o[g++]=p,o[g++]=u,o[g++]=y,o[g++]=f;if(s){const e=function(e){const t=new Uint8Array(16),r=Ms(t);t.set(e);const s=zs-e.length;for(let e=zs-s;e<zs;e++)t[e]=s;return r}(r.subarray(4*g));p^=e[0],u^=e[1],y^=e[2],f^=e[3],({s0:p,s1:u,s2:y,s3:f}=ca(n,p,u,y,f)),o[g++]=p,o[g++]=u,o[g++]=y,o[g++]=f}return Ws(...l),c},decrypt(r,a){!function(e){if(Vs(e),e.length%zs!=0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size 16")}(r);const n=function(e){const t=na(e),r=t.slice(),s=t.length,{sbox2:a}=ra,{T0:n,T1:i,T2:o,T3:c}=sa;for(let e=0;e<s;e+=4)for(let a=0;a<4;a++)r[e+a]=t[s-e-4+a];Ws(t);for(let e=4;e<s-4;e++){const t=r[e],s=oa(a,t,t,t,t);r[e]=n[255&s]^i[s>>>8&255]^o[s>>>16&255]^c[s>>>24]}return r}(e);let i=t;const o=[n];$s(i)||o.push(i=Ys(i));const c=Ms(i);a=Hs(r.length,a),$s(r)||o.push(r=Ys(r)),Gs(r,a);const d=Ms(r),l=Ms(a);let h=c[0],p=c[1],u=c[2],y=c[3];for(let e=0;e+4<=d.length;){const t=h,r=p,s=u,a=y;h=d[e+0],p=d[e+1],u=d[e+2],y=d[e+3];const{s0:i,s1:o,s2:c,s3:f}=da(n,h,p,u,y);l[e++]=i^t,l[e++]=o^r,l[e++]=c^s,l[e++]=f^a}return Ws(...o),function(e,t){if(!t)return e;const r=e.length;if(!r)throw new Error("aes/pcks5: empty ciphertext not allowed");const s=e[r-1];if(s<=0||s>16)throw new Error("aes/pcks5: wrong padding");const a=e.subarray(0,-s);for(let t=0;t<s;t++)if(e[r-t-1]!==s)throw new Error("aes/pcks5: wrong padding");return a}(a,s)}}}));function ua(e,t,r,s=!0){if(!r.startsWith("aes-"))throw new Error("AES: unsupported mode");const a=e.length;if(r.startsWith("aes-128")&&16!==a||r.startsWith("aes-256")&&32!==a)throw new Error("AES: wrong key length");if(16!==t.length)throw new Error("AES: wrong IV length");if(["aes-128-cbc","aes-256-cbc"].includes(r))return pa(e,t,{disablePadding:!s});if(["aes-128-ctr","aes-256-ctr"].includes(r))return ha(e,t);throw new Error("AES: unsupported mode")}const ya=(e,t,r)=>{const s=(null==r?void 0:r.ephemPrivateKey)?Ut(r.ephemPrivateKey):rt(32),a=rt(16),n=ws.getPublicKey(s),i=ws.ProjectivePoint.fromHex(n).toRawBytes(!1),o=ws.getSharedSecret(s,Ut(e),!0).slice(1),c=qs(o),d=c.subarray(0,32),l=c.subarray(32),h=function(e,t,r,s="aes-128-ctr",a=!0){return ua(t,r,s,a).encrypt(e)}(Ft(t),d,a,"aes-256-cbc"),p=Wt([a,i,h]),u=Bs(l,p);return{iv:Me(a),ephemPublicKey:Me(i),ciphertext:Me(h),mac:Me(u)}},fa=(e,t)=>{let r;try{r=ws.getSharedSecret(Ut(e),t.ephemPublicKey,!0).slice(1)}catch(e){throw new Error(`Invalid MAC: data integrity check failed: ${e}`)}const s=qs(r),a=s.subarray(0,32),n=s.subarray(32),i=Ut(t.ciphertext),o=Ut(t.iv),c=Ut(t.ephemPublicKey),d=Ut(t.mac),l=Wt([o,c,i]);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e[s]^t[s];return 0===r}(Bs(n,l),d))throw new Error("Invalid MAC: data integrity check failed");const h=function(e,t,r,s="aes-128-ctr",a=!0){return ua(t,r,s,a).decrypt(e)}(i,a,o,"aes-256-cbc");return function(e){if(!(e instanceof Uint8Array))throw new TypeError("bytesToUtf8 expected Uint8Array, got "+typeof e);return(new TextDecoder).decode(e)}(h)};const ga=(e,t,r)=>{const s=Mt(e);return ya("04"+s,t,r)},wa=(e,t)=>{const r=qt(e);return fa(r,t)},ma=e=>(e=>{const t=Ft(e),r=Vt(Me(t)),s=Ds(Ut(r));return Vt(Me(s))})(e);function va(e,t,r,s=!0,a){Lt(r,32),ot("compressed",s);const n=function(e){return Lt(e,64),ws.Signature.fromCompact(e)}(e);return function(e=e=>new Uint8Array(e),t,r){return"function"==typeof e&&(e=e(t)),Lt(e,t),r&&e.set(r),e}(a,s?33:65,n.addRecoveryBit(t).recoverPublicKey(r).toRawBytes(s))}ws.ProjectivePoint,ws.CURVE.n;const Sa={keccak256:ma};function _a(e){if(!Aa(e))throw new Error("Invalid JSON string");return JSON.parse(e)}function Aa(e){if("string"!=typeof e)return!1;try{return JSON.parse(e),!0}catch(e){return!1}}function Ea(e,t,r,s){ke(e);const a=function(e,t){if(void 0!==t&&"[object Object]"!=={}.toString.call(t))throw new Error("options should be object or undefined");return Object.assign(e,t)}({dkLen:32,asyncTick:10},s),{c:n,dkLen:i,asyncTick:o}=a;if(Pe(n),Pe(i),Pe(o),n<1)throw new Error("iterations (c) should be >= 1");const c=Xe(t),d=Xe(r),l=new Uint8Array(i),h=Pr.create(e,c),p=h._cloneInto().update(d);return{c:n,dkLen:i,asyncTick:o,DK:l,PRF:h,PRFSalt:p}}function ba(e,t,r,s){const{c:a,dkLen:n,DK:i,PRF:o,PRFSalt:c}=Ea(e,t,r,s);let d;const l=new Uint8Array(4),h=Ne(l),p=new Uint8Array(o.outputLen);for(let e=1,t=0;t<n;e++,t+=o.outputLen){const r=i.subarray(t,t+o.outputLen);h.setInt32(0,e,!1),(d=c._cloneInto(d)).update(l).digestInto(p),r.set(p.subarray(0,r.length));for(let e=1;e<a;e++){o._cloneInto(d).update(p).digestInto(p);for(let e=0;e<r.length;e++)r[e]^=p[e]}}return function(e,t,r,s,a){return e.destroy(),t.destroy(),s&&s.destroy(),Oe(a),r}(o,c,i,d,p)}const Ia="wsdkmk:v1:";function Pa(e){if(ze(e).length<16)throw new Error("Salt is too short: must be at least 16 bytes");if(new Set(e).size<=6)throw new Error("Weak salt: too few unique characters")}function Ta({password:e,salt:t}){Pa(t);const r=function(e,t,r,s,a){if(!["sha256","sha512"].includes(a))throw new Error("Only sha256 and sha512 are supported");return Lt(e),Lt(t),ba(Ar,e,t,{c:r,dkLen:s})}(ze(e.normalize("NFKC").trim()),ze(t),131072,32,"sha256");return Ls(r)}function ka(e,t){return Ia+function(e,t){return a.AES.encrypt(e,t).toString()}("string"==typeof e?e:JSON.stringify(e),t)}function Ca(e,t){const r=function(e,t){return a.AES.decrypt(e,t).toString(a.enc.Utf8)}(e.startsWith(Ia)?e.slice(10):e,t);if(r)return Aa(r)?_a(r):r}class xa{constructor(){}validatePrivateKey(e){!function(e){if(!/^0x[0-9a-fA-F]{64}$/.test(e))throw new Error("Invalid private key: must be a 32-byte hex string");if(!ws.utils.isValidPrivateKey(e.slice(2)))throw new Error("Invalid private key: outside secp256k1 scalar range")}(e)}getMasterKey(){return{buffer:ze(me),key:me}}encryptWithMasterKey({data:e}){return ka(e,this.getMasterKey().key)}isWrappedByMasterKey(e){return function(e){return e.startsWith(Ia)||e.startsWith("U2FsdGVkX1")}(e)}decryptWithMasterKey({cipherText:e}){try{const t=Ca(e,this.getMasterKey().key);if(void 0!==t)return t}catch(e){return void ue.error("Decryption failed with master key",e)}ue.error("Decryption failed with master key")}validatePublicKey(e){!function(e){if(!/^[0-9a-fA-F]{128}$/.test(e))throw new Error("Invalid public key: must be a 64-byte raw uncompressed hex string");if(new Set(e).size<=8)throw new Error("Weak public key: too few unique characters")}(e)}validateSalt(e){Pa(e)}sign({message:e,signingKey:t}){try{this.validatePrivateKey(t);const r=ma(e);return{message:e,signature:Us(t,r),hashedMessage:r}}catch(e){throw ue.error("SDK::Cipher::sign",e),new Error(`Error signing message: ${e}`)}}async encrypt({data:e,encryptionKey:t}){try{return this.validatePublicKey(t),await ga(t,e)}catch(e){throw ue.error("Error encrypting data: ",e),new Error("Something happened during data encryption.")}}async decrypt({cipherText:e,decryptionKey:t}){try{this.validatePrivateKey(t);return await wa(t,(r=e,"string"==typeof r?JSON.parse(r):r))}catch(e){throw ue.error("SDK::CipherService::decrypt::error: ",e),new Error("That doesn’t seem right. Check your login details and try again.")}var r}async getCredentialsKeyPair(e){try{let t;switch(e.authType){case exports.AuthType.Password:if(!e.password||!e.salt)throw new Error("Password and salt are required");return t=await this.deriveKeyPairFromPassword({password:e.password,salt:e.salt}),t;case exports.AuthType.Passkey:if(!e.prfValue)throw new Error("PRF value is required");return t=await this.deriveKeyPairFromPasskey({inputKeyMaterial:e.prfValue}),t;default:throw new Error(`Unknown AuthType: ${e.authType}`)}}catch(e){return ue.error("SDK::CipherService::getCredentialsKeyPair::error",e),Promise.reject(e)}}async prepareDataForTransport({data:e,wallabyPublicKey:t}){try{return ga(t,e)}catch(e){throw ue.error("SDK::CipherService::prepareDataForTransport::error",e),new Error("Error preparing data for transport")}}async prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:t,wallabyPublicKey:r,options:s}){const a=await this.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:t,options:s});return this.prepareDataForTransport({data:a,wallabyPublicKey:r})}async doubleEncrypt({decryptedData:e,credentialsKeyPair:t,deviceKeyPair:r}){try{const s=await this.encrypt({data:e,encryptionKey:r.publicKey});return await this.encrypt({data:JSON.stringify(s),encryptionKey:t.publicKey})}catch(e){throw ue.error("SDK::doubleEncrypt::error",e),e}}async prepareTransportDataForStorage({transportData:e,credentialsKeyPair:t,deviceKeyPair:r}){try{const s=await this.decrypt({cipherText:e,decryptionKey:r.privateKey}),a=await this.encrypt({data:s,encryptionKey:r.publicKey});return await this.encrypt({data:JSON.stringify(a),encryptionKey:t.publicKey})}catch(e){throw ue.error("SDK::prepareTransportDataForStorage::error",e),e}}async displayDataFromServer({encryptedData:e,encryptedDevicePrivateKey:t,options:r}){try{const s=await this.getCredentialsKeyPair(r),a=await this.decrypt({cipherText:t,decryptionKey:s.privateKey});if(!a)throw new Error("That doesn’t seem right. Check your login details and try again.");return await this.decrypt({cipherText:e,decryptionKey:a})}catch(e){throw ue.error("SDK::CipherService::displayDataFromServer::error",e),e}}async displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:t,options:r}){const s=await this.getCredentialsKeyPair(r),a=await this.decrypt({cipherText:t,decryptionKey:s.privateKey});if(!a)throw new Error("Credentials are not correct, please provide the correct credentials");const n=await this.decrypt({cipherText:e,decryptionKey:s.privateKey});if(!n)throw new Error("That doesn’t seem right. Check your login details and try again.");const i=await this.decrypt({cipherText:JSON.parse(n),decryptionKey:a});if(!i)throw new Error("That doesn’t seem right. Check your login details and try again.");return i}async flipEncryptedData({cipherText:e,decryptionKey:t,encryptionKey:r}){try{const s=await this.decrypt({cipherText:e,decryptionKey:t});return await this.encrypt({data:s,encryptionKey:r})}catch(e){throw ue.error("SDK::CipherService::displayDataFromServer::error",e),e}}async deriveKeyPairFromPasskey({inputKeyMaterial:e}){return function({inputKeyMaterial:e}){return Ls(e)}({inputKeyMaterial:e})}async deriveKeyPairFromPassword({password:e,salt:t}){return Ta({password:e,salt:t})}}class Ka{constructor(){this.activeLocks=new Set}async withLock(e,t){const r="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator?navigator.locks:void 0;if(r)return r.request(e,{ifAvailable:!0},(async r=>{if(!r)throw new Error(`Operation '${e}' is already in progress. Please wait for it to complete.`);return t()}));if(this.activeLocks.has(e))throw new Error(`Operation '${e}' is already in progress. Please wait for it to complete.`);this.activeLocks.add(e);try{return await t()}finally{this.activeLocks.delete(e)}}isLocked(e){return this.activeLocks.has(e)}clearAllLocks(){this.activeLocks.clear()}}const Oa=new Ka;class Na{constructor({deviceStorage:e,userId:t,environment:r}){this._walletSpecificKeys=[exports.V2KeyNames.EncryptedStandardSeedPhrase,exports.V2KeyNames.PrimaryDeviceKeyShare,exports.V2KeyNames.BackupDeviceKeyShare],this._keysProtectedByMasterKey=[exports.V2KeyNames.AccessToken,exports.V2KeyNames.RefreshToken,exports.V2KeyNames.PasskeyCredential,exports.V2KeyNames.ClientAuthToken],this.userId=t,this.environment=null!=r?r:ge,this.shortenedEnv=this.environment.slice(0,1),this.deviceLocalStorage=e,this.cipher=new xa}async getFromDeviceStorage(e){return this.deviceLocalStorage.getItem?this.deviceLocalStorage.getItem(e):this.deviceLocalStorage.getItemAsync?await this.deviceLocalStorage.getItemAsync(e):null}async setInDeviceStorage(e,t){return this.deviceLocalStorage.setItem?this.deviceLocalStorage.setItem(e,t):this.deviceLocalStorage.setItemAsync?await this.deviceLocalStorage.setItemAsync(e,t):void 0}async fetch(e,t){var r;let s;if(await(null!==(r=this._walRecovery)&&void 0!==r?r:this._walRecovery=this.recoverCommit().catch((e=>{ue.error("SDK::StorageService::fetch::wal recovery failed",e)}))),this._walletSpecificKeys.includes(e)){if(!(null==t?void 0:t.walletId))throw new Error(`A walletId is required to fetch: ${e}`);s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t.walletId}`}else s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;Se.isNative&&(s=be(s));const a=await this.getItem(s);if(a){if(this._keysProtectedByMasterKey.includes(e)){if(!this.cipher.isWrappedByMasterKey(a))return a;const e=this.cipher.decryptWithMasterKey({cipherText:a});return e||void ue.error(`Failed to decrypt item with key ${s}`)}return a}ue.debug(`(404): Item with key ${s} was not found in storage.`)}async save(e,t,r){let s,a;if(this._walletSpecificKeys.includes(e)){if(!(null==r?void 0:r.walletId))throw new Error(`A walletId is required to save: ${e}`);s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${r.walletId}`}else s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;if(Se.isNative&&(s=be(s)),this._keysProtectedByMasterKey.includes(e)){a=this.cipher.encryptWithMasterKey({data:t})}else a="string"==typeof t?t:JSON.stringify(t);return await this.setItem(s,a)}async saveInBulk(e){await Promise.all(e.map((e=>this.save(e.key,e.value,{walletId:e.walletId}))))}_computeRawKey(e,t){let r;if(this._walletSpecificKeys.includes(e)){if(!t)throw new Error(`A walletId is required to compute key: ${e}`);r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t}`}else r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;return ve?r:be(r)}_serializeValue(e,t){return this._keysProtectedByMasterKey.includes(e)?this.cipher.encryptWithMasterKey({data:t}):"string"==typeof t?t:JSON.stringify(t)}async _applyWAL(e){for(const{rawKey:t,value:r}of e.writes)await this.setItem(t,r);for(const t of e.deletes)await this.removeItem(t)}async commitBatch(e,t){const r={writes:e.map((({key:e,value:t,walletId:r})=>({rawKey:this._computeRawKey(e,r),value:this._serializeValue(e,t)}))),deletes:(null!=t?t:[]).map((({key:e,walletId:t})=>this._computeRawKey(e,t)))};await this.recoverCommit();const s=this._computeRawKey(exports.V2KeyNames.PendingCommit);await this.setItem(s,JSON.stringify(r)),await this._applyWAL(r),await this.removeItem(s)}async recoverCommit(){const e=this._computeRawKey(exports.V2KeyNames.PendingCommit),t=await this.getItem(e);if(!t)return;let r;try{r=_a(t)}catch(t){return ue.error("SDK::StorageService::recoverCommit::corrupt WAL, discarding",t),void await this.removeItem(e)}await this._applyWAL(r),await this.removeItem(e)}async delete(e,t){let r;if(this._walletSpecificKeys.includes(e)){if(!(null==t?void 0:t.walletId))throw new Error(`A walletId is required to delete: ${e}`);r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t.walletId}`}else r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;return Se.isNative&&(r=be(r)),await this.removeItem(r)}setItem(e,t){if(this.deviceLocalStorage.setItem)return this.deviceLocalStorage.setItem(e,t);if(this.deviceLocalStorage.setItemAsync)return this.deviceLocalStorage.setItemAsync(e,t);throw new Error("setItem function is is not defined")}getItem(e){if(this.deviceLocalStorage.getItem)return this.deviceLocalStorage.getItem(e);if(this.deviceLocalStorage.getItemAsync)return this.deviceLocalStorage.getItemAsync(e);throw new Error("getItem function is not defined")}removeItem(e){if(this.deviceLocalStorage.removeItem)return this.deviceLocalStorage.removeItem(e);if(this.deviceLocalStorage.deleteItemAsync)return this.deviceLocalStorage.deleteItemAsync(e);throw new Error("removeItem function is not defined")}async checkPrivateKeyExists(){return!!await this.getEncryptedPrivateKey()}async checkPrimaryKeyShareExists(e){return!!await this.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:e})}async checkBackupKeyShareExists(e){return!!await this.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e})}async checkSeedPhraseExists(e){return!!await this.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard,e)}getSeedPhraseV2KeyName(e){if(e===exports.SeedPhraseType.Standard)return exports.V2KeyNames.EncryptedStandardSeedPhrase;throw new Error(`Unsupported seed phrase type: ${e}`)}async setEncryptedPrivateKey(e,t){const r=a.AES.encrypt(e,t).toString();await this.setItem(`${this.environment}-client-auth-private-key-${this.userId}`,r)}async getV1EncryptedPrivateKey(){const e=`encryptedPrivateKey_${this.userId}`,t=`${this.environment}-client-auth-private-key-${this.userId}`,r=await this.getItem(t),s=await this.getItem(e);return r||s}async getEncryptedPrivateKey(){const e=await this.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey);if(e)return e;const t=`encryptedPrivateKey_${this.userId}`,r=await this.getItem(t);if(r)return r;{const e=`${this.environment}-client-auth-private-key-${this.userId}`,t=await this.getItem(e);if(t)return t}ue.error("SDK::StorageService::getEncryptedPrivateKey: private key not found")}async getDecryptedV1PrivateKey(e){try{const t=await this.getV1EncryptedPrivateKey();if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return r||void 0}catch(e){return void ue.error("SDK::StorageService::getDecryptedV1PrivateKey::error",e)}}async getDecryptedPrivateKey(e){try{const t=await this.getEncryptedPrivateKey();if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return r||void 0}catch(e){return void ue.error("SDK::StorageService::getDecryptedPrivateKey::error",e)}}async setEncryptedSeedPhrase({decryptedSeedPhrase:e,seedPhraseType:t,password:r,deviceAuthPublicKey:s,getUserSalt:n,salt:i,walletId:o}){const c=await ga(s,e),d=null!=i?i:await n();if(!d)throw new Error("User salt could not be retrieved, Seed phrase could not be encrypted");const l=`${d}${r}`,h=await a.AES.encrypt(JSON.stringify(c),l),p=this.getSeedPhraseV2KeyName(t);return await this.save(p,h.toString(),{walletId:o}),!0}async getEncryptedSeedPhrase(e,t){const r=this.getSeedPhraseV2KeyName(e),s=await this.fetch(r,{walletId:t});if(s)return s;if(!await this.isLegacySeedFallbackSafeFor(t))return;let a;if(e===exports.SeedPhraseType.Standard&&(a=`encryptedSeed_${this.userId}`),a){const e=await this.getItem(a);if(e){return await this.claimLegacySeedFallbackFor(t)?e:void 0}}if(!s){const r=`${this.environment}-encrypted-${e}-seedPhrase-${this.userId}`,s=await this.getItem(r);if(s){return await this.claimLegacySeedFallbackFor(t)?s:void 0}}}async isLegacySeedFallbackSafeFor(e){const t=await this.fetch(exports.V2KeyNames.LegacySeedClaimedWalletId);return!t||t===e}async claimLegacySeedFallbackFor(e){const t=`legacy-seed-claim:${this.environment}:${this.userId}`;try{return await Oa.withLock(t,(async()=>{const t=await this.fetch(exports.V2KeyNames.LegacySeedClaimedWalletId);return t?t===e:(await this.save(exports.V2KeyNames.LegacySeedClaimedWalletId,e),!0)}))}catch(e){return ue.error("SDK::StorageService::claimLegacySeedFallbackFor::lock contention, treating as lost race",e),!1}}async getV1EncryptedSeedPhrase(){const e=`${this.environment}-encrypted-${exports.SeedPhraseType.Standard}-seedPhrase-${this.userId}`,t=await this.getItem(e);if(t)return t}async getV1DecryptedSeedPhrase(e,t){const r=await this.getV1EncryptedSeedPhrase(),s=await this.getDecryptedV1PrivateKey(e);if(!r||!s)return;const n=`${t}${e}`,i=_a(a.AES.decrypt(r,n).toString(a.enc.Utf8));return await wa(s,i)}async getDecryptedSeedPhrase({password:e,seedPhraseType:t,getUserSalt:r,salt:s,walletId:n}){const i=await this.getEncryptedSeedPhrase(t,n),o=await this.getDecryptedPrivateKey(e);if(!i||!o)return;const c=`${null!=s?s:await r()}${e}`,d=_a(a.AES.decrypt(i,c).toString(a.enc.Utf8));return await wa(o,d)}async setAccessToken(e){await this.save(exports.LocalStorageItems.AccessToken,e)}async getAccessToken(){let e=await this.fetch(exports.LocalStorageItems.AccessToken);if(e)return e;const t=`accessToken_${this.userId}`,r=await this.getItem(t);if(r)e=r;else{const t=`${this.environment}-access-token-${this.userId}`,r=await this.getItem(t);r&&(e=r)}return e?(await this.setAccessToken(e),e):void 0}async clearLocalStorage(e){const t=[exports.LocalStorageItems.AccessToken,exports.LocalStorageItems.RefreshToken,exports.V2KeyNames.EncryptedDevicePrivateKey,exports.V2KeyNames.ClientAuthPublicKey,exports.V2KeyNames.WallabyAuthPubKey,exports.V2KeyNames.PasskeyCredential,exports.V2KeyNames.MigrationVersion,exports.V2KeyNames.LastMigratedAt,exports.V2KeyNames.ClientAuthToken,exports.V2KeyNames.PasswordResetAttempts,exports.V2KeyNames.MigrationAttempts,exports.V2KeyNames.CredentialConversionInProgress,exports.V2KeyNames.PendingCommit];await Promise.all(t.map((e=>this.delete(e)))),e&&await Promise.all(this._walletSpecificKeys.map((t=>this.delete(t,{walletId:e}))));const r=[`${this.environment}-access-token-${this.userId}`,`${this.environment}-encrypted-${exports.SeedPhraseType.Standard}-seedPhrase-${this.userId}`,`${this.environment}-client-auth-private-key-${this.userId}`,`${this.environment}-wallaby-auth-public-key-${this.userId}`,`encryptedPrivateKey_${this.userId}`,`wallabyAuthPubKey_${this.userId}`,`encryptedSeed_${this.userId}`,`accessToken_${this.userId}`];await Promise.all(r.map((e=>this.removeItem(e)))),await this.delete(exports.V2KeyNames.LegacySeedClaimedWalletId)}async loadDeviceInformation(e){return{authTokens:{accessToken:await this.fetch(exports.LocalStorageItems.AccessToken),clientAuthToken:await this.fetch(exports.LocalStorageItems.ClientAuthToken)},user:{clientUserId:this.userId,encryptedStandardSeedPhrase:await this.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:e}),wallabyUserId:void 0},credentials:{deviceAuthPrivateKey:void 0,deviceAuthPublicKey:void 0,deviceEncryptedPrivateKey:await this.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),wallabyPublicKey:await this.fetch(exports.V2KeyNames.WallabyAuthPubKey)},hostname:"undefined"==typeof window?"republic.com":window.location.hostname}}}function Ra(e,t=Date.now){return!e||La(e,t)<=0}function Da(e,t,r=Date.now){return!!e&&La(e,r)<=1e3*t}function La(e,t=Date.now){const r=n.jwtDecode(e).exp;return 1e3*(null!=r?r:0)-t()}const Ua={signatureMessage:{fullPath:"/auth/signature-message",method:exports.RequestMethod.Post,requiresAccessToken:!1},signIn:{fullPath:"/auth/sign-in",method:exports.RequestMethod.Post,requiresAccessToken:!1},signUp:{fullPath:"/auth/sign-up",method:exports.RequestMethod.Post,requiresAccessToken:!1},refreshAccessToken:{fullPath:"/auth/refresh-access-token",method:exports.RequestMethod.Post,requiresAccessToken:!0},clientAuthPubKey:{fullPath:"auth/client-auth-pubkey",method:exports.RequestMethod.Put,requiresAccessToken:!0},wallabyAuthPublicKey:{fullPath:"/auth/wallaby-auth-pubkey",method:exports.RequestMethod.Get,requiresAccessToken:!0},getUserSalt:{fullPath:"/users/salt",method:exports.RequestMethod.Get,requiresAccessToken:!0},getPasskeyCredentials:{fullPath:"/auth/passkey-credentials",method:exports.RequestMethod.Get,requiresAccessToken:!0},issueJwtToken:{fullPath:"/auth/issue-jwt-token",method:exports.RequestMethod.Post,requiresAccessToken:!1}};function Ba(e){return/^[a-zA-Z0-9-_]+$/.test(e)}function qa(e){return"string"!=typeof e?"":e.normalize("NFKD").trim().toLowerCase().replace(/\s+/g," ")}function Va(e){return t.validateMnemonic(qa(e))}function Ma(e,t="The seed phrase is not a valid BIP-39 mnemonic. Expected 12, 15, 18, 21 or 24 words from the BIP-39 English wordlist."){if(!Va(e))throw new V({message:t,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return qa(e)}function Wa(e){const{apiKey:t,baseUrl:r,userId:s,clientAuthToken:a,options:i}=e;if("string"!=typeof t||!Ba(t))throw new Error("Invalid or empty API key provided.");if("string"!=typeof r||!function(e){try{return new URL(e),!0}catch(e){return!1}}(r))throw new Error("Invalid or empty base URL provided.");if("string"!=typeof s||!Ba(s))throw new Error("Invalid or empty user ID provided.");if("string"!=typeof a||!function(e){if("string"!=typeof e)return!1;if(3!==e.split(".").length)return!1;try{return n.jwtDecode(e),!0}catch(e){return!1}}(a))throw new Error("Invalid or empty client auth token provided.");if(i&&"object"!=typeof i)throw new Error("Invalid options provided.");return Object.freeze({apiKey:t.trim(),baseUrl:r.trim(),userId:s.trim(),clientAuthToken:a.trim(),options:i?Object.freeze(Object.assign({},i)):void 0})}const Fa={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Ga(e){return Fa}function ja(e){const t=typeof e;return"string"===t?`"${e}"`:"number"===t||"bigint"===t||"boolean"===t?`${e}`:"object"===t||"function"===t?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function Ha(e,t,r,s,a){const n=a&&"input"in a?a.input:r.value,i=a?.expected??e.expects??null,o=a?.received??ja(n),c={kind:e.kind,type:e.type,input:n,expected:i,received:o,message:`Invalid ${t}: ${i?`Expected ${i} but r`:"R"}eceived ${o}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},d="schema"===e.kind,l=a?.message??e.message??(e.reference,void c.lang)??(d?void c.lang:null)??s.message??void c.lang;void 0!==l&&(c.message="function"==typeof l?l(c):l),d&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}const $a=new WeakMap;function Ya(e){let t=$a.get(e);return t||(t={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},Ga())},$a.set(e,t)),t}function za(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}function Ja(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function Xa(e,t,r){return"function"==typeof e.fallback?e.fallback(t,r):e.fallback}function Za(e,t,r){return"function"==typeof e.default?e.default(t,r):e.default}function Qa(){return{kind:"schema",type:"any",reference:Qa,expects:"any",async:!1,get"~standard"(){return Ya(this)},"~run":e=>(e.typed=!0,e)}}function en(e,t){return{kind:"schema",type:"array",reference:en,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return Ya(this)},"~run"(e,t){const r=e.value;if(Array.isArray(r)){e.typed=!0,e.value=[];for(let s=0;s<r.length;s++){const a=r[s],n=this.item["~run"]({value:a},t);if(n.issues){const i={type:"array",origin:"value",input:r,key:s,value:a};for(const t of n.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||(e.issues=n.issues),t.abortEarly){e.typed=!1;break}}n.typed||(e.typed=!1),e.value.push(n.value)}}else Ha(this,"type",e,t);return e}}}function tn(e){return{kind:"schema",type:"boolean",reference:tn,expects:"boolean",async:!1,message:e,get"~standard"(){return Ya(this)},"~run"(e,t){return"boolean"==typeof e.value?e.typed=!0:Ha(this,"type",e,t),e}}}function rn(e,t){if(typeof e==typeof t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{value:e};if(e&&t&&e.constructor===Object&&t.constructor===Object){const r={...e};for(const s in t)if(Object.prototype.hasOwnProperty.call(e,s)){const a=rn(e[s],t[s]);if(a.issue)return a;r[s]=a.value}else r[s]=t[s];return{value:r}}if(Array.isArray(e)&&Array.isArray(t)&&e.length===t.length){const r=[...e];for(let s=0;s<e.length;s++){const a=rn(e[s],t[s]);if(a.issue)return a;r[s]=a.value}return{value:r}}}return{issue:!0}}function sn(e,t){return{kind:"schema",type:"intersect",reference:sn,expects:Ja(e.map((e=>e.expects)),"&"),async:!1,options:e,message:t,get"~standard"(){return Ya(this)},"~run"(e,t){if(this.options.length){const r=e.value;let s;e.typed=!0;for(const a of this.options){const n=a["~run"]({value:r},t);if(n.issues){if(e.issues)for(const t of n.issues)e.issues.push(t);else e.issues=n.issues;if(t.abortEarly){e.typed=!1;break}}n.typed||(e.typed=!1),e.typed&&(s?s.push(n.value):s=[n.value])}if(e.typed){e.value=s[0];for(let r=1;r<s.length;r++){const a=rn(e.value,s[r]);if(a.issue){Ha(this,"type",e,t,{received:"unknown"});break}e.value=a.value}}}else Ha(this,"type",e,t);return e}}}function an(e){return{kind:"schema",type:"lazy",reference:an,expects:"unknown",async:!1,getter:e,get"~standard"(){return Ya(this)},"~run"(e,t){return this.getter(e.value)["~run"](e,t)}}}function nn(e,t){return{kind:"schema",type:"nullable",reference:nn,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return Ya(this)},"~run"(e,t){return null===e.value&&(void 0!==this.default&&(e.value=Za(this,e,t)),null===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function on(e){return{kind:"schema",type:"number",reference:on,expects:"number",async:!1,message:e,get"~standard"(){return Ya(this)},"~run"(e,t){return"number"!=typeof e.value||isNaN(e.value)?Ha(this,"type",e,t):e.typed=!0,e}}}function cn(e,t){return{kind:"schema",type:"object",reference:cn,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return Ya(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in this.entries){const a=this.entries[s];if(s in r||("exact_optional"===a.type||"optional"===a.type||"nullish"===a.type)&&void 0!==a.default){const n=s in r?r[s]:Za(a),i=a["~run"]({value:n},t);if(i.issues){const a={type:"object",origin:"value",input:r,key:s,value:n};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value[s]=i.value}else if(void 0!==a.fallback)e.value[s]=Xa(a);else if("exact_optional"!==a.type&&"optional"!==a.type&&"nullish"!==a.type&&(Ha(this,"key",e,t,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:r,key:s,value:r[s]}]}),t.abortEarly))break}}else Ha(this,"type",e,t);return e}}}function dn(e,t){return{kind:"schema",type:"optional",reference:dn,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return Ya(this)},"~run"(e,t){return void 0===e.value&&(void 0!==this.default&&(e.value=Za(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function ln(e,t){return{kind:"schema",type:"picklist",reference:ln,expects:Ja(e.map(ja),"|"),async:!1,options:e,message:t,get"~standard"(){return Ya(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:Ha(this,"type",e,t),e}}}function hn(e,t,r){return{kind:"schema",type:"record",reference:hn,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return Ya(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in r)if(za(r,s)){const a=r[s],n=this.key["~run"]({value:s},t);if(n.issues){const i={type:"object",origin:"key",input:r,key:s,value:a};for(const t of n.issues)t.path=[i],e.issues?.push(t);if(e.issues||(e.issues=n.issues),t.abortEarly){e.typed=!1;break}}const i=this.value["~run"]({value:a},t);if(i.issues){const n={type:"object",origin:"value",input:r,key:s,value:a};for(const t of i.issues)t.path?t.path.unshift(n):t.path=[n],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}n.typed&&i.typed||(e.typed=!1),n.typed&&(e.value[n.value]=i.value)}}else Ha(this,"type",e,t);return e}}}function pn(e){return{kind:"schema",type:"string",reference:pn,expects:"string",async:!1,message:e,get"~standard"(){return Ya(this)},"~run"(e,t){return"string"==typeof e.value?e.typed=!0:Ha(this,"type",e,t),e}}}function un(e){let t;if(e)for(const r of e)if(t)for(const e of r.issues)t.push(e);else t=r.issues;return t}function yn(e,t){return{kind:"schema",type:"union",reference:yn,expects:Ja(e.map((e=>e.expects)),"|"),async:!1,options:e,message:t,get"~standard"(){return Ya(this)},"~run"(e,t){let r,s,a;for(const n of this.options){const i=n["~run"]({value:e.value},t);if(i.typed){if(!i.issues){r=i;break}s?s.push(i):s=[i]}else a?a.push(i):a=[i]}if(r)return r;if(s){if(1===s.length)return s[0];Ha(this,"type",e,t,{issues:un(s)}),e.typed=!0}else{if(1===a?.length)return a[0];Ha(this,"type",e,t,{issues:un(a)})}return e}}}const fn=cn({message:pn(),environment:pn()}),gn=cn({clientAuthPubKey:pn(),passkeyChallengeType:dn(ln(["webauthn.create","webauthn.get"])),walletId:dn(pn())}),wn=cn({message:pn(),wallabyAuthPubKey:dn(pn()),foundDevicePublicKey:tn(),challenge:dn(pn()),registrationOptions:dn(hn(pn(),Qa())),authenticationOptions:dn(hn(pn(),Qa()))}),mn=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),externalUserId:pn(),firstName:dn(pn()),lastName:dn(pn()),merchantId:dn(pn()),passkeyRegistrationResponse:dn(hn(pn(),Qa()))}),vn=cn({id:pn(),firstName:dn(pn()),externalUserId:pn(),role:dn(ln(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),clientSalt:dn(pn()),clientAuthPubKey:dn(pn())}),Sn=cn({accessToken:pn(),refreshToken:dn(pn()),user:an((()=>vn))}),_n=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),externalUserId:dn(pn()),firstName:dn(pn()),lastName:dn(pn()),merchantId:dn(pn()),passkeyRegistrationResponse:dn(hn(pn(),Qa()))}),An=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),passkeyRegistrationResponse:dn(hn(pn(),Qa())),passkeyAuthenticationResponse:dn(hn(pn(),Qa()))}),En=cn({id:pn(),externalUserId:pn(),clientSalt:pn()}),bn=cn({accessToken:pn(),refreshToken:pn(),user:an((()=>En))}),In=cn({refreshToken:pn()}),Pn=cn({accessToken:pn(),refreshToken:pn()}),Tn=cn({message:pn()}),kn=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),newClientAuthPubKey:pn()}),Cn=cn({user:an((()=>vn))}),xn=cn({clientAuthPubKey:pn()}),Kn=cn({wallabyAuthPubKey:pn()}),On=cn({id:pn(),externalUserId:pn(),merchantId:pn(),role:ln(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]),firstName:dn(pn()),walletsCount:on(),latestWallabyAuthPubKey:dn(pn()),latestWallabyAuthPubKeyVersion:dn(pn()),portalInvitationStatus:dn(nn(ln(["pending","accepted","rejected"]))),createdAt:pn(),updatedAt:pn(),hasFullPermissions:tn()}),Nn=cn({id:pn(),userId:pn(),publicKey:pn(),status:ln(["active","invalidated"]),createdAt:pn(),updatedAt:pn()}),Rn=cn({id:pn(),authenticatorGlobalId:pn(),credentialID:pn(),publicKey:pn(),authPublicKeyId:pn(),counter:on(),transports:pn(),credentialDeviceType:pn(),credentialBackedUp:tn(),user:sn([an((()=>On))]),authPublicKeys:dn(en(an((()=>Nn)))),userId:pn(),externalUserId:pn(),createdAt:pn(),updatedAt:pn(),authenticatorName:dn(pn())}),Dn=cn({credentials:en(an((()=>Rn)))}),Ln=cn({totalRecords:on(),currentPage:on(),totalPages:on(),nextPage:nn(on()),previousPage:nn(on()),pageSize:on()}),Un=cn({address:pn(),publicKey:dn(pn()),type:dn(ln(["SEGWIT","LEGACY","DEFAULT"]))}),Bn=cn({id:pn(),name:pn(),nameSlugify:pn(),verified:tn(),status:ln(["active","inactive","invalidated"])}),qn=cn({id:pn(),userId:pn(),merchantId:pn(),chainId:pn(),userAssetAddress:pn(),walletId:pn(),configId:pn(),assetName:pn(),assetSymbol:pn(),balance:nn(pn()),balanceUpdatedAt:nn(pn()),claimableBalance:dn(nn(pn())),claimableBalanceUpdatedAt:dn(nn(pn())),claimablePaymentTokenContractAddress:dn(nn(pn())),claimablePaymentTokenAssetConfigId:dn(nn(pn())),lockedTokenBalance:nn(pn()),lockedTokenBalanceUpdatedAt:nn(pn()),mainnetBalance:nn(pn()),mainnetBalanceUpdatedAt:nn(pn()),testnetBalance:nn(pn()),testnetBalanceUpdatedAt:nn(pn()),mainnetLockedBalance:nn(pn()),mainnetLockedBalanceUpdatedAt:nn(pn()),testnetLockedBalance:nn(pn()),testnetLockedBalanceUpdatedAt:nn(pn()),defaultAddress:pn(),isVisible:tn(),source:ln(["merchant","user","republic"]),addresses:en(an((()=>Un))),ownershipType:pn(),priceConversion:dn(pn()),changePercentageLast24h:dn(pn()),createdAt:pn(),updatedAt:pn(),merchant:sn([an((()=>Bn))])}),Vn=cn({id:pn(),name:pn(),nameSlugify:pn()}),Mn=cn({address:pn(),topics:en(pn()),data:pn(),transactionIndex:on()}),Wn=cn({event:pn(),args:hn(pn(),yn([pn(),on(),tn()]))}),Fn=cn({message:nn(pn()),txLogs:nn(en(an((()=>Mn)))),txLogsDecoded:nn(en(an((()=>Wn)))),reqSignature:pn(),reason:nn(pn()),requestId:nn(pn()),signatureUsed:tn()}),Gn=cn({id:pn(),reference:nn(pn()),hash:dn(nn(pn())),merchantId:pn(),userEmail:pn(),chainId:pn(),chainName:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:on(),fromWalletId:pn(),fromAddress:pn(),toWalletId:pn(),toAddress:pn(),assetId:pn(),assetSymbol:pn(),tokenType:ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]),amount:pn(),fee:pn(),note:pn(),nonce:on(),gasPrice:on(),submitter:pn(),status:ln(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:nn(ln(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:ln(["SINGLE_OWNER","MULTI_SIG"]),txBlob:pn(),networkEnvironment:nn(ln(["mainnet","testnet"])),statusCheckAttempts:on(),statusCheckedAt:nn(pn()),createdAt:pn(),updatedAt:pn(),asset:sn([an((()=>ei))]),merchant:sn([an((()=>ti))]),adminTransactions:en(an((()=>Fn))),user:dn(an((()=>On))),chain:an((()=>di)),splitCoins:pn(),transferObjects:pn()}),jn=cn({id:on(),contractTypeName:pn(),assetContracts:en(an((()=>Hn)))}),Hn=cn({configId:pn(),contractTypeId:on(),contractAddress:pn(),assetConfig:sn([an((()=>ei))]),contractType:sn([an((()=>jn))])}),$n=cn({id:pn(),merchantId:pn(),configId:pn(),chainId:pn(),chainName:pn(),assetName:pn(),assetSymbol:pn(),isVisible:tn(),isDefault:tn(),createdAt:pn(),updatedAt:pn(),merchant:sn([an((()=>ti))]),config:sn([an((()=>ei))]),chain:sn([an((()=>di))])}),Yn=cn({id:pn(),typeName:pn(),createdAt:pn(),updatedAt:pn()}),zn=cn({id:pn(),objectId:pn(),packageId:pn(),moduleName:pn(),structName:pn(),coinType:pn(),createdAt:sn([an((()=>Yn))]),updatedAt:pn()}),Jn=cn({id:pn(),chainId:pn(),swapProviderId:pn(),providerChainIdentifier:pn(),chain:sn([an((()=>di))]),swapProvider:sn([an((()=>Xn))]),providerAssets:en(an((()=>Zn))),createdAt:pn(),updatedAt:pn()}),Xn=cn({id:pn(),name:pn(),explorerBaseUrl:pn(),isActive:tn(),chainMappings:en(an((()=>Jn))),providerAssets:en(an((()=>Zn))),createdAt:pn(),updatedAt:pn()}),Zn=cn({id:pn(),assetConfigId:pn(),swapProviderId:pn(),chainProviderMappingId:pn(),providerAssetIdentifier:pn(),lastSynced:dn(pn()),isEnabled:tn(),assetConfig:sn([an((()=>ei))]),swapProvider:sn([an((()=>Xn))]),chainProviderMapping:sn([an((()=>Jn))]),createdAt:pn(),updatedAt:pn()}),Qn=cn({id:pn(),config:an((()=>ei)),configId:pn(),timestamp:pn(),createdAt:pn()}),ei=cn({id:pn(),chainId:pn(),merchantId:dn(nn(pn())),chainName:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),name:pn(),symbol:pn(),verified:dn(tn()),isOffChain:dn(tn()),decimals:on(),iconUrl:dn(pn()),ticker:dn(nn(pn())),type:dn(ln(["COIN","TOKEN","OBJECT"])),tokenStandard:dn(nn(ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]))),assetIndex:dn(nn(on())),contractAddress:dn(nn(pn())),description:dn(nn(pn())),ownershipType:dn(ln(["SINGLE_OWNER","MULTI_SIG"])),ownerAddresses:dn(nn(en(pn()))),status:dn(ln(["active","inactive","archived"])),createdByUserId:dn(nn(pn())),createdByMerchantId:dn(nn(pn())),relayerAddress:dn(pn()),contractVersion:dn(pn()),chain:dn(an((()=>di))),createdByMerchant:dn(sn([an((()=>Vn))])),usersAssets:dn(en(an((()=>qn)))),transactions:dn(en(an((()=>Gn)))),assetContracts:dn(en(an((()=>Hn)))),merchantAssets:dn(en(an((()=>$n)))),createdByUser:dn(an((()=>On))),suiConfig:dn(an((()=>zn))),isAssetReady:tn(),extendedConfiguration:dn(hn(pn(),Qa())),requiresKyc:tn(),swapProviderAssets:dn(en(an((()=>Zn)))),tokenDistributions:dn(en(an((()=>Qn))))}),ti=cn({id:pn(),name:pn(),nameSlugify:pn(),verified:tn(),contactEmail:pn(),contactPhoneNumber:pn(),usersCount:on(),assetsCount:on(),tokensCount:on(),coinsCount:on(),walletsCount:on(),status:ln(["active","inactive","invalidated"]),createdAt:pn(),updatedAt:pn(),createdAssets:en(an((()=>ei))),merchantAssets:dn(en(an((()=>$n))))}),ri=cn({id:on(),name:ln(["wallaby_share","owner_main_device_share","owner_backup_device_share"]),keyShares:en(an((()=>si)))}),si=cn({id:pn(),user:an((()=>On)),wallet:an((()=>ii)),encryptedKey:pn(),type:an((()=>ri)),createdAt:pn(),updatedAt:pn(),migratedWallabyShareAt:dn(nn(pn())),wrappingPublicKey:dn(pn()),migrationStatus:ln(["not_required","pending","migrated","failed"]),migrationErrorMessage:dn(nn(pn()))}),ai=cn({id:on(),roles:en(ln(["single_sig","shares_single_owner","pooled_custodial","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),wallets:en(an((()=>ii)))}),ni=cn({id:pn(),walletId:pn(),userId:pn(),shareCount:on(),createdAt:pn(),updatedAt:pn()}),ii=cn({id:pn(),userId:pn(),merchantId:pn(),revisionId:pn(),revisionName:pn(),hashedSeedPhraseSalt:pn(),hashedEthAddressSalt:pn(),recoveryCount:on(),assetsCount:on(),createdAt:pn(),updatedAt:pn(),lastVerifiedAt:nn(pn()),userAssets:dn(en(an((()=>qn)))),merchant:dn(an((()=>ti))),keyShares:dn(en(an((()=>si)))),type:an((()=>ai)),creationType:dn(nn(ln(["user_imported","user_created"]))),keyMigrationStatus:ln(["not_required","pending","migrated","failed"]),migrationErrorMessage:dn(nn(pn())),walletAddresses:dn(en(an((()=>ci)))),walletKeks:dn(en(an((()=>ni))))}),oi=cn({id:on(),name:ln(["BTC:MAINNET:SEGWIT","BTC:MAINNET:LEGACY","BTC:TESTNET:SEGWIT","BTC:TESTNET:LEGACY","ETH:ALL:DEFAULT","ALGO:ALL:DEFAULT","SUI:ALL:DEFAULT","INJ:ALL:DEFAULT","APT:ALL:DEFAULT","SOL:ALL:DEFAULT","POLYX:ALL:DEFAULT","BSC:ALL:DEFAULT","AVAX:ALL:DEFAULT","POL:ALL:DEFAULT","BASE:ALL:DEFAULT","SEI:ALL:DEFAULT","HBAR:ALL:DEFAULT","CC:ALL:DEFAULT"]),walletAddresses:an((()=>ci))}),ci=cn({id:pn(),walletId:pn(),wallet:an((()=>ii)),chain:an((()=>di)),typeId:on(),type:an((()=>oi)),address:pn(),publicKey:pn(),createdAt:pn(),updatedAt:pn()}),di=cn({id:pn(),name:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),isEvm:tn(),iconUrl:dn(nn(pn())),mainnetId:dn(pn()),mainnetIndexUrl:dn(nn(pn())),mainnetExplorerUrl:dn(pn()),testnetId:dn(pn()),testnetExplorerUrl:dn(nn(pn())),testnetIndexUrl:dn(nn(pn())),derivationPath:dn(nn(pn())),addressRegex:dn(nn(pn())),slip44:ln([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767]),signatureScheme:dn(ln(["secp256k1","ed25519","sr25519"])),status:dn(ln(["UP","DOWN"])),search:dn(pn()),createdAt:pn(),updatedAt:pn(),walletAddresses:dn(en(an((()=>ci)))),isChainReady:tn(),supportsSwaps:tn(),swapChainMappings:dn(en(an((()=>Jn)))),indexUrl:dn(nn(pn())),chainId:dn(pn())}),li=cn({pagination:sn([an((()=>Ln))]),chains:en(an((()=>di)))}),hi=cn({name:pn(),isEvm:tn(),mainnetRpcUrl:pn(),mainnetIndexUrl:dn(pn()),testnetId:dn(pn()),testnetRpcUrl:pn(),testnetIndexUrl:pn(),derivationPath:pn(),addressRegex:pn(),slip44:on(),signatureScheme:ln(["secp256k1","ed25519","sr25519"])}),pi=cn({chain:an((()=>di))}),ui=cn({name:dn(ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),isEvm:dn(tn()),mainnetId:dn(pn()),mainnetRpcUrl:dn(pn()),mainnetIndexUrl:dn(pn()),testnetId:dn(pn()),testnetRpcUrl:dn(pn()),testnetIndexUrl:dn(pn()),derivationPath:dn(pn()),addressRegex:dn(pn()),slip44:dn(ln([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767])),signatureScheme:dn(ln(["secp256k1","ed25519","sr25519"])),supportSwaps:dn(tn())}),yi=cn({chain:an((()=>di))}),fi=cn({pagination:sn([an((()=>Ln))]),assets:en(an((()=>ei)))}),gi=cn({asset:an((()=>ei))}),wi=cn({chainId:pn(),name:pn(),symbol:pn(),verified:dn(tn()),isOffChain:dn(tn()),decimals:on(),iconUrl:dn(pn()),ticker:pn(),type:ln(["COIN","TOKEN","OBJECT"]),tokenStandard:dn(ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),assetIndex:dn(on()),contractAddress:dn(pn()),description:dn(pn()),createdByUserId:dn(pn()),createdByMerchantId:dn(pn()),suiObjectId:dn(pn()),relayerAddress:dn(pn()),isAssetReady:dn(tn()),requiresKyc:dn(tn())}),mi=cn({asset:an((()=>ei))}),vi=cn({name:dn(pn()),symbol:dn(pn()),isOffChain:dn(tn()),decimals:dn(on()),iconUrl:dn(pn()),ticker:dn(pn()),type:dn(ln(["COIN","TOKEN","OBJECT"])),tokenStandard:dn(ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),assetIndex:dn(on()),contractAddress:dn(pn()),relayerAddress:dn(pn()),description:dn(pn()),suiObjectId:dn(pn())}),Si=cn({asset:an((()=>ei))}),_i=cn({message:pn()}),Ai=cn({pagination:sn([an((()=>Ln))]),merchants:en(an((()=>ti)))}),Ei=cn({name:pn(),contactEmail:pn(),contactPhoneNumber:dn(pn()),status:dn(ln(["active","inactive","invalidated"]))}),bi=cn({name:dn(pn()),contactEmail:dn(pn()),contactPhoneNumber:dn(pn()),status:dn(ln(["active","inactive","invalidated"]))}),Ii=cn({merchant:an((()=>ti))}),Pi=cn({merchant:an((()=>ti))}),Ti=cn({pagination:sn([an((()=>Ln))]),merchant:an((()=>ti)),assets:dn(en(an((()=>$n)))),merchantAssets:en(an((()=>$n)))}),ki=cn({id:pn(),name:dn(pn())}),Ci=cn({id:pn(),externalUserId:pn(),walletsCount:on(),createdAt:pn(),updatedAt:pn(),merchantId:dn(pn()),firstName:dn(pn()),email:dn(pn()),role:dn(ln(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),polymeshDID:dn(pn()),userMerchants:dn(en(an((()=>ki))))}),xi=cn({pagination:sn([an((()=>Ln))]),merchant:an((()=>ti)),users:en(an((()=>Ci)))}),Ki=cn({merchantId:pn(),email:pn(),firstName:pn(),lastName:pn(),role:pn()}),Oi=cn({message:dn(pn()),user:an((()=>Ci))}),Ni=cn({message:dn(pn()),user:an((()=>Ci))}),Ri=cn({pagination:sn([an((()=>Ln))]),merchant:an((()=>ti)),wallets:en(an((()=>ii)))}),Di=cn({assetConfigId:pn(),userId:pn(),walletId:pn()}),Li=cn({merchantId:pn(),assets:en(an((()=>Di))),updateExistingWallets:dn(tn())}),Ui=cn({message:dn(pn())}),Bi=cn({merchantId:pn(),assetConfigId:dn(pn()),isDefault:dn(tn()),addToExistingWallets:dn(tn()),addToWallets:dn(en(pn())),config:dn(an((()=>ei)))}),qi=cn({message:dn(pn()),merchantAsset:an((()=>$n))}),Vi=cn({merchantId:pn(),assetConfigId:pn()}),Mi=cn({message:dn(pn())}),Wi=cn({merchantId:pn(),assetConfigId:pn(),isVisible:tn()}),Fi=cn({message:dn(pn()),merchantAsset:an((()=>$n))}),Gi=cn({merchantId:pn(),assetConfigId:pn(),isDefault:tn()}),ji=cn({message:dn(pn()),merchantAsset:an((()=>$n))}),Hi=cn({iv:pn(),ephemPublicKey:pn(),ciphertext:pn(),mac:pn()}),$i=cn({id:pn(),merchantId:dn(pn()),appName:pn(),ipAddresses:en(pn()),domainNames:en(pn()),status:ln(["active","inactive"]),clientJWTPubKey:pn(),usersCount:on(),requestsCount:on(),totalRequestSizeInKb:on(),totalResponseSizeInKb:on(),totalResponseTimeInKb:on(),lastRequestAt:nn(pn()),onlyDashboardAccess:tn(),allowMobileAccess:tn(),createdAt:pn(),updatedAt:pn(),merchant:dn(an((()=>ti))),origins:dn(en(an((()=>Yi))))}),Yi=cn({id:pn(),merchantId:dn(pn()),apiKeyId:pn(),origin:pn(),createdAt:pn(),updatedAt:pn(),merchant:dn(an((()=>ti))),apiKey:dn(an((()=>$i)))}),zi=cn({id:pn(),merchantId:pn(),appName:pn(),apiKey:an((()=>Hi)),status:ln(["active","inactive"]),clientJWTPubKey:pn(),allowMobileAccess:tn(),createdAt:pn(),updatedAt:pn(),origins:dn(en(an((()=>Yi))))}),Ji=cn({pagination:sn([an((()=>Ln))]),apiKeys:en(an((()=>zi)))}),Xi=cn({pagination:sn([an((()=>Ln))]),apiKeyOrigins:en(an((()=>Yi)))}),Zi=cn({clientJWTPubKey:dn(pn()),wrappingPublicKey:dn(pn()),allowMobileAccess:dn(tn()),appName:dn(pn())}),Qi=cn({message:dn(pn()),apiKey:an((()=>zi)),clientJWTPrivKey:dn(sn([an((()=>Hi))]))}),eo=cn({merchantId:pn(),apiKeyId:pn(),origins:en(pn())}),to=cn({message:dn(pn()),apiKeyOrigins:en(an((()=>Yi)))}),ro=cn({clientJWTPubKey:dn(pn()),wrappingPublicKey:pn(),appName:dn(pn()),status:dn(ln(["active","inactive"])),allowMobileAccess:dn(tn())}),so=cn({message:dn(pn()),apiKey:an((()=>zi))}),ao=cn({pagination:sn([an((()=>Ln))]),wallets:en(an((()=>ii)))}),no=cn({message:pn(),clientAuthPubKey:pn(),signature:pn()}),io=cn({id:pn(),userId:pn(),merchantId:pn(),chainId:pn(),userAssetAddress:pn(),walletId:pn(),configId:pn(),assetName:pn(),assetSymbol:pn(),balance:nn(pn()),balanceUpdatedAt:nn(pn()),claimableBalance:dn(nn(pn())),claimableBalanceUpdatedAt:dn(nn(pn())),claimablePaymentTokenContractAddress:dn(nn(pn())),claimablePaymentTokenAssetConfigId:dn(nn(pn())),lockedTokenBalance:nn(pn()),lockedTokenBalanceUpdatedAt:nn(pn()),mainnetBalance:nn(pn()),mainnetBalanceUpdatedAt:nn(pn()),testnetBalance:nn(pn()),testnetBalanceUpdatedAt:nn(pn()),mainnetLockedBalance:nn(pn()),mainnetLockedBalanceUpdatedAt:nn(pn()),testnetLockedBalance:nn(pn()),testnetLockedBalanceUpdatedAt:nn(pn()),defaultAddress:pn(),isVisible:tn(),source:ln(["merchant","user","republic"]),addresses:en(an((()=>Un))),ownershipType:pn(),priceConversion:dn(pn()),changePercentageLast24h:dn(pn()),createdAt:pn(),updatedAt:pn(),merchant:sn([an((()=>Bn))]),config:an((()=>ei))}),oo=cn({id:pn(),userId:pn(),revisionName:pn()}),co=cn({iv:pn(),ephemPublicKey:pn(),ciphertext:pn(),mac:pn()}),lo=cn({encrypted:sn([an((()=>co))]),wrappingPublicKey:pn(),type:ln(["wallaby_share","owner_main_device_share","owner_backup_device_share"])}),ho=cn({v:on(),iv:pn(),ciphertext:pn(),tag:pn()}),po=cn({address:pn(),type:ln(["BTC:MAINNET:SEGWIT","BTC:MAINNET:LEGACY","BTC:TESTNET:SEGWIT","BTC:TESTNET:LEGACY","ETH:ALL:DEFAULT","ALGO:ALL:DEFAULT","SUI:ALL:DEFAULT","INJ:ALL:DEFAULT","APT:ALL:DEFAULT","SOL:ALL:DEFAULT","POLYX:ALL:DEFAULT","BSC:ALL:DEFAULT","AVAX:ALL:DEFAULT","POL:ALL:DEFAULT","BASE:ALL:DEFAULT","SEI:ALL:DEFAULT","HBAR:ALL:DEFAULT","CC:ALL:DEFAULT"]),chainId:pn(),chainName:pn()}),uo=cn({wallabyAuthPubKey:dn(pn()),assets:en(an((()=>io))),encryptedSeed:dn(yn([an((()=>co)),an((()=>ho))])),wallet:sn([an((()=>oo))]),shares:dn(en(an((()=>lo)))),encryptedBackupShare:dn(sn([an((()=>ho))])),reference:dn(pn()),encryptedSeedForSharesSplit:dn(an((()=>co))),walletAddressesInfo:en(an((()=>po)))}),yo=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedShares:dn(en(an((()=>co)))),encryptedSeed:dn(sn([an((()=>co))])),walletId:pn()}),fo=cn({isAccessVerified:tn()}),go=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),adminWalletTypes:en(ln(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]))}),wo=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),returnWalletOption:ln(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:pn(),numShares:dn(on()),threshold:dn(on()),wallabyKeepsOne:dn(tn()),backupDevicePublicKey:dn(pn()),walletOwnershipType:dn(ln(["SINGLE_OWNER"]))}),mo=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedSeed:sn([an((()=>co))]),walletId:dn(pn()),returnWalletOption:ln(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:pn(),numShares:dn(on()),threshold:dn(on()),wallabyKeepsOne:dn(tn()),backupDevicePublicKey:dn(pn()),walletOwnershipType:dn(ln(["SINGLE_OWNER"]))}),vo=cn({clientAuthPubKey:pn(),walletId:pn(),encryptedBackupShare:yn([an((()=>ho)),an((()=>Hi))])}),So=cn({reference:pn(),share:sn([an((()=>lo))])}),_o=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedSeed:sn([an((()=>co))]),walletId:dn(pn())}),Ao=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),encryptedSeed:dn(sn([an((()=>co))])),encryptedShares:dn(en(an((()=>co)))),chainName:dn(ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]))}),Eo=cn({id:pn(),walletId:pn(),typeId:on(),type:an((()=>oi)),address:pn(),publicKey:pn()}),bo=cn({walletAddressesInfo:en(an((()=>po))),walletAddresses:en(an((()=>Eo)))}),Io=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),encryptedShares:en(an((()=>co))),chain:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),accountIndexes:en(on()),startingAddressIndex:dn(on())}),Po=cn({accountIndex:on(),addresses:hn(pn(),pn())}),To=cn({walletId:pn(),chain:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),accounts:en(an((()=>Po)))}),ko=cn({pagination:sn([an((()=>Ln))]),assets:en(an((()=>io))),groupedAssets:dn(hn(pn(),en(an((()=>io))))),walletAddressesInfo:en(an((()=>po)))}),Co=cn({pagination:sn([an((()=>Ln))]),addresses:en(an((()=>po)))}),xo=cn({assetSymbol:pn(),blockchainName:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])}),Ko=cn({configId:pn(),assetName:dn(pn()),assetSymbol:dn(pn()),isVisible:dn(tn()),walletId:pn()}),Oo=cn({userAsset:sn([an((()=>io))]),message:pn()}),No=cn({fromAssetConfigId:pn(),toAssetConfigId:pn(),fromAmount:dn(pn()),toAmount:dn(pn()),slippage:dn(on())}),Ro=cn({amount:pn(),amountUSD:dn(nn(pn())),symbol:dn(pn()),icon:dn(pn())}),Do=cn({id:pn(),gasFee:dn(en(an((()=>Ro)))),providerFee:dn(en(an((()=>Ro)))),republicFee:dn(en(an((()=>Ro)))),allowanceFee:dn(en(an((()=>Ro)))),fromAssetConfigId:pn(),fromAssetSymbol:pn(),fromAssetChain:pn(),toAssetConfigId:pn(),toAssetSymbol:pn(),toAssetChain:pn(),fromAmount:pn(),fromAddress:pn(),toAmount:pn(),toAddress:pn(),slippage:on(),expiresAt:dn(pn())}),Lo=cn({id:pn(),fromAssetSymbol:pn(),fromAssetChainName:pn(),toAssetSymbol:pn(),toAssetChainName:pn(),fromAddress:pn(),toAddress:pn(),fromAmount:pn(),toAmount:pn(),slippage:on(),gasFee:dn(nn(en(an((()=>Ro))))),providerFee:dn(nn(en(an((()=>Ro))))),republicFee:dn(nn(en(an((()=>Ro))))),allowanceFee:dn(nn(en(an((()=>Ro))))),status:ln(["quote","executing","in_progress","completed","failed","abandoned","execution_failed","invalid"]),executedAt:nn(pn()),completedAt:nn(pn()),transactionId:nn(pn()),transactionHash:nn(pn()),explorerLink:nn(pn())}),Uo=cn({pagination:sn([an((()=>Ln))]),swaps:en(an((()=>Lo)))}),Bo=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),quoteId:pn(),encryptedSeed:dn(sn([an((()=>co))])),encryptedShares:dn(en(an((()=>co))))}),qo=cn({swapQuoteId:pn(),status:pn(),explorerLink:pn(),transactionHash:pn()}),Vo=cn({id:pn(),reference:nn(pn()),hash:dn(nn(pn())),merchantId:pn(),userEmail:pn(),chainId:pn(),chainName:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:on(),fromWalletId:pn(),fromAddress:pn(),toWalletId:pn(),toAddress:pn(),assetId:pn(),assetSymbol:pn(),tokenType:ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]),amount:pn(),fee:pn(),note:pn(),nonce:on(),gasPrice:on(),submitter:pn(),status:ln(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:nn(ln(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:ln(["SINGLE_OWNER","MULTI_SIG"]),txBlob:pn(),networkEnvironment:nn(ln(["mainnet","testnet"])),statusCheckAttempts:on(),statusCheckedAt:nn(pn()),createdAt:pn(),updatedAt:pn(),asset:sn([an((()=>ei))]),merchant:sn([an((()=>ti))]),adminTransactions:en(an((()=>Fn))),user:dn(an((()=>On))),chain:an((()=>di)),splitCoins:pn(),transferObjects:pn(),type:dn(ln(["INCOMING","OUTGOING","SWAP","UNKNOWN"])),entryType:dn(ln(["INCOMING","OUTGOING","SWAP","UNKNOWN"]))}),Mo=cn({pagination:sn([an((()=>Ln))]),transactions:en(an((()=>Vo)))}),Wo=cn({id:pn(),amount:pn(),sender:pn(),asset:dn(sn([an((()=>ei))])),expires:dn(pn())}),Fo=cn({transactions:en(an((()=>Wo)))}),Go=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),id:pn(),choice:ln(["approve","deny"]),symbol:pn(),chainName:pn(),walletId:pn(),encryptedSeed:dn(sn([an((()=>co))])),encryptedShares:dn(en(an((()=>co))))}),jo=cn({id:pn(),status:ln(["confirmed","denied"]),hash:dn(pn()),asset:dn(sn([an((()=>ei))]))}),Ho=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),recipientAddress:pn(),assetId:pn(),amount:pn(),reference:pn(),encryptedSeed:sn([an((()=>co))]),memo:dn(pn()),transactionType:dn(ln(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"]))}),$o=cn({transaction:sn([an((()=>Gn))]),message:dn(pn())}),Yo=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),recipientAddress:pn(),assetId:pn(),amount:pn(),reference:pn(),memo:dn(pn()),transactionType:dn(ln(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"])),encryptedShares:en(an((()=>co)))}),zo=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),reference:pn(),note:dn(pn()),encryptedSeed:sn([an((()=>co))]),assetIndex:on()}),Jo=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),reference:pn(),note:dn(pn()),encryptedSeed:sn([an((()=>co))]),appIndex:on()}),Xo=cn({feePaymentSymbol:pn(),fee:pn(),lowestFee:dn(pn()),highestFee:dn(pn())}),Zo=cn({address:en(pn()),amount:pn(),txId:pn()}),Qo=cn({status:ln(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionHash:pn(),reference:pn(),assetSymbol:pn(),transactionValue:pn(),fromAddress:pn(),toAddress:pn(),chain:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),fee:pn(),nonce:dn(on()),timestamp:dn(on()),blockNumber:dn(on()),memo:dn(pn()),origins:dn(en(an((()=>Zo)))),recipients:dn(en(an((()=>Zo))))}),ec=cn({canTransfer:tn(),restrictionCode:pn(),tokenContractAddress:pn(),fromAddress:pn(),toAddress:pn(),value:pn(),assetId:pn()}),tc=cn({restrictionCode:on(),restrictionCodeMessage:pn()}),rc=cn({canTransfer:tn(),message:pn(),restrictionCode:pn()}),sc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),ownerAddress:pn(),spenderAddress:pn(),amount:pn(),reference:pn(),memo:dn(pn()),encryptedSeed:dn(sn([an((()=>co))])),encryptedShares:dn(en(an((()=>co)))),chainName:dn(pn()),assetSymbol:dn(pn()),assetId:dn(pn()),contractAddress:dn(pn())}),ac=cn({transaction:sn([an((()=>Gn))])}),nc=cn({paymentTokenContractAddress:pn(),assetConfigId:pn(),balance:pn()}),ic=cn({address:pn(),assetSymbol:pn(),tokenStandard:dn(ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),tokenType:dn(ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),chainName:dn(ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:dn(pn()),balance:nn(pn()),claimable:dn(sn([an((()=>nc))])),lockedTokenBalance:dn(nn(pn())),unlockedTokenBalance:dn(pn()),stakedBalance:dn(pn()),claimableBalance:dn(pn()),assetConfigId:dn(pn()),balanceUpdatedAt:dn(pn())}),oc=cn({address:pn(),assetSymbol:pn(),tokenStandard:dn(ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),tokenType:dn(ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),chainName:dn(ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:dn(pn())}),cc=cn({assets:en(an((()=>oc)))}),dc=cn({balances:en(an((()=>ic)))}),lc=cn({walletId:pn()}),hc=cn({assetSymbol:dn(pn()),timestamp:on(),from:pn(),gas:on(),gasPrice:dn(pn()),gasUsed:dn(on()),hash:pn(),input:dn(pn()),nonce:dn(on()),to:pn(),value:pn(),amount:dn(pn()),memo:dn(pn()),tokenTransfers:dn(en(hn(pn(),Qa()))),transactionType:dn(pn()),status:ln(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),origins:dn(en(an((()=>Zo)))),recipients:dn(en(an((()=>Zo)))),createdAt:pn()}),pc=cn({address:pn(),transactions:en(an((()=>hc)))}),uc=cn({decimals:on(),symbol:pn(),name:pn(),tokenContractAddress:dn(pn())}),yc=cn({symbol:pn(),price:pn(),changePercentageLast24h:dn(pn())}),fc=cn({data:en(an((()=>yc)))}),gc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedShares:en(an((()=>co))),recoveryPubKey:dn(pn()),walletId:pn()}),wc=cn({encryptedSeed:sn([an((()=>co))])}),mc=cn({pagination:sn([an((()=>Ln))]),users:en(an((()=>Ci)))}),vc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),email:dn(pn()),firstName:dn(pn()),lastName:dn(pn())}),Sc=cn({message:pn(),user:dn(sn([an((()=>On))]))}),_c=cn({user:sn([an((()=>Ci))])}),Ac=cn({clientSalt:pn()}),Ec=cn({wallets:en(an((()=>ii)))}),bc=cn({pagination:sn([an((()=>Ln))]),assets:en(an((()=>qn))),groupedAssets:dn(hn(pn(),en(an((()=>qn)))))}),Ic=cn({name:pn(),symbol:pn(),decimals:on(),contractAddress:pn(),chainId:dn(pn()),chainName:dn(ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),tokenStandard:dn(ln(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),ticker:dn(pn()),iconUrl:dn(pn())}),Pc=cn({assetConfigId:dn(pn()),walletId:pn(),userId:dn(pn()),config:dn(sn([an((()=>Ic))])),message:dn(pn()),clientAuthPubKey:dn(pn()),signature:dn(pn()),encryptedSeed:dn(sn([an((()=>co))])),encryptedShares:dn(en(an((()=>co))))}),Tc=cn({asset:sn([an((()=>qn))])}),kc=cn({message:pn()}),Cc=cn({user:sn([an((()=>Ci))])}),xc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),releaseCount:on(),delayUntilFirstReleaseInSeconds:on(),initialReleasePortionInBips:on(),periodBetweenReleasesInSeconds:on(),walletId:pn(),encryptedSeed:sn([an((()=>ho))])}),Kc=cn({reference:pn()}),Oc=cn({address:pn(),amount:pn(),commencementTimestamp:dn(on()),scheduleId:dn(on()),cancelableBy:dn(en(pn()))}),Nc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),mints:en(an((()=>Oc))),walletId:pn(),encryptedSeed:sn([an((()=>ho))])}),Rc=cn({references:en(an((()=>Kc)))}),Dc=cn({address:pn(),amount:pn(),commencementTimestamp:dn(on()),scheduleId:dn(on()),timelockIndex:dn(on()),reclaimTokenTo:dn(pn())}),Lc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),burns:en(an((()=>Dc))),walletId:pn(),encryptedSeed:sn([an((()=>ho))])}),Uc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:pn(),payerAddress:pn(),tokenRecipientAddress:pn(),originatorPurchaseAmount:pn(),mintAmount:pn(),adminFeeAmount:pn(),totalAmount:pn(),walletId:pn(),encryptedSeed:sn([an((()=>ho))])}),Bc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:pn(),payerAddress:pn(),tokenRecipientAddress:pn(),originatorPurchaseAmount:pn(),mintAmount:pn(),prefundedInterestAmount:pn(),adminFeeExcludingPrefundedInterestAmount:pn(),totalAmount:pn(),walletId:pn(),encryptedSeed:sn([an((()=>ho))])}),qc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),owner:pn(),regions:en(pn()),accreditationType:on(),lastAmlKycChangeTimestamp:on(),lastAccreditationChangeTimestamp:on(),amlKycPassed:tn(),walletId:pn(),encryptedSeed:sn([an((()=>ho))])}),Vc=cn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:ln(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),wallet:pn(),amount:pn(),walletId:pn(),encryptedSeed:sn([an((()=>ho))])}),Mc=cn({assetSymbol:pn(),blockchainName:pn(),releaseCount:on(),delayUntilFirstReleaseInSeconds:on(),initialReleasePortionInBips:on(),periodBetweenReleasesInSeconds:on(),scheduleId:on()}),Wc=cn({adminTransaction:sn([an((()=>Fn))])}),Fc=cn({status:ln(["QUEUED","PENDING","SUCCESS","FAILED"]),message:dn(pn()),txHash:dn(pn()),txLogs:dn(en(an((()=>Mn)))),txLogsDecoded:dn(en(an((()=>Wn)))),reqSignature:dn(pn()),clientRequestSignature:dn(pn()),requestId:dn(pn()),reason:dn(pn()),txId:dn(pn())}),Gc=cn({message:pn()}),jc=cn({chainsCount:on(),chains:en(an((()=>di))),merchantsCount:on(),merchants:en(an((()=>ti))),assetsCount:on(),usersCount:on(),users:en(an((()=>Ci))),adminsCount:on(),walletsCount:on()}),Hc=cn({id:pn(),userId:pn(),merchantId:pn(),action:dn(nn(ln(["logged_in","logged_out","created_wallet","updated_wallet","deleted_wallet","created_merchant","updated_merchant","deleted_merchant"]))),requestUrl:pn(),requestMethod:pn(),createdAt:pn(),updatedAt:pn(),merchant:dn(an((()=>ti)))}),$c=cn({pagination:sn([an((()=>Ln))]),activities:en(an((()=>Hc)))}),Yc=[{method:"GET",path:"/",response:an((()=>fn))},{method:"GET",path:"/healthz",response:an((()=>fn))},{method:"POST",path:"/auth/signature-message/external",request:an((()=>gn)),response:an((()=>wn))},{method:"POST",path:"/auth/signature-message",request:an((()=>gn)),response:an((()=>wn))},{method:"POST",path:"/auth/sign-up",request:an((()=>mn)),response:an((()=>Sn))},{method:"POST",path:"/auth/sign-up/external",request:an((()=>_n)),response:an((()=>Sn))},{method:"POST",path:"/auth/sign-in",request:an((()=>An)),response:an((()=>Sn))},{method:"POST",path:"/auth/issue-jwt-token",response:an((()=>bn))},{method:"POST",path:"/auth/refresh-access-token",request:an((()=>In)),response:an((()=>Pn))},{method:"POST",path:"/auth/logout",response:an((()=>Tn))},{method:"PUT",path:"/auth/client-auth-pubkey",request:an((()=>kn)),response:an((()=>Cn))},{method:"POST",path:"/auth/wallaby-auth-pubkey",request:an((()=>xn)),response:an((()=>Kn))},{method:"GET",path:"/auth/passkey-credentials",response:an((()=>Dn))},{method:"GET",path:"/chains",response:an((()=>li))},{method:"POST",path:"/chains",request:an((()=>hi)),response:an((()=>pi))},{method:"PUT",path:"/chains/{chainId}",request:an((()=>ui)),response:an((()=>yi))},{method:"GET",path:"/assets/configurations",response:an((()=>fi))},{method:"POST",path:"/assets/configurations",request:an((()=>wi)),response:an((()=>mi))},{method:"GET",path:"/assets/configurations/{assetConfigId}",response:an((()=>gi))},{method:"PUT",path:"/assets/configurations/{assetConfigId}",request:an((()=>vi)),response:an((()=>Si))},{method:"POST",path:"/assets/configurations/{assetConfigId}/verify",response:an((()=>_i))},{method:"DELETE",path:"/assets/configurations/{assetConfigId}/unverify",response:an((()=>_i))},{method:"POST",path:"/assets/configurations/{assetConfigId}/archive",response:an((()=>_i))},{method:"POST",path:"/assets/configurations/{assetConfigId}/unarchive",response:an((()=>_i))},{method:"GET",path:"/merchants",response:an((()=>Ai))},{method:"POST",path:"/merchants",request:an((()=>Ei)),response:an((()=>Ei))},{method:"PUT",path:"/merchants/{merchantId}",request:an((()=>bi)),response:an((()=>Ii))},{method:"GET",path:"/merchants/{merchantId}",response:an((()=>Pi))},{method:"GET",path:"/merchants/{merchantId}/assets",response:an((()=>Ti))},{method:"GET",path:"/merchants/{merchantId}/users",response:an((()=>xi))},{method:"GET",path:"/merchants/{merchantId}/admins",response:an((()=>xi))},{method:"POST",path:"/merchants/admins/invite",request:an((()=>Ki)),response:an((()=>Oi))},{method:"DELETE",path:"/merchants/{merchantId}/admins/{userId}",response:an((()=>Ni))},{method:"GET",path:"/merchants/{merchantId}/wallets",response:an((()=>Ri))},{method:"POST",path:"/merchants/wallets/add-assets",request:an((()=>Li)),response:an((()=>Ui))},{method:"POST",path:"/merchants/assets/add",request:an((()=>Bi)),response:an((()=>qi))},{method:"DELETE",path:"/merchants/assets/delete",request:an((()=>Vi)),response:an((()=>Mi))},{method:"POST",path:"/merchants/assets/update-visibility",request:an((()=>Wi)),response:an((()=>Fi))},{method:"POST",path:"/merchants/assets/update-default-status",request:an((()=>Gi)),response:an((()=>ji))},{method:"GET",path:"/merchants/{merchantId}/api-keys",response:an((()=>Ji))},{method:"POST",path:"/merchants/{merchantId}/api-keys",request:an((()=>Zi)),response:an((()=>Qi))},{method:"GET",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/origins",response:an((()=>Xi))},{method:"POST",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/whitelist-origins",request:an((()=>eo)),response:an((()=>to))},{method:"PUT",path:"/merchants/{merchantId}/api-keys/{apiKeyId}",request:an((()=>ro)),response:an((()=>so))},{method:"GET",path:"/wallets",response:an((()=>ao))},{method:"POST",path:"/wallets/create",request:an((()=>no)),response:an((()=>uo))},{method:"POST",path:"/wallets/verify-access",request:an((()=>yo)),response:an((()=>fo))},{method:"POST",path:"/wallets/create-admin-server-wallet",request:an((()=>go)),response:an((()=>uo))},{method:"POST",path:"/wallets/create-with-shares",request:an((()=>wo)),response:an((()=>uo))},{method:"POST",path:"/wallets/create-shares-based-wallet-from-seed",request:an((()=>mo)),response:an((()=>uo))},{method:"POST",path:"/wallets/add-new-device",request:an((()=>vo)),response:an((()=>So))},{method:"POST",path:"/wallets/import-seed-phrase",request:an((()=>_o)),response:an((()=>uo))},{method:"POST",path:"/wallets/generate-wallet-addresses",request:an((()=>Ao)),response:an((()=>bo))},{method:"POST",path:"/wallets/derive-addresses/batch",request:an((()=>Io)),response:an((()=>To))},{method:"GET",path:"/wallets/{walletId}/assets",response:an((()=>ko))},{method:"GET",path:"/wallets/{walletId}/addresses",response:an((()=>Co))},{method:"GET",path:"/wallets/asset",request:an((()=>xo)),response:an((()=>io))},{method:"PUT",path:"/wallets/asset/update",request:an((()=>Ko)),response:an((()=>Oo))},{method:"POST",path:"/wallets/{walletId}/swap/quote",request:an((()=>No)),response:an((()=>Do))},{method:"GET",path:"/wallets/{walletId}/swaps",response:an((()=>Uo))},{method:"GET",path:"/wallets/{walletId}/swaps/{swapId}",response:an((()=>Lo))},{method:"POST",path:"/wallets/execute-swap",request:an((()=>Bo)),response:an((()=>qo))},{method:"GET",path:"/transactions",response:an((()=>Mo))},{method:"GET",path:"/transactions/pending",response:an((()=>Fo))},{method:"POST",path:"/transactions/resolve",request:an((()=>Go)),response:an((()=>jo))},{method:"POST",path:"/transactions/transfer",request:an((()=>Ho)),response:an((()=>$o))},{method:"POST",path:"/transactions/transfer-with-shares",request:an((()=>Yo)),response:an((()=>$o))},{method:"POST",path:"/transactions/asset-optin",request:an((()=>zo)),response:an((()=>$o))},{method:"POST",path:"/transactions/app-optin",request:an((()=>Jo)),response:an((()=>$o))},{method:"GET",path:"/transactions/estimate-fee",response:an((()=>Xo))},{method:"GET",path:"/transactions/status",response:an((()=>Qo))},{method:"GET",path:"/transactions/raw-status",response:an((()=>Gn))},{method:"GET",path:"/transactions/detect-transfers-restrictions",response:an((()=>ec))},{method:"GET",path:"/transactions/transfer-restriction-message",response:an((()=>tc))},{method:"GET",path:"/transactions/restriction",response:an((()=>rc))},{method:"GET",path:"/transactions/check-asset-optin",response:en(hn(pn(),Qa()))},{method:"GET",path:"/transactions/check-app-optin",response:en(hn(pn(),Qa()))},{method:"POST",path:"/transactions/create-allowance",request:an((()=>sc)),response:an((()=>ac))},{method:"GET",path:"/query/assets/balance",response:an((()=>ic))},{method:"GET",path:"/query/address/balance",response:an((()=>ic))},{method:"POST",path:"/query/assets/bulk-balance",request:an((()=>cc)),response:an((()=>dc))},{method:"POST",path:"/query/assets/wallet-bulk-balance",request:an((()=>lc)),response:an((()=>dc))},{method:"GET",path:"/query/transactions",response:an((()=>pc))},{method:"GET",path:"/query/fetch-token-info",response:an((()=>uc))},{method:"GET",path:"/query/get-asset-price",response:an((()=>fc))},{method:"POST",path:"/mpc/reconstruct-seed-phrase",request:an((()=>gc)),response:an((()=>wc))},{method:"GET",path:"/users",response:an((()=>mc))},{method:"PUT",path:"/users/profile",request:an((()=>vc)),response:an((()=>Sc))},{method:"GET",path:"/users/profile",response:an((()=>_c))},{method:"GET",path:"/users/salt",response:an((()=>Ac))},{method:"GET",path:"/users/{userId}/wallets",response:an((()=>Ec))},{method:"GET",path:"/users/merchants/assets",response:an((()=>Ti))},{method:"GET",path:"/users/merchant/assets",response:an((()=>Ti))},{method:"GET",path:"/users/{userId}/assets",response:an((()=>bc))},{method:"POST",path:"/users/assets/add",request:an((()=>Pc)),response:an((()=>Tc))},{method:"DELETE",path:"/users/{userId}/wallets/{walletId}/assets/{assetConfigId}",response:an((()=>kc))},{method:"GET",path:"/users/{userId}",response:an((()=>_c))},{method:"GET",path:"/users/{externalUserId}/externalUserId",response:an((()=>Cc))},{method:"POST",path:"/transactions/admin/release-schedule",request:an((()=>xc)),response:an((()=>Kc))},{method:"GET",path:"/transactions/admin/release-schedule",response:an((()=>Mc))},{method:"POST",path:"/transactions/admin/mint",request:an((()=>Nc)),response:an((()=>Rc))},{method:"POST",path:"/transactions/admin/burn",request:an((()=>Lc)),response:an((()=>Rc))},{method:"POST",path:"/transactions/admin/execute-purchase",request:an((()=>Uc)),response:an((()=>Kc))},{method:"POST",path:"/transactions/admin/execute-purchase-with-interest",request:an((()=>Bc)),response:an((()=>Kc))},{method:"POST",path:"/transactions/admin/set-identity",request:an((()=>qc)),response:an((()=>Kc))},{method:"POST",path:"/transactions/admin/force-claim",request:an((()=>Vc)),response:an((()=>Kc))},{method:"POST",path:"/transactions/admin/force-claim-principal",request:an((()=>Vc)),response:an((()=>Kc))},{method:"GET",path:"/transactions/admin/{referenceId}",response:an((()=>Wc))},{method:"POST",path:"/transactions/admin/callback",request:an((()=>Fc)),response:an((()=>Gc))},{method:"GET",path:"/dashboard",response:an((()=>jc))},{method:"GET",path:"/users-activities",response:an((()=>$c))}],zc=new Map,Jc=[];for(const e of Yc)if(e.path.includes("{")){const t=e.path.replace(/\{[^/]+\}/g,"[^/]+");Jc.push({method:e.method,regex:new RegExp(`^${t}$`),entry:e})}else zc.set(`${e.method} ${e.path}`,e);const Xc={response:{statusCode:200,errorCode:exports.ErrorResponseCodes.sdk_invalid_response,tag:"InvalidResponse"},request:{statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter,tag:"InvalidRequest"}};function Zc(e,t,r,s,a){var n;if("off"===a)return;const i=null===(n=function(e,t){const r=e.toUpperCase(),s=function(e){var t;const r=null!==(t=e.split("?")[0])&&void 0!==t?t:"";return(r.startsWith("/")?r:`/${r}`).replace(/^\/api\/v1/,"")||"/"}(t),a=zc.get(`${r} ${s}`);if(a)return{request:a.request,response:a.response};const n=Jc.find((({method:e,regex:t})=>e===r&&t.test(s)));return n?{request:n.entry.request,response:n.entry.response}:void 0}(t,r))||void 0===n?void 0:n[e];if(!i)return;const o=function(e,t){const r=e["~run"]({value:t},Ga());return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}(i,s);if(o.success)return;const c=`${t} ${r}: ${d=o.issues,d.slice(0,3).map((e=>{var t;return`${null!==(t=function(e){if(e.path){let t="";for(const r of e.path){if("string"!=typeof r.key&&"number"!=typeof r.key)return null;t+=t?`.${r.key}`:r.key}return t}return null}(e))&&void 0!==t?t:"<root>"}: expected ${e.expected}, got ${e.received}`})).join("; ")}`;var d;const{statusCode:l,errorCode:h,tag:p}=Xc[e];if("throw"===a)throw new V({kind:"validation",message:c,statusCode:l,errorCode:h,data:{method:t,path:r,issues:o.issues}});ue.warn(`SDK::ApiValidation::${p} ${c}`)}function Qc({method:e,path:t,data:r,mode:s}){Zc("response",e,t,r,s)}function ed({method:e,path:t,body:r,mode:s}){Zc("request",e,t,r,s)}const td=new Set([exports.ErrorResponseCodes.auth_api_jwt_invalid,exports.ErrorResponseCodes.auth_api_jwt_not_active,exports.ErrorResponseCodes.auth_api_jwt_not_provided,exports.ErrorResponseCodes.auth_api_jwt_expired,exports.ErrorResponseCodes.auth_api_unauthorized]),rd=new Set([exports.ErrorResponseCodes.auth_refresh_token_not_found,exports.ErrorResponseCodes.auth_refresh_token_expired,exports.ErrorResponseCodes.auth_refresh_token_reuse_detected]);function sd(e){var t,r,s,a,n;return null!==(a=null!==(r=null!==(t=null==e?void 0:e.status)&&void 0!==t?t:null==e?void 0:e.statusCode)&&void 0!==r?r:null===(s=null==e?void 0:e.error)||void 0===s?void 0:s.statusCode)&&void 0!==a?a:null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.statusCode}function ad(e){var t,r,s,a;return null!==(s=null!==(t=null==e?void 0:e.errorCode)&&void 0!==t?t:null===(r=null==e?void 0:e.error)||void 0===r?void 0:r.errorCode)&&void 0!==s?s:null===(a=null==e?void 0:e.data)||void 0===a?void 0:a.errorCode}function nd(e){if(401!==sd(e))return!1;const t=ad(e);return!t||td.has(t)}const id=new class{constructor(){this.inFlightOperations=new Map}withDedupe(e,t){const r=this.inFlightOperations.get(e);if(r)return r;const s=Promise.resolve().then(t).finally((()=>{this.inFlightOperations.delete(e)}));return this.inFlightOperations.set(e,s),s}isInFlight(e){return this.inFlightOperations.has(e)}clearAll(){this.inFlightOperations.clear()}},od=new Ka;class cd{constructor(t,r={}){var s,a,n,i,o;const c=Wa(t);this.apiKey=c.apiKey,this.baseUrl=c.baseUrl,this.userId=c.userId,this.options=c.options,(null===(s=this.options)||void 0===s?void 0:s.platform)&&(Se.platform=this.options.platform,Se.isNative="ios"===this.options.platform||"android"===this.options.platform,Se.isWeb=!Se.isNative),this.cipher=null!==(a=r.cipher)&&void 0!==a?a:new xa,this.transport=null!==(n=r.transport)&&void 0!==n?n:(...e)=>fetch(...e),this.clock=null!==(i=r.clock)&&void 0!==i?i:{now:()=>Date.now()},this.lockManager=od,this._initializeClientAuthToken(c.clientAuthToken),this.request=this.request.bind(this);const d=new e.H({baseUrl:this.baseUrl.replace(/\/api\/v1\/?$/,""),baseApiParams:{secure:!0},securityWorker:this.securityWorker.bind(this),customFetch:this.transport}),l=d.request.bind(d);d.request=async e=>{const t=async r=>{try{ed({method:e.method,path:e.path,body:e.body,mode:this.validationMode});const t=await l(e);return Qc({method:e.method,path:e.path,data:t,mode:this.validationMode}),t}catch(e){if(!r&&nd(e))return await this._performTokenRefresh(),t(!0);if(null==e?void 0:e.error){const t=e.error;throw this.toWallabyError({message:t.message||"API request failed",statusCode:t.statusCode||e.status||500,errorCode:t.errorCode,data:t})}if(e instanceof V)throw e;throw this.toWallabyError({message:e.message||"Network request failed",statusCode:0,errorCode:"NETWORK_ERROR",data:{code:e.code||e.name,originalError:e},cause:e.cause})}};return t(!1)},this.api=new e.A(d),this.api.http.setSecurityData(Object.assign({"x-api-key":t.apiKey,"x-client-jwt":t.clientAuthToken},null===(o=this.options)||void 0===o?void 0:o.headers))}set setClientAuthToken(e){this._initializeClientAuthToken(e)}get version(){const e=_e;return ue.log(`wsdk is running v${e}`),e}_initializeClientAuthToken(e){if(t=e,r=this.userId,!t||!r||n.jwtDecode(t).externalUserId!==r)throw new V({message:"Client auth token does not match the user id. Blocking API call.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_jwt_invalid});var t,r;this.clientAuthToken=e,!function(e){return n.jwtDecode(e).mfaVerified}(e)?this.deviceAuthType=exports.AuthType.Passkey:this.deviceAuthType=exports.AuthType.Password}get deviceLocalStorage(){var e;if(null===(e=this.options)||void 0===e?void 0:e.storage)return this.options.storage;if("undefined"!=typeof window&&"localStorage"in window)return window.localStorage;throw new V({message:"Your device storage is not supported natively yet, please provide a custom storage in the config options.",statusCode:400,errorCode:"device_storage_unsupported"})}get validationMode(){var e,t;return null!==(t=null===(e=this.options)||void 0===e?void 0:e.runtimeValidation)&&void 0!==t?t:"throw"}get settings(){var e,t,r,s,a,n;return Object.freeze({apiKey:this.apiKey,baseUrl:this.baseUrl,environment:null!==(t=null===(e=this.options)||void 0===e?void 0:e.environment)&&void 0!==t?t:ge,network:null!==(s=null===(r=this.options)||void 0===r?void 0:r.network)&&void 0!==s?s:we,hostname:null!==(n=null===(a=this.options)||void 0===a?void 0:a.hostname)&&void 0!==n?n:"https://www.republic.com"})}get localStorageService(){var e;if(!this.clientAuthToken)throw new V({message:"A client authentication token (JWT) is required",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return null!==(e=this._localStorageService)&&void 0!==e?e:this._localStorageService=new Na({deviceStorage:this.deviceLocalStorage,userId:this.userId,environment:this.settings.environment})}async _performTokenRefresh(e){const t=`refresh:${this.userId}:${this.settings.environment}:${this.settings.network}`;await id.withDedupe(t,(async()=>{var t;const r=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(r)try{const s=await this.request(Ua.refreshAccessToken,{payload:{refreshToken:r}},!1,null!==(t=null==e?void 0:e.silent)&&void 0!==t&&t);await this.localStorageService.save(exports.LocalStorageItems.AccessToken,s.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,s.refreshToken)}catch(e){throw function(e){const t=sd(e),r=ad(e);return 401===t||!!r&&rd.has(r)}(e)&&(await this.localStorageService.delete(exports.LocalStorageItems.AccessToken),await this.localStorageService.delete(exports.LocalStorageItems.RefreshToken)),e}}))}toWallabyError(e){var t,r;const s=new V(e);try{null===(r=null===(t=this.options)||void 0===t?void 0:t.onError)||void 0===r||r.call(t,s)}catch(e){ue.error("SDK::Base::toWallabyError::onError handler threw",{error:e})}return s}async request(e,t,r=!1,s=!1){var a;const n=e=>s?new V(e):this.toWallabyError(e);if(e!==Ua.refreshAccessToken&&!r){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(e&&Da(e,60,this.clock.now))try{await this._performTokenRefresh({silent:!0})}catch(e){}}let i="string"==typeof e.fullPath?e.fullPath:e.fullPath(null==t?void 0:t.payload);(null==t?void 0:t.queryParams)&&(i+=`?${function(e){const t=new URLSearchParams;return Object.keys(e).forEach((r=>{null!==e[r]&&void 0!==e[r]&&""!==e[r]&&t.append(r,e[r])})),t.toString()}(t.queryParams)}`);const o=`${this.baseUrl}${i}`,c=Object.assign(Object.assign({},await this._getRequestHeaders()),null===(a=this.options)||void 0===a?void 0:a.headers);try{ed({method:e.method,path:i,body:null==t?void 0:t.payload,mode:this.validationMode});const s={method:e.method,headers:c};e.method!==exports.RequestMethod.Get&&(null==t?void 0:t.payload)&&(s.body=JSON.stringify(t.payload)),ue.debug(`SDK::Base::${e.method}::Request`,{path:o,payload:null==t?void 0:t.payload});const a=await this.transport(o,s),d=a.headers.get("content-type");let l;if(null==d?void 0:d.includes("application/json"))l=await a.json();else{const e=await a.text();try{l=JSON.parse(e)}catch(t){l=e}}if(ue.debug(`SDK::Base::${e.method}::Response`,{status:a.status,statusText:a.statusText,data:l}),!a.ok){if(!r&&e!==Ua.refreshAccessToken&&nd({status:a.status,errorCode:null==l?void 0:l.errorCode}))return await this._performTokenRefresh(),this.request(e,t,!0);throw n({message:(null==l?void 0:l.message)||a.statusText||"Request failed",statusCode:a.status,errorCode:null==l?void 0:l.errorCode,data:l})}return Qc({method:e.method,path:i,data:l,mode:this.validationMode}),l}catch(t){if(t instanceof V)throw t;if(null==t?void 0:t.error){ue.error("SDK::Base::handleApiCall::API Error",{error:t});const e=t.error;throw n({message:e.message||"API request failed",statusCode:e.statusCode||500,errorCode:e.errorCode,data:e})}throw ue.error(`SDK::Base::${e.method}::NetworkError`,{message:t.message,name:t.name,error:t}),n({message:t.message||"Network request failed",statusCode:0,errorCode:"NETWORK_ERROR",data:{code:t.code||t.name,originalError:t},cause:t.cause})}}async _getRequestHeaders(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(Ra(this.clientAuthToken,this.clock.now))throw new V({message:"Auth token has expired",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_jwt_expired});const t={"Content-Type":"application/json","x-api-key":this.settings.apiKey,"x-client-jwt":this.clientAuthToken,[Ae]:Ee};return e&&(t.Authorization="Bearer "+e),t}async securityWorker(e){try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&Da(e,60,this.clock.now)&&await this._performTokenRefresh({silent:!0})}catch(e){}const t=Object.assign(Object.assign({"Content-Type":"application/json"},e||{}),{[Ae]:Ee});try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&(t.Authorization=`Bearer ${e}`)}catch(e){}return{headers:t}}}const dd={importSeedPhraseV2:{fullPath:"/wallets/create-shares-based-wallet-from-seed",method:exports.RequestMethod.Post,requiresAccessToken:!0},addNewDevice:{fullPath:"/wallets/add-new-device",method:exports.RequestMethod.Post,requiresAccessToken:!0},initKeyExchange:{fullPath:"/mpc/init-key-exchange",method:exports.RequestMethod.Post,requiresAccessToken:!0},retrieveSeedPhrase:{fullPath:"/mpc/reconstruct-seed-phrase",method:exports.RequestMethod.Post,requiresAccessToken:!0},createWithKeyShares:{fullPath:"/wallets/create-with-shares",method:exports.RequestMethod.Post,requiresAccessToken:!0},create:{fullPath:"/wallets/create",method:exports.RequestMethod.Post,requiresAccessToken:!0},import:{fullPath:"/wallets/import-seed-phrase",method:exports.RequestMethod.Post,requiresAccessToken:!0},getTokenBalance:{fullPath:({address:e,assetSymbol:t,chainName:r,tokenStandard:s})=>`/query/assets/balance?address=${e}&assetSymbol=${t}`+(s?`&tokenType=${s}`:"")+(r?`&chainName=${r}`:""),method:exports.RequestMethod.Get,requiresAccessToken:!1},getMultiTokenBalances:{fullPath:"/query/assets/bulk-balance",method:exports.RequestMethod.Post,requiresAccessToken:!1},getWalletBalances:{fullPath:"/query/assets/wallet-bulk-balance",method:exports.RequestMethod.Post,requiresAccessToken:!1},getWalletAssets:{fullPath:({walletId:e})=>`/wallets/${e}/assets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserAssets:{fullPath:({userId:e})=>`/users/${e}/assets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},addTokenToWallet:{fullPath:"/users/assets/add",method:exports.RequestMethod.Post,requiresAccessToken:!1},generateWalletAddresses:{fullPath:"/wallets/generate-wallet-addresses",method:exports.RequestMethod.Post,requiresAccessToken:!0},updateAsset:{fullPath:"/wallets/asset/update",method:exports.RequestMethod.Put,requiresAccessToken:!1},getUserWallets:{fullPath:({userId:e})=>`/users/${e}/wallets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},convertMnemonicSeedPhrase:{fullPath:"/wallets/convert-mnemonic-seed",method:exports.RequestMethod.Post,requiresAccessToken:!0},createMultisigAsset:{fullPath:"/wallets/create-multisig-asset",method:exports.RequestMethod.Post,requiresAccessToken:!0},verifyAccess:{fullPath:"/wallets/verify-access",method:exports.RequestMethod.Post,requiresAccessToken:!0}},ld={getSupportedBlockchains:{fullPath:"/chains",method:exports.RequestMethod.Get,requiresAccessToken:!1},getSupportedTokens:{fullPath:"/assets/configurations",method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserByExternalUserId:{fullPath:({externalUserId:e})=>`/users/${e}/externalUserId`,method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserData:{fullPath:({userId:e})=>`/users/${e}`,method:exports.RequestMethod.Get,requiresAccessToken:!1},fetchTokenInfo:{fullPath:()=>"/query/fetch-token-info",method:exports.RequestMethod.Get,requiresAccessToken:!1}},hd={transfer:{fullPath:"/transactions/transfer",method:exports.RequestMethod.Post,requiresAccessToken:!0},transferWithShares:{fullPath:"/transactions/transfer-with-shares",method:exports.RequestMethod.Post,requiresAccessToken:!0},createAllowance:{fullPath:"/transactions/create-allowance",method:exports.RequestMethod.Post,requiresAccessToken:!0},estimateFee:{fullPath:"/transactions/estimate-fee",method:exports.RequestMethod.Get,requiresAccessToken:!0},getTransaction:{fullPath:"/transactions/status",method:exports.RequestMethod.Get,requiresAccessToken:!0},getTransactions:{fullPath:"/transactions",method:exports.RequestMethod.Get,requiresAccessToken:!0},detectTransferRestrictions:{fullPath:"/transactions/detect-transfers-restrictions",method:exports.RequestMethod.Get,requiresAccessToken:!0},transferRestrictionMessage:{fullPath:"/transactions/transfer-restriction-message",method:exports.RequestMethod.Get,requiresAccessToken:!0},restriction:{fullPath:"/transactions/restriction",method:exports.RequestMethod.Get,requiresAccessToken:!0},getPendingTransactions:{fullPath:"/transactions/pending",method:exports.RequestMethod.Get,requiresAccessToken:!0},confirmPendingTransaction:{fullPath:"/transactions/resolve",method:exports.RequestMethod.Post,requiresAccessToken:!0}},pd={getQuote:{fullPath:({walletId:e})=>`/wallets/${e}/swap/quote`,method:exports.RequestMethod.Post,requiresAccessToken:!0},executeSwap:{fullPath:"/wallets/execute-swap",method:exports.RequestMethod.Post,requiresAccessToken:!0},getSwaps:{fullPath:({walletId:e})=>`/wallets/${e}/swaps`,method:exports.RequestMethod.Get,requiresAccessToken:!0}};function ud(e,t){if(!e)return{};const r=new Set(t);return Object.fromEntries(Object.entries(e).filter((([e])=>!r.has(e))))}class yd{constructor(){}async register({optionsJSON:e}){if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new V({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await u.startRegistration({optionsJSON:e})}async authenticate({optionsJSON:e,useBrowserAutofill:t=!1,skipUserVerification:r=!1}){try{if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new V({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await u.startAuthentication({optionsJSON:Object.assign(Object.assign({},e),{userVerification:r?"discouraged":e.userVerification}),useBrowserAutofill:t})}catch(e){throw this.handlePasskeyError(e),e}}handlePasskeyError(e){return ue.error("SDK::Authenticator::handlePasskeyError",e),this.throwPasskeyError(this.classifyPasskeyError(e),e)}classifyPasskeyError(e){return e instanceof u.WebAuthnError?(ue.debug("SDK::Authenticator::handlePasskeyError - WebAuthnError",e),{errorCode:e.code}):e instanceof Error?(ue.debug("SDK::Authenticator::handlePasskeyError - Error",e),{errorMessage:e.message}):null!==e&&"object"==typeof e&&e.error&&e.message?(ue.debug("SDK::Authenticator::handlePasskeyError - Object",e),{errorCode:e.error,errorMessage:e.message}):"string"==typeof e?(ue.debug("SDK::Authenticator::handlePasskeyError - String",e),{errorMessage:e}):(ue.debug("SDK::Authenticator::handlePasskeyError - Unknown",e),{})}throwPasskeyError({errorCode:e,errorMessage:t},r){var s,a,n;ue.error("SDK::Authenticator::throwPasskeyError",e);const i=he.find((t=>t.error===e));throw ue.error("SDK::Authenticator::error",i),new V({message:null!==(a=null!==(s=null==i?void 0:i.message)&&void 0!==s?s:t)&&void 0!==a?a:M.message,statusCode:400,errorCode:null!==(n=null==i?void 0:i.error)&&void 0!==n?n:e,cause:r})}}function fd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");return t.padEnd(t.length+(4-t.length%4)%4,"=")}function gd(e){try{return o.toUint8Array(e)}catch(r){return t=e,o.toUint8Array(fd(t))}var t}function wd(e){const t=fd(e),r=o.atob(t),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}class md{constructor(e,t,r,s=new xa){this.cipher=s,this.localStorageService=t,this.userId=e,this.request=r,this.authenticator=new yd}preparePasskeyRequestOptions(e){var t,r,s,a,n,i,o,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?wd(e.extensions.prf.eval.base64):(null===(a=null===(s=e.extensions)||void 0===s?void 0:s.prf.eval)||void 0===a?void 0:a.first)instanceof ArrayBuffer?new Uint8Array(e.extensions.prf.eval.first):"object"==typeof(null===(i=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===i?void 0:i.first)?new Uint8Array(Object.values(e.extensions.prf.eval.first)):void 0,l=Object.assign(Object.assign({},e),{extensions:Object.assign(Object.assign({},e.extensions),{prf:void 0!==d?{eval:{first:d}}:null!==(c=null===(o=e.extensions)||void 0===o?void 0:o.prf)&&void 0!==c?c:{}})});return ue.log("SDK::PasskeyService::preparePasskeyRequestOptions::parsedOptions",!!l),l}preparePasskeyCreationOptions(e){var t,r,s,a,n,i,o,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?wd(e.extensions.prf.eval.base64):(null===(a=null===(s=e.extensions)||void 0===s?void 0:s.prf.eval)||void 0===a?void 0:a.first)instanceof ArrayBuffer?new Uint8Array(e.extensions.prf.eval.first):"object"==typeof(null===(i=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===i?void 0:i.first)?new Uint8Array(Object.values(e.extensions.prf.eval.first)):void 0,l=Object.assign(Object.assign({},e),{extensions:Object.assign(Object.assign({},e.extensions),{prf:void 0!==d?{eval:{first:d}}:null!==(c=null===(o=e.extensions)||void 0===o?void 0:o.prf)&&void 0!==c?c:{}})});return ue.log("SDK::PasskeyService::preparePasskeyCreationOptions::parsedOptions",!!l),l}async addNewPasskey({deviceKeyPair:e,getSignature:t}){try{let r,s;ue.log("SDK::PasskeyService::addNewPasskey: start adding new passkey");try{const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});if(!a.registrationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const n=this.preparePasskeyCreationOptions(a.registrationOptions);ue.log("SDK::PasskeyService::addNewPasskey: about to register passkey credential"),r=await this.authenticator.register({optionsJSON:n}),ue.log("SDK::PasskeyService::addNewPasskey: finished registering passkey credential");const i=await this.handleCredentialsCreationFromPrfExtension(r);ue.log("SDK::PasskeyService::addNewPasskey:: finished deriving credentials key pair",i.publicKey),s=await this.request(Ua.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyRegistrationResponse:r}}),ue.log("SDK::PasskeyService::addNewPasskey:: signInResponse",s);const o=await this.cipher.encrypt({data:e.privateKey,encryptionKey:i.publicKey});return await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:o},passkeyCredential:r}),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:i.prfValue})}catch(a){if(ue.error("SDK::PasskeyService::addNewPasskey::error",a),a&&a.code===ie.error){const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if(!a.authenticationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const n=this.preparePasskeyRequestOptions(a.authenticationOptions);ue.log("SDK::PasskeyService::addNewPasskey::catch: about to authenticate with passkey"),r=await this.authenticator.authenticate({optionsJSON:n}),ue.log("SDK::PasskeyService::addNewPasskey::catch: finished authenticating with passkey"),s=await this.request(Ua.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyAuthenticationResponse:r}}),ue.log("SDK::PasskeyService::addNewPasskey::catch: finished signing in with passkey",{signInResponse:s});const i=await this.handleCredentialsCreationFromPrfExtension(r);ue.log("SDK::PasskeyService::addNewPasskey::catch: finished deriving credentials key pair",i.publicKey);const o=await this.cipher.encrypt({data:e.privateKey,encryptionKey:i.publicKey});return ue.log("SDK::PasskeyService::addNewPasskey::catch: about to store data"),await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:o},passkeyCredential:r}),ue.log("SDK::PasskeyService::addNewPasskey::catch: finished storing data"),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:i.prfValue})}throw a}}catch(e){if(e instanceof V)throw e;throw this.authenticator.handlePasskeyError(e)}}async authenticate({deviceKeyPair:e,challengeResponse:t}){var r,s;try{if(!t.authenticationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const a=this.preparePasskeyRequestOptions(t.authenticationOptions),n=null===(s=null===(r=a.extensions.prf)||void 0===r?void 0:r.eval)||void 0===s?void 0:s.first,i=Object.assign(Object.assign({},t.authenticationOptions),{extensions:Object.assign(Object.assign({},ud(a.extensions,["credProps"])),{prf:{eval:{first:n}}})}),o=await this.authenticator.authenticate({optionsJSON:i}),c=await this.handleCredentialsCreationFromPrfExtension(o),d=t.signature?t.signature:await this.getDeviceSignature({message:t.message,credentialsKeyPair:c,deviceKeyPair:e}),l=await this.request(Ua.signIn,{payload:{externalUserId:this.userId,message:t.message,clientAuthPubKey:e.publicKey,signature:d,passkeyAuthenticationResponse:o}}),h=e.decryptedPrivateKey?e.decryptedPrivateKey:e.encryptedDevicePrivateKey?await this.cipher.decrypt({cipherText:e.encryptedDevicePrivateKey,decryptionKey:c.privateKey}):void 0;if(!h)throw new V({message:"Device private key is not available for storage.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const p=await this.cipher.encrypt({data:h,encryptionKey:c.publicKey});return await this.handleStoringData({authenticationResponse:l,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:p},passkeyCredential:o}),Object.freeze(Object.assign(Object.assign({},l),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(e instanceof V)throw e;throw this.authenticator.handlePasskeyError(e)}}async getDeviceSignature({message:e,credentialsKeyPair:t,deviceKeyPair:r}){let s;if(r.decryptedPrivateKey)s=r.decryptedPrivateKey;else{if(!r.encryptedDevicePrivateKey)throw new V({message:"Device private key is not available for signing the message.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});s=await this.cipher.decrypt({cipherText:r.encryptedDevicePrivateKey,decryptionKey:t.privateKey})}return(await this.cipher.sign({message:e,signingKey:s})).signature}async register({deviceKeyPair:e,challengeResponse:t}){var r;try{if(!t.registrationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});ue.log("SDK::PasskeyService::register:: got challenge",{registrationOptions:t.registrationOptions});const s=this.preparePasskeyCreationOptions(t.registrationOptions);ue.log("SDK::PasskeyService::register:: registering passkey",{parsedOptions:s});const a=await this.authenticator.register({optionsJSON:s});if(ue.log("SDK::PasskeyService::register:: got passkey credential",{id:a.id,type:a.type}),!(null===(r=a.clientExtensionResults.prf)||void 0===r?void 0:r.enabled))throw new V({message:"Device is not compatible with this feature. Try using a different authentication method.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});ue.log("SDK::PasskeyService::register:: getting signature",{message:t.message});const{signature:n,message:i}=await this.cipher.sign({message:t.message,signingKey:e.privateKey}),o=await this.request(Ua.signUp,{payload:{externalUserId:this.userId,message:i,signature:n,clientAuthPubKey:e.publicKey,passkeyRegistrationResponse:a}}),c=await this.handleCredentialsCreationFromPrfExtension(a),d=await this.cipher.encrypt({data:e.privateKey,encryptionKey:c.publicKey});return await this.handleStoringData({authenticationResponse:o,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:d},passkeyCredential:a}),Object.freeze(Object.assign(Object.assign({},o),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(ue.log("SDK::PasskeyService::register::error",{error:e,errorCode:e.code,errorMessage:e.message}),e instanceof V)throw ue.log("SDK::PasskeyService::register::API error detected",{error:e}),e;if(e&&e.code===ie.error||e.code===oe.error||"The authenticator was previously registered."===e.message)throw ue.log("SDK::PasskeyService::register::ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",!0),e;throw this.authenticator.handlePasskeyError(e)}}async isDevicePrfCompatible(){var e;try{if("undefined"!=typeof window&&"function"==typeof(null===(e=window.PublicKeyCredential)||void 0===e?void 0:e.getClientCapabilities)){const e=await window.PublicKeyCredential.getClientCapabilities();return ue.log("SDK::PasskeyService::isDevicePrfCompatible::capabilities",e),e["extension:prf"]}return!1}catch(e){return!1}}async publicKeyCredential(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.PasskeyCredential);return null!=e?e:"There are no passkeys stored on this device"}async handleStoringData({authenticationResponse:e,deviceKeyPair:t,passkeyCredential:r}){return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:t.encryptedDevicePrivateKey},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:t.publicKey},{key:exports.LocalStorageItems.PasskeyCredential,value:r},{key:exports.LocalStorageItems.AccessToken,value:e.accessToken},...e.refreshToken?[{key:exports.LocalStorageItems.RefreshToken,value:e.refreshToken}]:[]])}async handleCredentialsCreationFromPrfExtension(e){var t,r,s,a,n;try{const i=e.clientExtensionResults;if(ue.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::extensions",i),!(null===(t=i.prf)||void 0===t?void 0:t.enabled)&&!(null===(s=null===(r=i.prf)||void 0===r?void 0:r.results)||void 0===s?void 0:s.first))throw new V({message:"Device is not compatible with this feature. Try using a different authentication method.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});if(ue.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prf is enabled",i.prf.enabled),!(null===(a=i.prf.results)||void 0===a?void 0:a.first))throw new V({message:"PRF extension did not return any results. Cannot proceed with authentication.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});const o=null===(n=i.prf.results)||void 0===n?void 0:n.first;let c;if("string"==typeof o)c=gd(o);else if(o instanceof Uint8Array)c=o;else if(o instanceof ArrayBuffer)c=new Uint8Array(o);else if(ArrayBuffer.isView(o))c=new Uint8Array(o.buffer);else if(Array.isArray(o))c=new Uint8Array(o);else{if(!o||"object"!=typeof o)throw new V({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});{const e=o.data;if(Array.isArray(e))c=new Uint8Array(e);else{const e=Object.values(o);if(!e.length||!e.every((e=>"number"==typeof e)))throw new V({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});c=new Uint8Array(e)}}}ue.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prfValue",c);const d=await this.cipher.getCredentialsKeyPair({prfValue:c,authType:exports.AuthType.Passkey});return ue.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::credentials key pair was created",!!d),Object.assign(Object.assign({},d),{prfValue:c})}catch(e){if(e instanceof V)throw e;if(e instanceof Error)throw new V({message:e.message,statusCode:400,errorCode:"sdk_passkey_prf_handling_failed",data:e,cause:e.cause});throw this.authenticator.handlePasskeyError(e)}}}function vd(e){return function(t,r,s){if(!s.value)return;const a=s.value;return s.value=async function(...s){var n,i,o,c,d;const l=this.lockManager,h=e||`${t.constructor.name}:${r}`,p=null!==(i=null===(n=this.options)||void 0===n?void 0:n.environment)&&void 0!==i?i:ge,u=null!==(c=null===(o=this.options)||void 0===o?void 0:o.network)&&void 0!==c?c:we,y=`${null!==(d=this.userId)&&void 0!==d?d:"anon"}:${p}:${u}:${h}`;return l.withLock(y,(()=>a.apply(this,s)))},s}}class Sd extends cd{constructor(e,t={}){super(e,t),this.getUserSalt=this.getUserSalt.bind(this),this.passkeyService=new md(e.userId,this.localStorageService,this.request,this.cipher)}async isDevicePrfCompatible(){return await this.passkeyService.isDevicePrfCompatible()}async validateSession(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken),t=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);return!!e&&!Ra(e)||!!t}async refreshAuthTokens(){if(!await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken))throw new V({message:"Refresh token is required",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_refresh_token_missing});await this._performTokenRefresh();const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken),t=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(!e||!t)throw new V({message:"Token refresh failed: tokens not present in storage after refresh",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_refresh_token_missing});return{accessToken:e,refreshToken:t}}async validatePassword({password:e,salt:t}){const r=null!=t?t:await this.getUserSalt();try{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)throw new V({message:"V2 Private key was not found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const s=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:r});return!!await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:s.privateKey})}catch(t){ue.warn("SDK::AuthService::validatePassword::error",t);return!!await this.localStorageService.getDecryptedV1PrivateKey(`${e}`)}}async getUserSalt(){try{return(await this.api.users.getCurrentUserSalt()).clientSalt}catch(e){throw ue.error("SDK::AuthService::getUserSalt::error",e),e}}async getSignature({deviceAuthKeys:e,walletId:t,passkeyChallengeType:r}){try{ue.debug("SDK::AuthService::getSignature::authType",this.deviceAuthType);const s=this.deviceAuthType===exports.AuthType.Passkey?null!=r?r:exports.PasskeyChallengeType.REGISTRATION:void 0;ue.debug("SDK::AuthService::getSignature::challengeType",s);const a=await this.request(Ua.signatureMessage,{payload:{walletId:t,clientAuthPubKey:e.publicKey,passkeyChallengeType:s}}),{signature:n,hashedMessage:i}=await this.cipher.sign({message:a.message,signingKey:e.privateKey});return Object.freeze(Object.assign(Object.assign({},a),{signature:n,hashedMessage:i,authenticationOptions:a.authenticationOptions,registrationOptions:a.registrationOptions}))}catch(e){throw ue.error("SDK::AuthService::getSignatureMessage::error",e),e}}async signUp(e){ue.info("starting signup");const t=Ls();let r;ue.info("key pair generated",!!t);try{const s=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});switch(ue.info("signature has been generated",!!s),this.deviceAuthType){case exports.AuthType.Passkey:ue.info("registering a new passkey"),r=await this.passkeyService.register({deviceKeyPair:t,challengeResponse:s});break;case exports.AuthType.Password:ue.info("signing up with password"),r=await this.handleSignUpWithPassword({signatureMessage:s,deviceKeyPair:t,input:e});break;default:throw new V({message:"Encryption mechanism not supported",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}return Object.freeze(Object.assign(Object.assign(Object.assign({},r),e),{signatureMessageResponse:s}))}catch(e){if(ue.error("SDK::AuthService::signUp::error",e),e&&e.error===oe.error||e.code===ie.error){ue.info("SDK::AuthService::signUp::handling previously registered passkey error");const e=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});return r=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:t.publicKey,decryptedPrivateKey:t.privateKey},challengeResponse:e}),r}throw e}}async signIn(e){let t;try{switch(this.deviceAuthType){case exports.AuthType.Passkey:t=await this.handleSignInWithPasskey({input:e});break;case exports.AuthType.Password:t=await this.handleSignInWithPassword({input:e});break;default:throw new V({message:"Encryption mechanism not supported",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,t.accessToken),t.refreshToken&&await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,t.refreshToken),Object.freeze(Object.assign(Object.assign({},t),e))}catch(e){throw ue.error("SDK::AuthService::signIn::error",e),e}}async hasStoredDevicePublicKey(){return!!await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey)}async handleSignInWithPassword({input:e}){if(!e.password)throw new V({message:"Password is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),r=await this.localStorageService.getEncryptedPrivateKey(),s=await this.getUserSalt(),a=await this.cipher.getCredentialsKeyPair({password:e.password,salt:s,authType:this.deviceAuthType});let n;if(t||r){if(!await this.validatePassword({password:e.password,salt:s}))throw ue.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password, please try again."),new V({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(t){const e=_a(t);n=await this.cipher.decrypt({cipherText:e,decryptionKey:a.privateKey})}else n=await this.localStorageService.getDecryptedV1PrivateKey(e.password)}else{if(await this.hasStoredDevicePublicKey())throw ue.error("SDK::AuthService::handleSignInWithPassword::error","Device key missing but wallet data exists"),new V({message:"Device key could not be read but existing wallet data was found on this device. Refusing to create a new identity to avoid orphaning wallet data.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_device_key_missing_with_existing_data});ue.info("No device data found, treating as a fresh device and creating a new key pair");n=Ls().privateKey}if(!n)throw ue.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const i=ms(n);await this.storeDeviceKeyPair({deviceAuthKeyPair:{publicKey:i,privateKey:n},credentialsKeyPair:a});const o=await this.getSignature({deviceAuthKeys:{publicKey:i,privateKey:n}}),c=await this.request(Ua.signIn,{payload:{externalUserId:this.userId,message:o.message,signature:o.signature,clientAuthPubKey:i}});return Object.assign(Object.assign({},c),{signatureMessageResponse:o,password:e.password,clientSalt:c.user.clientSalt})}async handleSignInWithPasskey({input:e}){let t;try{const r=await this.localStorageService.fetch(exports.LocalStorageItems.PasskeyCredential),s=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),a=await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey);let n;if(r){ue.debug("SDK::AuthService::handleSignInWithPasskey:: using existing key pair");const e=await this.request(Ua.signatureMessage,{payload:{clientAuthPubKey:a,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}});t=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:a,encryptedDevicePrivateKey:_a(s)},challengeResponse:e}),ue.debug("SDK::AuthService::handleSignInWithPasskey:: passkey authentication finished",!!t)}else{if(a||s)throw ue.error("SDK::AuthService::handleSignInWithPasskey::error","Passkey credential missing but device data exists"),new V({message:"Passkey credential could not be read but existing wallet data was found on this device. Refusing to create a new identity to avoid orphaning wallet data.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_device_key_missing_with_existing_data});n=Ls(),t=await this.passkeyService.addNewPasskey({deviceKeyPair:n,getSignature:this.getSignature.bind(this)}),ue.debug("SDK::AuthService::handleSignInWithPasskey:: passkey registration finished",t)}return Object.assign(Object.assign(Object.assign({},t),{prfValue:t.prfValue}),e)}catch(e){throw ue.error("SDK::AuthService::handleSignInWithPasskey::error ",e),e}}async storeDeviceKeyPair({deviceAuthKeyPair:e,credentialsKeyPair:t}){const r=await this.cipher.encrypt({data:e.privateKey,encryptionKey:t.publicKey});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:r},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:e.publicKey}])}async handleSignUpWithPassword({signatureMessage:e,input:t,deviceKeyPair:r}){if(!t.password)throw new V({message:"Password is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const s=await this.validatePasswordStrength(t.password);if(!s.valid)throw new V({message:s.message||"Invalid password",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const a=await this.request(Ua.signUp,{payload:{externalUserId:this.userId,message:e.message,signature:e.signature,clientAuthPubKey:r.publicKey}}).then((async e=>{const s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t.password,salt:e.user.clientSalt}),a=await this.cipher.encrypt({data:r.privateKey,encryptionKey:s.publicKey});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:a},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:r.publicKey},{key:exports.LocalStorageItems.AccessToken,value:e.accessToken},...e.refreshToken?[{key:exports.LocalStorageItems.RefreshToken,value:e.refreshToken}]:[]]),e}));return Object.assign(Object.assign({},a),{password:t.password,clientSalt:a.user.clientSalt,signatureMessageResponse:e})}async getPasskeyCredentials(){try{return await this.api.auth.getPasskeyCredentials()}catch(e){if(ue.error("SDK::AuthService::getPasskeyCredentials::error",e),"string"==typeof e)throw new V({message:e,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});if(e&&"object"==typeof e&&"message"in e)throw new V({message:e.message,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_unknown_error,data:e});throw e}}async validatePasswordStrength(e){return e?e.length<8?{valid:!1,message:"Password must be at least 8 characters long"}:e.length>128?{valid:!1,message:"Password must not exceed 128 characters"}:{valid:!0}:{valid:!1,message:"Password is required"}}async exchangeClientToken(){try{const e=await this.request(Ua.issueJwtToken);return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,e.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,e.refreshToken),e}catch(e){throw ue.error("SDK::Auth::exchangeClientToken::error",e),e}}}e._([vd("signUp"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Sd.prototype,"signUp",null),e._([vd("signIn"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Sd.prototype,"signIn",null),e._([vd("storeDeviceKeyPair"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Sd.prototype,"storeDeviceKeyPair",null);class _d extends cd{constructor(e,t={}){super(e,t),this.authService=new Sd(e,t),this.userId=e.userId}async handleImportWallet(e,t){var r,s,a,n,i;try{const{signature:i,message:o,wallabyAuthPubKey:c}=await this.authService.getSignature({walletId:null!==(r=t.walletId)&&void 0!==r?r:t.reference,deviceAuthKeys:{publicKey:e.publicKey,privateKey:e.privateKey},passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0});if(!c)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});if((t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||t.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!t.keyShareOptions)throw new V({message:"Key share options are required when requesting to split the seed phrase",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const{numberOfKeyShares:d,threshold:l}=null!==(s=t.keyShareOptions)&&void 0!==s?s:{};if(l&&d&&d<l)throw new V({message:"Number of shares must be greater than or equal to the threshold",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const h=await this.cipher.encrypt({data:Ma(t.seedPhrase),encryptionKey:c}),p={reference:t.reference,walletId:t.walletId,message:o,signature:i,encryptedSeed:h,clientAuthPubKey:e.publicKey,returnWalletOption:t.returnWalletOption,numShares:d,threshold:l,walletOwnershipType:exports.WalletOwnershipType.SingleOwner,wallabyKeepsOne:null!==(n=null===(a=t.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n},u=await this.request(dd.importSeedPhraseV2,{payload:p}),y=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:t.authenticationOptions.user.clientSalt,password:t.authenticationOptions.password,prfValue:t.authenticationOptions.prfValue});return u.encryptedSeed&&t.returnWalletOption!==exports.ReturnWalletOption.ReturnOnlyEncryptedShares&&await this.handleSeedPhraseFromResponse({walletId:u.wallet.id,encryptedSeed:u.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:t.storeSeedPhrase,credentialsKeyPair:y}),u.shares&&u.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:u.wallet.id,shares:u.shares,credentialsKeyPair:y,encryptedBackupShare:u.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign({},u)}catch(e){throw new V({message:null!==(i=e.message)&&void 0!==i?i:"Failed to handle importing the wallet",statusCode:e.statusCode,errorCode:e.errorCode,data:e.data,cause:e.cause})}}async handleWalletCreation(e,t){var s,a,n,i,o,c;try{const{signature:o,message:c,hashedMessage:d}=await this.authService.getSignature({deviceAuthKeys:{publicKey:e.publicKey,privateKey:e.privateKey},passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if((t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||t.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!t.keyShareOptions)throw new V({message:"Key share options are required when requesting to split the seed phrase",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const{numberOfKeyShares:l,threshold:h}=null!==(s=t.keyShareOptions)&&void 0!==s?s:{};if(h&&l&&l<h)throw new V({message:"Number of shares must be greater than or equal to the threshold",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const p={reference:r.v4(),message:c,signature:o,hashedMessage:d,clientAuthPubKey:e.publicKey,returnWalletOption:t.returnWalletOption,numShares:l,threshold:h,wallabyKeepsOne:null!==(n=null===(a=t.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n,walletOwnershipType:null!==(i=t.walletOwnershipType)&&void 0!==i?i:exports.WalletOwnershipType.SingleOwner},u=await this.request(dd.createWithKeyShares,{payload:p});let y;const f=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:t.authenticationOptions.user.clientSalt,password:t.authenticationOptions.password,prfValue:t.authenticationOptions.prfValue});return u.encryptedSeed&&(y=await this.handleSeedPhraseFromResponse({walletId:u.wallet.id,encryptedSeed:u.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:t.storeSeedPhrase,credentialsKeyPair:f})),u.shares&&u.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:u.wallet.id,shares:u.shares,credentialsKeyPair:f,encryptedBackupShare:u.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign(Object.assign({},u),{standardSeedPhrase:y})}catch(e){throw ue.error("SDK::handleWalletCreation::error",e),new V({message:null!==(o=e.message)&&void 0!==o?o:"Failed to handle creating the wallet",statusCode:e.statusCode,errorCode:null!==(c=e.errorCode)&&void 0!==c?c:"unspecified_error",data:e.data,cause:e.cause})}}async handleKeySharesFromResponse({walletId:e,shares:t,credentialsKeyPair:r,encryptedBackupShare:s,devicePrivateKey:a}){try{!function(e){if(!e.length)throw new V({message:"No key shares were returned from the API.",statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}(t);try{await this.cipher.decrypt({cipherText:t[0].encrypted,decryptionKey:a})}catch(e){throw new V({message:"Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.",statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_key_share_decryption_failed,cause:e})}const n=await this.cipher.encrypt({data:JSON.stringify(t[0].encrypted),encryptionKey:r.publicKey}),i=await this.cipher.encrypt({data:JSON.stringify(s),encryptionKey:r.publicKey});return await this.localStorageService.saveInBulk([{key:exports.V2KeyNames.PrimaryDeviceKeyShare,value:n,walletId:e},{key:exports.V2KeyNames.BackupDeviceKeyShare,value:i,walletId:e}]),[n,i]}catch(e){throw ue.error("SDK::handleKeySharesFromResponse::error",e),e}}async handleSeedPhraseFromResponse({walletId:e,encryptedSeed:t,devicePrivateKey:r,credentialsKeyPair:s,storeSeedPhrase:a}){try{const n=await this.cipher.decrypt({cipherText:t,decryptionKey:r});if(a){const t=ms(r),a=await this.cipher.encrypt({data:n,encryptionKey:t}),i=await this.cipher.encrypt({data:JSON.stringify(a),encryptionKey:s.publicKey});await this.localStorageService.save(exports.V2KeyNames.EncryptedStandardSeedPhrase,i,{walletId:e})}return n}catch(e){throw ue.error("SDK::handleSeedPhraseFromResponse::error",e),e}}}function Ad(e){const t=[];let r=0,s=0;for(const a of e)r|=a<<s,s+=8,s>=11&&(t.push(2047&r),r>>>=11,s-=11);return s>0&&t.push(2047&r),t}class Ed extends cd{constructor(e,t={}){super(e,t),this.authService=new Sd(e,t),this.handlers=new _d(e,t),this.userId=e.userId,this.passkeyService=new md(e.userId,this.localStorageService,this.request,this.cipher)}async getRateState(e){const t=Date.now(),r=await this.localStorageService.fetch(e),s=r?_a(r):void 0;return!s||t-s.windowStart>Ed.RATE_LIMIT_WINDOW_MS?{count:0,windowStart:t}:s}async recordRateAttempt(e){const t=await this.getRateState(e);return t.count+=1,await this.localStorageService.save(e,JSON.stringify(t)),t.count}async assertUnderRateLimit(e,t){const{count:r}=await this.getRateState(e);if(r>Ed.RATE_LIMIT_MAX)throw new V({message:t,statusCode:429,errorCode:exports.ErrorResponseCodes.sdk_too_many_requests})}async hasSeedPhraseOnDevice({walletId:e}){return await this.localStorageService.checkSeedPhraseExists(e)}async hasPrimaryKeyShareOnDevice({walletId:e}){return await this.localStorageService.checkPrimaryKeyShareExists(e)}async hasBackupKeyShareOnDevice({walletId:e}){return await this.localStorageService.checkBackupKeyShareExists(e)}async hasWalletOnDevice({walletId:e}){return await this.hasSeedPhraseOnDevice({walletId:e})||await this.hasPrimaryKeyShareOnDevice({walletId:e})}async create(e){try{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)throw new V({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const r=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,prfValue:e.authenticationOptions.prfValue,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt}),s=await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:r.privateKey});if(!s)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const a=ms(s);return await this.handlers.handleWalletCreation({publicKey:a,privateKey:s},e)}catch(e){throw ue.error("SDK::Wallet::create::error",e),e}}async export({walletId:e,authenticationOptions:t,exportOptions:r}){try{if(!r.algorandSeedPhrase&&!r.standardSeedPhrase&&!r.keyShares)throw new V({message:"exportOptions must be provided with at least one of the following options: algorandSeedPhrase, standardSeedPhrase, keyShares",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&t.password&&await this.migrateToV2Safe({password:t.password,walletId:e});const s=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:e}),a=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:e}),n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);let i,o,c;if(!n)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const d=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}),l=_a(n),h=await this.cipher.decrypt({cipherText:l,decryptionKey:d.privateKey});if(!h)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});if(r.keyShares){if(!a)throw new V({message:"You do not have any key shares stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const e=_a(a);i=await this.cipher.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:l,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}})}if(r.standardSeedPhrase||r.algorandSeedPhrase)if(s){const e=_a(s);if(o=await this.cipher.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:l,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),r.algorandSeedPhrase&&(c=this.getAlgorandSeedPhrase(o),!c))throw new V({message:"Something went wrong decrypting algorand seed phrase.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed})}else{if(!a)throw new V({message:"You do not have a wallet stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const s=_a(a),n={publicKey:ms(h),privateKey:h},{signature:i,message:d,wallabyAuthPubKey:p}=await this.authService.getSignature({deviceAuthKeys:n,walletId:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),u=p;if(!u)throw new V({message:"Wallaby public key is required for wallet export.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:s,encryptedDevicePrivateKey:l,wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),f=await this.request(dd.retrieveSeedPhrase,{payload:{walletId:e,signature:i,message:d,clientAuthPubKey:n.publicKey,recoveryPubKey:n.publicKey,encryptedShares:[y]}});o=await this.cipher.decrypt({cipherText:f.encryptedSeed,decryptionKey:h}),r.algorandSeedPhrase&&(c=this.getAlgorandSeedPhrase(o))}return{keyShares:r.keyShares&&i?i:void 0,standardSeedPhrase:r.standardSeedPhrase&&o?o:void 0,algorandSeedPhrase:r.algorandSeedPhrase&&c?c:void 0}}catch(e){throw ue.error("SDK::WalletService::export::error",e),e}}async import(e){var t;try{const s=null!==(t=e.reference)&&void 0!==t?t:r.v4(),a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new V({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=_a(a),i=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue}),o=await this.cipher.decrypt({cipherText:n,decryptionKey:i.privateKey});if(!o)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ms(o);return await this.handlers.handleImportWallet({publicKey:c,privateKey:o},Object.assign(Object.assign({},e),{reference:s}))}catch(e){throw ue.error("SDK::WalletService::import::error",e),e}}async changePassword({walletId:e,oldPassword:t,newPassword:r}){try{if(await this.recordRateAttempt(exports.V2KeyNames.PasswordResetAttempts)>Ed.RATE_LIMIT_MAX)throw new V({message:"Too many password change attempts. Please try again later.",statusCode:429,errorCode:exports.ErrorResponseCodes.sdk_too_many_requests});this.deviceAuthType===exports.AuthType.Password&&t&&await this.migrateToV2Safe({password:t,walletId:e});const s=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),a=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:e}),n=await this.localStorageService.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:e}),i=await this.localStorageService.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e});if(!s||"undefined"===s)throw new V({message:"Could not locate client keys on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=await this.authService.getUserSalt(),c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t,salt:o});if(!c.privateKey)throw new V({message:"Could not derive keys from old password. Please make sure the password is correct.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const d=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,salt:o});if(!d.publicKey||!d.privateKey)throw new V({message:"Could not derive keys for new password.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const l=await this.cipher.flipEncryptedData({cipherText:JSON.parse(s),decryptionKey:c.privateKey,encryptionKey:d.publicKey});if(!l)throw new V({message:"Failed to re-wrap device private key during password change.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});await this.assertRoundTrip(l,d.privateKey,"device key");const h=a?await this.cipher.flipEncryptedData({cipherText:_a(a),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,p=n?await this.cipher.flipEncryptedData({cipherText:_a(n),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,u=i?await this.cipher.flipEncryptedData({cipherText:_a(i),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null;return h&&await this.assertRoundTrip(h,d.privateKey,"seed phrase"),p&&await this.assertRoundTrip(p,d.privateKey,"primary share"),u&&await this.assertRoundTrip(u,d.privateKey,"backup share"),await this.localStorageService.commitBatch([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:l},...h?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,value:h,walletId:e}]:[],...p?[{key:exports.LocalStorageItems.PrimaryDeviceKeyShare,value:p,walletId:e}]:[],...u?[{key:exports.LocalStorageItems.BackupDeviceKeyShare,value:u,walletId:e}]:[]]),await this.localStorageService.delete(exports.V2KeyNames.PasswordResetAttempts),!0}catch(e){throw ue.error("SDK::Wallet::changePassword::error",e),e}}getAlgorandSeedPhrase(e){try{const r=h.mnemonicToSeedSync(e),s=function(e){if(32!==e.length)throw new Error(`Algorand seed must be 32 bytes, got ${e.length}`);const r=t.wordlists.english,s=Ad(e).map((e=>r[e])),a=Ad(br(e).subarray(0,2))[0];return[...s,r[a]].join(" ")}(r.slice(0,32));return s}catch(e){throw ue.error("SDK::Wallet::getAlgorandSeedPhrase::error",e),new V({message:e instanceof Error?e.message:"Failed to convert seed phrase to Algorand mnemonic.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}async initAddNewDevice(e){const{walletId:t,backupUrl:r,authenticationOptions:s}=e,a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=_a(a);this.deviceAuthType===exports.AuthType.Password&&e.authenticationOptions.password&&await this.migrateToV2Safe({password:e.authenticationOptions.password,walletId:e.walletId});const i=await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare,{walletId:t});if(!i)throw new V({message:"You do not have any additional key shares stored on this device, you cannot add a new device from here.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const o=_a(i),c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:s.password,salt:s.user.clientSalt,prfValue:s.prfValue});if(!await this.cipher.decrypt({cipherText:n,decryptionKey:c.privateKey}))throw new V({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});return{walletId:t,backupUrl:r,encryptedBackupShare:_a(await this.cipher.decrypt({cipherText:o,decryptionKey:c.privateKey}))}}async addNewDevice(e){var t;try{const r=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!r)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue}),a=await this.cipher.decrypt({cipherText:JSON.parse(r),decryptionKey:s.privateKey});if(!a)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const n=null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey))&&void 0!==t?t:ms(a),i=await this.authService.getSignature({deviceAuthKeys:{privateKey:a,publicKey:n},walletId:e.walletId,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),o=await this.request(dd.addNewDevice,{payload:{walletId:e.walletId,clientAuthPubKey:n,signature:i.signature,message:i.message,wallabyAuthPubKey:i.wallabyAuthPubKey,encryptedBackupShare:e.encryptedBackupShare}});return await this.handlers.handleKeySharesFromResponse({walletId:e.walletId,shares:[o.share],credentialsKeyPair:s,encryptedBackupShare:e.encryptedBackupShare,devicePrivateKey:a}),{success:!0,reference:o.reference}}catch(e){throw ue.error("SDK::Wallet::backupKeyShare::error",e),e}}async generateWalletAddresses(e){const{walletId:t}=e;if(!t)throw new V({message:"Wallet ID is missing in the request",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&e.authenticationOptions.password&&await this.migrateToV2Safe({password:e.authenticationOptions.password,walletId:e.walletId});try{const r=await this.prepareWalletOperationAuth({walletId:t,authenticationOptions:e.authenticationOptions});return await this.request(dd.generateWalletAddresses,{payload:{walletId:t,message:r.signatureMessage.message,clientAuthPubKey:r.deviceAuthPublicKey,signature:r.signatureMessage.signature,encryptedSeed:r.readyForTransportSeedPhrase,encryptedShares:r.sharesEncryptedWithWallabyPubKey,chainName:e.blockchainName}})}catch(e){throw ue.error("SDK::Wallet::generateWalletAddresses::error",e),e}}async migrateToV2Safe({password:e,walletId:t}){try{await this.handleUpdateToV2({password:e,walletId:t})}catch(e){if(e instanceof V&&e.errorCode===exports.ErrorResponseCodes.sdk_ambiguous_legacy_migration_data)throw e;throw ue.error("SDK::WalletService::migrateToV2Safe::error",e),new V({message:"Error accessing user wallet on this device. Please ensure the password is correct and try again.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}assertValidDeviceKey(e){try{this.cipher.validatePrivateKey(e)}catch(e){throw ue.error("SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material",e),new V({message:"Could not access your device key — your stored wallet credentials appear to be corrupted.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed})}}async handleUpdateToV2({password:e,walletId:t}){const r=Date.now();await this.assertUnderRateLimit(exports.V2KeyNames.MigrationAttempts,"Too many migration attempts. Please try again later.");try{if(!e)throw new V({message:"Password is required for migration to v2",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const s=this.version,n=await this.localStorageService.fetch(exports.V2KeyNames.MigrationVersion),i=await this.localStorageService.fetch(exports.V2KeyNames.LastMigratedAt);if(ue.info("SDK::WalletService::handleUpdateToV2::starting migration check",{timestamp:new Date(r).toISOString(),walletId:t.substring(0,8)+"...",lastMigratedAt:i,currentSdkVersion:s,sdkMigrationVersion:n}),i&&"never"!==i&&n)return void ue.info("SDK::WalletService::handleUpdateToV2::Migration already completed successfully, skipping",{migratedVersion:n,migratedAt:i});const o=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),c=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:t}),d=await this.localStorageService.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:t}),l=await this.authService.getUserSalt(),h=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:l});if(o&&(c||d))try{await this.cipher.decrypt({cipherText:_a(o),decryptionKey:h.privateKey});const t=c||d;return await this.cipher.displayStoredData({storedEncryptedData:_a(t),encryptedDevicePrivateKey:_a(o),options:{authType:exports.AuthType.Password,password:e,salt:l}}),ue.info("SDK::WalletService::handleUpdateToV2::V2 items already exist and are valid, no migration needed"),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,(new Date).toISOString()),void await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,s)}catch(e){ue.info("SDK::WalletService::handleUpdateToV2::V2 items exist but decryption failed, proceeding with migration",{error:JSON.stringify(e)})}let p,u;await this.recordRateAttempt(exports.V2KeyNames.MigrationAttempts);const y=await this.localStorageService.isLegacySeedFallbackSafeFor(t),f=y?await this.localStorageService.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`):void 0,g=await this.localStorageService.getDecryptedV1PrivateKey(e);if(f&&g){this.assertValidDeviceKey(g),ue.info("SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration",{storageFormat:"legacy"});try{const r=_a(a.AES.decrypt(f,`${l}${e}`).toString(a.enc.Utf8));if(p=wa(g,r),u=g,!p)throw new V({message:"Failed to decrypt legacy seed phrase items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});ue.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted legacy items"),await this.localStorageService.claimLegacySeedFallbackFor(t)}catch(e){throw ue.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt legacy items",e),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}else{const r=await this.localStorageService.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard,t),s=await this.localStorageService.getEncryptedPrivateKey();if(!r||!s){if(!y){const e=await this.localStorageService.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`),t=await this.localStorageService.getV1EncryptedSeedPhrase();if(e||t)throw ue.error("SDK::WalletService::handleUpdateToV2::Legacy seed data on this device is already claimed by a different wallet; refusing to migrate ambiguously"),new V({message:"Legacy wallet data on this device is associated with a different wallet and cannot be safely migrated for this wallet.",statusCode:409,errorCode:exports.ErrorResponseCodes.sdk_ambiguous_legacy_migration_data})}return ue.info("SDK::WalletService::handleUpdateToV2::No legacy or V1 items found to migrate"),void ue.info("SDK::WalletService::handleUpdateToV2:: You do not have a wallet stored on this device. Nothing to migrate.")}u=await this.localStorageService.getDecryptedV1PrivateKey(e),u&&this.assertValidDeviceKey(u),ue.info("SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration",{storageFormat:"v1",validPrivateKey:!!u});try{if(ue.log("Attempting to decrypt V1 items during migration..."),ue.log("getV1DecryptedSeedPhrase should be called with password and clientSalt:",{hasPassword:!!e,hasClientSalt:!!l}),p=await this.localStorageService.getV1DecryptedSeedPhrase(e,l),u=await this.localStorageService.getDecryptedV1PrivateKey(e),!p||!u)throw new V({message:"Failed to decrypt V1 items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});ue.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted V1 items"),await this.localStorageService.claimLegacySeedFallbackFor(t)}catch(e){throw ue.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt V1 items",e),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}if(p&&u){ue.info("SDK::WalletService::handleUpdateToV2::Initiating wallet recovery for V2 migration"),ue.info("SDK::WalletService::handleUpdateToV2::Migration data prepared"),ue.info("SDK::WalletService::handleUpdateToV2::Seed phrase available:",!!p);const e=ms(u),s=await this.authService.getSignature({deviceAuthKeys:{publicKey:e,privateKey:u},walletId:t}),a=await this.request(Ua.signIn,{payload:{externalUserId:this.userId,message:s.message,signature:s.signature,clientAuthPubKey:e}}),n=await this.cipher.encrypt({data:u,encryptionKey:h.publicKey}),i=await this.cipher.doubleEncrypt({decryptedData:p,credentialsKeyPair:h,deviceKeyPair:{publicKey:e,privateKey:u}});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.AccessToken,value:a.accessToken},{key:exports.V2KeyNames.EncryptedStandardSeedPhrase,value:i,walletId:t},{key:exports.V2KeyNames.EncryptedDevicePrivateKey,value:n}]),ue.info("SDK::WalletService::handleUpdateToV2::Migration completed successfully",{timestamp:(new Date).toISOString(),duration:Date.now()-r,devicePublicKey:e.substring(0,16)+"...",migratedKeys:["EncryptedDevicePrivateKey","EncryptedStandardSeedPhrase"]}),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,(new Date).toISOString()),void await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,this.version)}throw new V({message:"Decrypted data required for migration is missing, operation cannot be completed.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}catch(e){throw ue.error("SDK::WalletService::handleUpdateToV2::Migration failed",{timestamp:(new Date).toISOString(),duration:Date.now()-r,error:e instanceof Error?e.message:"Unknown error"}),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,"never"),await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,this.version),e}}async verifyAccess(e){try{const{readyForTransportSeedPhrase:t,sharesEncryptedWithWallabyPubKey:r,hasShares:s,signatureMessage:a,deviceAuthPublicKey:n}=await this.prepareWalletOperationAuth({authenticationOptions:e.authenticationOptions,walletId:e.walletId}),i=t&&!s;return await this.api.wallets.verifyAccess({message:a.message,signature:a.signature,clientAuthPubKey:n,encryptedSeed:i?t:void 0,encryptedShares:i?void 0:r,walletId:e.walletId})}catch(e){throw ue.error("SDK::WalletService::verifyAccess::Error occurred",e),e}}async clearDevice({walletId:e}){await this.localStorageService.clearLocalStorage(e)}async prepareWalletOperationAuth({authenticationOptions:e,walletId:t}){const{password:r,prfValue:s,user:a}=e,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!n)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}),o=await this.cipher.decrypt({cipherText:JSON.parse(n),decryptionKey:i.privateKey});if(!o)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ms(o),d=await this.authService.getSignature({deviceAuthKeys:{publicKey:c,privateKey:o},walletId:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),l=d.wallabyAuthPubKey;if(!l)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const h=[];let p;const u=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(u){const e=_a(u),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(n),wallabyPublicKey:l,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}});h.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to complete this request.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const i=_a(e);p=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:i,encryptedDevicePrivateKey:JSON.parse(n),wallabyPublicKey:l,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}})}return{deviceAuthPublicKey:c,signatureMessage:d,readyForTransportSeedPhrase:p,sharesEncryptedWithWallabyPubKey:h.length?h:void 0,hasShares:h.length>0}}async convertToPasskey(e){let t=!1;try{const s=await this.localStorageService.fetch(exports.V2KeyNames.CredentialConversionInProgress),a=s?_a(s):void 0;(null==a?void 0:a.encryptedDevicePrivateKey)&&await this.localStorageService.save(exports.LocalStorageItems.EncryptedDevicePrivateKey,a.encryptedDevicePrivateKey),(null==a?void 0:a.walletId)===e.walletId&&ue.info("SDK::WalletService::convertToPasskey::resuming interrupted conversion");const n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:e.walletId}),o=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:e.walletId}),c=await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare,{walletId:e.walletId}),d=await this.authService.getUserSalt(),l=await this.cipher.getCredentialsKeyPair({password:e.password,salt:d,authType:exports.AuthType.Password});let h;if(!await this.authService.validatePassword({password:e.password,salt:d}))throw ue.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password"),new V({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(n){ue.log("SDK::WalletService::convertToPasskey::Decrypting v2 device private key with password-derived key");const e=_a(n);h=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}else ue.log("SDK::WalletService::convertToPasskey::No encrypted device private key found, checking for v1 format"),h=await this.localStorageService.getDecryptedV1PrivateKey(e.password);if(!h)throw ue.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new V({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const p=ms(h);await this.localStorageService.save(exports.V2KeyNames.CredentialConversionInProgress,Object.assign({walletId:e.walletId},n?{encryptedDevicePrivateKey:n}:{}));const u=await this.passkeyService.addNewPasskey({deviceKeyPair:{publicKey:p,privateKey:h},getSignature:this.authService.getSignature.bind(this)});t=!0;const y=u.prfValue;if(!(y&&y instanceof Uint8Array&&0!==y.length))throw ue.error("SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array"),new V({message:"PRF value from passkey is required to derive credentials and could not be obtained",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});let f,g,w;if(ue.log("SDK::WalletService::convertToPasskey::Received authentication response",!!u),i&&n)try{f=await this.cipher.displayStoredData({storedEncryptedData:_a(i),encryptedDevicePrivateKey:_a(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){ue.error("SDK::WalletService::convertToPasskey::seed_decryption_error",e)}if(!f)try{f=await this.localStorageService.getV1DecryptedSeedPhrase(e.password,d)}catch(e){ue.error("SDK::WalletService::convertToPasskey::v1_seed_decryption_error",e)}if(o&&n)try{const t=_a(o);g=await this.cipher.displayStoredData({storedEncryptedData:t,encryptedDevicePrivateKey:_a(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){ue.error("SDK::WalletService::convertToPasskey::primary_share_decryption_error",e)}if(c)try{const e=_a(c);w=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}catch(e){ue.error("SDK::WalletService::convertToPasskey::backup_share_decryption_error",e)}if(!f&&!(!!g||!!w))throw new V({message:"Seed phrase or key shares on this device could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});if(f&&!g)return ue.info("SDK::WalletService::convertToPasskey::No primary share found, importing wallet"),await this.handlers.handleImportWallet({publicKey:p,privateKey:h},{authenticationOptions:u,seedPhrase:f,storeSeedPhrase:!1,returnWalletOption:exports.ReturnWalletOption.ReturnOnlyEncryptedShares,walletId:e.walletId,reference:r.v4(),keyShareOptions:{threshold:2,numberOfKeyShares:3,numberOfSharesReturned:2,storeOneKeyShareWithWallaby:!0}}),await this.localStorageService.commitBatch([],[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId},{key:exports.V2KeyNames.CredentialConversionInProgress}]),ue.info("SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed"),{authentication:u,seedPhrase:f};const m=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Passkey,prfValue:y}),v=[];if(g){const t=await this.cipher.doubleEncrypt({decryptedData:g,credentialsKeyPair:m,deviceKeyPair:{publicKey:p,privateKey:h}}),r=await this.cipher.decrypt({cipherText:t,decryptionKey:m.privateKey});if((r?await this.cipher.decrypt({cipherText:_a(r),decryptionKey:h}):null)!==g)throw new V({message:"Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});v.push({key:exports.V2KeyNames.PrimaryDeviceKeyShare,value:t,walletId:e.walletId})}if(w){const t=await this.cipher.encrypt({data:w,encryptionKey:m.publicKey});v.push({key:exports.V2KeyNames.BackupDeviceKeyShare,value:t,walletId:e.walletId})}for(const e of v)await this.assertRoundTrip(e.value,m.privateKey,e.key);if(await this.localStorageService.commitBatch(v,[...i?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId}]:[],{key:exports.V2KeyNames.CredentialConversionInProgress}]),i&&ue.info("SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey"),!f&&g){const t={publicKey:p,privateKey:h},{signature:r,message:s,wallabyAuthPubKey:a}=await this.authService.getSignature({deviceAuthKeys:t,walletId:e.walletId,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if(!a)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const n=await this.cipher.encrypt({data:g,encryptionKey:a}),i=await this.request(dd.retrieveSeedPhrase,{payload:{walletId:e.walletId,signature:r,message:s,clientAuthPubKey:t.publicKey,recoveryPubKey:t.publicKey,encryptedShares:[n]}});f=await this.cipher.decrypt({cipherText:i.encryptedSeed,decryptionKey:h})}if(!f)throw new V({message:"Seed phrase could not be reconstructed from the provided shares",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});return{authentication:u,seedPhrase:f}}catch(e){throw ue.error("SDK::WalletService::convertToPasskey::error",e),t||await this.localStorageService.delete(exports.V2KeyNames.CredentialConversionInProgress),e}}async assertRoundTrip(e,t,r){try{await this.cipher.decrypt({cipherText:e,decryptionKey:t})}catch(e){throw new V({message:`Re-wrap validation failed for ${r}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}}Ed.RATE_LIMIT_MAX=5,Ed.RATE_LIMIT_WINDOW_MS=18e5,e._([vd("create"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Ed.prototype,"create",null),e._([vd("import"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Ed.prototype,"import",null),e._([vd("credential-rewrap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Ed.prototype,"changePassword",null),e._([vd("migrateToV2"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Ed.prototype,"handleUpdateToV2",null),e._([vd("credential-rewrap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Ed.prototype,"convertToPasskey",null);class bd extends cd{constructor(e,t={}){super(e,t),this.userId=e.userId,this.walletService=new Ed(e,t)}validateWalletAddressInfo(e,t){return e.some((e=>e.chainName===t))}async getTokenBalance({address:e,assetSymbol:t,tokenStandard:r,chainName:s}){try{if(!e||!t||!s&&!r)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(dd.getTokenBalance,{payload:{address:e,assetSymbol:t,chainName:s,tokenStandard:r}})}catch(e){throw ue.error("SDK::WalletDataService::getTokenBalance::error",e),e}}async getMultiTokenBalances({walletId:e,tokensAndAddressesList:t}){try{if(!t.length)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(dd.getMultiTokenBalances,{payload:{assets:t,walletId:e}})}catch(e){throw ue.error("SDK::WalletDataService::getMultiTokenBalances::error",e),e}}async getWalletBalances({walletId:e}){try{if(!e)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(dd.getWalletBalances,{payload:{walletId:e}})}catch(e){throw ue.error("SDK::WalletDataService::getWalletBalances::error",e),e}}async getUserAssets({userId:e,queryOptions:t}){try{if(!e)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(dd.getUserAssets,{payload:{userId:e},queryParams:t})}catch(e){throw ue.error("SDK::WalletDataService::getUserAssets::error",e),e}}async getUserWallets({userId:e,queryOptions:t}){try{return await this.request(dd.getUserWallets,{payload:{userId:e},queryParams:t})}catch(e){throw ue.error("SDK::WalletDataService::getUserWallets::error",e),e}}async getWalletAssets({walletId:e,queryOptions:t}){try{if(void 0!==(null==t?void 0:t.search)&&t.search.length<3)throw new V({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(dd.getWalletAssets,{payload:{walletId:e},queryParams:t})}catch(e){throw ue.error("SDK::WalletDataService::getWalletAssets::error",e),e}}async addTokenToWallet({assetConfigId:e,walletId:t,userId:r,config:s,authenticationOptions:a}){try{if(!t)throw new V({message:"Wallet ID is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!e&&!s)throw new V({message:"Either assetConfigId or config must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});let n={};if(a){const e=await this.walletService.prepareWalletOperationAuth({walletId:t,authenticationOptions:a});n={message:e.signatureMessage.message,clientAuthPubKey:e.deviceAuthPublicKey,signature:e.signatureMessage.signature,encryptedSeed:e.readyForTransportSeedPhrase,encryptedShares:e.sharesEncryptedWithWallabyPubKey}}return await this.request(dd.addTokenToWallet,{payload:Object.assign({assetConfigId:e,walletId:t,userId:r||void 0,config:s},n)})}catch(e){throw ue.error("SDK::WalletDataService::addTokenToWallet::error",e),e}}async addNewChainAndTokenToWallet(e){const{authenticationOptions:t,walletId:r,userId:s,assetConfigId:a,blockchainName:n}=e;if(!(t&&r&&s&&a&&n))throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&t.password&&await this.walletService.migrateToV2Safe({password:t.password,walletId:r});try{const t=await this.walletService.generateWalletAddresses({walletId:e.walletId,authenticationOptions:e.authenticationOptions});if(this.validateWalletAddressInfo(t.walletAddressesInfo,n)){const t=(await this.getWalletAssets({walletId:r})).assets.find((e=>e.configId===a));if(t)return{asset:t};return await this.addTokenToWallet({assetConfigId:a,walletId:r,userId:s,authenticationOptions:e.authenticationOptions})}throw new V({message:`Wallet address is not present for blockchain: ${n}`,statusCode:400,errorCode:"sdk_wallet_address_not_found"})}catch(e){throw ue.error("SDK::WalletDataService::addNewChainAndTokenToWallet::error",e),e}}async updateAsset(t){var{configId:r,walletId:s}=t,a=e.b(t,["configId","walletId"]);try{if(!r||!s)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(dd.updateAsset,{payload:Object.assign({configId:r,walletId:s},a)})}catch(e){throw ue.error("SDK::WalletDataService::updateAsset::error",e),e}}}class Id extends cd{constructor(e,t={}){super(e,t),this.getDecryptedPrivateKey=async e=>{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return""!==r?r:void 0},this.decryptDevicePrivateKey=({encryptedPrivateKey:e,password:t})=>{const r=a.AES.decrypt(e,t).toString(a.enc.Utf8);return""!==r?r:void 0},this.auth=new Sd(e,t)}async decryptSeedPhrase({password:e}){var t;const r=await this.auth.getUserSalt();if(!r)throw new Error("Salt could not be found");const s=`${r}${e}`,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase);if(!n)throw new Error("Seed phrase could not be found");const i=_a(a.AES.decrypt(n,s).toString(a.enc.Utf8)),o=this.decryptDevicePrivateKey({encryptedPrivateKey:null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey))&&void 0!==t?t:"",password:e});if(!o)throw ue.error("SDK::Utils::decryptSeedPhrase::devicePrivateKey: Device private key could not be decrypted"),new Error("Device private key could not be decrypted");return await wa(o,i)}async fetchFromEndpoint({endpoint:e,method:t,requiresAccessToken:r,payload:s}){try{const a=new RegExp("https?://[^/]*.?wallaby.cash/api/v1","i"),n={fullPath:e.replace(a,""),method:t,requiresAccessToken:null!=r&&r};return await this.request(n,{payload:s})}catch(e){return ue.error("SDK::Utils::fetchFromEndpoint::error",e),Promise.reject(e)}}async validatePassword({password:e}){const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return{valid:!1,message:"Could not locate client keys or seed phrase on this device."};try{const r=await this.auth.getUserSalt(),s=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:r});return await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:s.privateKey})?{valid:!0}:{valid:!1,message:"Password is incorrect"}}catch(e){return ue.error("SDK::Utils::validatePassword::error",e),{valid:!1,message:"Password is incorrect."}}}}class Pd extends cd{constructor(e,t={}){super(e,t)}}class Td extends cd{constructor(e,t={}){super(e,t),this.authService=new Sd(e,t),this.walletService=new Ed(e,t)}async getQuote(e){try{const{walletId:t,fromAssetConfigId:r,toAssetConfigId:s,fromAmount:a,toAmount:n,slippage:i}=e;if(!t||!r||!s)throw new V({message:"Missing required parameters: walletId, fromAssetConfigId, and toAssetConfigId",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!a&&!n)throw new V({message:"Either fromAmount or toAmount must be provided",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(a&&n)throw new V({message:"Only one of fromAmount or toAmount may be provided, not both",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const o={walletId:t},c=Object.assign(Object.assign(Object.assign({fromAssetConfigId:r,toAssetConfigId:s},a&&{fromAmount:a}),n&&{toAmount:n}),null!=i&&{slippage:i});return await this.request(Object.assign(Object.assign({},pd.getQuote),{fullPath:pd.getQuote.fullPath(o)}),{payload:c})}catch(e){throw ue.error("SDK::Swap::getQuote::error",e),e}}async executeSwap({walletId:e,quoteId:t,authenticationOptions:r}){try{this.deviceAuthType===exports.AuthType.Password&&r.password&&await this.walletService.migrateToV2Safe({password:r.password,walletId:e});const{deviceAuthPublicKey:s,signatureMessage:a,readyForTransportSeedPhrase:n,sharesEncryptedWithWallabyPubKey:i,hasShares:o}=await this.prepareSwapAuth(r,e);let c;if(n)c=await this.request(Object.assign(Object.assign({},pd.executeSwap),{fullPath:pd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedSeed:n}});else{if(!o)throw new V({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});c=await this.request(Object.assign(Object.assign({},pd.executeSwap),{fullPath:pd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedShares:i}})}return c}catch(e){throw ue.error("SDK::Swap::executeSwap::error",e),e}}async getSwaps({walletId:e,queryParams:t}){try{if(!e)throw new V({message:"Missing required parameter: walletId",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const r={walletId:e};return await this.request(Object.assign(Object.assign({},pd.getSwaps),{fullPath:pd.getSwaps.fullPath(r)}),{queryParams:t})}catch(e){throw ue.error("SDK::Swap::getSwaps::error",e),e}}async prepareSwapAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!i)throw new V({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:o}),d=await this.cipher.decrypt({cipherText:JSON.parse(i),decryptionKey:c.privateKey});if(!d)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ms(d),h=await this.authService.getSignature({deviceAuthKeys:{publicKey:l,privateKey:d},passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0,walletId:t}),p=h.wallabyAuthPubKey;if(!p)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const u=[];let y;const f=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(f){const e=_a(f),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}});u.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to sign the transaction.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const a=_a(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:u,hasShares:u.length>0})}}e._([vd("executeSwap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Td.prototype,"executeSwap",null);class kd extends cd{constructor(e,t={}){super(e,t)}async getSupportedBlockchains(e){try{return(await this.request(ld.getSupportedBlockchains,{queryParams:void 0!==(null==e?void 0:e.supportSwaps)?{supportSwaps:e.supportSwaps}:void 0})).chains}catch(e){throw ue.error("SDK::System::getSupportedBlockchains::error",e),e}}validateContractAddress({blockchain:e,contractAddress:t,suiObjectId:r}){switch(e){case exports.BlockchainName.Algorand:case exports.BlockchainName.Bitcoin:throw new V({message:`${e} does not support contract addresses.`,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});case exports.BlockchainName.Sui:if(r&&t)throw new V({message:"You can only provide either suiObjectId or contractAddress",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(t)throw new V({message:"You can only provide suiObjectId for SUI blockchain",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(!r)throw new V({message:"You must provide suiObjectId for SUI blockchain",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return(e=>{if(!e)throw new Error("Sui object ID is required");if(!e.startsWith("0x"))throw new Error("Invalid Sui object ID");return e.includes("::")?e.split("::")[0]:e})(r);default:if(!t)throw new V({message:"You must provide contractAddress for non-SUI blockchains",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return t}}async fetchTokenInfo({blockchain:e,contractAddress:t,suiObjectId:r,assetSymbol:s}){try{const a=this.validateContractAddress({blockchain:e,contractAddress:t,suiObjectId:r}),n=null!=s?s:e===exports.BlockchainName.Sui?(e=>{var t;if(!e||!e.includes("::"))return;const r=e.split("::");return(null===(t=r[r.length-1])||void 0===t?void 0:t.trim())||void 0})(r):void 0;return await this.request(ld.fetchTokenInfo,{queryParams:Object.assign({chainName:e,tokenContractAddress:a},n?{assetSymbol:n}:{})})}catch(e){throw ue.error("SDK::Wallet::fetchTokenInfo::error",e),e}}async getSupportedTokens(e){try{if(void 0!==(null==e?void 0:e.search)&&e.search.length<3)throw new V({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(ld.getSupportedTokens,{queryParams:e})}catch(e){throw ue.error("SDK::System::getSupportedTokens::error",e),e}}async getUserData(e){try{return(await this.request(ld.getUserData,{payload:{userId:e}})).user}catch(e){throw ue.error("SDK::System::getUserData::error",e),e}}async getUserByExternalUserId(e){try{return(await this.request(ld.getUserByExternalUserId,{payload:{externalUserId:e}})).user}catch(e){throw ue.error("SDK::System::getUserByExternalUserId::error",e),e}}}class Cd extends cd{constructor(e,t={}){super(e,t),this.authService=new Sd(e,t),this.walletService=new Ed(e,t),this.userId=e.userId}async estimateFee({originAddress:e,recipientAddress:t,amount:r,transactionType:s,token:a}){try{return await this.request(hd.estimateFee,{queryParams:Object.assign({chainName:a.chainName,originAddress:e,recipientAddress:t,amount:r,assetSymbol:a.symbol,transactionType:s},a.tokenStandard&&{tokenStandard:a.tokenStandard})})}catch(e){throw ue.error("SDK::Transactions::estimateFee::error",e),e}}async getTransactionStatus({transactionHash:e,reference:t,blockchain:r}){try{return await this.request(hd.getTransaction,{payload:{transactionHash:e,transactionReference:t,chain:r.toString().toUpperCase()}})}catch(e){throw ue.error("SDK::Transactions::getTransactionStatus::error",e),e}}async getTransactions(e){try{return await this.request(hd.getTransactions,{queryParams:e})}catch(e){throw ue.error("SDK::Transactions::getTransactions::error",e),e}}async getRestriction(e){try{const t=Boolean(e.assetId),r=Boolean(e.contractAddress&&e.blockchainName);if(!t&&!r)throw new V({message:"Either assetId or both contractAddress and blockchainName must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(hd.restriction,{queryParams:Object.assign(Object.assign(Object.assign({fromAddress:e.fromAddress,toAddress:e.toAddress,amount:e.amount},e.assetId&&{assetId:e.assetId}),e.contractAddress&&{contractAddress:e.contractAddress}),e.blockchainName&&{blockchainName:e.blockchainName})})}catch(e){throw ue.error("SDK::Transactions::getRestriction::error",e),e}}async transfer({originAddress:e,recipientAddress:t,amount:s,assetId:a,walletId:n,reference:i,authenticationOptions:o,memo:c,transactionType:d}){try{this.deviceAuthType===exports.AuthType.Password&&o.password&&await this.walletService.migrateToV2Safe({password:o.password,walletId:n});const{deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:p,sharesEncryptedWithWallabyPubKey:u,hasShares:y}=await this.prepareTransactionAuth(o,n);let f;if(p)f=await this.request(hd.transfer,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedSeed:p,originAddress:e,recipientAddress:t,assetId:a,amount:s,reference:i||r.v4(),memo:c,transactionType:d}});else{if(!y)throw new V({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});f=await this.request(hd.transferWithShares,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedShares:u,originAddress:e,recipientAddress:t,assetId:a,amount:s,reference:i||r.v4(),memo:c,transactionType:d}})}return f}catch(e){throw ue.error("SDK::Transactions::transfer::error",e),e}}async createAllowance({authenticationOptions:e,walletId:t,ownerAddress:r,spenderAddress:s,amount:a,assetId:n,suiObjectId:i,contractAddress:o,chainName:c,assetSymbol:d,reference:l,memo:h,transactionType:p}){try{if(!(i||o||n||d||c))throw new V({message:"AssetId, asset symbol, chain name or contract address must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(d&&!c||!d&&c)throw new V({message:"Asset symbol and chain name must be provided when asset is not in user wallet.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&e.password&&await this.walletService.migrateToV2Safe({password:e.password,walletId:t});const{deviceAuthPublicKey:u,signatureMessage:y,readyForTransportSeedPhrase:f,sharesEncryptedWithWallabyPubKey:g,hasShares:w}=await this.prepareTransactionAuth(e,t),{message:m,signature:v}=y;if(!f&&!w)throw new Error("No valid seed option found on this device.");const S=Object.assign({message:m,signature:v,walletId:t,clientAuthPubKey:u,ownerAddress:r,spenderAddress:s,chainName:c,assetSymbol:d,amount:a,assetId:n,contractAddress:null!=o?o:i,reference:l,memo:h,transactionType:p},w?{encryptedShares:g}:{encryptedSeed:f});return await this.request(hd.createAllowance,{payload:S})}catch(e){throw ue.error("SDK::Transactions::createAllowance::error",e),e}}async getPendingTransactions({walletId:e,chainName:t}){try{return await this.request(hd.getPendingTransactions,{queryParams:{walletId:e,chainName:t}})}catch(e){throw ue.error("SDK::Transactions::getPendingTransactions::error",e),e}}async resolvePendingTransaction({id:e,choice:t,symbol:r,chainName:s,walletId:a,authenticationOptions:n}){try{this.deviceAuthType===exports.AuthType.Password&&n.password&&await this.walletService.migrateToV2Safe({password:n.password,walletId:a});const{deviceAuthPublicKey:i,signatureMessage:o,readyForTransportSeedPhrase:c,sharesEncryptedWithWallabyPubKey:d,hasShares:l}=await this.prepareTransactionAuth(n,a);if(!c&&!l)throw new Error("No valid seed option found on this device.");return await this.request(hd.confirmPendingTransaction,{payload:{message:o.message,signature:o.signature,clientAuthPubKey:i,encryptedShares:d,encryptedSeed:c,id:e,choice:t,symbol:r,chainName:s,walletId:a}})}catch(e){throw ue.error("SDK::Transactions::transfer::error",e),e}}async prepareTransactionAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!i)throw new V({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:o}),d=await this.cipher.decrypt({cipherText:JSON.parse(i),decryptionKey:c.privateKey});if(!d)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ms(d),h=await this.authService.getSignature({deviceAuthKeys:{publicKey:l,privateKey:d},walletId:t,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),p=h.wallabyAuthPubKey;if(!p)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const u=[];let y;const f=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(f){const e=_a(f),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}});u.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to sign the transaction.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const a=_a(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:u,hasShares:u.length>0})}}e._([vd("transaction-restriction-message"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"getRestriction",null),e._([vd("transfer"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"transfer",null),e._([vd("createAllowance"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"createAllowance",null),e._([vd("confirmPendingTransaction"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"resolvePendingTransaction",null);const xd={mainnet:{genesisHash:"0x6fbd74e5e1d0a61d52ccfe9d4adaed16dd3a7caa37c6bc4d0c2fa12e8b2f4063",specVersion:7003003,transactionVersion:7,ss58Format:12,balanceDecimals:6},testnet:{genesisHash:"0x2ace05e703aa50b48c0ccccfc8b424f7aab9a1e2c424ed12e45d20b1e8ffd0d6",specVersion:7003003,transactionVersion:7,ss58Format:42,balanceDecimals:6}};function Kd(e){return"mainnet"===e||"testnet"===e}class Od extends Error{constructor(e,t,r){super(r),this.name=e,this.reason=t}}class Nd extends Od{constructor(e,t){super("PolymeshDecodeError",e,t),this.reason=e}}class Rd extends Od{constructor(e,t){super("PolymeshVerifyError",e,t),this.reason=e}}const Dd=/^[0-9a-fA-F]*$/;function Ld(e){return"0x"+Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Ud(...e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}const Bd=c.Bytes(32),qd=c.Bytes(32),Vd=c.Bytes(16),Md=c.Bytes(32),Wd=c.u64,Fd=c.Enum({Id:Bd},[0]),Gd=c.Enum({Default:c._void,User:c.u64},[0,1]),jd=c.Struct({did:qd,kind:Gd}),Hd=c.Enum({SettleOnAffirmation:c._void},[0]),$d=c.Enum({Fungible:c.Struct({sender:jd,receiver:jd,assetId:Vd,amount:c.u128})},[0]),Yd=c.Struct({fungible:c.u32,nonFungible:c.u32,offChain:c.u32}),zd=c.Struct({senderAssetCount:Yd,receiverAssetCount:Yd,offchainCount:c.u32});function Jd(e){return e.replace(/^0x/i,"").toLowerCase()}const Xd={"5:1":{variant:"balances.transferWithMemo",codec:c.Struct({dest:Fd,value:c.compact,memo:c.Option(Md)})},"37:20":{variant:"settlement.addAndAffirmWithMediators",codec:c.Struct({venueId:c.Option(c.u64),settlementType:Hd,tradeDate:c.Option(c.u64),valueDate:c.Option(c.u64),legs:c.Vector($d),portfolios:c.Vector(jd),instructionMemo:c.Option(Md),mediators:c.Vector(qd)})},"37:16":{variant:"settlement.affirmInstruction",codec:c.Struct({id:Wd,portfolios:c.Vector(jd),numberOfAssets:c.Option(zd)})},"37:11":{variant:"settlement.affirmInstruction",codec:c.Struct({id:Wd,portfolios:c.Vector(jd)})},"37:17":{variant:"settlement.rejectInstruction",codec:c.Struct({id:Wd,portfolio:jd,numberOfAssets:c.Option(Yd)})},"37:13":{variant:"settlement.rejectInstruction",codec:c.Struct({id:Wd,portfolio:jd})}};function Zd(e,t,r){if(!t.genesisHash)throw new Nd("context-not-pinned","Polymesh chain context has no pinned genesisHash — see context.ts before using this in production");if(!r.genesisHash)throw new Nd("genesis-hash-mismatch","No genesisHash was observed on the transaction under verification — cannot confirm which chain this call targets");if(Jd(r.genesisHash)!==Jd(t.genesisHash))throw new Nd("genesis-hash-mismatch",`Observed genesisHash ${r.genesisHash} does not match the pinned genesisHash ${t.genesisHash} for this network`);if(r.specVersion!==t.specVersion)throw new Nd("spec-version-mismatch",`Observed specVersion ${r.specVersion} does not match the pinned specVersion ${t.specVersion} this decoder was validated against`);if(void 0!==r.transactionVersion&&r.transactionVersion!==t.transactionVersion)throw new Nd("transaction-version-mismatch",`Observed transactionVersion ${r.transactionVersion} does not match the pinned transactionVersion ${t.transactionVersion} this decoder was validated against`);let s;try{s=function(e){const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0)throw new Error("hexToU8a: hex string must have an even number of digits");if(!Dd.test(t))throw new Error("hexToU8a: invalid hex string");const r=new Uint8Array(t.length/2);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}(e)}catch(e){throw new Nd("malformed",`Call bytes are not valid hex: ${e.message}`)}if(s.length<2)throw new Nd("malformed","Call bytes are too short to contain a pallet/call index");const[a,n]=s,i=Xd[`${a}:${n}`];if(!i)throw new Nd("unrecognized-call",`Unrecognized or unsupported Polymesh call (pallet=${a}, call=${n})`);const o=s.slice(2);let c,d;try{c=i.codec.dec(o)}catch(e){throw new Nd("malformed",`Failed to decode ${i.variant} args: ${e.message}`)}try{d=i.codec.enc(c)}catch(e){throw new Nd("malformed",`Failed to re-encode decoded ${i.variant} args: ${e.message}`)}if(!function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(d,o))throw new Nd("trailing-bytes",`Decoded ${i.variant} args do not round-trip to the original bytes — unrecognized trailing data`);return{variant:i.variant,args:c}}const Qd=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),el=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),tl=new Uint32Array(32);function rl(e,t,r,s,a,n){const i=a[n],o=a[n+1];let c=tl[2*e],d=tl[2*e+1],l=tl[2*t],h=tl[2*t+1],p=tl[2*r],u=tl[2*r+1],y=tl[2*s],f=tl[2*s+1],g=nr(c,l,i);var w,m;d=ir(g,d,h,o),c=0|g,({Dh:f,Dl:y}={Dh:f^d,Dl:y^c}),({Dh:f,Dl:y}={Dh:(m=y,m),Dl:(w=f,w)}),({h:u,l:p}=ar(u,p,f,y)),({Bh:h,Bl:l}={Bh:h^u,Bl:l^p}),({Bh:h,Bl:l}={Bh:er(h,l,24),Bl:tr(h,l,24)}),tl[2*e]=c,tl[2*e+1]=d,tl[2*t]=l,tl[2*t+1]=h,tl[2*r]=p,tl[2*r+1]=u,tl[2*s]=y,tl[2*s+1]=f}function sl(e,t,r,s,a,n){const i=a[n],o=a[n+1];let c=tl[2*e],d=tl[2*e+1],l=tl[2*t],h=tl[2*t+1],p=tl[2*r],u=tl[2*r+1],y=tl[2*s],f=tl[2*s+1],g=nr(c,l,i);d=ir(g,d,h,o),c=0|g,({Dh:f,Dl:y}={Dh:f^d,Dl:y^c}),({Dh:f,Dl:y}={Dh:er(f,y,16),Dl:tr(f,y,16)}),({h:u,l:p}=ar(u,p,f,y)),({Bh:h,Bl:l}={Bh:h^u,Bl:l^p}),({Bh:h,Bl:l}={Bh:rr(h,l,63),Bl:sr(h,l,63)}),tl[2*e]=c,tl[2*e+1]=d,tl[2*t]=l,tl[2*t+1]=h,tl[2*r]=p,tl[2*r+1]=u,tl[2*s]=y,tl[2*s+1]=f}class al extends Ze{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Pe(e),Pe(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=Ke(this.buffer)}update(e){Ce(this),Te(e=Je(e));const{blockLen:t,buffer:r,buffer32:s}=this,a=e.length,n=e.byteOffset,i=e.buffer;for(let o=0;o<a;){this.pos===t&&(Be(s),this.compress(s,0,!1),Be(s),this.pos=0);const c=Math.min(t-this.pos,a-o),d=n+o;if(c!==t||d%4||!(o+c<a))r.set(e.subarray(o,o+c),this.pos),this.pos+=c,this.length+=c,o+=c;else{const e=new Uint32Array(i,d,Math.floor((a-o)/4));Be(e);for(let r=0;o+t<a;r+=s.length,o+=t)this.length+=t,this.compress(e,r,!1);Be(e)}}return this}digestInto(e){Ce(this),xe(e,this);const{pos:t,buffer32:r}=this;this.finished=!0,Oe(this.buffer.subarray(t)),Be(r),this.compress(r,0,!0),Be(r);const s=Ke(e);this.get().forEach(((e,t)=>s[t]=Ue(e)))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){const{buffer:t,length:r,finished:s,destroyed:a,outputLen:n,pos:i}=this;return e||(e=new this.constructor({dkLen:n})),e.set(...this.get()),e.buffer.set(t),e.destroyed=a,e.finished=s,e.length=r,e.pos=i,e.outputLen=n,e}clone(){return this._cloneInto()}}class nl extends al{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|el[0],this.v0h=0|el[1],this.v1l=0|el[2],this.v1h=0|el[3],this.v2l=0|el[4],this.v2h=0|el[5],this.v3l=0|el[6],this.v3h=0|el[7],this.v4l=0|el[8],this.v4h=0|el[9],this.v5l=0|el[10],this.v5h=0|el[11],this.v6l=0|el[12],this.v6h=0|el[13],this.v7l=0|el[14],this.v7h=0|el[15],function(e,t={},r,s,a){if(Pe(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");const{key:n,salt:i,personalization:o}=t;if(void 0!==n&&(n.length<1||n.length>r))throw new Error("key length must be undefined or 1.."+r);if(void 0!==i&&i.length!==s)throw new Error("salt must be undefined or "+s);if(void 0!==o&&o.length!==a)throw new Error("personalization must be undefined or "+a)}(t,e,64,16,16);let{key:r,personalization:s,salt:a}=e,n=0;if(void 0!==r&&(r=Je(r),n=r.length),this.v0l^=this.outputLen|n<<8|65536|1<<24,void 0!==a){a=Je(a);const e=Ke(a);this.v4l^=Ue(e[0]),this.v4h^=Ue(e[1]),this.v5l^=Ue(e[2]),this.v5h^=Ue(e[3])}if(void 0!==s){s=Je(s);const e=Ke(s);this.v6l^=Ue(e[0]),this.v6h^=Ue(e[1]),this.v7l^=Ue(e[2]),this.v7h^=Ue(e[3])}if(void 0!==r){const e=new Uint8Array(this.blockLen);e.set(r),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:r,v1h:s,v2l:a,v2h:n,v3l:i,v3h:o,v4l:c,v4h:d,v5l:l,v5h:h,v6l:p,v6h:u,v7l:y,v7h:f}=this;return[e,t,r,s,a,n,i,o,c,d,l,h,p,u,y,f]}set(e,t,r,s,a,n,i,o,c,d,l,h,p,u,y,f){this.v0l=0|e,this.v0h=0|t,this.v1l=0|r,this.v1h=0|s,this.v2l=0|a,this.v2h=0|n,this.v3l=0|i,this.v3h=0|o,this.v4l=0|c,this.v4h=0|d,this.v5l=0|l,this.v5h=0|h,this.v6l=0|p,this.v6h=0|u,this.v7l=0|y,this.v7h=0|f}compress(e,t,r){this.get().forEach(((e,t)=>tl[t]=e)),tl.set(el,16);let{h:s,l:a}=Jt(BigInt(this.length));tl[24]=el[8]^a,tl[25]=el[9]^s,r&&(tl[28]=~tl[28],tl[29]=~tl[29]);let n=0;const i=Qd;for(let r=0;r<12;r++)rl(0,4,8,12,e,t+2*i[n++]),sl(0,4,8,12,e,t+2*i[n++]),rl(1,5,9,13,e,t+2*i[n++]),sl(1,5,9,13,e,t+2*i[n++]),rl(2,6,10,14,e,t+2*i[n++]),sl(2,6,10,14,e,t+2*i[n++]),rl(3,7,11,15,e,t+2*i[n++]),sl(3,7,11,15,e,t+2*i[n++]),rl(0,5,10,15,e,t+2*i[n++]),sl(0,5,10,15,e,t+2*i[n++]),rl(1,6,11,12,e,t+2*i[n++]),sl(1,6,11,12,e,t+2*i[n++]),rl(2,7,8,13,e,t+2*i[n++]),sl(2,7,8,13,e,t+2*i[n++]),rl(3,4,9,14,e,t+2*i[n++]),sl(3,4,9,14,e,t+2*i[n++]);this.v0l^=tl[0]^tl[16],this.v0h^=tl[1]^tl[17],this.v1l^=tl[2]^tl[18],this.v1h^=tl[3]^tl[19],this.v2l^=tl[4]^tl[20],this.v2h^=tl[5]^tl[21],this.v3l^=tl[6]^tl[22],this.v3h^=tl[7]^tl[23],this.v4l^=tl[8]^tl[24],this.v4h^=tl[9]^tl[25],this.v5l^=tl[10]^tl[26],this.v5h^=tl[11]^tl[27],this.v6l^=tl[12]^tl[28],this.v6h^=tl[13]^tl[29],this.v7l^=tl[14]^tl[30],this.v7h^=tl[15]^tl[31],Oe(tl)}destroy(){this.destroyed=!0,Oe(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const il=et((e=>new nl(e))),ol="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const cl=(new TextEncoder).encode("SS58PRE");function dl(e,t){if(32!==e.length)throw new Error("encodeAccountId32: expected a 32-byte public key");if(t<0||t>=64)throw new Error("encodeAccountId32: only single-byte ss58Format prefixes (0-63) are supported");const r=Ud(new Uint8Array([t]),e),s=function(e){return il(Ud(cl,e),{dkLen:64}).slice(0,2)}(r);return function(e){let t=0;for(;t<e.length&&0===e[t];)t++;const r=[];for(let s=t;s<e.length;s++){let t=e[s];for(let e=0;e<r.length;e++)t+=r[e]<<8,r[e]=t%58,t=Math.floor(t/58);for(;t>0;)r.push(t%58),t=Math.floor(t/58)}let s=ol[0].repeat(t);for(let e=r.length-1;e>=0;e--)s+=ol[r[e]];return s}(Ud(r,s))}const ll=/^\d+$/,hl=/^\d+(?:\.\d+)?$/;function pl(e){return e.replace(/^0x/i,"").replace(/-/g,"").toLowerCase()}function ul(e,t,r="amount"){if("string"!=typeof e||!hl.test(e))throw new Rd("intent-field-malformed",`intent.${r} must be a non-negative decimal string in human-readable units (e.g. "1.5"), got ${JSON.stringify(e)}`);const[s,a=""]=e.split(".");if(a.length>t)throw new Rd("intent-field-malformed",`intent.${r} "${e}" has ${a.length} decimal places, more than this chain's ${t} — refusing to round a verification input`);return BigInt(s+a.padEnd(t,"0"))}function yl(e,t,r){const s=e[t];if(!s)throw new Rd("intent-field-missing",`${r}: intent.${String(t)} is required to verify this call — refusing to report a call as verified with this field unchecked`);return s}function fl(e,t,r){const s=[],{ss58Format:a,balanceDecimals:n}=r;switch(e.variant){case"balances.transferWithMemo":{const{args:r}=e,i=yl(t,"recipientAddress",e.variant),o=dl(r.dest.value,a);s.push({field:"destination",enforced:!0,matched:o===i,expected:t.recipientAddress,actual:o});const c=ul(yl(t,"amount",e.variant),n);s.push({field:"amount",enforced:!0,matched:BigInt(r.value)===c,expected:c.toString(),actual:String(r.value)});const d=yl(t,"assetSymbol",e.variant),l="POLYX";s.push({field:"asset",enforced:!0,matched:d.toUpperCase()===l,expected:d,actual:l});break}case"settlement.addAndAffirmWithMediators":{const{args:r}=e;if(1!==r.legs.length)throw new Rd("unsupported-call-shape",`settlement.addAndAffirmWithMediators carries ${r.legs.length} legs; an Intent describes a single transfer, so this call shape cannot be verified`);const a=r.legs[0].value;s.push({field:"destination",enforced:!1,actual:`did:${Ld(a.receiver.did)}`});const i=ul(yl(t,"amount",e.variant),n);s.push({field:"amount",enforced:!0,matched:BigInt(a.amount)===i,expected:i.toString(),actual:String(a.amount)});const o=yl(t,"assetId",e.variant),c=Ld(a.assetId);s.push({field:"asset",enforced:!0,matched:pl(c)===pl(o),expected:o,actual:c});break}case"settlement.affirmInstruction":case"settlement.rejectInstruction":{const{args:r}=e,a=function(e,t){if("string"!=typeof e||!ll.test(e))throw new Rd("intent-field-malformed",`intent.${t} must be a plain base-10 integer string, got ${JSON.stringify(e)}`);return BigInt(e)}(yl(t,"instructionId",e.variant),"instructionId");s.push({field:"instructionId",enforced:!0,matched:BigInt(r.id)===a,expected:a.toString(),actual:String(r.id)});const n=yl(t,"instructionDecision",e.variant),i="settlement.affirmInstruction"===e.variant?"approve":"deny";s.push({field:"instructionDecision",enforced:!0,matched:i===n,expected:n,actual:i});break}default:throw new Rd("unsupported-call-shape",`No verification rules are defined for Polymesh call variant "${e.variant}"`)}const i=s.filter((e=>e.enforced));if(0===i.length)throw new Rd("no-enforced-fields",`${e.variant} produced no enforced fields — refusing to report a call as verified with nothing checked`);return{chainName:exports.BlockchainName.Polymesh,callVariant:e.variant,fields:s,verified:i.every((e=>!0===e.matched))}}function gl(e,t,r,s){if(!Kd(r))throw new Rd("intent-field-malformed",`Unknown Polymesh network ${JSON.stringify(r)} — expected "mainnet" or "testnet"`);const a=xd[r];return fl(Zd(e,a,s),t,a)}const wl=Object.freeze(Object.defineProperty({__proto__:null,POLYMESH_CONTEXT:xd,PolymeshDecodeError:Nd,PolymeshVerificationError:Od,PolymeshVerifyError:Rd,decimalAmountToBaseUnits:ul,decodePolymeshCall:Zd,isPolymeshNetwork:Kd,verifyPolymeshCallAgainstIntent:gl,verifyPolymeshIntent:fl},Symbol.toStringTag,{value:"Module"}));exports.WallabyApiClient=e.A,exports.WallabyHttpClient=e.H,exports.AndroidVersionNotSupportedError=F,exports.AuthenticatorGeneralError=se,exports.AuthenticatorMissingDiscoverableCredentialSupportError=ae,exports.AuthenticatorMissingUserVerificationSupportError=ne,exports.AuthenticatorNoSupportedPubKeyCredParamsAlgError=ce,exports.AuthenticatorNotRegisteredError={error:"ERROR_AUTHENTICATOR_NOT_REGISTERED",message:"Authenticator is not registered."},exports.AuthenticatorPreviouslyRegisteredError=ie,exports.AutoRegisterUserVerificationFailureError=de,exports.BadConfiguration=Y,exports.CeremonyAbortedError=Z,exports.IOSVersionNotSupportedError=W,exports.InterruptedError=J,exports.InvalidChallengeError=H,exports.InvalidDomainError=Q,exports.InvalidRpIdError=ee,exports.InvalidStateError=oe,exports.InvalidUserIdError=$,exports.InvalidUserIdLengthError=te,exports.MalformedPubKeyCredParamsError=re,exports.NativeError=(e="An unknown error occurred")=>({error:"Unknown",message:e}),exports.NoCredentialsError=z,exports.NotAllowedError={error:"NotAllowedError",message:"CredentialContainer request is not allowed."},exports.PasskeyErrorCodes=he,exports.PassthroughSeeCausePropertyError=le,exports.RequestFailedError=G,exports.TimeoutError=X,exports.UnknownError=M,exports.UserCancelledError=j,exports.Wallaby=class{constructor(e,t={}){this.wallet=new Ed(e,t),this.walletData=new bd(e,t),this.utils=new Id(e,t),this.auth=new Sd(e,t),this.system=new kd(e,t),this.transactions=new Cd(e,t),this.swap=new Td(e,t),this.httpApi=new Pd(e,t)}get version(){return _e}},exports.WallabyError=V,exports.createIdentity=Ls,exports.decryptWithPrivateKey=wa,exports.encryptWithPublicKey=ga,exports.hash=Sa,exports.isValidSeedPhrase=Va,exports.keccak256=ma,exports.normalizeSeedPhrase=qa,exports.publicKeyByPrivateKey=ms,exports.recoverPublicKey=(e,t)=>{const r=qt(e),s=r.substring(0,r.length-2),a="1c"===r.slice(-2)?1:0;let n=Me(va(Ut(s),a,Ut(qt(t)),!1));return n=n.slice(2),n},exports.sign=Us,exports.verification=wl,exports.verifyCallAgainstIntent=function(e,t,r,s,a){if(r.chainName!==e)throw new Error(`verifyCallAgainstIntent: intent is for chain "${r.chainName}" but the call is for "${e}" — refusing to verify across chains`);if(e===exports.BlockchainName.Polymesh)return gl(t,r,s,a);throw new Error(`verifyCallAgainstIntent: no verifier registered for chain "${e}"`)};//# sourceMappingURL=index.cjs.map
13
+ var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ms(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ws(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Fs=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Gs(e,t){if(s=t,(r=e).buffer===s.buffer&&r.byteOffset<s.byteOffset+s.byteLength&&s.byteOffset<r.byteOffset+r.byteLength&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported");var r,s}const js=(e,t)=>{function r(r,...s){if(Vs(r),!Fs)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=s[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?Vs(t):Vs(t,e.nonceLength)}const a=e.tagLength;a&&void 0!==s[1]&&Vs(s[1]);const n=t(r,...s),i=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Vs(t)}};let o=!1;const c={encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Vs(e),i(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(Vs(e),a&&e.length<a)throw new Error("invalid ciphertext length: smaller than tagLength="+a);return i(n.decrypt.length,t),n.decrypt(e,t)}};return c}return Object.assign(r,e),r};function Hs(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!$s(t))throw new Error("invalid output, must be aligned");return t}function $s(e){return e.byteOffset%4==0}function Ys(e){return Uint8Array.from(e)}const zs=16;function Js(e){return e<<1^283&-(e>>7)}function Xs(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Js(e);return r}const Zs=(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Js(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let s=e[255-r];s|=s<<8,t[e[r]]=255&(s^s>>4^s>>5^s>>6^s>>7^99)}return Ws(e),t})(),Qs=Zs.map(((e,t)=>Zs.indexOf(t))),ea=e=>e<<8|e>>>24;function ta(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map(((r,s)=>t(e[s]))),s=r.map(ea),a=s.map(ea),n=a.map(ea),i=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let d=0;d<256;d++){const l=256*t+d;i[l]=r[t]^s[d],o[l]=a[t]^n[d],c[l]=e[t]<<8|e[d]}return{sbox:e,sbox2:c,T0:r,T1:s,T2:a,T3:n,T01:i,T23:o}}const ra=ta(Zs,(e=>Xs(e,3)<<24|e<<16|e<<8|Xs(e,2))),sa=ta(Qs,(e=>Xs(e,11)<<24|Xs(e,13)<<16|Xs(e,9)<<8|Xs(e,14))),aa=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Js(r))e[t]=r;return e})();function na(e){Vs(e);const t=e.length;if(![16,24,32].includes(t))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+t);const{sbox2:r}=ra,s=[];$s(e)||s.push(e=Ys(e));const a=Ms(e),n=a.length,i=e=>oa(r,e,e,e,e),o=new Uint32Array(t+28);o.set(a);for(let e=n;e<o.length;e++){let t=o[e-1];e%n==0?t=i((c=t)<<24|c>>>8)^aa[e/n-1]:n>6&&e%n==4&&(t=i(t)),o[e]=o[e-n]^t}var c;return Ws(...s),o}function ia(e,t,r,s,a,n){return e[r<<8&65280|s>>>8&255]^t[a>>>8&65280|n>>>24&255]}function oa(e,t,r,s,a){return e[255&t|65280&r]|e[s>>>16&255|a>>>16&65280]<<16}function ca(e,t,r,s,a){const{sbox2:n,T01:i,T23:o}=ra;let c=0;t^=e[c++],r^=e[c++],s^=e[c++],a^=e[c++];const d=e.length/4-2;for(let n=0;n<d;n++){const n=e[c++]^ia(i,o,t,r,s,a),d=e[c++]^ia(i,o,r,s,a,t),l=e[c++]^ia(i,o,s,a,t,r),h=e[c++]^ia(i,o,a,t,r,s);t=n,r=d,s=l,a=h}return{s0:e[c++]^oa(n,t,r,s,a),s1:e[c++]^oa(n,r,s,a,t),s2:e[c++]^oa(n,s,a,t,r),s3:e[c++]^oa(n,a,t,r,s)}}function da(e,t,r,s,a){const{sbox2:n,T01:i,T23:o}=sa;let c=0;t^=e[c++],r^=e[c++],s^=e[c++],a^=e[c++];const d=e.length/4-2;for(let n=0;n<d;n++){const n=e[c++]^ia(i,o,t,a,s,r),d=e[c++]^ia(i,o,r,t,a,s),l=e[c++]^ia(i,o,s,r,t,a),h=e[c++]^ia(i,o,a,s,r,t);t=n,r=d,s=l,a=h}return{s0:e[c++]^oa(n,t,a,s,r),s1:e[c++]^oa(n,r,t,a,s),s2:e[c++]^oa(n,s,r,t,a),s3:e[c++]^oa(n,a,s,r,t)}}function la(e,t,r,s){Vs(t,zs),Vs(r);const a=r.length;Gs(r,s=Hs(a,s));const n=t,i=Ms(n);let{s0:o,s1:c,s2:d,s3:l}=ca(e,i[0],i[1],i[2],i[3]);const h=Ms(r),u=Ms(s);for(let t=0;t+4<=h.length;t+=4){u[t+0]=h[t+0]^o,u[t+1]=h[t+1]^c,u[t+2]=h[t+2]^d,u[t+3]=h[t+3]^l;let r=1;for(let e=n.length-1;e>=0;e--)r=r+(255&n[e])|0,n[e]=255&r,r>>>=8;({s0:o,s1:c,s2:d,s3:l}=ca(e,i[0],i[1],i[2],i[3]))}const p=zs*Math.floor(h.length/4);if(p<a){const e=new Uint32Array([o,c,d,l]),t=(y=e,new Uint8Array(y.buffer,y.byteOffset,y.byteLength));for(let e=p,n=0;e<a;e++,n++)s[e]=r[e]^t[n];Ws(e)}var y;return s}const ha=js({blockSize:16,nonceLength:16},(function(e,t){function r(r,s){if(Vs(r),void 0!==s&&(Vs(s),!$s(s)))throw new Error("unaligned destination");const a=na(e),n=Ys(t),i=[a,n];$s(r)||i.push(r=Ys(r));const o=la(a,n,r,s);return Ws(...i),o}return{encrypt:(e,t)=>r(e,t),decrypt:(e,t)=>r(e,t)}}));const ua=js({blockSize:16,nonceLength:16},(function(e,t,r={}){const s=!r.disablePadding;return{encrypt(r,a){const n=na(e),{b:i,o:o,out:c}=function(e,t,r){Vs(e);let s=e.length;const a=s%zs;if(!t&&0!==a)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");$s(e)||(e=Ys(e));const n=Ms(e);if(t){let e=zs-a;e||(e=zs),s+=e}return Gs(e,r=Hs(s,r)),{b:n,o:Ms(r),out:r}}(r,s,a);let d=t;const l=[n];$s(d)||l.push(d=Ys(d));const h=Ms(d);let u=h[0],p=h[1],y=h[2],f=h[3],g=0;for(;g+4<=i.length;)u^=i[g+0],p^=i[g+1],y^=i[g+2],f^=i[g+3],({s0:u,s1:p,s2:y,s3:f}=ca(n,u,p,y,f)),o[g++]=u,o[g++]=p,o[g++]=y,o[g++]=f;if(s){const e=function(e){const t=new Uint8Array(16),r=Ms(t);t.set(e);const s=zs-e.length;for(let e=zs-s;e<zs;e++)t[e]=s;return r}(r.subarray(4*g));u^=e[0],p^=e[1],y^=e[2],f^=e[3],({s0:u,s1:p,s2:y,s3:f}=ca(n,u,p,y,f)),o[g++]=u,o[g++]=p,o[g++]=y,o[g++]=f}return Ws(...l),c},decrypt(r,a){!function(e){if(Vs(e),e.length%zs!=0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size 16")}(r);const n=function(e){const t=na(e),r=t.slice(),s=t.length,{sbox2:a}=ra,{T0:n,T1:i,T2:o,T3:c}=sa;for(let e=0;e<s;e+=4)for(let a=0;a<4;a++)r[e+a]=t[s-e-4+a];Ws(t);for(let e=4;e<s-4;e++){const t=r[e],s=oa(a,t,t,t,t);r[e]=n[255&s]^i[s>>>8&255]^o[s>>>16&255]^c[s>>>24]}return r}(e);let i=t;const o=[n];$s(i)||o.push(i=Ys(i));const c=Ms(i);a=Hs(r.length,a),$s(r)||o.push(r=Ys(r)),Gs(r,a);const d=Ms(r),l=Ms(a);let h=c[0],u=c[1],p=c[2],y=c[3];for(let e=0;e+4<=d.length;){const t=h,r=u,s=p,a=y;h=d[e+0],u=d[e+1],p=d[e+2],y=d[e+3];const{s0:i,s1:o,s2:c,s3:f}=da(n,h,u,p,y);l[e++]=i^t,l[e++]=o^r,l[e++]=c^s,l[e++]=f^a}return Ws(...o),function(e,t){if(!t)return e;const r=e.length;if(!r)throw new Error("aes/pcks5: empty ciphertext not allowed");const s=e[r-1];if(s<=0||s>16)throw new Error("aes/pcks5: wrong padding");const a=e.subarray(0,-s);for(let t=0;t<s;t++)if(e[r-t-1]!==s)throw new Error("aes/pcks5: wrong padding");return a}(a,s)}}}));function pa(e,t,r,s=!0){if(!r.startsWith("aes-"))throw new Error("AES: unsupported mode");const a=e.length;if(r.startsWith("aes-128")&&16!==a||r.startsWith("aes-256")&&32!==a)throw new Error("AES: wrong key length");if(16!==t.length)throw new Error("AES: wrong IV length");if(["aes-128-cbc","aes-256-cbc"].includes(r))return ua(e,t,{disablePadding:!s});if(["aes-128-ctr","aes-256-ctr"].includes(r))return ha(e,t);throw new Error("AES: unsupported mode")}const ya=(e,t,r)=>{const s=(null==r?void 0:r.ephemPrivateKey)?Ut(r.ephemPrivateKey):rt(32),a=rt(16),n=ws.getPublicKey(s),i=ws.ProjectivePoint.fromHex(n).toRawBytes(!1),o=ws.getSharedSecret(s,Ut(e),!0).slice(1),c=qs(o),d=c.subarray(0,32),l=c.subarray(32),h=function(e,t,r,s="aes-128-ctr",a=!0){return pa(t,r,s,a).encrypt(e)}(Ft(t),d,a,"aes-256-cbc"),u=Wt([a,i,h]),p=Bs(l,u);return{iv:Me(a),ephemPublicKey:Me(i),ciphertext:Me(h),mac:Me(p)}},fa=(e,t)=>{let r;try{r=ws.getSharedSecret(Ut(e),t.ephemPublicKey,!0).slice(1)}catch(e){throw new Error(`Invalid MAC: data integrity check failed: ${e}`)}const s=qs(r),a=s.subarray(0,32),n=s.subarray(32),i=Ut(t.ciphertext),o=Ut(t.iv),c=Ut(t.ephemPublicKey),d=Ut(t.mac),l=Wt([o,c,i]);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e[s]^t[s];return 0===r}(Bs(n,l),d))throw new Error("Invalid MAC: data integrity check failed");const h=function(e,t,r,s="aes-128-ctr",a=!0){return pa(t,r,s,a).decrypt(e)}(i,a,o,"aes-256-cbc");return function(e){if(!(e instanceof Uint8Array))throw new TypeError("bytesToUtf8 expected Uint8Array, got "+typeof e);return(new TextDecoder).decode(e)}(h)};const ga=(e,t,r)=>{const s=Mt(e);return ya("04"+s,t,r)},wa=(e,t)=>{const r=qt(e);return fa(r,t)},ma=e=>(e=>{const t=Ft(e),r=Vt(Me(t)),s=Ds(Ut(r));return Vt(Me(s))})(e);function va(e,t,r,s=!0,a){Lt(r,32),ot("compressed",s);const n=function(e){return Lt(e,64),ws.Signature.fromCompact(e)}(e);return function(e=e=>new Uint8Array(e),t,r){return"function"==typeof e&&(e=e(t)),Lt(e,t),r&&e.set(r),e}(a,s?33:65,n.addRecoveryBit(t).recoverPublicKey(r).toRawBytes(s))}ws.ProjectivePoint,ws.CURVE.n;const Sa={keccak256:ma};function _a(e){if(!Aa(e))throw new Error("Invalid JSON string");return JSON.parse(e)}function Aa(e){if("string"!=typeof e)return!1;try{return JSON.parse(e),!0}catch(e){return!1}}function Ea(e,t,r,s){ke(e);const a=function(e,t){if(void 0!==t&&"[object Object]"!=={}.toString.call(t))throw new Error("options should be object or undefined");return Object.assign(e,t)}({dkLen:32,asyncTick:10},s),{c:n,dkLen:i,asyncTick:o}=a;if(Pe(n),Pe(i),Pe(o),n<1)throw new Error("iterations (c) should be >= 1");const c=Xe(t),d=Xe(r),l=new Uint8Array(i),h=Pr.create(e,c),u=h._cloneInto().update(d);return{c:n,dkLen:i,asyncTick:o,DK:l,PRF:h,PRFSalt:u}}function ba(e,t,r,s){const{c:a,dkLen:n,DK:i,PRF:o,PRFSalt:c}=Ea(e,t,r,s);let d;const l=new Uint8Array(4),h=Ne(l),u=new Uint8Array(o.outputLen);for(let e=1,t=0;t<n;e++,t+=o.outputLen){const r=i.subarray(t,t+o.outputLen);h.setInt32(0,e,!1),(d=c._cloneInto(d)).update(l).digestInto(u),r.set(u.subarray(0,r.length));for(let e=1;e<a;e++){o._cloneInto(d).update(u).digestInto(u);for(let e=0;e<r.length;e++)r[e]^=u[e]}}return function(e,t,r,s,a){return e.destroy(),t.destroy(),s&&s.destroy(),Oe(a),r}(o,c,i,d,u)}const Ia="wsdkmk:v1:";function Pa(e){if(ze(e).length<16)throw new Error("Salt is too short: must be at least 16 bytes");if(new Set(e).size<=6)throw new Error("Weak salt: too few unique characters")}function Ta({password:e,salt:t}){Pa(t);const r=function(e,t,r,s,a){if(!["sha256","sha512"].includes(a))throw new Error("Only sha256 and sha512 are supported");return Lt(e),Lt(t),ba(Ar,e,t,{c:r,dkLen:s})}(ze(e.normalize("NFKC").trim()),ze(t),131072,32,"sha256");return Ls(r)}function ka(e,t){return Ia+function(e,t){return a.AES.encrypt(e,t).toString()}("string"==typeof e?e:JSON.stringify(e),t)}function Ca(e,t){const r=function(e,t){return a.AES.decrypt(e,t).toString(a.enc.Utf8)}(e.startsWith(Ia)?e.slice(10):e,t);if(r)return Aa(r)?_a(r):r}function xa(e,t){return JSON.stringify({material:e,destinationPubKey:t})}class Ka{constructor(){}validatePrivateKey(e){!function(e){if(!/^0x[0-9a-fA-F]{64}$/.test(e))throw new Error("Invalid private key: must be a 32-byte hex string");if(!ws.utils.isValidPrivateKey(e.slice(2)))throw new Error("Invalid private key: outside secp256k1 scalar range")}(e)}getMasterKey(){return{buffer:ze(me),key:me}}encryptWithMasterKey({data:e}){return ka(e,this.getMasterKey().key)}isWrappedByMasterKey(e){return function(e){return e.startsWith(Ia)||e.startsWith("U2FsdGVkX1")}(e)}decryptWithMasterKey({cipherText:e}){try{const t=Ca(e,this.getMasterKey().key);if(void 0!==t)return t}catch(e){return void pe.error("Decryption failed with master key",e)}pe.error("Decryption failed with master key")}validatePublicKey(e){!function(e){if(!/^[0-9a-fA-F]{128}$/.test(e))throw new Error("Invalid public key: must be a 64-byte raw uncompressed hex string");if(new Set(e).size<=8)throw new Error("Weak public key: too few unique characters")}(e)}validateSalt(e){Pa(e)}sign({message:e,signingKey:t}){try{this.validatePrivateKey(t);const r=ma(e);return{message:e,signature:Us(t,r),hashedMessage:r}}catch(e){throw pe.error("SDK::Cipher::sign",e),new Error(`Error signing message: ${e}`)}}async encrypt({data:e,encryptionKey:t}){try{return this.validatePublicKey(t),await ga(t,e)}catch(e){throw pe.error("Error encrypting data: ",e),new Error("Something happened during data encryption.")}}async decrypt({cipherText:e,decryptionKey:t}){try{this.validatePrivateKey(t);return await wa(t,(r=e,"string"==typeof r?JSON.parse(r):r))}catch(e){throw pe.error("SDK::CipherService::decrypt::error: ",e),new Error("That doesn’t seem right. Check your login details and try again.")}var r}async getCredentialsKeyPair(e){try{let t;switch(e.authType){case exports.AuthType.Password:if(!e.password||!e.salt)throw new Error("Password and salt are required");return t=await this.deriveKeyPairFromPassword({password:e.password,salt:e.salt}),t;case exports.AuthType.Passkey:if(!e.prfValue)throw new Error("PRF value is required");return t=await this.deriveKeyPairFromPasskey({inputKeyMaterial:e.prfValue}),t;default:throw new Error(`Unknown AuthType: ${e.authType}`)}}catch(e){return pe.error("SDK::CipherService::getCredentialsKeyPair::error",e),Promise.reject(e)}}async prepareDataForTransport({data:e,wallabyPublicKey:t,destinationPubKey:r}){try{const s=r?xa(e,r):e;return ga(t,s)}catch(e){throw pe.error("SDK::CipherService::prepareDataForTransport::error",e),new Error("Error preparing data for transport")}}async prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:t,wallabyPublicKey:r,options:s,destinationPubKey:a}){const n=await this.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:t,options:s});return this.prepareDataForTransport({data:n,wallabyPublicKey:r,destinationPubKey:a})}async doubleEncrypt({decryptedData:e,credentialsKeyPair:t,deviceKeyPair:r}){try{const s=await this.encrypt({data:e,encryptionKey:r.publicKey});return await this.encrypt({data:JSON.stringify(s),encryptionKey:t.publicKey})}catch(e){throw pe.error("SDK::doubleEncrypt::error",e),e}}async prepareTransportDataForStorage({transportData:e,credentialsKeyPair:t,deviceKeyPair:r}){try{const s=await this.decrypt({cipherText:e,decryptionKey:r.privateKey}),a=await this.encrypt({data:s,encryptionKey:r.publicKey});return await this.encrypt({data:JSON.stringify(a),encryptionKey:t.publicKey})}catch(e){throw pe.error("SDK::prepareTransportDataForStorage::error",e),e}}async displayDataFromServer({encryptedData:e,encryptedDevicePrivateKey:t,options:r}){try{const s=await this.getCredentialsKeyPair(r),a=await this.decrypt({cipherText:t,decryptionKey:s.privateKey});if(!a)throw new Error("That doesn’t seem right. Check your login details and try again.");return await this.decrypt({cipherText:e,decryptionKey:a})}catch(e){throw pe.error("SDK::CipherService::displayDataFromServer::error",e),e}}async displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:t,options:r}){const s=await this.getCredentialsKeyPair(r),a=await this.decrypt({cipherText:t,decryptionKey:s.privateKey});if(!a)throw new Error("Credentials are not correct, please provide the correct credentials");const n=await this.decrypt({cipherText:e,decryptionKey:s.privateKey});if(!n)throw new Error("That doesn’t seem right. Check your login details and try again.");const i=await this.decrypt({cipherText:JSON.parse(n),decryptionKey:a});if(!i)throw new Error("That doesn’t seem right. Check your login details and try again.");return i}async flipEncryptedData({cipherText:e,decryptionKey:t,encryptionKey:r}){try{const s=await this.decrypt({cipherText:e,decryptionKey:t});return await this.encrypt({data:s,encryptionKey:r})}catch(e){throw pe.error("SDK::CipherService::displayDataFromServer::error",e),e}}async deriveKeyPairFromPasskey({inputKeyMaterial:e}){return function({inputKeyMaterial:e}){return Ls(e)}({inputKeyMaterial:e})}async deriveKeyPairFromPassword({password:e,salt:t}){return Ta({password:e,salt:t})}}class Oa{constructor(){this.activeLocks=new Set}async withLock(e,t){const r="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator?navigator.locks:void 0;if(r)return r.request(e,{ifAvailable:!0},(async r=>{if(!r)throw new Error(`Operation '${e}' is already in progress. Please wait for it to complete.`);return t()}));if(this.activeLocks.has(e))throw new Error(`Operation '${e}' is already in progress. Please wait for it to complete.`);this.activeLocks.add(e);try{return await t()}finally{this.activeLocks.delete(e)}}isLocked(e){return this.activeLocks.has(e)}clearAllLocks(){this.activeLocks.clear()}}const Na=new Oa;class Ra{constructor({deviceStorage:e,userId:t,environment:r}){this._walletSpecificKeys=[exports.V2KeyNames.EncryptedStandardSeedPhrase,exports.V2KeyNames.PrimaryDeviceKeyShare,exports.V2KeyNames.BackupDeviceKeyShare],this._keysProtectedByMasterKey=[exports.V2KeyNames.AccessToken,exports.V2KeyNames.RefreshToken,exports.V2KeyNames.PasskeyCredential,exports.V2KeyNames.ClientAuthToken],this.userId=t,this.environment=null!=r?r:ge,this.shortenedEnv=this.environment.slice(0,1),this.deviceLocalStorage=e,this.cipher=new Ka}async getFromDeviceStorage(e){return this.deviceLocalStorage.getItem?this.deviceLocalStorage.getItem(e):this.deviceLocalStorage.getItemAsync?await this.deviceLocalStorage.getItemAsync(e):null}async setInDeviceStorage(e,t){return this.deviceLocalStorage.setItem?this.deviceLocalStorage.setItem(e,t):this.deviceLocalStorage.setItemAsync?await this.deviceLocalStorage.setItemAsync(e,t):void 0}async fetch(e,t){var r;let s;if(await(null!==(r=this._walRecovery)&&void 0!==r?r:this._walRecovery=this.recoverCommit().catch((e=>{pe.error("SDK::StorageService::fetch::wal recovery failed",e)}))),this._walletSpecificKeys.includes(e)){if(!(null==t?void 0:t.walletId))throw new Error(`A walletId is required to fetch: ${e}`);s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t.walletId}`}else s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;Se.isNative&&(s=be(s));const a=await this.getItem(s);if(a){if(this._keysProtectedByMasterKey.includes(e)){if(!this.cipher.isWrappedByMasterKey(a))return a;const e=this.cipher.decryptWithMasterKey({cipherText:a});return e||void pe.error(`Failed to decrypt item with key ${s}`)}return a}pe.debug(`(404): Item with key ${s} was not found in storage.`)}async save(e,t,r){let s,a;if(this._walletSpecificKeys.includes(e)){if(!(null==r?void 0:r.walletId))throw new Error(`A walletId is required to save: ${e}`);s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${r.walletId}`}else s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;if(Se.isNative&&(s=be(s)),this._keysProtectedByMasterKey.includes(e)){a=this.cipher.encryptWithMasterKey({data:t})}else a="string"==typeof t?t:JSON.stringify(t);return await this.setItem(s,a)}async saveInBulk(e){await Promise.all(e.map((e=>this.save(e.key,e.value,{walletId:e.walletId}))))}_computeRawKey(e,t){let r;if(this._walletSpecificKeys.includes(e)){if(!t)throw new Error(`A walletId is required to compute key: ${e}`);r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t}`}else r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;return ve?r:be(r)}_serializeValue(e,t){return this._keysProtectedByMasterKey.includes(e)?this.cipher.encryptWithMasterKey({data:t}):"string"==typeof t?t:JSON.stringify(t)}async _applyWAL(e){for(const{rawKey:t,value:r}of e.writes)await this.setItem(t,r);for(const t of e.deletes)await this.removeItem(t)}async commitBatch(e,t){const r={writes:e.map((({key:e,value:t,walletId:r})=>({rawKey:this._computeRawKey(e,r),value:this._serializeValue(e,t)}))),deletes:(null!=t?t:[]).map((({key:e,walletId:t})=>this._computeRawKey(e,t)))};await this.recoverCommit();const s=this._computeRawKey(exports.V2KeyNames.PendingCommit);await this.setItem(s,JSON.stringify(r)),await this._applyWAL(r),await this.removeItem(s)}async recoverCommit(){const e=this._computeRawKey(exports.V2KeyNames.PendingCommit),t=await this.getItem(e);if(!t)return;let r;try{r=_a(t)}catch(t){return pe.error("SDK::StorageService::recoverCommit::corrupt WAL, discarding",t),void await this.removeItem(e)}await this._applyWAL(r),await this.removeItem(e)}async delete(e,t){let r;if(this._walletSpecificKeys.includes(e)){if(!(null==t?void 0:t.walletId))throw new Error(`A walletId is required to delete: ${e}`);r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t.walletId}`}else r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;return Se.isNative&&(r=be(r)),await this.removeItem(r)}setItem(e,t){if(this.deviceLocalStorage.setItem)return this.deviceLocalStorage.setItem(e,t);if(this.deviceLocalStorage.setItemAsync)return this.deviceLocalStorage.setItemAsync(e,t);throw new Error("setItem function is is not defined")}getItem(e){if(this.deviceLocalStorage.getItem)return this.deviceLocalStorage.getItem(e);if(this.deviceLocalStorage.getItemAsync)return this.deviceLocalStorage.getItemAsync(e);throw new Error("getItem function is not defined")}removeItem(e){if(this.deviceLocalStorage.removeItem)return this.deviceLocalStorage.removeItem(e);if(this.deviceLocalStorage.deleteItemAsync)return this.deviceLocalStorage.deleteItemAsync(e);throw new Error("removeItem function is not defined")}async checkPrivateKeyExists(){return!!await this.getEncryptedPrivateKey()}async checkPrimaryKeyShareExists(e){return!!await this.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:e})}async checkBackupKeyShareExists(e){return!!await this.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e})}async checkSeedPhraseExists(e){return!!await this.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard,e)}getSeedPhraseV2KeyName(e){if(e===exports.SeedPhraseType.Standard)return exports.V2KeyNames.EncryptedStandardSeedPhrase;throw new Error(`Unsupported seed phrase type: ${e}`)}async setEncryptedPrivateKey(e,t){const r=a.AES.encrypt(e,t).toString();await this.setItem(`${this.environment}-client-auth-private-key-${this.userId}`,r)}async getV1EncryptedPrivateKey(){const e=`encryptedPrivateKey_${this.userId}`,t=`${this.environment}-client-auth-private-key-${this.userId}`,r=await this.getItem(t),s=await this.getItem(e);return r||s}async getEncryptedPrivateKey(){const e=await this.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey);if(e)return e;const t=`encryptedPrivateKey_${this.userId}`,r=await this.getItem(t);if(r)return r;{const e=`${this.environment}-client-auth-private-key-${this.userId}`,t=await this.getItem(e);if(t)return t}pe.error("SDK::StorageService::getEncryptedPrivateKey: private key not found")}async getDecryptedV1PrivateKey(e){try{const t=await this.getV1EncryptedPrivateKey();if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return r||void 0}catch(e){return void pe.error("SDK::StorageService::getDecryptedV1PrivateKey::error",e)}}async getDecryptedPrivateKey(e){try{const t=await this.getEncryptedPrivateKey();if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return r||void 0}catch(e){return void pe.error("SDK::StorageService::getDecryptedPrivateKey::error",e)}}async setEncryptedSeedPhrase({decryptedSeedPhrase:e,seedPhraseType:t,password:r,deviceAuthPublicKey:s,getUserSalt:n,salt:i,walletId:o}){const c=await ga(s,e),d=null!=i?i:await n();if(!d)throw new Error("User salt could not be retrieved, Seed phrase could not be encrypted");const l=`${d}${r}`,h=await a.AES.encrypt(JSON.stringify(c),l),u=this.getSeedPhraseV2KeyName(t);return await this.save(u,h.toString(),{walletId:o}),!0}async getEncryptedSeedPhrase(e,t){const r=this.getSeedPhraseV2KeyName(e),s=await this.fetch(r,{walletId:t});if(s)return s;if(!await this.isLegacySeedFallbackSafeFor(t))return;let a;if(e===exports.SeedPhraseType.Standard&&(a=`encryptedSeed_${this.userId}`),a){const e=await this.getItem(a);if(e){return await this.claimLegacySeedFallbackFor(t)?e:void 0}}if(!s){const r=`${this.environment}-encrypted-${e}-seedPhrase-${this.userId}`,s=await this.getItem(r);if(s){return await this.claimLegacySeedFallbackFor(t)?s:void 0}}}async isLegacySeedFallbackSafeFor(e){const t=await this.fetch(exports.V2KeyNames.LegacySeedClaimedWalletId);return!t||t===e}async claimLegacySeedFallbackFor(e){const t=`legacy-seed-claim:${this.environment}:${this.userId}`;try{return await Na.withLock(t,(async()=>{const t=await this.fetch(exports.V2KeyNames.LegacySeedClaimedWalletId);return t?t===e:(await this.save(exports.V2KeyNames.LegacySeedClaimedWalletId,e),!0)}))}catch(e){return pe.error("SDK::StorageService::claimLegacySeedFallbackFor::lock contention, treating as lost race",e),!1}}async getV1EncryptedSeedPhrase(){const e=`${this.environment}-encrypted-${exports.SeedPhraseType.Standard}-seedPhrase-${this.userId}`,t=await this.getItem(e);if(t)return t}async getV1DecryptedSeedPhrase(e,t){const r=await this.getV1EncryptedSeedPhrase(),s=await this.getDecryptedV1PrivateKey(e);if(!r||!s)return;const n=`${t}${e}`,i=_a(a.AES.decrypt(r,n).toString(a.enc.Utf8));return await wa(s,i)}async getDecryptedSeedPhrase({password:e,seedPhraseType:t,getUserSalt:r,salt:s,walletId:n}){const i=await this.getEncryptedSeedPhrase(t,n),o=await this.getDecryptedPrivateKey(e);if(!i||!o)return;const c=`${null!=s?s:await r()}${e}`,d=_a(a.AES.decrypt(i,c).toString(a.enc.Utf8));return await wa(o,d)}async setAccessToken(e){await this.save(exports.LocalStorageItems.AccessToken,e)}async getAccessToken(){let e=await this.fetch(exports.LocalStorageItems.AccessToken);if(e)return e;const t=`accessToken_${this.userId}`,r=await this.getItem(t);if(r)e=r;else{const t=`${this.environment}-access-token-${this.userId}`,r=await this.getItem(t);r&&(e=r)}return e?(await this.setAccessToken(e),e):void 0}async clearLocalStorage(e){const t=[exports.LocalStorageItems.AccessToken,exports.LocalStorageItems.RefreshToken,exports.V2KeyNames.EncryptedDevicePrivateKey,exports.V2KeyNames.ClientAuthPublicKey,exports.V2KeyNames.WallabyAuthPubKey,exports.V2KeyNames.PasskeyCredential,exports.V2KeyNames.MigrationVersion,exports.V2KeyNames.LastMigratedAt,exports.V2KeyNames.ClientAuthToken,exports.V2KeyNames.PasswordResetAttempts,exports.V2KeyNames.MigrationAttempts,exports.V2KeyNames.CredentialConversionInProgress,exports.V2KeyNames.PendingCommit];await Promise.all(t.map((e=>this.delete(e)))),e&&await Promise.all(this._walletSpecificKeys.map((t=>this.delete(t,{walletId:e}))));const r=[`${this.environment}-access-token-${this.userId}`,`${this.environment}-encrypted-${exports.SeedPhraseType.Standard}-seedPhrase-${this.userId}`,`${this.environment}-client-auth-private-key-${this.userId}`,`${this.environment}-wallaby-auth-public-key-${this.userId}`,`encryptedPrivateKey_${this.userId}`,`wallabyAuthPubKey_${this.userId}`,`encryptedSeed_${this.userId}`,`accessToken_${this.userId}`];await Promise.all(r.map((e=>this.removeItem(e)))),await this.delete(exports.V2KeyNames.LegacySeedClaimedWalletId)}async loadDeviceInformation(e){return{authTokens:{accessToken:await this.fetch(exports.LocalStorageItems.AccessToken),clientAuthToken:await this.fetch(exports.LocalStorageItems.ClientAuthToken)},user:{clientUserId:this.userId,encryptedStandardSeedPhrase:await this.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:e}),wallabyUserId:void 0},credentials:{deviceAuthPrivateKey:void 0,deviceAuthPublicKey:void 0,deviceEncryptedPrivateKey:await this.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),wallabyPublicKey:await this.fetch(exports.V2KeyNames.WallabyAuthPubKey)},hostname:"undefined"==typeof window?"republic.com":window.location.hostname}}}function Da(e,t=Date.now){return!e||Ua(e,t)<=0}function La(e,t,r=Date.now){return!!e&&Ua(e,r)<=1e3*t}function Ua(e,t=Date.now){const r=n.jwtDecode(e).exp;return 1e3*(null!=r?r:0)-t()}const Ba={signatureMessage:{fullPath:"/auth/signature-message",method:exports.RequestMethod.Post,requiresAccessToken:!1},signIn:{fullPath:"/auth/sign-in",method:exports.RequestMethod.Post,requiresAccessToken:!1},signUp:{fullPath:"/auth/sign-up",method:exports.RequestMethod.Post,requiresAccessToken:!1},refreshAccessToken:{fullPath:"/auth/refresh-access-token",method:exports.RequestMethod.Post,requiresAccessToken:!0},clientAuthPubKey:{fullPath:"auth/client-auth-pubkey",method:exports.RequestMethod.Put,requiresAccessToken:!0},wallabyAuthPublicKey:{fullPath:"/auth/wallaby-auth-pubkey",method:exports.RequestMethod.Get,requiresAccessToken:!0},getUserSalt:{fullPath:"/users/salt",method:exports.RequestMethod.Get,requiresAccessToken:!0},getPasskeyCredentials:{fullPath:"/auth/passkey-credentials",method:exports.RequestMethod.Get,requiresAccessToken:!0},issueJwtToken:{fullPath:"/auth/issue-jwt-token",method:exports.RequestMethod.Post,requiresAccessToken:!1}};function qa(e){return/^[a-zA-Z0-9-_]+$/.test(e)}function Va(e){return"string"!=typeof e?"":e.normalize("NFKD").trim().toLowerCase().replace(/\s+/g," ")}function Ma(e){return t.validateMnemonic(Va(e))}function Wa(e,t="The seed phrase is not a valid BIP-39 mnemonic. Expected 12, 15, 18, 21 or 24 words from the BIP-39 English wordlist."){if(!Ma(e))throw new V({message:t,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return Va(e)}function Fa(e){const{apiKey:t,baseUrl:r,userId:s,clientAuthToken:a,options:i}=e;if("string"!=typeof t||!qa(t))throw new Error("Invalid or empty API key provided.");if("string"!=typeof r||!function(e){try{return new URL(e),!0}catch(e){return!1}}(r))throw new Error("Invalid or empty base URL provided.");if("string"!=typeof s||!qa(s))throw new Error("Invalid or empty user ID provided.");if("string"!=typeof a||!function(e){if("string"!=typeof e)return!1;if(3!==e.split(".").length)return!1;try{return n.jwtDecode(e),!0}catch(e){return!1}}(a))throw new Error("Invalid or empty client auth token provided.");if(i&&"object"!=typeof i)throw new Error("Invalid options provided.");return Object.freeze({apiKey:t.trim(),baseUrl:r.trim(),userId:s.trim(),clientAuthToken:a.trim(),options:i?Object.freeze(Object.assign({},i)):void 0})}const Ga={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function ja(e){return Ga}function Ha(e){const t=typeof e;return"string"===t?`"${e}"`:"number"===t||"bigint"===t||"boolean"===t?`${e}`:"object"===t||"function"===t?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function $a(e,t,r,s,a){const n=a&&"input"in a?a.input:r.value,i=a?.expected??e.expects??null,o=a?.received??Ha(n),c={kind:e.kind,type:e.type,input:n,expected:i,received:o,message:`Invalid ${t}: ${i?`Expected ${i} but r`:"R"}eceived ${o}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},d="schema"===e.kind,l=a?.message??e.message??(e.reference,void c.lang)??(d?void c.lang:null)??s.message??void c.lang;void 0!==l&&(c.message="function"==typeof l?l(c):l),d&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}const Ya=new WeakMap;function za(e){let t=Ya.get(e);return t||(t={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},ja())},Ya.set(e,t)),t}function Ja(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}function Xa(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function Za(e,t,r){return"function"==typeof e.fallback?e.fallback(t,r):e.fallback}function Qa(e,t,r){return"function"==typeof e.default?e.default(t,r):e.default}function en(){return{kind:"schema",type:"any",reference:en,expects:"any",async:!1,get"~standard"(){return za(this)},"~run":e=>(e.typed=!0,e)}}function tn(e,t){return{kind:"schema",type:"array",reference:tn,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){const r=e.value;if(Array.isArray(r)){e.typed=!0,e.value=[];for(let s=0;s<r.length;s++){const a=r[s],n=this.item["~run"]({value:a},t);if(n.issues){const i={type:"array",origin:"value",input:r,key:s,value:a};for(const t of n.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||(e.issues=n.issues),t.abortEarly){e.typed=!1;break}}n.typed||(e.typed=!1),e.value.push(n.value)}}else $a(this,"type",e,t);return e}}}function rn(e){return{kind:"schema",type:"boolean",reference:rn,expects:"boolean",async:!1,message:e,get"~standard"(){return za(this)},"~run"(e,t){return"boolean"==typeof e.value?e.typed=!0:$a(this,"type",e,t),e}}}function sn(e,t){if(typeof e==typeof t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{value:e};if(e&&t&&e.constructor===Object&&t.constructor===Object){const r={...e};for(const s in t)if(Object.prototype.hasOwnProperty.call(e,s)){const a=sn(e[s],t[s]);if(a.issue)return a;r[s]=a.value}else r[s]=t[s];return{value:r}}if(Array.isArray(e)&&Array.isArray(t)&&e.length===t.length){const r=[...e];for(let s=0;s<e.length;s++){const a=sn(e[s],t[s]);if(a.issue)return a;r[s]=a.value}return{value:r}}}return{issue:!0}}function an(e,t){return{kind:"schema",type:"intersect",reference:an,expects:Xa(e.map((e=>e.expects)),"&"),async:!1,options:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){if(this.options.length){const r=e.value;let s;e.typed=!0;for(const a of this.options){const n=a["~run"]({value:r},t);if(n.issues){if(e.issues)for(const t of n.issues)e.issues.push(t);else e.issues=n.issues;if(t.abortEarly){e.typed=!1;break}}n.typed||(e.typed=!1),e.typed&&(s?s.push(n.value):s=[n.value])}if(e.typed){e.value=s[0];for(let r=1;r<s.length;r++){const a=sn(e.value,s[r]);if(a.issue){$a(this,"type",e,t,{received:"unknown"});break}e.value=a.value}}}else $a(this,"type",e,t);return e}}}function nn(e){return{kind:"schema",type:"lazy",reference:nn,expects:"unknown",async:!1,getter:e,get"~standard"(){return za(this)},"~run"(e,t){return this.getter(e.value)["~run"](e,t)}}}function on(e,t){return{kind:"schema",type:"nullable",reference:on,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return za(this)},"~run"(e,t){return null===e.value&&(void 0!==this.default&&(e.value=Qa(this,e,t)),null===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function cn(e){return{kind:"schema",type:"number",reference:cn,expects:"number",async:!1,message:e,get"~standard"(){return za(this)},"~run"(e,t){return"number"!=typeof e.value||isNaN(e.value)?$a(this,"type",e,t):e.typed=!0,e}}}function dn(e,t){return{kind:"schema",type:"object",reference:dn,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in this.entries){const a=this.entries[s];if(s in r||("exact_optional"===a.type||"optional"===a.type||"nullish"===a.type)&&void 0!==a.default){const n=s in r?r[s]:Qa(a),i=a["~run"]({value:n},t);if(i.issues){const a={type:"object",origin:"value",input:r,key:s,value:n};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value[s]=i.value}else if(void 0!==a.fallback)e.value[s]=Za(a);else if("exact_optional"!==a.type&&"optional"!==a.type&&"nullish"!==a.type&&($a(this,"key",e,t,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:r,key:s,value:r[s]}]}),t.abortEarly))break}}else $a(this,"type",e,t);return e}}}function ln(e,t){return{kind:"schema",type:"optional",reference:ln,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return za(this)},"~run"(e,t){return void 0===e.value&&(void 0!==this.default&&(e.value=Qa(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function hn(e,t){return{kind:"schema",type:"picklist",reference:hn,expects:Xa(e.map(Ha),"|"),async:!1,options:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:$a(this,"type",e,t),e}}}function un(e,t,r){return{kind:"schema",type:"record",reference:un,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return za(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in r)if(Ja(r,s)){const a=r[s],n=this.key["~run"]({value:s},t);if(n.issues){const i={type:"object",origin:"key",input:r,key:s,value:a};for(const t of n.issues)t.path=[i],e.issues?.push(t);if(e.issues||(e.issues=n.issues),t.abortEarly){e.typed=!1;break}}const i=this.value["~run"]({value:a},t);if(i.issues){const n={type:"object",origin:"value",input:r,key:s,value:a};for(const t of i.issues)t.path?t.path.unshift(n):t.path=[n],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}n.typed&&i.typed||(e.typed=!1),n.typed&&(e.value[n.value]=i.value)}}else $a(this,"type",e,t);return e}}}function pn(e){return{kind:"schema",type:"string",reference:pn,expects:"string",async:!1,message:e,get"~standard"(){return za(this)},"~run"(e,t){return"string"==typeof e.value?e.typed=!0:$a(this,"type",e,t),e}}}function yn(e){let t;if(e)for(const r of e)if(t)for(const e of r.issues)t.push(e);else t=r.issues;return t}function fn(e,t){return{kind:"schema",type:"union",reference:fn,expects:Xa(e.map((e=>e.expects)),"|"),async:!1,options:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){let r,s,a;for(const n of this.options){const i=n["~run"]({value:e.value},t);if(i.typed){if(!i.issues){r=i;break}s?s.push(i):s=[i]}else a?a.push(i):a=[i]}if(r)return r;if(s){if(1===s.length)return s[0];$a(this,"type",e,t,{issues:yn(s)}),e.typed=!0}else{if(1===a?.length)return a[0];$a(this,"type",e,t,{issues:yn(a)})}return e}}}const gn=dn({message:pn(),environment:pn()}),wn=dn({clientAuthPubKey:pn(),passkeyChallengeType:ln(hn(["webauthn.create","webauthn.get"])),walletId:ln(pn())}),mn=dn({message:pn(),wallabyAuthPubKey:ln(pn()),foundDevicePublicKey:rn(),challenge:ln(pn()),registrationOptions:ln(un(pn(),en())),authenticationOptions:ln(un(pn(),en()))}),vn=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),externalUserId:pn(),firstName:ln(pn()),lastName:ln(pn()),merchantId:ln(pn()),passkeyRegistrationResponse:ln(un(pn(),en()))}),Sn=dn({id:pn(),firstName:ln(pn()),externalUserId:pn(),role:ln(hn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),clientSalt:ln(pn()),clientAuthPubKey:ln(pn())}),_n=dn({accessToken:pn(),refreshToken:ln(pn()),user:nn((()=>Sn))}),An=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),externalUserId:ln(pn()),firstName:ln(pn()),lastName:ln(pn()),merchantId:ln(pn()),passkeyRegistrationResponse:ln(un(pn(),en()))}),En=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),passkeyRegistrationResponse:ln(un(pn(),en())),passkeyAuthenticationResponse:ln(un(pn(),en()))}),bn=dn({id:pn(),externalUserId:pn(),clientSalt:pn()}),In=dn({accessToken:pn(),refreshToken:pn(),user:nn((()=>bn))}),Pn=dn({refreshToken:pn()}),Tn=dn({accessToken:pn(),refreshToken:pn()}),kn=dn({message:pn()}),Cn=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),newClientAuthPubKey:pn()}),xn=dn({user:nn((()=>Sn))}),Kn=dn({clientAuthPubKey:pn()}),On=dn({wallabyAuthPubKey:pn()}),Nn=dn({id:pn(),externalUserId:pn(),merchantId:pn(),role:hn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]),firstName:ln(pn()),walletsCount:cn(),latestWallabyAuthPubKey:ln(pn()),latestWallabyAuthPubKeyVersion:ln(pn()),portalInvitationStatus:ln(on(hn(["pending","accepted","rejected"]))),createdAt:pn(),updatedAt:pn(),hasFullPermissions:rn()}),Rn=dn({id:pn(),userId:pn(),publicKey:pn(),status:hn(["active","invalidated"]),createdAt:pn(),updatedAt:pn()}),Dn=dn({id:pn(),authenticatorGlobalId:pn(),credentialID:pn(),publicKey:pn(),authPublicKeyId:pn(),counter:cn(),transports:pn(),credentialDeviceType:pn(),credentialBackedUp:rn(),user:an([nn((()=>Nn))]),authPublicKeys:ln(tn(nn((()=>Rn)))),userId:pn(),externalUserId:pn(),createdAt:pn(),updatedAt:pn(),authenticatorName:ln(pn())}),Ln=dn({credentials:tn(nn((()=>Dn)))}),Un=dn({totalRecords:cn(),currentPage:cn(),totalPages:cn(),nextPage:on(cn()),previousPage:on(cn()),pageSize:cn()}),Bn=dn({address:pn(),publicKey:ln(pn()),type:ln(hn(["SEGWIT","LEGACY","DEFAULT"]))}),qn=dn({id:pn(),name:pn(),nameSlugify:pn(),verified:rn(),status:hn(["active","inactive","invalidated"])}),Vn=dn({id:pn(),userId:pn(),merchantId:pn(),chainId:pn(),userAssetAddress:pn(),walletId:pn(),configId:pn(),assetName:pn(),assetSymbol:pn(),balance:on(pn()),balanceUpdatedAt:on(pn()),claimableBalance:ln(on(pn())),claimableBalanceUpdatedAt:ln(on(pn())),claimablePaymentTokenContractAddress:ln(on(pn())),claimablePaymentTokenAssetConfigId:ln(on(pn())),lockedTokenBalance:on(pn()),lockedTokenBalanceUpdatedAt:on(pn()),mainnetBalance:on(pn()),mainnetBalanceUpdatedAt:on(pn()),testnetBalance:on(pn()),testnetBalanceUpdatedAt:on(pn()),mainnetLockedBalance:on(pn()),mainnetLockedBalanceUpdatedAt:on(pn()),testnetLockedBalance:on(pn()),testnetLockedBalanceUpdatedAt:on(pn()),defaultAddress:pn(),isVisible:rn(),source:hn(["merchant","user","republic"]),addresses:tn(nn((()=>Bn))),ownershipType:pn(),priceConversion:ln(pn()),changePercentageLast24h:ln(pn()),createdAt:pn(),updatedAt:pn(),merchant:an([nn((()=>qn))])}),Mn=dn({id:pn(),name:pn(),nameSlugify:pn()}),Wn=dn({address:pn(),topics:tn(pn()),data:pn(),transactionIndex:cn()}),Fn=dn({event:pn(),args:un(pn(),fn([pn(),cn(),rn()]))}),Gn=dn({message:on(pn()),txLogs:on(tn(nn((()=>Wn)))),txLogsDecoded:on(tn(nn((()=>Fn)))),reqSignature:pn(),reason:on(pn()),requestId:on(pn()),signatureUsed:rn()}),jn=dn({id:pn(),reference:on(pn()),hash:ln(on(pn())),merchantId:pn(),userEmail:pn(),chainId:pn(),chainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:cn(),fromWalletId:pn(),fromAddress:pn(),toWalletId:pn(),toAddress:pn(),assetId:pn(),assetSymbol:pn(),tokenType:hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]),amount:pn(),fee:pn(),note:pn(),nonce:cn(),gasPrice:cn(),submitter:pn(),status:hn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:on(hn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:hn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:pn(),networkEnvironment:on(hn(["mainnet","testnet"])),statusCheckAttempts:cn(),statusCheckedAt:on(pn()),createdAt:pn(),updatedAt:pn(),asset:an([nn((()=>ti))]),merchant:an([nn((()=>ri))]),adminTransactions:tn(nn((()=>Gn))),user:ln(nn((()=>Nn))),chain:nn((()=>li)),splitCoins:pn(),transferObjects:pn()}),Hn=dn({id:cn(),contractTypeName:pn(),assetContracts:tn(nn((()=>$n)))}),$n=dn({configId:pn(),contractTypeId:cn(),contractAddress:pn(),assetConfig:an([nn((()=>ti))]),contractType:an([nn((()=>Hn))])}),Yn=dn({id:pn(),merchantId:pn(),configId:pn(),chainId:pn(),chainName:pn(),assetName:pn(),assetSymbol:pn(),isVisible:rn(),isDefault:rn(),createdAt:pn(),updatedAt:pn(),merchant:an([nn((()=>ri))]),config:an([nn((()=>ti))]),chain:an([nn((()=>li))])}),zn=dn({id:pn(),typeName:pn(),createdAt:pn(),updatedAt:pn()}),Jn=dn({id:pn(),objectId:pn(),packageId:pn(),moduleName:pn(),structName:pn(),coinType:pn(),createdAt:an([nn((()=>zn))]),updatedAt:pn()}),Xn=dn({id:pn(),chainId:pn(),swapProviderId:pn(),providerChainIdentifier:pn(),chain:an([nn((()=>li))]),swapProvider:an([nn((()=>Zn))]),providerAssets:tn(nn((()=>Qn))),createdAt:pn(),updatedAt:pn()}),Zn=dn({id:pn(),name:pn(),explorerBaseUrl:pn(),isActive:rn(),chainMappings:tn(nn((()=>Xn))),providerAssets:tn(nn((()=>Qn))),createdAt:pn(),updatedAt:pn()}),Qn=dn({id:pn(),assetConfigId:pn(),swapProviderId:pn(),chainProviderMappingId:pn(),providerAssetIdentifier:pn(),lastSynced:ln(pn()),isEnabled:rn(),assetConfig:an([nn((()=>ti))]),swapProvider:an([nn((()=>Zn))]),chainProviderMapping:an([nn((()=>Xn))]),createdAt:pn(),updatedAt:pn()}),ei=dn({id:pn(),config:nn((()=>ti)),configId:pn(),timestamp:pn(),createdAt:pn()}),ti=dn({id:pn(),chainId:pn(),merchantId:ln(on(pn())),chainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),name:pn(),symbol:pn(),verified:ln(rn()),isOffChain:ln(rn()),decimals:cn(),iconUrl:ln(pn()),ticker:ln(on(pn())),type:ln(hn(["COIN","TOKEN","OBJECT"])),tokenStandard:ln(on(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]))),assetIndex:ln(on(cn())),contractAddress:ln(on(pn())),description:ln(on(pn())),ownershipType:ln(hn(["SINGLE_OWNER","MULTI_SIG"])),ownerAddresses:ln(on(tn(pn()))),status:ln(hn(["active","inactive","archived"])),createdByUserId:ln(on(pn())),createdByMerchantId:ln(on(pn())),relayerAddress:ln(pn()),contractVersion:ln(pn()),chain:ln(nn((()=>li))),createdByMerchant:ln(an([nn((()=>Mn))])),usersAssets:ln(tn(nn((()=>Vn)))),transactions:ln(tn(nn((()=>jn)))),assetContracts:ln(tn(nn((()=>$n)))),merchantAssets:ln(tn(nn((()=>Yn)))),createdByUser:ln(nn((()=>Nn))),suiConfig:ln(nn((()=>Jn))),isAssetReady:rn(),extendedConfiguration:ln(un(pn(),en())),requiresKyc:rn(),swapProviderAssets:ln(tn(nn((()=>Qn)))),tokenDistributions:ln(tn(nn((()=>ei))))}),ri=dn({id:pn(),name:pn(),nameSlugify:pn(),verified:rn(),contactEmail:pn(),contactPhoneNumber:pn(),usersCount:cn(),assetsCount:cn(),tokensCount:cn(),coinsCount:cn(),walletsCount:cn(),status:hn(["active","inactive","invalidated"]),createdAt:pn(),updatedAt:pn(),createdAssets:tn(nn((()=>ti))),merchantAssets:ln(tn(nn((()=>Yn))))}),si=dn({id:cn(),name:hn(["wallaby_share","owner_main_device_share","owner_backup_device_share"]),keyShares:tn(nn((()=>ai)))}),ai=dn({id:pn(),user:nn((()=>Nn)),wallet:nn((()=>oi)),encryptedKey:pn(),type:nn((()=>si)),createdAt:pn(),updatedAt:pn(),migratedWallabyShareAt:ln(on(pn())),wrappingPublicKey:ln(pn()),migrationStatus:hn(["not_required","pending","migrated","failed"]),migrationErrorMessage:ln(on(pn()))}),ni=dn({id:cn(),roles:tn(hn(["single_sig","shares_single_owner","pooled_custodial","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),wallets:tn(nn((()=>oi)))}),ii=dn({id:pn(),walletId:pn(),userId:pn(),shareCount:cn(),createdAt:pn(),updatedAt:pn()}),oi=dn({id:pn(),userId:pn(),merchantId:pn(),revisionId:pn(),revisionName:pn(),hashedSeedPhraseSalt:pn(),hashedEthAddressSalt:pn(),recoveryCount:cn(),assetsCount:cn(),createdAt:pn(),updatedAt:pn(),lastVerifiedAt:on(pn()),userAssets:ln(tn(nn((()=>Vn)))),merchant:ln(nn((()=>ri))),keyShares:ln(tn(nn((()=>ai)))),type:nn((()=>ni)),creationType:ln(on(hn(["user_imported","user_created"]))),keyMigrationStatus:hn(["not_required","pending","migrated","failed"]),migrationErrorMessage:ln(on(pn())),walletAddresses:ln(tn(nn((()=>di)))),walletKeks:ln(tn(nn((()=>ii))))}),ci=dn({id:cn(),name:hn(["BTC:MAINNET:SEGWIT","BTC:MAINNET:LEGACY","BTC:TESTNET:SEGWIT","BTC:TESTNET:LEGACY","ETH:ALL:DEFAULT","ALGO:ALL:DEFAULT","SUI:ALL:DEFAULT","INJ:ALL:DEFAULT","APT:ALL:DEFAULT","SOL:ALL:DEFAULT","POLYX:ALL:DEFAULT","BSC:ALL:DEFAULT","AVAX:ALL:DEFAULT","POL:ALL:DEFAULT","BASE:ALL:DEFAULT","SEI:ALL:DEFAULT","HBAR:ALL:DEFAULT","CC:ALL:DEFAULT"]),walletAddresses:nn((()=>di))}),di=dn({id:pn(),walletId:pn(),wallet:nn((()=>oi)),chain:nn((()=>li)),typeId:cn(),type:nn((()=>ci)),address:pn(),publicKey:pn(),createdAt:pn(),updatedAt:pn()}),li=dn({id:pn(),name:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),isEvm:rn(),iconUrl:ln(on(pn())),mainnetId:ln(pn()),mainnetIndexUrl:ln(on(pn())),mainnetExplorerUrl:ln(pn()),testnetId:ln(pn()),testnetExplorerUrl:ln(on(pn())),testnetIndexUrl:ln(on(pn())),derivationPath:ln(on(pn())),addressRegex:ln(on(pn())),slip44:hn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767]),signatureScheme:ln(hn(["secp256k1","ed25519","sr25519"])),status:ln(hn(["UP","DOWN"])),search:ln(pn()),createdAt:pn(),updatedAt:pn(),walletAddresses:ln(tn(nn((()=>di)))),isChainReady:rn(),supportsSwaps:rn(),swapChainMappings:ln(tn(nn((()=>Xn)))),indexUrl:ln(on(pn())),chainId:ln(pn())}),hi=dn({pagination:an([nn((()=>Un))]),chains:tn(nn((()=>li)))}),ui=dn({name:pn(),isEvm:rn(),mainnetRpcUrl:pn(),mainnetIndexUrl:ln(pn()),testnetId:ln(pn()),testnetRpcUrl:pn(),testnetIndexUrl:pn(),derivationPath:pn(),addressRegex:pn(),slip44:cn(),signatureScheme:hn(["secp256k1","ed25519","sr25519"])}),pi=dn({chain:nn((()=>li))}),yi=dn({name:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),isEvm:ln(rn()),mainnetId:ln(pn()),mainnetRpcUrl:ln(pn()),mainnetIndexUrl:ln(pn()),testnetId:ln(pn()),testnetRpcUrl:ln(pn()),testnetIndexUrl:ln(pn()),derivationPath:ln(pn()),addressRegex:ln(pn()),slip44:ln(hn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767])),signatureScheme:ln(hn(["secp256k1","ed25519","sr25519"])),supportSwaps:ln(rn())}),fi=dn({chain:nn((()=>li))}),gi=dn({pagination:an([nn((()=>Un))]),assets:tn(nn((()=>ti)))}),wi=dn({asset:nn((()=>ti))}),mi=dn({chainId:pn(),name:pn(),symbol:pn(),verified:ln(rn()),isOffChain:ln(rn()),decimals:cn(),iconUrl:ln(pn()),ticker:pn(),type:hn(["COIN","TOKEN","OBJECT"]),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),assetIndex:ln(cn()),contractAddress:ln(pn()),description:ln(pn()),createdByUserId:ln(pn()),createdByMerchantId:ln(pn()),suiObjectId:ln(pn()),relayerAddress:ln(pn()),isAssetReady:ln(rn()),requiresKyc:ln(rn())}),vi=dn({asset:nn((()=>ti))}),Si=dn({name:ln(pn()),symbol:ln(pn()),isOffChain:ln(rn()),decimals:ln(cn()),iconUrl:ln(pn()),ticker:ln(pn()),type:ln(hn(["COIN","TOKEN","OBJECT"])),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),assetIndex:ln(cn()),contractAddress:ln(pn()),relayerAddress:ln(pn()),description:ln(pn()),suiObjectId:ln(pn())}),_i=dn({asset:nn((()=>ti))}),Ai=dn({message:pn()}),Ei=dn({pagination:an([nn((()=>Un))]),merchants:tn(nn((()=>ri)))}),bi=dn({name:pn(),contactEmail:pn(),contactPhoneNumber:ln(pn()),status:ln(hn(["active","inactive","invalidated"]))}),Ii=dn({name:ln(pn()),contactEmail:ln(pn()),contactPhoneNumber:ln(pn()),status:ln(hn(["active","inactive","invalidated"]))}),Pi=dn({merchant:nn((()=>ri))}),Ti=dn({merchant:nn((()=>ri))}),ki=dn({pagination:an([nn((()=>Un))]),merchant:nn((()=>ri)),assets:ln(tn(nn((()=>Yn)))),merchantAssets:tn(nn((()=>Yn)))}),Ci=dn({id:pn(),name:ln(pn())}),xi=dn({id:pn(),externalUserId:pn(),walletsCount:cn(),createdAt:pn(),updatedAt:pn(),merchantId:ln(pn()),firstName:ln(pn()),email:ln(pn()),role:ln(hn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),polymeshDID:ln(pn()),userMerchants:ln(tn(nn((()=>Ci))))}),Ki=dn({pagination:an([nn((()=>Un))]),merchant:nn((()=>ri)),users:tn(nn((()=>xi)))}),Oi=dn({merchantId:pn(),email:pn(),firstName:pn(),lastName:pn(),role:pn()}),Ni=dn({message:ln(pn()),user:nn((()=>xi))}),Ri=dn({message:ln(pn()),user:nn((()=>xi))}),Di=dn({pagination:an([nn((()=>Un))]),merchant:nn((()=>ri)),wallets:tn(nn((()=>oi)))}),Li=dn({assetConfigId:pn(),userId:pn(),walletId:pn()}),Ui=dn({merchantId:pn(),assets:tn(nn((()=>Li))),updateExistingWallets:ln(rn())}),Bi=dn({message:ln(pn())}),qi=dn({merchantId:pn(),assetConfigId:ln(pn()),isDefault:ln(rn()),addToExistingWallets:ln(rn()),addToWallets:ln(tn(pn())),config:ln(nn((()=>ti)))}),Vi=dn({message:ln(pn()),merchantAsset:nn((()=>Yn))}),Mi=dn({merchantId:pn(),assetConfigId:pn()}),Wi=dn({message:ln(pn())}),Fi=dn({merchantId:pn(),assetConfigId:pn(),isVisible:rn()}),Gi=dn({message:ln(pn()),merchantAsset:nn((()=>Yn))}),ji=dn({merchantId:pn(),assetConfigId:pn(),isDefault:rn()}),Hi=dn({message:ln(pn()),merchantAsset:nn((()=>Yn))}),$i=dn({iv:pn(),ephemPublicKey:pn(),ciphertext:pn(),mac:pn()}),Yi=dn({id:pn(),merchantId:ln(pn()),appName:pn(),ipAddresses:tn(pn()),domainNames:tn(pn()),status:hn(["active","inactive"]),clientJWTPubKey:pn(),usersCount:cn(),requestsCount:cn(),totalRequestSizeInKb:cn(),totalResponseSizeInKb:cn(),totalResponseTimeInKb:cn(),lastRequestAt:on(pn()),onlyDashboardAccess:rn(),allowMobileAccess:rn(),createdAt:pn(),updatedAt:pn(),merchant:ln(nn((()=>ri))),origins:ln(tn(nn((()=>zi))))}),zi=dn({id:pn(),merchantId:ln(pn()),apiKeyId:pn(),origin:pn(),createdAt:pn(),updatedAt:pn(),merchant:ln(nn((()=>ri))),apiKey:ln(nn((()=>Yi)))}),Ji=dn({id:pn(),merchantId:pn(),appName:pn(),apiKey:nn((()=>$i)),status:hn(["active","inactive"]),clientJWTPubKey:pn(),allowMobileAccess:rn(),createdAt:pn(),updatedAt:pn(),origins:ln(tn(nn((()=>zi))))}),Xi=dn({pagination:an([nn((()=>Un))]),apiKeys:tn(nn((()=>Ji)))}),Zi=dn({pagination:an([nn((()=>Un))]),apiKeyOrigins:tn(nn((()=>zi)))}),Qi=dn({clientJWTPubKey:ln(pn()),wrappingPublicKey:ln(pn()),allowMobileAccess:ln(rn()),appName:ln(pn())}),eo=dn({message:ln(pn()),apiKey:nn((()=>Ji)),clientJWTPrivKey:ln(an([nn((()=>$i))]))}),to=dn({merchantId:pn(),apiKeyId:pn(),origins:tn(pn())}),ro=dn({message:ln(pn()),apiKeyOrigins:tn(nn((()=>zi)))}),so=dn({clientJWTPubKey:ln(pn()),wrappingPublicKey:pn(),appName:ln(pn()),status:ln(hn(["active","inactive"])),allowMobileAccess:ln(rn())}),ao=dn({message:ln(pn()),apiKey:nn((()=>Ji))}),no=dn({pagination:an([nn((()=>Un))]),wallets:tn(nn((()=>oi)))}),io=dn({message:pn(),clientAuthPubKey:pn(),signature:pn()}),oo=dn({id:pn(),userId:pn(),merchantId:pn(),chainId:pn(),userAssetAddress:pn(),walletId:pn(),configId:pn(),assetName:pn(),assetSymbol:pn(),balance:on(pn()),balanceUpdatedAt:on(pn()),claimableBalance:ln(on(pn())),claimableBalanceUpdatedAt:ln(on(pn())),claimablePaymentTokenContractAddress:ln(on(pn())),claimablePaymentTokenAssetConfigId:ln(on(pn())),lockedTokenBalance:on(pn()),lockedTokenBalanceUpdatedAt:on(pn()),mainnetBalance:on(pn()),mainnetBalanceUpdatedAt:on(pn()),testnetBalance:on(pn()),testnetBalanceUpdatedAt:on(pn()),mainnetLockedBalance:on(pn()),mainnetLockedBalanceUpdatedAt:on(pn()),testnetLockedBalance:on(pn()),testnetLockedBalanceUpdatedAt:on(pn()),defaultAddress:pn(),isVisible:rn(),source:hn(["merchant","user","republic"]),addresses:tn(nn((()=>Bn))),ownershipType:pn(),priceConversion:ln(pn()),changePercentageLast24h:ln(pn()),createdAt:pn(),updatedAt:pn(),merchant:an([nn((()=>qn))]),config:nn((()=>ti))}),co=dn({id:pn(),userId:pn(),revisionName:pn()}),lo=dn({iv:pn(),ephemPublicKey:pn(),ciphertext:pn(),mac:pn()}),ho=dn({encrypted:an([nn((()=>lo))]),wrappingPublicKey:pn(),type:hn(["wallaby_share","owner_main_device_share","owner_backup_device_share"])}),uo=dn({v:cn(),iv:pn(),ciphertext:pn(),tag:pn()}),po=dn({address:pn(),type:hn(["BTC:MAINNET:SEGWIT","BTC:MAINNET:LEGACY","BTC:TESTNET:SEGWIT","BTC:TESTNET:LEGACY","ETH:ALL:DEFAULT","ALGO:ALL:DEFAULT","SUI:ALL:DEFAULT","INJ:ALL:DEFAULT","APT:ALL:DEFAULT","SOL:ALL:DEFAULT","POLYX:ALL:DEFAULT","BSC:ALL:DEFAULT","AVAX:ALL:DEFAULT","POL:ALL:DEFAULT","BASE:ALL:DEFAULT","SEI:ALL:DEFAULT","HBAR:ALL:DEFAULT","CC:ALL:DEFAULT"]),chainId:pn(),chainName:pn()}),yo=dn({wallabyAuthPubKey:ln(pn()),assets:tn(nn((()=>oo))),encryptedSeed:ln(fn([nn((()=>lo)),nn((()=>uo))])),wallet:an([nn((()=>co))]),shares:ln(tn(nn((()=>ho)))),encryptedBackupShare:ln(an([nn((()=>uo))])),reference:ln(pn()),encryptedSeedForSharesSplit:ln(nn((()=>lo))),walletAddressesInfo:tn(nn((()=>po)))}),fo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedShares:ln(tn(nn((()=>lo)))),encryptedSeed:ln(an([nn((()=>lo))])),walletId:pn()}),go=dn({isAccessVerified:rn()}),wo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),adminWalletTypes:tn(hn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]))}),mo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),returnWalletOption:hn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:pn(),numShares:ln(cn()),threshold:ln(cn()),wallabyKeepsOne:ln(rn()),backupDevicePublicKey:ln(pn()),walletOwnershipType:ln(hn(["SINGLE_OWNER"]))}),vo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedSeed:an([nn((()=>lo))]),walletId:ln(pn()),returnWalletOption:hn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:pn(),numShares:ln(cn()),threshold:ln(cn()),wallabyKeepsOne:ln(rn()),backupDevicePublicKey:ln(pn()),walletOwnershipType:ln(hn(["SINGLE_OWNER"]))}),So=dn({clientAuthPubKey:pn(),walletId:pn(),encryptedBackupShare:fn([nn((()=>uo)),nn((()=>$i))])}),_o=dn({reference:pn(),share:an([nn((()=>ho))])}),Ao=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedSeed:an([nn((()=>lo))]),walletId:ln(pn())}),Eo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo)))),chainName:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]))}),bo=dn({id:pn(),walletId:pn(),typeId:cn(),type:nn((()=>ci)),address:pn(),publicKey:pn()}),Io=dn({walletAddressesInfo:tn(nn((()=>po))),walletAddresses:tn(nn((()=>bo)))}),Po=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),encryptedShares:tn(nn((()=>lo))),chain:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),accountIndexes:tn(cn()),startingAddressIndex:ln(cn())}),To=dn({accountIndex:cn(),addresses:un(pn(),pn())}),ko=dn({walletId:pn(),chain:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),accounts:tn(nn((()=>To)))}),Co=dn({pagination:an([nn((()=>Un))]),assets:tn(nn((()=>oo))),groupedAssets:ln(un(pn(),tn(nn((()=>oo))))),walletAddressesInfo:tn(nn((()=>po)))}),xo=dn({pagination:an([nn((()=>Un))]),addresses:tn(nn((()=>po)))}),Ko=dn({assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])}),Oo=dn({configId:pn(),assetName:ln(pn()),assetSymbol:ln(pn()),isVisible:ln(rn()),walletId:pn()}),No=dn({userAsset:an([nn((()=>oo))]),message:pn()}),Ro=dn({fromAssetConfigId:pn(),toAssetConfigId:pn(),fromAmount:ln(pn()),toAmount:ln(pn()),slippage:ln(cn())}),Do=dn({amount:pn(),amountUSD:ln(on(pn())),symbol:ln(pn()),icon:ln(pn())}),Lo=dn({id:pn(),gasFee:ln(tn(nn((()=>Do)))),providerFee:ln(tn(nn((()=>Do)))),republicFee:ln(tn(nn((()=>Do)))),allowanceFee:ln(tn(nn((()=>Do)))),fromAssetConfigId:pn(),fromAssetSymbol:pn(),fromAssetChain:pn(),toAssetConfigId:pn(),toAssetSymbol:pn(),toAssetChain:pn(),fromAmount:pn(),fromAddress:pn(),toAmount:pn(),toAddress:pn(),slippage:cn(),expiresAt:ln(pn())}),Uo=dn({id:pn(),fromAssetSymbol:pn(),fromAssetChainName:pn(),toAssetSymbol:pn(),toAssetChainName:pn(),fromAddress:pn(),toAddress:pn(),fromAmount:pn(),toAmount:pn(),slippage:cn(),gasFee:ln(on(tn(nn((()=>Do))))),providerFee:ln(on(tn(nn((()=>Do))))),republicFee:ln(on(tn(nn((()=>Do))))),allowanceFee:ln(on(tn(nn((()=>Do))))),status:hn(["quote","executing","in_progress","completed","failed","abandoned","execution_failed","invalid"]),executedAt:on(pn()),completedAt:on(pn()),transactionId:on(pn()),transactionHash:on(pn()),explorerLink:on(pn())}),Bo=dn({pagination:an([nn((()=>Un))]),swaps:tn(nn((()=>Uo)))}),qo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),quoteId:pn(),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo))))}),Vo=dn({swapQuoteId:pn(),status:pn(),explorerLink:pn(),transactionHash:pn()}),Mo=dn({id:pn(),reference:on(pn()),hash:ln(on(pn())),merchantId:pn(),userEmail:pn(),chainId:pn(),chainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:cn(),fromWalletId:pn(),fromAddress:pn(),toWalletId:pn(),toAddress:pn(),assetId:pn(),assetSymbol:pn(),tokenType:hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]),amount:pn(),fee:pn(),note:pn(),nonce:cn(),gasPrice:cn(),submitter:pn(),status:hn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:on(hn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:hn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:pn(),networkEnvironment:on(hn(["mainnet","testnet"])),statusCheckAttempts:cn(),statusCheckedAt:on(pn()),createdAt:pn(),updatedAt:pn(),asset:an([nn((()=>ti))]),merchant:an([nn((()=>ri))]),adminTransactions:tn(nn((()=>Gn))),user:ln(nn((()=>Nn))),chain:nn((()=>li)),splitCoins:pn(),transferObjects:pn(),type:ln(hn(["INCOMING","OUTGOING","SWAP","UNKNOWN"])),entryType:ln(hn(["INCOMING","OUTGOING","SWAP","UNKNOWN"]))}),Wo=dn({pagination:an([nn((()=>Un))]),transactions:tn(nn((()=>Mo)))}),Fo=dn({id:pn(),amount:pn(),sender:pn(),asset:ln(an([nn((()=>ti))])),expires:ln(pn())}),Go=dn({transactions:tn(nn((()=>Fo)))}),jo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),id:pn(),choice:hn(["approve","deny"]),symbol:pn(),chainName:pn(),walletId:pn(),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo))))}),Ho=dn({id:pn(),status:hn(["confirmed","denied"]),hash:ln(pn()),asset:ln(an([nn((()=>ti))]))}),$o=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),recipientAddress:pn(),assetId:pn(),amount:pn(),reference:pn(),encryptedSeed:an([nn((()=>lo))]),memo:ln(pn()),transactionType:ln(hn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"]))}),Yo=dn({transaction:an([nn((()=>jn))]),message:ln(pn())}),zo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),recipientAddress:pn(),assetId:pn(),amount:pn(),reference:pn(),memo:ln(pn()),transactionType:ln(hn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"])),encryptedShares:tn(nn((()=>lo)))}),Jo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),reference:pn(),note:ln(pn()),encryptedSeed:an([nn((()=>lo))]),assetIndex:cn()}),Xo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),reference:pn(),note:ln(pn()),encryptedSeed:an([nn((()=>lo))]),appIndex:cn()}),Zo=dn({feePaymentSymbol:pn(),fee:pn(),lowestFee:ln(pn()),highestFee:ln(pn())}),Qo=dn({address:tn(pn()),amount:pn(),txId:pn()}),ec=dn({status:hn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionHash:pn(),reference:pn(),assetSymbol:pn(),transactionValue:pn(),fromAddress:pn(),toAddress:pn(),chain:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),fee:pn(),nonce:ln(cn()),timestamp:ln(cn()),blockNumber:ln(cn()),memo:ln(pn()),origins:ln(tn(nn((()=>Qo)))),recipients:ln(tn(nn((()=>Qo))))}),tc=dn({canTransfer:rn(),restrictionCode:pn(),tokenContractAddress:pn(),fromAddress:pn(),toAddress:pn(),value:pn(),assetId:pn()}),rc=dn({restrictionCode:cn(),restrictionCodeMessage:pn()}),sc=dn({canTransfer:rn(),message:pn(),restrictionCode:pn()}),ac=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),ownerAddress:pn(),spenderAddress:pn(),amount:pn(),reference:pn(),memo:ln(pn()),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo)))),chainName:ln(pn()),assetSymbol:ln(pn()),assetId:ln(pn()),contractAddress:ln(pn())}),nc=dn({transaction:an([nn((()=>jn))])}),ic=dn({paymentTokenContractAddress:pn(),assetConfigId:pn(),balance:pn()}),oc=dn({address:pn(),assetSymbol:pn(),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),tokenType:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),chainName:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:ln(pn()),balance:on(pn()),claimable:ln(an([nn((()=>ic))])),lockedTokenBalance:ln(on(pn())),unlockedTokenBalance:ln(pn()),stakedBalance:ln(pn()),claimableBalance:ln(pn()),assetConfigId:ln(pn()),balanceUpdatedAt:ln(pn())}),cc=dn({address:pn(),assetSymbol:pn(),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),tokenType:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),chainName:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:ln(pn())}),dc=dn({assets:tn(nn((()=>cc)))}),lc=dn({balances:tn(nn((()=>oc)))}),hc=dn({walletId:pn()}),uc=dn({assetSymbol:ln(pn()),timestamp:cn(),from:pn(),gas:cn(),gasPrice:ln(pn()),gasUsed:ln(cn()),hash:pn(),input:ln(pn()),nonce:ln(cn()),to:pn(),value:pn(),amount:ln(pn()),memo:ln(pn()),tokenTransfers:ln(tn(un(pn(),en()))),transactionType:ln(pn()),status:hn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),origins:ln(tn(nn((()=>Qo)))),recipients:ln(tn(nn((()=>Qo)))),createdAt:pn()}),pc=dn({address:pn(),transactions:tn(nn((()=>uc)))}),yc=dn({decimals:cn(),symbol:pn(),name:pn(),tokenContractAddress:ln(pn())}),fc=dn({symbol:pn(),price:pn(),changePercentageLast24h:ln(pn())}),gc=dn({data:tn(nn((()=>fc)))}),wc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedShares:tn(nn((()=>lo))),recoveryPubKey:ln(pn()),walletId:pn()}),mc=dn({encryptedSeed:an([nn((()=>lo))])}),vc=dn({pagination:an([nn((()=>Un))]),users:tn(nn((()=>xi)))}),Sc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),email:ln(pn()),firstName:ln(pn()),lastName:ln(pn())}),_c=dn({message:pn(),user:ln(an([nn((()=>Nn))]))}),Ac=dn({user:an([nn((()=>xi))])}),Ec=dn({clientSalt:pn()}),bc=dn({wallets:tn(nn((()=>oi)))}),Ic=dn({pagination:an([nn((()=>Un))]),assets:tn(nn((()=>Vn))),groupedAssets:ln(un(pn(),tn(nn((()=>Vn)))))}),Pc=dn({name:pn(),symbol:pn(),decimals:cn(),contractAddress:pn(),chainId:ln(pn()),chainName:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),ticker:ln(pn()),iconUrl:ln(pn())}),Tc=dn({assetConfigId:ln(pn()),walletId:pn(),userId:ln(pn()),config:ln(an([nn((()=>Pc))])),message:ln(pn()),clientAuthPubKey:ln(pn()),signature:ln(pn()),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo))))}),kc=dn({asset:an([nn((()=>Vn))])}),Cc=dn({message:pn()}),xc=dn({user:an([nn((()=>xi))])}),Kc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),releaseCount:cn(),delayUntilFirstReleaseInSeconds:cn(),initialReleasePortionInBips:cn(),periodBetweenReleasesInSeconds:cn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Oc=dn({reference:pn()}),Nc=dn({address:pn(),amount:pn(),commencementTimestamp:ln(cn()),scheduleId:ln(cn()),cancelableBy:ln(tn(pn()))}),Rc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),mints:tn(nn((()=>Nc))),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Dc=dn({references:tn(nn((()=>Oc)))}),Lc=dn({address:pn(),amount:pn(),commencementTimestamp:ln(cn()),scheduleId:ln(cn()),timelockIndex:ln(cn()),reclaimTokenTo:ln(pn())}),Uc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),burns:tn(nn((()=>Lc))),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Bc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:pn(),payerAddress:pn(),tokenRecipientAddress:pn(),originatorPurchaseAmount:pn(),mintAmount:pn(),adminFeeAmount:pn(),totalAmount:pn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),qc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:pn(),payerAddress:pn(),tokenRecipientAddress:pn(),originatorPurchaseAmount:pn(),mintAmount:pn(),prefundedInterestAmount:pn(),adminFeeExcludingPrefundedInterestAmount:pn(),totalAmount:pn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Vc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),owner:pn(),regions:tn(pn()),accreditationType:cn(),lastAmlKycChangeTimestamp:cn(),lastAccreditationChangeTimestamp:cn(),amlKycPassed:rn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Mc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),wallet:pn(),amount:pn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Wc=dn({assetSymbol:pn(),blockchainName:pn(),releaseCount:cn(),delayUntilFirstReleaseInSeconds:cn(),initialReleasePortionInBips:cn(),periodBetweenReleasesInSeconds:cn(),scheduleId:cn()}),Fc=dn({adminTransaction:an([nn((()=>Gn))])}),Gc=dn({status:hn(["QUEUED","PENDING","SUCCESS","FAILED"]),message:ln(pn()),txHash:ln(pn()),txLogs:ln(tn(nn((()=>Wn)))),txLogsDecoded:ln(tn(nn((()=>Fn)))),reqSignature:ln(pn()),clientRequestSignature:ln(pn()),requestId:ln(pn()),reason:ln(pn()),txId:ln(pn())}),jc=dn({message:pn()}),Hc=dn({chainsCount:cn(),chains:tn(nn((()=>li))),merchantsCount:cn(),merchants:tn(nn((()=>ri))),assetsCount:cn(),usersCount:cn(),users:tn(nn((()=>xi))),adminsCount:cn(),walletsCount:cn()}),$c=dn({id:pn(),userId:pn(),merchantId:pn(),action:ln(on(hn(["logged_in","logged_out","created_wallet","updated_wallet","deleted_wallet","created_merchant","updated_merchant","deleted_merchant"]))),requestUrl:pn(),requestMethod:pn(),createdAt:pn(),updatedAt:pn(),merchant:ln(nn((()=>ri)))}),Yc=dn({pagination:an([nn((()=>Un))]),activities:tn(nn((()=>$c)))}),zc=[{method:"GET",path:"/",response:nn((()=>gn))},{method:"GET",path:"/healthz",response:nn((()=>gn))},{method:"POST",path:"/auth/signature-message/external",request:nn((()=>wn)),response:nn((()=>mn))},{method:"POST",path:"/auth/signature-message",request:nn((()=>wn)),response:nn((()=>mn))},{method:"POST",path:"/auth/sign-up",request:nn((()=>vn)),response:nn((()=>_n))},{method:"POST",path:"/auth/sign-up/external",request:nn((()=>An)),response:nn((()=>_n))},{method:"POST",path:"/auth/sign-in",request:nn((()=>En)),response:nn((()=>_n))},{method:"POST",path:"/auth/issue-jwt-token",response:nn((()=>In))},{method:"POST",path:"/auth/refresh-access-token",request:nn((()=>Pn)),response:nn((()=>Tn))},{method:"POST",path:"/auth/logout",response:nn((()=>kn))},{method:"PUT",path:"/auth/client-auth-pubkey",request:nn((()=>Cn)),response:nn((()=>xn))},{method:"POST",path:"/auth/wallaby-auth-pubkey",request:nn((()=>Kn)),response:nn((()=>On))},{method:"GET",path:"/auth/passkey-credentials",response:nn((()=>Ln))},{method:"GET",path:"/chains",response:nn((()=>hi))},{method:"POST",path:"/chains",request:nn((()=>ui)),response:nn((()=>pi))},{method:"PUT",path:"/chains/{chainId}",request:nn((()=>yi)),response:nn((()=>fi))},{method:"GET",path:"/assets/configurations",response:nn((()=>gi))},{method:"POST",path:"/assets/configurations",request:nn((()=>mi)),response:nn((()=>vi))},{method:"GET",path:"/assets/configurations/{assetConfigId}",response:nn((()=>wi))},{method:"PUT",path:"/assets/configurations/{assetConfigId}",request:nn((()=>Si)),response:nn((()=>_i))},{method:"POST",path:"/assets/configurations/{assetConfigId}/verify",response:nn((()=>Ai))},{method:"DELETE",path:"/assets/configurations/{assetConfigId}/unverify",response:nn((()=>Ai))},{method:"POST",path:"/assets/configurations/{assetConfigId}/archive",response:nn((()=>Ai))},{method:"POST",path:"/assets/configurations/{assetConfigId}/unarchive",response:nn((()=>Ai))},{method:"GET",path:"/merchants",response:nn((()=>Ei))},{method:"POST",path:"/merchants",request:nn((()=>bi)),response:nn((()=>bi))},{method:"PUT",path:"/merchants/{merchantId}",request:nn((()=>Ii)),response:nn((()=>Pi))},{method:"GET",path:"/merchants/{merchantId}",response:nn((()=>Ti))},{method:"GET",path:"/merchants/{merchantId}/assets",response:nn((()=>ki))},{method:"GET",path:"/merchants/{merchantId}/users",response:nn((()=>Ki))},{method:"GET",path:"/merchants/{merchantId}/admins",response:nn((()=>Ki))},{method:"POST",path:"/merchants/admins/invite",request:nn((()=>Oi)),response:nn((()=>Ni))},{method:"DELETE",path:"/merchants/{merchantId}/admins/{userId}",response:nn((()=>Ri))},{method:"GET",path:"/merchants/{merchantId}/wallets",response:nn((()=>Di))},{method:"POST",path:"/merchants/wallets/add-assets",request:nn((()=>Ui)),response:nn((()=>Bi))},{method:"POST",path:"/merchants/assets/add",request:nn((()=>qi)),response:nn((()=>Vi))},{method:"DELETE",path:"/merchants/assets/delete",request:nn((()=>Mi)),response:nn((()=>Wi))},{method:"POST",path:"/merchants/assets/update-visibility",request:nn((()=>Fi)),response:nn((()=>Gi))},{method:"POST",path:"/merchants/assets/update-default-status",request:nn((()=>ji)),response:nn((()=>Hi))},{method:"GET",path:"/merchants/{merchantId}/api-keys",response:nn((()=>Xi))},{method:"POST",path:"/merchants/{merchantId}/api-keys",request:nn((()=>Qi)),response:nn((()=>eo))},{method:"GET",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/origins",response:nn((()=>Zi))},{method:"POST",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/whitelist-origins",request:nn((()=>to)),response:nn((()=>ro))},{method:"PUT",path:"/merchants/{merchantId}/api-keys/{apiKeyId}",request:nn((()=>so)),response:nn((()=>ao))},{method:"GET",path:"/wallets",response:nn((()=>no))},{method:"POST",path:"/wallets/create",request:nn((()=>io)),response:nn((()=>yo))},{method:"POST",path:"/wallets/verify-access",request:nn((()=>fo)),response:nn((()=>go))},{method:"POST",path:"/wallets/create-admin-server-wallet",request:nn((()=>wo)),response:nn((()=>yo))},{method:"POST",path:"/wallets/create-with-shares",request:nn((()=>mo)),response:nn((()=>yo))},{method:"POST",path:"/wallets/create-shares-based-wallet-from-seed",request:nn((()=>vo)),response:nn((()=>yo))},{method:"POST",path:"/wallets/add-new-device",request:nn((()=>So)),response:nn((()=>_o))},{method:"POST",path:"/wallets/import-seed-phrase",request:nn((()=>Ao)),response:nn((()=>yo))},{method:"POST",path:"/wallets/generate-wallet-addresses",request:nn((()=>Eo)),response:nn((()=>Io))},{method:"POST",path:"/wallets/derive-addresses/batch",request:nn((()=>Po)),response:nn((()=>ko))},{method:"GET",path:"/wallets/{walletId}/assets",response:nn((()=>Co))},{method:"GET",path:"/wallets/{walletId}/addresses",response:nn((()=>xo))},{method:"GET",path:"/wallets/asset",request:nn((()=>Ko)),response:nn((()=>oo))},{method:"PUT",path:"/wallets/asset/update",request:nn((()=>Oo)),response:nn((()=>No))},{method:"POST",path:"/wallets/{walletId}/swap/quote",request:nn((()=>Ro)),response:nn((()=>Lo))},{method:"GET",path:"/wallets/{walletId}/swaps",response:nn((()=>Bo))},{method:"GET",path:"/wallets/{walletId}/swaps/{swapId}",response:nn((()=>Uo))},{method:"POST",path:"/wallets/execute-swap",request:nn((()=>qo)),response:nn((()=>Vo))},{method:"GET",path:"/transactions",response:nn((()=>Wo))},{method:"GET",path:"/transactions/pending",response:nn((()=>Go))},{method:"POST",path:"/transactions/resolve",request:nn((()=>jo)),response:nn((()=>Ho))},{method:"POST",path:"/transactions/transfer",request:nn((()=>$o)),response:nn((()=>Yo))},{method:"POST",path:"/transactions/transfer-with-shares",request:nn((()=>zo)),response:nn((()=>Yo))},{method:"POST",path:"/transactions/asset-optin",request:nn((()=>Jo)),response:nn((()=>Yo))},{method:"POST",path:"/transactions/app-optin",request:nn((()=>Xo)),response:nn((()=>Yo))},{method:"GET",path:"/transactions/estimate-fee",response:nn((()=>Zo))},{method:"GET",path:"/transactions/status",response:nn((()=>ec))},{method:"GET",path:"/transactions/raw-status",response:nn((()=>jn))},{method:"GET",path:"/transactions/detect-transfers-restrictions",response:nn((()=>tc))},{method:"GET",path:"/transactions/transfer-restriction-message",response:nn((()=>rc))},{method:"GET",path:"/transactions/restriction",response:nn((()=>sc))},{method:"GET",path:"/transactions/check-asset-optin",response:tn(un(pn(),en()))},{method:"GET",path:"/transactions/check-app-optin",response:tn(un(pn(),en()))},{method:"POST",path:"/transactions/create-allowance",request:nn((()=>ac)),response:nn((()=>nc))},{method:"GET",path:"/query/assets/balance",response:nn((()=>oc))},{method:"GET",path:"/query/address/balance",response:nn((()=>oc))},{method:"POST",path:"/query/assets/bulk-balance",request:nn((()=>dc)),response:nn((()=>lc))},{method:"POST",path:"/query/assets/wallet-bulk-balance",request:nn((()=>hc)),response:nn((()=>lc))},{method:"GET",path:"/query/transactions",response:nn((()=>pc))},{method:"GET",path:"/query/fetch-token-info",response:nn((()=>yc))},{method:"GET",path:"/query/get-asset-price",response:nn((()=>gc))},{method:"POST",path:"/mpc/reconstruct-seed-phrase",request:nn((()=>wc)),response:nn((()=>mc))},{method:"GET",path:"/users",response:nn((()=>vc))},{method:"PUT",path:"/users/profile",request:nn((()=>Sc)),response:nn((()=>_c))},{method:"GET",path:"/users/profile",response:nn((()=>Ac))},{method:"GET",path:"/users/salt",response:nn((()=>Ec))},{method:"GET",path:"/users/{userId}/wallets",response:nn((()=>bc))},{method:"GET",path:"/users/merchants/assets",response:nn((()=>ki))},{method:"GET",path:"/users/merchant/assets",response:nn((()=>ki))},{method:"GET",path:"/users/{userId}/assets",response:nn((()=>Ic))},{method:"POST",path:"/users/assets/add",request:nn((()=>Tc)),response:nn((()=>kc))},{method:"DELETE",path:"/users/{userId}/wallets/{walletId}/assets/{assetConfigId}",response:nn((()=>Cc))},{method:"GET",path:"/users/{userId}",response:nn((()=>Ac))},{method:"GET",path:"/users/{externalUserId}/externalUserId",response:nn((()=>xc))},{method:"POST",path:"/transactions/admin/release-schedule",request:nn((()=>Kc)),response:nn((()=>Oc))},{method:"GET",path:"/transactions/admin/release-schedule",response:nn((()=>Wc))},{method:"POST",path:"/transactions/admin/mint",request:nn((()=>Rc)),response:nn((()=>Dc))},{method:"POST",path:"/transactions/admin/burn",request:nn((()=>Uc)),response:nn((()=>Dc))},{method:"POST",path:"/transactions/admin/execute-purchase",request:nn((()=>Bc)),response:nn((()=>Oc))},{method:"POST",path:"/transactions/admin/execute-purchase-with-interest",request:nn((()=>qc)),response:nn((()=>Oc))},{method:"POST",path:"/transactions/admin/set-identity",request:nn((()=>Vc)),response:nn((()=>Oc))},{method:"POST",path:"/transactions/admin/force-claim",request:nn((()=>Mc)),response:nn((()=>Oc))},{method:"POST",path:"/transactions/admin/force-claim-principal",request:nn((()=>Mc)),response:nn((()=>Oc))},{method:"GET",path:"/transactions/admin/{referenceId}",response:nn((()=>Fc))},{method:"POST",path:"/transactions/admin/callback",request:nn((()=>Gc)),response:nn((()=>jc))},{method:"GET",path:"/dashboard",response:nn((()=>Hc))},{method:"GET",path:"/users-activities",response:nn((()=>Yc))}],Jc=new Map,Xc=[];for(const e of zc)if(e.path.includes("{")){const t=e.path.replace(/\{[^/]+\}/g,"[^/]+");Xc.push({method:e.method,regex:new RegExp(`^${t}$`),entry:e})}else Jc.set(`${e.method} ${e.path}`,e);const Zc={response:{statusCode:200,errorCode:exports.ErrorResponseCodes.sdk_invalid_response,tag:"InvalidResponse"},request:{statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter,tag:"InvalidRequest"}};function Qc(e,t,r,s,a){var n;if("off"===a)return;const i=null===(n=function(e,t){const r=e.toUpperCase(),s=function(e){var t;const r=null!==(t=e.split("?")[0])&&void 0!==t?t:"";return(r.startsWith("/")?r:`/${r}`).replace(/^\/api\/v1/,"")||"/"}(t),a=Jc.get(`${r} ${s}`);if(a)return{request:a.request,response:a.response};const n=Xc.find((({method:e,regex:t})=>e===r&&t.test(s)));return n?{request:n.entry.request,response:n.entry.response}:void 0}(t,r))||void 0===n?void 0:n[e];if(!i)return;const o=function(e,t){const r=e["~run"]({value:t},ja());return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}(i,s);if(o.success)return;const c=`${t} ${r}: ${d=o.issues,d.slice(0,3).map((e=>{var t;return`${null!==(t=function(e){if(e.path){let t="";for(const r of e.path){if("string"!=typeof r.key&&"number"!=typeof r.key)return null;t+=t?`.${r.key}`:r.key}return t}return null}(e))&&void 0!==t?t:"<root>"}: expected ${e.expected}, got ${e.received}`})).join("; ")}`;var d;const{statusCode:l,errorCode:h,tag:u}=Zc[e];if("throw"===a)throw new V({kind:"validation",message:c,statusCode:l,errorCode:h,data:{method:t,path:r,issues:o.issues}});pe.warn(`SDK::ApiValidation::${u} ${c}`)}function ed({method:e,path:t,data:r,mode:s}){Qc("response",e,t,r,s)}function td({method:e,path:t,body:r,mode:s}){Qc("request",e,t,r,s)}const rd=new Set([exports.ErrorResponseCodes.auth_api_jwt_invalid,exports.ErrorResponseCodes.auth_api_jwt_not_active,exports.ErrorResponseCodes.auth_api_jwt_not_provided,exports.ErrorResponseCodes.auth_api_jwt_expired,exports.ErrorResponseCodes.auth_api_unauthorized]),sd=new Set([exports.ErrorResponseCodes.auth_refresh_token_not_found,exports.ErrorResponseCodes.auth_refresh_token_expired,exports.ErrorResponseCodes.auth_refresh_token_reuse_detected]);function ad(e){var t,r,s,a,n;return null!==(a=null!==(r=null!==(t=null==e?void 0:e.status)&&void 0!==t?t:null==e?void 0:e.statusCode)&&void 0!==r?r:null===(s=null==e?void 0:e.error)||void 0===s?void 0:s.statusCode)&&void 0!==a?a:null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.statusCode}function nd(e){var t,r,s,a;return null!==(s=null!==(t=null==e?void 0:e.errorCode)&&void 0!==t?t:null===(r=null==e?void 0:e.error)||void 0===r?void 0:r.errorCode)&&void 0!==s?s:null===(a=null==e?void 0:e.data)||void 0===a?void 0:a.errorCode}function id(e){if(401!==ad(e))return!1;const t=nd(e);return!t||rd.has(t)}const od=new class{constructor(){this.inFlightOperations=new Map}withDedupe(e,t){const r=this.inFlightOperations.get(e);if(r)return r;const s=Promise.resolve().then(t).finally((()=>{this.inFlightOperations.delete(e)}));return this.inFlightOperations.set(e,s),s}isInFlight(e){return this.inFlightOperations.has(e)}clearAll(){this.inFlightOperations.clear()}},cd=new Oa;class dd{constructor(t,r={}){var s,a,n,i,o;const c=Fa(t);this.apiKey=c.apiKey,this.baseUrl=c.baseUrl,this.userId=c.userId,this.options=c.options,(null===(s=this.options)||void 0===s?void 0:s.platform)&&(Se.platform=this.options.platform,Se.isNative="ios"===this.options.platform||"android"===this.options.platform,Se.isWeb=!Se.isNative),this.cipher=null!==(a=r.cipher)&&void 0!==a?a:new Ka,this.transport=null!==(n=r.transport)&&void 0!==n?n:(...e)=>fetch(...e),this.clock=null!==(i=r.clock)&&void 0!==i?i:{now:()=>Date.now()},this.lockManager=cd,this._initializeClientAuthToken(c.clientAuthToken),this.request=this.request.bind(this);const d=new e.H({baseUrl:this.baseUrl.replace(/\/api\/v1\/?$/,""),baseApiParams:{secure:!0},securityWorker:this.securityWorker.bind(this),customFetch:this.transport}),l=d.request.bind(d);d.request=async e=>{const t=async r=>{try{td({method:e.method,path:e.path,body:e.body,mode:this.validationMode});const t=await l(e);return ed({method:e.method,path:e.path,data:t,mode:this.validationMode}),t}catch(e){if(!r&&id(e))return await this._performTokenRefresh(),t(!0);if(null==e?void 0:e.error){const t=e.error;throw this.toWallabyError({message:t.message||"API request failed",statusCode:t.statusCode||e.status||500,errorCode:t.errorCode,data:t})}if(e instanceof V)throw e;throw this.toWallabyError({message:e.message||"Network request failed",statusCode:0,errorCode:"NETWORK_ERROR",data:{code:e.code||e.name,originalError:e},cause:e.cause})}};return t(!1)},this.api=new e.A(d),this.api.http.setSecurityData(Object.assign({"x-api-key":t.apiKey,"x-client-jwt":t.clientAuthToken},null===(o=this.options)||void 0===o?void 0:o.headers))}set setClientAuthToken(e){this._initializeClientAuthToken(e)}get version(){const e=_e;return pe.log(`wsdk is running v${e}`),e}_initializeClientAuthToken(e){if(t=e,r=this.userId,!t||!r||n.jwtDecode(t).externalUserId!==r)throw new V({message:"Client auth token does not match the user id. Blocking API call.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_jwt_invalid});var t,r;this.clientAuthToken=e,!function(e){return n.jwtDecode(e).mfaVerified}(e)?this.deviceAuthType=exports.AuthType.Passkey:this.deviceAuthType=exports.AuthType.Password}get deviceLocalStorage(){var e;if(null===(e=this.options)||void 0===e?void 0:e.storage)return this.options.storage;if("undefined"!=typeof window&&"localStorage"in window)return window.localStorage;throw new V({message:"Your device storage is not supported natively yet, please provide a custom storage in the config options.",statusCode:400,errorCode:"device_storage_unsupported"})}get validationMode(){var e,t;return null!==(t=null===(e=this.options)||void 0===e?void 0:e.runtimeValidation)&&void 0!==t?t:"throw"}get settings(){var e,t,r,s,a,n;return Object.freeze({apiKey:this.apiKey,baseUrl:this.baseUrl,environment:null!==(t=null===(e=this.options)||void 0===e?void 0:e.environment)&&void 0!==t?t:ge,network:null!==(s=null===(r=this.options)||void 0===r?void 0:r.network)&&void 0!==s?s:we,hostname:null!==(n=null===(a=this.options)||void 0===a?void 0:a.hostname)&&void 0!==n?n:"https://www.republic.com"})}get localStorageService(){var e;if(!this.clientAuthToken)throw new V({message:"A client authentication token (JWT) is required",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return null!==(e=this._localStorageService)&&void 0!==e?e:this._localStorageService=new Ra({deviceStorage:this.deviceLocalStorage,userId:this.userId,environment:this.settings.environment})}async _performTokenRefresh(e){const t=`refresh:${this.userId}:${this.settings.environment}:${this.settings.network}`;await od.withDedupe(t,(async()=>{var t;const r=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(r)try{const s=await this.request(Ba.refreshAccessToken,{payload:{refreshToken:r}},!1,null!==(t=null==e?void 0:e.silent)&&void 0!==t&&t);await this.localStorageService.save(exports.LocalStorageItems.AccessToken,s.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,s.refreshToken)}catch(e){throw function(e){const t=ad(e),r=nd(e);return 401===t||!!r&&sd.has(r)}(e)&&(await this.localStorageService.delete(exports.LocalStorageItems.AccessToken),await this.localStorageService.delete(exports.LocalStorageItems.RefreshToken)),e}}))}toWallabyError(e){var t,r;const s=new V(e);try{null===(r=null===(t=this.options)||void 0===t?void 0:t.onError)||void 0===r||r.call(t,s)}catch(e){pe.error("SDK::Base::toWallabyError::onError handler threw",{error:e})}return s}async request(e,t,r=!1,s=!1){var a;const n=e=>s?new V(e):this.toWallabyError(e);if(e!==Ba.refreshAccessToken&&!r){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(e&&La(e,60,this.clock.now))try{await this._performTokenRefresh({silent:!0})}catch(e){}}let i="string"==typeof e.fullPath?e.fullPath:e.fullPath(null==t?void 0:t.payload);(null==t?void 0:t.queryParams)&&(i+=`?${function(e){const t=new URLSearchParams;return Object.keys(e).forEach((r=>{null!==e[r]&&void 0!==e[r]&&""!==e[r]&&t.append(r,e[r])})),t.toString()}(t.queryParams)}`);const o=`${this.baseUrl}${i}`,c=Object.assign(Object.assign({},await this._getRequestHeaders()),null===(a=this.options)||void 0===a?void 0:a.headers);try{td({method:e.method,path:i,body:null==t?void 0:t.payload,mode:this.validationMode});const s={method:e.method,headers:c};e.method!==exports.RequestMethod.Get&&(null==t?void 0:t.payload)&&(s.body=JSON.stringify(t.payload)),pe.debug(`SDK::Base::${e.method}::Request`,{path:o,payload:null==t?void 0:t.payload});const a=await this.transport(o,s),d=a.headers.get("content-type");let l;if(null==d?void 0:d.includes("application/json"))l=await a.json();else{const e=await a.text();try{l=JSON.parse(e)}catch(t){l=e}}if(pe.debug(`SDK::Base::${e.method}::Response`,{status:a.status,statusText:a.statusText,data:l}),!a.ok){if(!r&&e!==Ba.refreshAccessToken&&id({status:a.status,errorCode:null==l?void 0:l.errorCode}))return await this._performTokenRefresh(),this.request(e,t,!0);throw n({message:(null==l?void 0:l.message)||a.statusText||"Request failed",statusCode:a.status,errorCode:null==l?void 0:l.errorCode,data:l})}return ed({method:e.method,path:i,data:l,mode:this.validationMode}),l}catch(t){if(t instanceof V)throw t;if(null==t?void 0:t.error){pe.error("SDK::Base::handleApiCall::API Error",{error:t});const e=t.error;throw n({message:e.message||"API request failed",statusCode:e.statusCode||500,errorCode:e.errorCode,data:e})}throw pe.error(`SDK::Base::${e.method}::NetworkError`,{message:t.message,name:t.name,error:t}),n({message:t.message||"Network request failed",statusCode:0,errorCode:"NETWORK_ERROR",data:{code:t.code||t.name,originalError:t},cause:t.cause})}}async _getRequestHeaders(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(Da(this.clientAuthToken,this.clock.now))throw new V({message:"Auth token has expired",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_jwt_expired});const t={"Content-Type":"application/json","x-api-key":this.settings.apiKey,"x-client-jwt":this.clientAuthToken,[Ae]:Ee};return e&&(t.Authorization="Bearer "+e),t}async securityWorker(e){try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&La(e,60,this.clock.now)&&await this._performTokenRefresh({silent:!0})}catch(e){}const t=Object.assign(Object.assign({"Content-Type":"application/json"},e||{}),{[Ae]:Ee});try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&(t.Authorization=`Bearer ${e}`)}catch(e){}return{headers:t}}}const ld={importSeedPhraseV2:{fullPath:"/wallets/create-shares-based-wallet-from-seed",method:exports.RequestMethod.Post,requiresAccessToken:!0},addNewDevice:{fullPath:"/wallets/add-new-device",method:exports.RequestMethod.Post,requiresAccessToken:!0},initKeyExchange:{fullPath:"/mpc/init-key-exchange",method:exports.RequestMethod.Post,requiresAccessToken:!0},retrieveSeedPhrase:{fullPath:"/mpc/reconstruct-seed-phrase",method:exports.RequestMethod.Post,requiresAccessToken:!0},createWithKeyShares:{fullPath:"/wallets/create-with-shares",method:exports.RequestMethod.Post,requiresAccessToken:!0},create:{fullPath:"/wallets/create",method:exports.RequestMethod.Post,requiresAccessToken:!0},import:{fullPath:"/wallets/import-seed-phrase",method:exports.RequestMethod.Post,requiresAccessToken:!0},getTokenBalance:{fullPath:({address:e,assetSymbol:t,chainName:r,tokenStandard:s})=>`/query/assets/balance?address=${e}&assetSymbol=${t}`+(s?`&tokenType=${s}`:"")+(r?`&chainName=${r}`:""),method:exports.RequestMethod.Get,requiresAccessToken:!1},getMultiTokenBalances:{fullPath:"/query/assets/bulk-balance",method:exports.RequestMethod.Post,requiresAccessToken:!1},getWalletBalances:{fullPath:"/query/assets/wallet-bulk-balance",method:exports.RequestMethod.Post,requiresAccessToken:!1},getWalletAssets:{fullPath:({walletId:e})=>`/wallets/${e}/assets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserAssets:{fullPath:({userId:e})=>`/users/${e}/assets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},addTokenToWallet:{fullPath:"/users/assets/add",method:exports.RequestMethod.Post,requiresAccessToken:!1},generateWalletAddresses:{fullPath:"/wallets/generate-wallet-addresses",method:exports.RequestMethod.Post,requiresAccessToken:!0},updateAsset:{fullPath:"/wallets/asset/update",method:exports.RequestMethod.Put,requiresAccessToken:!1},getUserWallets:{fullPath:({userId:e})=>`/users/${e}/wallets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},convertMnemonicSeedPhrase:{fullPath:"/wallets/convert-mnemonic-seed",method:exports.RequestMethod.Post,requiresAccessToken:!0},createMultisigAsset:{fullPath:"/wallets/create-multisig-asset",method:exports.RequestMethod.Post,requiresAccessToken:!0},verifyAccess:{fullPath:"/wallets/verify-access",method:exports.RequestMethod.Post,requiresAccessToken:!0}},hd={getSupportedBlockchains:{fullPath:"/chains",method:exports.RequestMethod.Get,requiresAccessToken:!1},getSupportedTokens:{fullPath:"/assets/configurations",method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserByExternalUserId:{fullPath:({externalUserId:e})=>`/users/${e}/externalUserId`,method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserData:{fullPath:({userId:e})=>`/users/${e}`,method:exports.RequestMethod.Get,requiresAccessToken:!1},fetchTokenInfo:{fullPath:()=>"/query/fetch-token-info",method:exports.RequestMethod.Get,requiresAccessToken:!1}},ud={transfer:{fullPath:"/transactions/transfer",method:exports.RequestMethod.Post,requiresAccessToken:!0},transferWithShares:{fullPath:"/transactions/transfer-with-shares",method:exports.RequestMethod.Post,requiresAccessToken:!0},createAllowance:{fullPath:"/transactions/create-allowance",method:exports.RequestMethod.Post,requiresAccessToken:!0},estimateFee:{fullPath:"/transactions/estimate-fee",method:exports.RequestMethod.Get,requiresAccessToken:!0},getTransaction:{fullPath:"/transactions/status",method:exports.RequestMethod.Get,requiresAccessToken:!0},getTransactions:{fullPath:"/transactions",method:exports.RequestMethod.Get,requiresAccessToken:!0},detectTransferRestrictions:{fullPath:"/transactions/detect-transfers-restrictions",method:exports.RequestMethod.Get,requiresAccessToken:!0},transferRestrictionMessage:{fullPath:"/transactions/transfer-restriction-message",method:exports.RequestMethod.Get,requiresAccessToken:!0},restriction:{fullPath:"/transactions/restriction",method:exports.RequestMethod.Get,requiresAccessToken:!0},getPendingTransactions:{fullPath:"/transactions/pending",method:exports.RequestMethod.Get,requiresAccessToken:!0},confirmPendingTransaction:{fullPath:"/transactions/resolve",method:exports.RequestMethod.Post,requiresAccessToken:!0}},pd={getQuote:{fullPath:({walletId:e})=>`/wallets/${e}/swap/quote`,method:exports.RequestMethod.Post,requiresAccessToken:!0},executeSwap:{fullPath:"/wallets/execute-swap",method:exports.RequestMethod.Post,requiresAccessToken:!0},getSwaps:{fullPath:({walletId:e})=>`/wallets/${e}/swaps`,method:exports.RequestMethod.Get,requiresAccessToken:!0}};function yd(e,t){if(!e)return{};const r=new Set(t);return Object.fromEntries(Object.entries(e).filter((([e])=>!r.has(e))))}class fd{constructor(){}async register({optionsJSON:e}){if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new V({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await p.startRegistration({optionsJSON:e})}async authenticate({optionsJSON:e,useBrowserAutofill:t=!1,skipUserVerification:r=!1}){try{if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new V({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await p.startAuthentication({optionsJSON:Object.assign(Object.assign({},e),{userVerification:r?"discouraged":e.userVerification}),useBrowserAutofill:t})}catch(e){throw this.handlePasskeyError(e),e}}handlePasskeyError(e){return pe.error("SDK::Authenticator::handlePasskeyError",e),this.throwPasskeyError(this.classifyPasskeyError(e),e)}classifyPasskeyError(e){return e instanceof p.WebAuthnError?(pe.debug("SDK::Authenticator::handlePasskeyError - WebAuthnError",e),{errorCode:e.code}):e instanceof Error?(pe.debug("SDK::Authenticator::handlePasskeyError - Error",e),{errorMessage:e.message}):null!==e&&"object"==typeof e&&e.error&&e.message?(pe.debug("SDK::Authenticator::handlePasskeyError - Object",e),{errorCode:e.error,errorMessage:e.message}):"string"==typeof e?(pe.debug("SDK::Authenticator::handlePasskeyError - String",e),{errorMessage:e}):(pe.debug("SDK::Authenticator::handlePasskeyError - Unknown",e),{})}throwPasskeyError({errorCode:e,errorMessage:t},r){var s,a,n;pe.error("SDK::Authenticator::throwPasskeyError",e);const i=he.find((t=>t.error===e));throw pe.error("SDK::Authenticator::error",i),new V({message:null!==(a=null!==(s=null==i?void 0:i.message)&&void 0!==s?s:t)&&void 0!==a?a:M.message,statusCode:400,errorCode:null!==(n=null==i?void 0:i.error)&&void 0!==n?n:e,cause:r})}}function gd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");return t.padEnd(t.length+(4-t.length%4)%4,"=")}function wd(e){try{return o.toUint8Array(e)}catch(r){return t=e,o.toUint8Array(gd(t))}var t}function md(e){const t=gd(e),r=o.atob(t),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}class vd{constructor(e,t,r,s=new Ka){this.cipher=s,this.localStorageService=t,this.userId=e,this.request=r,this.authenticator=new fd}preparePasskeyRequestOptions(e){var t,r,s,a,n,i,o,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?md(e.extensions.prf.eval.base64):(null===(a=null===(s=e.extensions)||void 0===s?void 0:s.prf.eval)||void 0===a?void 0:a.first)instanceof ArrayBuffer?new Uint8Array(e.extensions.prf.eval.first):"object"==typeof(null===(i=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===i?void 0:i.first)?new Uint8Array(Object.values(e.extensions.prf.eval.first)):void 0,l=Object.assign(Object.assign({},e),{extensions:Object.assign(Object.assign({},e.extensions),{prf:void 0!==d?{eval:{first:d}}:null!==(c=null===(o=e.extensions)||void 0===o?void 0:o.prf)&&void 0!==c?c:{}})});return pe.log("SDK::PasskeyService::preparePasskeyRequestOptions::parsedOptions",!!l),l}preparePasskeyCreationOptions(e){var t,r,s,a,n,i,o,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?md(e.extensions.prf.eval.base64):(null===(a=null===(s=e.extensions)||void 0===s?void 0:s.prf.eval)||void 0===a?void 0:a.first)instanceof ArrayBuffer?new Uint8Array(e.extensions.prf.eval.first):"object"==typeof(null===(i=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===i?void 0:i.first)?new Uint8Array(Object.values(e.extensions.prf.eval.first)):void 0,l=Object.assign(Object.assign({},e),{extensions:Object.assign(Object.assign({},e.extensions),{prf:void 0!==d?{eval:{first:d}}:null!==(c=null===(o=e.extensions)||void 0===o?void 0:o.prf)&&void 0!==c?c:{}})});return pe.log("SDK::PasskeyService::preparePasskeyCreationOptions::parsedOptions",!!l),l}async addNewPasskey({deviceKeyPair:e,getSignature:t}){try{let r,s;pe.log("SDK::PasskeyService::addNewPasskey: start adding new passkey");try{const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});if(!a.registrationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const n=this.preparePasskeyCreationOptions(a.registrationOptions);pe.log("SDK::PasskeyService::addNewPasskey: about to register passkey credential"),r=await this.authenticator.register({optionsJSON:n}),pe.log("SDK::PasskeyService::addNewPasskey: finished registering passkey credential");const i=await this.handleCredentialsCreationFromPrfExtension(r);pe.log("SDK::PasskeyService::addNewPasskey:: finished deriving credentials key pair",i.publicKey),s=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyRegistrationResponse:r}}),pe.log("SDK::PasskeyService::addNewPasskey:: signInResponse",s);const o=await this.cipher.encrypt({data:e.privateKey,encryptionKey:i.publicKey});return await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:o},passkeyCredential:r}),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:i.prfValue})}catch(a){if(pe.error("SDK::PasskeyService::addNewPasskey::error",a),a&&a.code===ie.error){const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if(!a.authenticationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const n=this.preparePasskeyRequestOptions(a.authenticationOptions);pe.log("SDK::PasskeyService::addNewPasskey::catch: about to authenticate with passkey"),r=await this.authenticator.authenticate({optionsJSON:n}),pe.log("SDK::PasskeyService::addNewPasskey::catch: finished authenticating with passkey"),s=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyAuthenticationResponse:r}}),pe.log("SDK::PasskeyService::addNewPasskey::catch: finished signing in with passkey",{signInResponse:s});const i=await this.handleCredentialsCreationFromPrfExtension(r);pe.log("SDK::PasskeyService::addNewPasskey::catch: finished deriving credentials key pair",i.publicKey);const o=await this.cipher.encrypt({data:e.privateKey,encryptionKey:i.publicKey});return pe.log("SDK::PasskeyService::addNewPasskey::catch: about to store data"),await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:o},passkeyCredential:r}),pe.log("SDK::PasskeyService::addNewPasskey::catch: finished storing data"),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:i.prfValue})}throw a}}catch(e){if(e instanceof V)throw e;throw this.authenticator.handlePasskeyError(e)}}async authenticate({deviceKeyPair:e,challengeResponse:t}){var r,s;try{if(!t.authenticationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const a=this.preparePasskeyRequestOptions(t.authenticationOptions),n=null===(s=null===(r=a.extensions.prf)||void 0===r?void 0:r.eval)||void 0===s?void 0:s.first,i=Object.assign(Object.assign({},t.authenticationOptions),{extensions:Object.assign(Object.assign({},yd(a.extensions,["credProps"])),{prf:{eval:{first:n}}})}),o=await this.authenticator.authenticate({optionsJSON:i}),c=await this.handleCredentialsCreationFromPrfExtension(o),d=t.signature?t.signature:await this.getDeviceSignature({message:t.message,credentialsKeyPair:c,deviceKeyPair:e}),l=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:t.message,clientAuthPubKey:e.publicKey,signature:d,passkeyAuthenticationResponse:o}}),h=e.decryptedPrivateKey?e.decryptedPrivateKey:e.encryptedDevicePrivateKey?await this.cipher.decrypt({cipherText:e.encryptedDevicePrivateKey,decryptionKey:c.privateKey}):void 0;if(!h)throw new V({message:"Device private key is not available for storage.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const u=await this.cipher.encrypt({data:h,encryptionKey:c.publicKey});return await this.handleStoringData({authenticationResponse:l,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:u},passkeyCredential:o}),Object.freeze(Object.assign(Object.assign({},l),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(e instanceof V)throw e;throw this.authenticator.handlePasskeyError(e)}}async getDeviceSignature({message:e,credentialsKeyPair:t,deviceKeyPair:r}){let s;if(r.decryptedPrivateKey)s=r.decryptedPrivateKey;else{if(!r.encryptedDevicePrivateKey)throw new V({message:"Device private key is not available for signing the message.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});s=await this.cipher.decrypt({cipherText:r.encryptedDevicePrivateKey,decryptionKey:t.privateKey})}return(await this.cipher.sign({message:e,signingKey:s})).signature}async register({deviceKeyPair:e,challengeResponse:t}){var r;try{if(!t.registrationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});pe.log("SDK::PasskeyService::register:: got challenge",{registrationOptions:t.registrationOptions});const s=this.preparePasskeyCreationOptions(t.registrationOptions);pe.log("SDK::PasskeyService::register:: registering passkey",{parsedOptions:s});const a=await this.authenticator.register({optionsJSON:s});if(pe.log("SDK::PasskeyService::register:: got passkey credential",{id:a.id,type:a.type}),!(null===(r=a.clientExtensionResults.prf)||void 0===r?void 0:r.enabled))throw new V({message:"Device is not compatible with this feature. Try using a different authentication method.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});pe.log("SDK::PasskeyService::register:: getting signature",{message:t.message});const{signature:n,message:i}=await this.cipher.sign({message:t.message,signingKey:e.privateKey}),o=await this.request(Ba.signUp,{payload:{externalUserId:this.userId,message:i,signature:n,clientAuthPubKey:e.publicKey,passkeyRegistrationResponse:a}}),c=await this.handleCredentialsCreationFromPrfExtension(a),d=await this.cipher.encrypt({data:e.privateKey,encryptionKey:c.publicKey});return await this.handleStoringData({authenticationResponse:o,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:d},passkeyCredential:a}),Object.freeze(Object.assign(Object.assign({},o),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(pe.log("SDK::PasskeyService::register::error",{error:e,errorCode:e.code,errorMessage:e.message}),e instanceof V)throw pe.log("SDK::PasskeyService::register::API error detected",{error:e}),e;if(e&&e.code===ie.error||e.code===oe.error||"The authenticator was previously registered."===e.message)throw pe.log("SDK::PasskeyService::register::ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",!0),e;throw this.authenticator.handlePasskeyError(e)}}async isDevicePrfCompatible(){var e;try{if("undefined"!=typeof window&&"function"==typeof(null===(e=window.PublicKeyCredential)||void 0===e?void 0:e.getClientCapabilities)){const e=await window.PublicKeyCredential.getClientCapabilities();return pe.log("SDK::PasskeyService::isDevicePrfCompatible::capabilities",e),e["extension:prf"]}return!1}catch(e){return!1}}async publicKeyCredential(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.PasskeyCredential);return null!=e?e:"There are no passkeys stored on this device"}async handleStoringData({authenticationResponse:e,deviceKeyPair:t,passkeyCredential:r}){return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:t.encryptedDevicePrivateKey},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:t.publicKey},{key:exports.LocalStorageItems.PasskeyCredential,value:r},{key:exports.LocalStorageItems.AccessToken,value:e.accessToken},...e.refreshToken?[{key:exports.LocalStorageItems.RefreshToken,value:e.refreshToken}]:[]])}async handleCredentialsCreationFromPrfExtension(e){var t,r,s,a,n;try{const i=e.clientExtensionResults;if(pe.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::extensions",i),!(null===(t=i.prf)||void 0===t?void 0:t.enabled)&&!(null===(s=null===(r=i.prf)||void 0===r?void 0:r.results)||void 0===s?void 0:s.first))throw new V({message:"Device is not compatible with this feature. Try using a different authentication method.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});if(pe.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prf is enabled",i.prf.enabled),!(null===(a=i.prf.results)||void 0===a?void 0:a.first))throw new V({message:"PRF extension did not return any results. Cannot proceed with authentication.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});const o=null===(n=i.prf.results)||void 0===n?void 0:n.first;let c;if("string"==typeof o)c=wd(o);else if(o instanceof Uint8Array)c=o;else if(o instanceof ArrayBuffer)c=new Uint8Array(o);else if(ArrayBuffer.isView(o))c=new Uint8Array(o.buffer);else if(Array.isArray(o))c=new Uint8Array(o);else{if(!o||"object"!=typeof o)throw new V({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});{const e=o.data;if(Array.isArray(e))c=new Uint8Array(e);else{const e=Object.values(o);if(!e.length||!e.every((e=>"number"==typeof e)))throw new V({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});c=new Uint8Array(e)}}}pe.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prfValue",c);const d=await this.cipher.getCredentialsKeyPair({prfValue:c,authType:exports.AuthType.Passkey});return pe.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::credentials key pair was created",!!d),Object.assign(Object.assign({},d),{prfValue:c})}catch(e){if(e instanceof V)throw e;if(e instanceof Error)throw new V({message:e.message,statusCode:400,errorCode:"sdk_passkey_prf_handling_failed",data:e,cause:e.cause});throw this.authenticator.handlePasskeyError(e)}}}function Sd(e){return function(t,r,s){if(!s.value)return;const a=s.value;return s.value=async function(...s){var n,i,o,c,d;const l=this.lockManager,h=e||`${t.constructor.name}:${r}`,u=null!==(i=null===(n=this.options)||void 0===n?void 0:n.environment)&&void 0!==i?i:ge,p=null!==(c=null===(o=this.options)||void 0===o?void 0:o.network)&&void 0!==c?c:we,y=`${null!==(d=this.userId)&&void 0!==d?d:"anon"}:${u}:${p}:${h}`;return l.withLock(y,(()=>a.apply(this,s)))},s}}class _d extends dd{constructor(e,t={}){super(e,t),this.getUserSalt=this.getUserSalt.bind(this),this.passkeyService=new vd(e.userId,this.localStorageService,this.request,this.cipher)}async isDevicePrfCompatible(){return await this.passkeyService.isDevicePrfCompatible()}async validateSession(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken),t=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);return!!e&&!Da(e)||!!t}async refreshAuthTokens(){if(!await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken))throw new V({message:"Refresh token is required",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_refresh_token_missing});await this._performTokenRefresh();const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken),t=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(!e||!t)throw new V({message:"Token refresh failed: tokens not present in storage after refresh",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_refresh_token_missing});return{accessToken:e,refreshToken:t}}async validatePassword({password:e,salt:t}){const r=null!=t?t:await this.getUserSalt();try{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)throw new V({message:"V2 Private key was not found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const s=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:r});return!!await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:s.privateKey})}catch(t){pe.warn("SDK::AuthService::validatePassword::error",t);return!!await this.localStorageService.getDecryptedV1PrivateKey(`${e}`)}}async getUserSalt(){try{return(await this.api.users.getCurrentUserSalt()).clientSalt}catch(e){throw pe.error("SDK::AuthService::getUserSalt::error",e),e}}async getSignature({deviceAuthKeys:e,walletId:t,passkeyChallengeType:r}){try{pe.debug("SDK::AuthService::getSignature::authType",this.deviceAuthType);const s=this.deviceAuthType===exports.AuthType.Passkey?null!=r?r:exports.PasskeyChallengeType.REGISTRATION:void 0;pe.debug("SDK::AuthService::getSignature::challengeType",s);const a=await this.request(Ba.signatureMessage,{payload:{walletId:t,clientAuthPubKey:e.publicKey,passkeyChallengeType:s}}),{signature:n,hashedMessage:i}=await this.cipher.sign({message:a.message,signingKey:e.privateKey});return Object.freeze(Object.assign(Object.assign({},a),{signature:n,hashedMessage:i,authenticationOptions:a.authenticationOptions,registrationOptions:a.registrationOptions}))}catch(e){throw pe.error("SDK::AuthService::getSignatureMessage::error",e),e}}async signUp(e){pe.info("starting signup");const t=Ls();let r;pe.info("key pair generated",!!t);try{const s=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});switch(pe.info("signature has been generated",!!s),this.deviceAuthType){case exports.AuthType.Passkey:pe.info("registering a new passkey"),r=await this.passkeyService.register({deviceKeyPair:t,challengeResponse:s});break;case exports.AuthType.Password:pe.info("signing up with password"),r=await this.handleSignUpWithPassword({signatureMessage:s,deviceKeyPair:t,input:e});break;default:throw new V({message:"Encryption mechanism not supported",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}return Object.freeze(Object.assign(Object.assign(Object.assign({},r),e),{signatureMessageResponse:s}))}catch(e){if(pe.error("SDK::AuthService::signUp::error",e),e&&e.error===oe.error||e.code===ie.error){pe.info("SDK::AuthService::signUp::handling previously registered passkey error");const e=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});return r=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:t.publicKey,decryptedPrivateKey:t.privateKey},challengeResponse:e}),r}throw e}}async signIn(e){let t;try{switch(this.deviceAuthType){case exports.AuthType.Passkey:t=await this.handleSignInWithPasskey({input:e});break;case exports.AuthType.Password:t=await this.handleSignInWithPassword({input:e});break;default:throw new V({message:"Encryption mechanism not supported",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,t.accessToken),t.refreshToken&&await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,t.refreshToken),Object.freeze(Object.assign(Object.assign({},t),e))}catch(e){throw pe.error("SDK::AuthService::signIn::error",e),e}}async hasStoredDevicePublicKey(){return!!await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey)}async handleSignInWithPassword({input:e}){if(!e.password)throw new V({message:"Password is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),r=await this.localStorageService.getEncryptedPrivateKey(),s=await this.getUserSalt(),a=await this.cipher.getCredentialsKeyPair({password:e.password,salt:s,authType:this.deviceAuthType});let n;if(t||r){if(!await this.validatePassword({password:e.password,salt:s}))throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password, please try again."),new V({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(t){const e=_a(t);n=await this.cipher.decrypt({cipherText:e,decryptionKey:a.privateKey})}else n=await this.localStorageService.getDecryptedV1PrivateKey(e.password)}else{if(await this.hasStoredDevicePublicKey())throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Device key missing but wallet data exists"),new V({message:"Device key could not be read but existing wallet data was found on this device. Refusing to create a new identity to avoid orphaning wallet data.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_device_key_missing_with_existing_data});pe.info("No device data found, treating as a fresh device and creating a new key pair");n=Ls().privateKey}if(!n)throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const i=ms(n);await this.storeDeviceKeyPair({deviceAuthKeyPair:{publicKey:i,privateKey:n},credentialsKeyPair:a});const o=await this.getSignature({deviceAuthKeys:{publicKey:i,privateKey:n}}),c=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:o.message,signature:o.signature,clientAuthPubKey:i}});return Object.assign(Object.assign({},c),{signatureMessageResponse:o,password:e.password,clientSalt:c.user.clientSalt})}async handleSignInWithPasskey({input:e}){let t;try{const r=await this.localStorageService.fetch(exports.LocalStorageItems.PasskeyCredential),s=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),a=await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey);let n;if(r){pe.debug("SDK::AuthService::handleSignInWithPasskey:: using existing key pair");const e=await this.request(Ba.signatureMessage,{payload:{clientAuthPubKey:a,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}});t=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:a,encryptedDevicePrivateKey:_a(s)},challengeResponse:e}),pe.debug("SDK::AuthService::handleSignInWithPasskey:: passkey authentication finished",!!t)}else{if(a||s)throw pe.error("SDK::AuthService::handleSignInWithPasskey::error","Passkey credential missing but device data exists"),new V({message:"Passkey credential could not be read but existing wallet data was found on this device. Refusing to create a new identity to avoid orphaning wallet data.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_device_key_missing_with_existing_data});n=Ls(),t=await this.passkeyService.addNewPasskey({deviceKeyPair:n,getSignature:this.getSignature.bind(this)}),pe.debug("SDK::AuthService::handleSignInWithPasskey:: passkey registration finished",t)}return Object.assign(Object.assign(Object.assign({},t),{prfValue:t.prfValue}),e)}catch(e){throw pe.error("SDK::AuthService::handleSignInWithPasskey::error ",e),e}}async storeDeviceKeyPair({deviceAuthKeyPair:e,credentialsKeyPair:t}){const r=await this.cipher.encrypt({data:e.privateKey,encryptionKey:t.publicKey});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:r},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:e.publicKey}])}async handleSignUpWithPassword({signatureMessage:e,input:t,deviceKeyPair:r}){if(!t.password)throw new V({message:"Password is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const s=await this.validatePasswordStrength(t.password);if(!s.valid)throw new V({message:s.message||"Invalid password",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const a=await this.request(Ba.signUp,{payload:{externalUserId:this.userId,message:e.message,signature:e.signature,clientAuthPubKey:r.publicKey}}).then((async e=>{const s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t.password,salt:e.user.clientSalt}),a=await this.cipher.encrypt({data:r.privateKey,encryptionKey:s.publicKey});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:a},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:r.publicKey},{key:exports.LocalStorageItems.AccessToken,value:e.accessToken},...e.refreshToken?[{key:exports.LocalStorageItems.RefreshToken,value:e.refreshToken}]:[]]),e}));return Object.assign(Object.assign({},a),{password:t.password,clientSalt:a.user.clientSalt,signatureMessageResponse:e})}async getPasskeyCredentials(){try{return await this.api.auth.getPasskeyCredentials()}catch(e){if(pe.error("SDK::AuthService::getPasskeyCredentials::error",e),"string"==typeof e)throw new V({message:e,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});if(e&&"object"==typeof e&&"message"in e)throw new V({message:e.message,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_unknown_error,data:e});throw e}}async validatePasswordStrength(e){return e?e.length<8?{valid:!1,message:"Password must be at least 8 characters long"}:e.length>128?{valid:!1,message:"Password must not exceed 128 characters"}:{valid:!0}:{valid:!1,message:"Password is required"}}async exchangeClientToken(){try{const e=await this.request(Ba.issueJwtToken);return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,e.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,e.refreshToken),e}catch(e){throw pe.error("SDK::Auth::exchangeClientToken::error",e),e}}}e._([Sd("signUp"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],_d.prototype,"signUp",null),e._([Sd("signIn"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],_d.prototype,"signIn",null),e._([Sd("storeDeviceKeyPair"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],_d.prototype,"storeDeviceKeyPair",null);class Ad extends dd{constructor(e,t={}){super(e,t),this.authService=new _d(e,t),this.userId=e.userId}async handleImportWallet(e,t){var r,s,a,n,i;try{const{signature:i,message:o,wallabyAuthPubKey:c}=await this.authService.getSignature({walletId:null!==(r=t.walletId)&&void 0!==r?r:t.reference,deviceAuthKeys:{publicKey:e.publicKey,privateKey:e.privateKey},passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0});if(!c)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});if((t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||t.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!t.keyShareOptions)throw new V({message:"Key share options are required when requesting to split the seed phrase",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const{numberOfKeyShares:d,threshold:l}=null!==(s=t.keyShareOptions)&&void 0!==s?s:{};if(l&&d&&d<l)throw new V({message:"Number of shares must be greater than or equal to the threshold",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const h=await this.cipher.encrypt({data:Wa(t.seedPhrase),encryptionKey:c}),u={reference:t.reference,walletId:t.walletId,message:o,signature:i,encryptedSeed:h,clientAuthPubKey:e.publicKey,returnWalletOption:t.returnWalletOption,numShares:d,threshold:l,walletOwnershipType:exports.WalletOwnershipType.SingleOwner,wallabyKeepsOne:null!==(n=null===(a=t.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n},p=await this.request(ld.importSeedPhraseV2,{payload:u}),y=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:t.authenticationOptions.user.clientSalt,password:t.authenticationOptions.password,prfValue:t.authenticationOptions.prfValue});return p.encryptedSeed&&t.returnWalletOption!==exports.ReturnWalletOption.ReturnOnlyEncryptedShares&&await this.handleSeedPhraseFromResponse({walletId:p.wallet.id,encryptedSeed:p.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:t.storeSeedPhrase,credentialsKeyPair:y}),p.shares&&p.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:p.wallet.id,shares:p.shares,credentialsKeyPair:y,encryptedBackupShare:p.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign({},p)}catch(e){throw new V({message:null!==(i=e.message)&&void 0!==i?i:"Failed to handle importing the wallet",statusCode:e.statusCode,errorCode:e.errorCode,data:e.data,cause:e.cause})}}async handleWalletCreation(e,t){var s,a,n,i,o,c;try{const{signature:o,message:c,hashedMessage:d}=await this.authService.getSignature({deviceAuthKeys:{publicKey:e.publicKey,privateKey:e.privateKey},passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if((t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||t.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!t.keyShareOptions)throw new V({message:"Key share options are required when requesting to split the seed phrase",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const{numberOfKeyShares:l,threshold:h}=null!==(s=t.keyShareOptions)&&void 0!==s?s:{};if(h&&l&&l<h)throw new V({message:"Number of shares must be greater than or equal to the threshold",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const u={reference:r.v4(),message:c,signature:o,hashedMessage:d,clientAuthPubKey:e.publicKey,returnWalletOption:t.returnWalletOption,numShares:l,threshold:h,wallabyKeepsOne:null!==(n=null===(a=t.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n,walletOwnershipType:null!==(i=t.walletOwnershipType)&&void 0!==i?i:exports.WalletOwnershipType.SingleOwner},p=await this.request(ld.createWithKeyShares,{payload:u});let y;const f=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:t.authenticationOptions.user.clientSalt,password:t.authenticationOptions.password,prfValue:t.authenticationOptions.prfValue});return p.encryptedSeed&&(y=await this.handleSeedPhraseFromResponse({walletId:p.wallet.id,encryptedSeed:p.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:t.storeSeedPhrase,credentialsKeyPair:f})),p.shares&&p.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:p.wallet.id,shares:p.shares,credentialsKeyPair:f,encryptedBackupShare:p.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign(Object.assign({},p),{standardSeedPhrase:y})}catch(e){throw pe.error("SDK::handleWalletCreation::error",e),new V({message:null!==(o=e.message)&&void 0!==o?o:"Failed to handle creating the wallet",statusCode:e.statusCode,errorCode:null!==(c=e.errorCode)&&void 0!==c?c:"unspecified_error",data:e.data,cause:e.cause})}}async handleKeySharesFromResponse({walletId:e,shares:t,credentialsKeyPair:r,encryptedBackupShare:s,devicePrivateKey:a}){try{!function(e){if(!e.length)throw new V({message:"No key shares were returned from the API.",statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}(t);try{await this.cipher.decrypt({cipherText:t[0].encrypted,decryptionKey:a})}catch(e){throw new V({message:"Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.",statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_key_share_decryption_failed,cause:e})}const n=await this.cipher.encrypt({data:JSON.stringify(t[0].encrypted),encryptionKey:r.publicKey}),i=await this.cipher.encrypt({data:JSON.stringify(s),encryptionKey:r.publicKey});return await this.localStorageService.saveInBulk([{key:exports.V2KeyNames.PrimaryDeviceKeyShare,value:n,walletId:e},{key:exports.V2KeyNames.BackupDeviceKeyShare,value:i,walletId:e}]),[n,i]}catch(e){throw pe.error("SDK::handleKeySharesFromResponse::error",e),e}}async handleSeedPhraseFromResponse({walletId:e,encryptedSeed:t,devicePrivateKey:r,credentialsKeyPair:s,storeSeedPhrase:a}){try{const n=await this.cipher.decrypt({cipherText:t,decryptionKey:r});if(a){const t=ms(r),a=await this.cipher.encrypt({data:n,encryptionKey:t}),i=await this.cipher.encrypt({data:JSON.stringify(a),encryptionKey:s.publicKey});await this.localStorageService.save(exports.V2KeyNames.EncryptedStandardSeedPhrase,i,{walletId:e})}return n}catch(e){throw pe.error("SDK::handleSeedPhraseFromResponse::error",e),e}}}function Ed(e){const t=[];let r=0,s=0;for(const a of e)r|=a<<s,s+=8,s>=11&&(t.push(2047&r),r>>>=11,s-=11);return s>0&&t.push(2047&r),t}class bd extends dd{constructor(e,t={}){super(e,t),this.authService=new _d(e,t),this.handlers=new Ad(e,t),this.userId=e.userId,this.passkeyService=new vd(e.userId,this.localStorageService,this.request,this.cipher)}async getRateState(e){const t=Date.now(),r=await this.localStorageService.fetch(e),s=r?_a(r):void 0;return!s||t-s.windowStart>bd.RATE_LIMIT_WINDOW_MS?{count:0,windowStart:t}:s}async recordRateAttempt(e){const t=await this.getRateState(e);return t.count+=1,await this.localStorageService.save(e,JSON.stringify(t)),t.count}async assertUnderRateLimit(e,t){const{count:r}=await this.getRateState(e);if(r>bd.RATE_LIMIT_MAX)throw new V({message:t,statusCode:429,errorCode:exports.ErrorResponseCodes.sdk_too_many_requests})}async hasSeedPhraseOnDevice({walletId:e}){return await this.localStorageService.checkSeedPhraseExists(e)}async hasPrimaryKeyShareOnDevice({walletId:e}){return await this.localStorageService.checkPrimaryKeyShareExists(e)}async hasBackupKeyShareOnDevice({walletId:e}){return await this.localStorageService.checkBackupKeyShareExists(e)}async hasWalletOnDevice({walletId:e}){return await this.hasSeedPhraseOnDevice({walletId:e})||await this.hasPrimaryKeyShareOnDevice({walletId:e})}async create(e){try{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)throw new V({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const r=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,prfValue:e.authenticationOptions.prfValue,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt}),s=await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:r.privateKey});if(!s)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const a=ms(s);return await this.handlers.handleWalletCreation({publicKey:a,privateKey:s},e)}catch(e){throw pe.error("SDK::Wallet::create::error",e),e}}async export({walletId:e,authenticationOptions:t,exportOptions:r}){try{if(!r.algorandSeedPhrase&&!r.standardSeedPhrase&&!r.keyShares)throw new V({message:"exportOptions must be provided with at least one of the following options: algorandSeedPhrase, standardSeedPhrase, keyShares",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&t.password&&await this.migrateToV2Safe({password:t.password,walletId:e});const s=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:e}),a=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:e}),n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);let i,o,c;if(!n)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const d=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}),l=_a(n),h=await this.cipher.decrypt({cipherText:l,decryptionKey:d.privateKey});if(!h)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});if(r.keyShares){if(!a)throw new V({message:"You do not have any key shares stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const e=_a(a);i=await this.cipher.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:l,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}})}if(r.standardSeedPhrase||r.algorandSeedPhrase)if(s){const e=_a(s);if(o=await this.cipher.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:l,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),r.algorandSeedPhrase&&(c=this.getAlgorandSeedPhrase(o),!c))throw new V({message:"Something went wrong decrypting algorand seed phrase.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed})}else{if(!a)throw new V({message:"You do not have a wallet stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const s=_a(a),n={publicKey:ms(h),privateKey:h},{signature:i,message:d,wallabyAuthPubKey:u}=await this.authService.getSignature({deviceAuthKeys:n,walletId:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),p=u;if(!p)throw new V({message:"Wallaby public key is required for wallet export.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:s,encryptedDevicePrivateKey:l,wallabyPublicKey:p,destinationPubKey:n.publicKey,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),f=await this.request(ld.retrieveSeedPhrase,{payload:{walletId:e,signature:i,message:d,clientAuthPubKey:n.publicKey,encryptedShares:[y]}});o=await this.cipher.decrypt({cipherText:f.encryptedSeed,decryptionKey:h}),r.algorandSeedPhrase&&(c=this.getAlgorandSeedPhrase(o))}return{keyShares:r.keyShares&&i?i:void 0,standardSeedPhrase:r.standardSeedPhrase&&o?o:void 0,algorandSeedPhrase:r.algorandSeedPhrase&&c?c:void 0}}catch(e){throw pe.error("SDK::WalletService::export::error",e),e}}async import(e){var t;try{const s=null!==(t=e.reference)&&void 0!==t?t:r.v4(),a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new V({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=_a(a),i=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue}),o=await this.cipher.decrypt({cipherText:n,decryptionKey:i.privateKey});if(!o)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ms(o);return await this.handlers.handleImportWallet({publicKey:c,privateKey:o},Object.assign(Object.assign({},e),{reference:s}))}catch(e){throw pe.error("SDK::WalletService::import::error",e),e}}async changePassword({walletId:e,oldPassword:t,newPassword:r}){try{if(await this.recordRateAttempt(exports.V2KeyNames.PasswordResetAttempts)>bd.RATE_LIMIT_MAX)throw new V({message:"Too many password change attempts. Please try again later.",statusCode:429,errorCode:exports.ErrorResponseCodes.sdk_too_many_requests});this.deviceAuthType===exports.AuthType.Password&&t&&await this.migrateToV2Safe({password:t,walletId:e});const s=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),a=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:e}),n=await this.localStorageService.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:e}),i=await this.localStorageService.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e});if(!s||"undefined"===s)throw new V({message:"Could not locate client keys on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=await this.authService.getUserSalt(),c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t,salt:o});if(!c.privateKey)throw new V({message:"Could not derive keys from old password. Please make sure the password is correct.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const d=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,salt:o});if(!d.publicKey||!d.privateKey)throw new V({message:"Could not derive keys for new password.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const l=await this.cipher.flipEncryptedData({cipherText:JSON.parse(s),decryptionKey:c.privateKey,encryptionKey:d.publicKey});if(!l)throw new V({message:"Failed to re-wrap device private key during password change.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});await this.assertRoundTrip(l,d.privateKey,"device key");const h=a?await this.cipher.flipEncryptedData({cipherText:_a(a),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,u=n?await this.cipher.flipEncryptedData({cipherText:_a(n),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,p=i?await this.cipher.flipEncryptedData({cipherText:_a(i),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null;return h&&await this.assertRoundTrip(h,d.privateKey,"seed phrase"),u&&await this.assertRoundTrip(u,d.privateKey,"primary share"),p&&await this.assertRoundTrip(p,d.privateKey,"backup share"),await this.localStorageService.commitBatch([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:l},...h?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,value:h,walletId:e}]:[],...u?[{key:exports.LocalStorageItems.PrimaryDeviceKeyShare,value:u,walletId:e}]:[],...p?[{key:exports.LocalStorageItems.BackupDeviceKeyShare,value:p,walletId:e}]:[]]),await this.localStorageService.delete(exports.V2KeyNames.PasswordResetAttempts),!0}catch(e){throw pe.error("SDK::Wallet::changePassword::error",e),e}}getAlgorandSeedPhrase(e){try{const r=h.mnemonicToSeedSync(e),s=function(e){if(32!==e.length)throw new Error(`Algorand seed must be 32 bytes, got ${e.length}`);const r=t.wordlists.english,s=Ed(e).map((e=>r[e])),a=Ed(br(e).subarray(0,2))[0];return[...s,r[a]].join(" ")}(r.slice(0,32));return s}catch(e){throw pe.error("SDK::Wallet::getAlgorandSeedPhrase::error",e),new V({message:e instanceof Error?e.message:"Failed to convert seed phrase to Algorand mnemonic.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}async initAddNewDevice(e){const{walletId:t,backupUrl:r,authenticationOptions:s}=e,a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=_a(a);this.deviceAuthType===exports.AuthType.Password&&e.authenticationOptions.password&&await this.migrateToV2Safe({password:e.authenticationOptions.password,walletId:e.walletId});const i=await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare,{walletId:t});if(!i)throw new V({message:"You do not have any additional key shares stored on this device, you cannot add a new device from here.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const o=_a(i),c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:s.password,salt:s.user.clientSalt,prfValue:s.prfValue});if(!await this.cipher.decrypt({cipherText:n,decryptionKey:c.privateKey}))throw new V({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});return{walletId:t,backupUrl:r,encryptedBackupShare:_a(await this.cipher.decrypt({cipherText:o,decryptionKey:c.privateKey}))}}async addNewDevice(e){var t;try{const r=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!r)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue}),a=await this.cipher.decrypt({cipherText:JSON.parse(r),decryptionKey:s.privateKey});if(!a)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const n=null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey))&&void 0!==t?t:ms(a),i=await this.authService.getSignature({deviceAuthKeys:{privateKey:a,publicKey:n},walletId:e.walletId,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),o=await this.request(ld.addNewDevice,{payload:{walletId:e.walletId,clientAuthPubKey:n,signature:i.signature,message:i.message,wallabyAuthPubKey:i.wallabyAuthPubKey,encryptedBackupShare:e.encryptedBackupShare}});return await this.handlers.handleKeySharesFromResponse({walletId:e.walletId,shares:[o.share],credentialsKeyPair:s,encryptedBackupShare:e.encryptedBackupShare,devicePrivateKey:a}),{success:!0,reference:o.reference}}catch(e){throw pe.error("SDK::Wallet::backupKeyShare::error",e),e}}async generateWalletAddresses(e){const{walletId:t}=e;if(!t)throw new V({message:"Wallet ID is missing in the request",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&e.authenticationOptions.password&&await this.migrateToV2Safe({password:e.authenticationOptions.password,walletId:e.walletId});try{const r=await this.prepareWalletOperationAuth({walletId:t,authenticationOptions:e.authenticationOptions});return await this.request(ld.generateWalletAddresses,{payload:{walletId:t,message:r.signatureMessage.message,clientAuthPubKey:r.deviceAuthPublicKey,signature:r.signatureMessage.signature,encryptedSeed:r.readyForTransportSeedPhrase,encryptedShares:r.sharesEncryptedWithWallabyPubKey,chainName:e.blockchainName}})}catch(e){throw pe.error("SDK::Wallet::generateWalletAddresses::error",e),e}}async migrateToV2Safe({password:e,walletId:t}){try{await this.handleUpdateToV2({password:e,walletId:t})}catch(e){if(e instanceof V&&e.errorCode===exports.ErrorResponseCodes.sdk_ambiguous_legacy_migration_data)throw e;throw pe.error("SDK::WalletService::migrateToV2Safe::error",e),new V({message:"Error accessing user wallet on this device. Please ensure the password is correct and try again.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}assertValidDeviceKey(e){try{this.cipher.validatePrivateKey(e)}catch(e){throw pe.error("SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material",e),new V({message:"Could not access your device key — your stored wallet credentials appear to be corrupted.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed})}}async handleUpdateToV2({password:e,walletId:t}){const r=Date.now();await this.assertUnderRateLimit(exports.V2KeyNames.MigrationAttempts,"Too many migration attempts. Please try again later.");try{if(!e)throw new V({message:"Password is required for migration to v2",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const s=this.version,n=await this.localStorageService.fetch(exports.V2KeyNames.MigrationVersion),i=await this.localStorageService.fetch(exports.V2KeyNames.LastMigratedAt);if(pe.info("SDK::WalletService::handleUpdateToV2::starting migration check",{timestamp:new Date(r).toISOString(),walletId:t.substring(0,8)+"...",lastMigratedAt:i,currentSdkVersion:s,sdkMigrationVersion:n}),i&&"never"!==i&&n)return void pe.info("SDK::WalletService::handleUpdateToV2::Migration already completed successfully, skipping",{migratedVersion:n,migratedAt:i});const o=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),c=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:t}),d=await this.localStorageService.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:t}),l=await this.authService.getUserSalt(),h=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:l});if(o&&(c||d))try{await this.cipher.decrypt({cipherText:_a(o),decryptionKey:h.privateKey});const t=c||d;return await this.cipher.displayStoredData({storedEncryptedData:_a(t),encryptedDevicePrivateKey:_a(o),options:{authType:exports.AuthType.Password,password:e,salt:l}}),pe.info("SDK::WalletService::handleUpdateToV2::V2 items already exist and are valid, no migration needed"),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,(new Date).toISOString()),void await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,s)}catch(e){pe.info("SDK::WalletService::handleUpdateToV2::V2 items exist but decryption failed, proceeding with migration",{error:JSON.stringify(e)})}let u,p;await this.recordRateAttempt(exports.V2KeyNames.MigrationAttempts);const y=await this.localStorageService.isLegacySeedFallbackSafeFor(t),f=y?await this.localStorageService.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`):void 0,g=await this.localStorageService.getDecryptedV1PrivateKey(e);if(f&&g){this.assertValidDeviceKey(g),pe.info("SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration",{storageFormat:"legacy"});try{const r=_a(a.AES.decrypt(f,`${l}${e}`).toString(a.enc.Utf8));if(u=wa(g,r),p=g,!u)throw new V({message:"Failed to decrypt legacy seed phrase items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});pe.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted legacy items"),await this.localStorageService.claimLegacySeedFallbackFor(t)}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt legacy items",e),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}else{const r=await this.localStorageService.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard,t),s=await this.localStorageService.getEncryptedPrivateKey();if(!r||!s){if(!y){const e=await this.localStorageService.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`),t=await this.localStorageService.getV1EncryptedSeedPhrase();if(e||t)throw pe.error("SDK::WalletService::handleUpdateToV2::Legacy seed data on this device is already claimed by a different wallet; refusing to migrate ambiguously"),new V({message:"Legacy wallet data on this device is associated with a different wallet and cannot be safely migrated for this wallet.",statusCode:409,errorCode:exports.ErrorResponseCodes.sdk_ambiguous_legacy_migration_data})}return pe.info("SDK::WalletService::handleUpdateToV2::No legacy or V1 items found to migrate"),void pe.info("SDK::WalletService::handleUpdateToV2:: You do not have a wallet stored on this device. Nothing to migrate.")}p=await this.localStorageService.getDecryptedV1PrivateKey(e),p&&this.assertValidDeviceKey(p),pe.info("SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration",{storageFormat:"v1",validPrivateKey:!!p});try{if(pe.log("Attempting to decrypt V1 items during migration..."),pe.log("getV1DecryptedSeedPhrase should be called with password and clientSalt:",{hasPassword:!!e,hasClientSalt:!!l}),u=await this.localStorageService.getV1DecryptedSeedPhrase(e,l),p=await this.localStorageService.getDecryptedV1PrivateKey(e),!u||!p)throw new V({message:"Failed to decrypt V1 items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});pe.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted V1 items"),await this.localStorageService.claimLegacySeedFallbackFor(t)}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt V1 items",e),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}if(u&&p){pe.info("SDK::WalletService::handleUpdateToV2::Initiating wallet recovery for V2 migration"),pe.info("SDK::WalletService::handleUpdateToV2::Migration data prepared"),pe.info("SDK::WalletService::handleUpdateToV2::Seed phrase available:",!!u);const e=ms(p),s=await this.authService.getSignature({deviceAuthKeys:{publicKey:e,privateKey:p},walletId:t}),a=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:s.message,signature:s.signature,clientAuthPubKey:e}}),n=await this.cipher.encrypt({data:p,encryptionKey:h.publicKey}),i=await this.cipher.doubleEncrypt({decryptedData:u,credentialsKeyPair:h,deviceKeyPair:{publicKey:e,privateKey:p}});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.AccessToken,value:a.accessToken},{key:exports.V2KeyNames.EncryptedStandardSeedPhrase,value:i,walletId:t},{key:exports.V2KeyNames.EncryptedDevicePrivateKey,value:n}]),pe.info("SDK::WalletService::handleUpdateToV2::Migration completed successfully",{timestamp:(new Date).toISOString(),duration:Date.now()-r,devicePublicKey:e.substring(0,16)+"...",migratedKeys:["EncryptedDevicePrivateKey","EncryptedStandardSeedPhrase"]}),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,(new Date).toISOString()),void await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,this.version)}throw new V({message:"Decrypted data required for migration is missing, operation cannot be completed.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Migration failed",{timestamp:(new Date).toISOString(),duration:Date.now()-r,error:e instanceof Error?e.message:"Unknown error"}),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,"never"),await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,this.version),e}}async verifyAccess(e){try{const{readyForTransportSeedPhrase:t,sharesEncryptedWithWallabyPubKey:r,hasShares:s,signatureMessage:a,deviceAuthPublicKey:n}=await this.prepareWalletOperationAuth({authenticationOptions:e.authenticationOptions,walletId:e.walletId}),i=t&&!s;return await this.api.wallets.verifyAccess({message:a.message,signature:a.signature,clientAuthPubKey:n,encryptedSeed:i?t:void 0,encryptedShares:i?void 0:r,walletId:e.walletId})}catch(e){throw pe.error("SDK::WalletService::verifyAccess::Error occurred",e),e}}async clearDevice({walletId:e}){await this.localStorageService.clearLocalStorage(e)}async prepareWalletOperationAuth({authenticationOptions:e,walletId:t}){const{password:r,prfValue:s,user:a}=e,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!n)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}),o=await this.cipher.decrypt({cipherText:JSON.parse(n),decryptionKey:i.privateKey});if(!o)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ms(o),d=await this.authService.getSignature({deviceAuthKeys:{publicKey:c,privateKey:o},walletId:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),l=d.wallabyAuthPubKey;if(!l)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const h=[];let u;const p=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(p){const e=_a(p),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(n),wallabyPublicKey:l,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}});h.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to complete this request.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const i=_a(e);u=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:i,encryptedDevicePrivateKey:JSON.parse(n),wallabyPublicKey:l,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}})}return{deviceAuthPublicKey:c,signatureMessage:d,readyForTransportSeedPhrase:u,sharesEncryptedWithWallabyPubKey:h.length?h:void 0,hasShares:h.length>0}}async convertToPasskey(e){let t=!1;try{const s=await this.localStorageService.fetch(exports.V2KeyNames.CredentialConversionInProgress),a=s?_a(s):void 0;(null==a?void 0:a.encryptedDevicePrivateKey)&&await this.localStorageService.save(exports.LocalStorageItems.EncryptedDevicePrivateKey,a.encryptedDevicePrivateKey),(null==a?void 0:a.walletId)===e.walletId&&pe.info("SDK::WalletService::convertToPasskey::resuming interrupted conversion");const n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:e.walletId}),o=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:e.walletId}),c=await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare,{walletId:e.walletId}),d=await this.authService.getUserSalt(),l=await this.cipher.getCredentialsKeyPair({password:e.password,salt:d,authType:exports.AuthType.Password});let h;if(!await this.authService.validatePassword({password:e.password,salt:d}))throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password"),new V({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(n){pe.log("SDK::WalletService::convertToPasskey::Decrypting v2 device private key with password-derived key");const e=_a(n);h=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}else pe.log("SDK::WalletService::convertToPasskey::No encrypted device private key found, checking for v1 format"),h=await this.localStorageService.getDecryptedV1PrivateKey(e.password);if(!h)throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new V({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const u=ms(h);await this.localStorageService.save(exports.V2KeyNames.CredentialConversionInProgress,Object.assign({walletId:e.walletId},n?{encryptedDevicePrivateKey:n}:{}));const p=await this.passkeyService.addNewPasskey({deviceKeyPair:{publicKey:u,privateKey:h},getSignature:this.authService.getSignature.bind(this)});t=!0;const y=p.prfValue;if(!(y&&y instanceof Uint8Array&&0!==y.length))throw pe.error("SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array"),new V({message:"PRF value from passkey is required to derive credentials and could not be obtained",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});let f,g,w;if(pe.log("SDK::WalletService::convertToPasskey::Received authentication response",!!p),i&&n)try{f=await this.cipher.displayStoredData({storedEncryptedData:_a(i),encryptedDevicePrivateKey:_a(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){pe.error("SDK::WalletService::convertToPasskey::seed_decryption_error",e)}if(!f)try{f=await this.localStorageService.getV1DecryptedSeedPhrase(e.password,d)}catch(e){pe.error("SDK::WalletService::convertToPasskey::v1_seed_decryption_error",e)}if(o&&n)try{const t=_a(o);g=await this.cipher.displayStoredData({storedEncryptedData:t,encryptedDevicePrivateKey:_a(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){pe.error("SDK::WalletService::convertToPasskey::primary_share_decryption_error",e)}if(c)try{const e=_a(c);w=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}catch(e){pe.error("SDK::WalletService::convertToPasskey::backup_share_decryption_error",e)}if(!f&&!(!!g||!!w))throw new V({message:"Seed phrase or key shares on this device could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});if(f&&!g)return pe.info("SDK::WalletService::convertToPasskey::No primary share found, importing wallet"),await this.handlers.handleImportWallet({publicKey:u,privateKey:h},{authenticationOptions:p,seedPhrase:f,storeSeedPhrase:!1,returnWalletOption:exports.ReturnWalletOption.ReturnOnlyEncryptedShares,walletId:e.walletId,reference:r.v4(),keyShareOptions:{threshold:2,numberOfKeyShares:3,numberOfSharesReturned:2,storeOneKeyShareWithWallaby:!0}}),await this.localStorageService.commitBatch([],[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId},{key:exports.V2KeyNames.CredentialConversionInProgress}]),pe.info("SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed"),{authentication:p,seedPhrase:f};const m=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Passkey,prfValue:y}),v=[];if(g){const t=await this.cipher.doubleEncrypt({decryptedData:g,credentialsKeyPair:m,deviceKeyPair:{publicKey:u,privateKey:h}}),r=await this.cipher.decrypt({cipherText:t,decryptionKey:m.privateKey});if((r?await this.cipher.decrypt({cipherText:_a(r),decryptionKey:h}):null)!==g)throw new V({message:"Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});v.push({key:exports.V2KeyNames.PrimaryDeviceKeyShare,value:t,walletId:e.walletId})}if(w){const t=await this.cipher.encrypt({data:w,encryptionKey:m.publicKey});v.push({key:exports.V2KeyNames.BackupDeviceKeyShare,value:t,walletId:e.walletId})}for(const e of v)await this.assertRoundTrip(e.value,m.privateKey,e.key);if(await this.localStorageService.commitBatch(v,[...i?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId}]:[],{key:exports.V2KeyNames.CredentialConversionInProgress}]),i&&pe.info("SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey"),!f&&g){const t={publicKey:u,privateKey:h},{signature:r,message:s,wallabyAuthPubKey:a}=await this.authService.getSignature({deviceAuthKeys:t,walletId:e.walletId,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if(!a)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const n=await this.cipher.encrypt({data:xa(g,t.publicKey),encryptionKey:a}),i=await this.request(ld.retrieveSeedPhrase,{payload:{walletId:e.walletId,signature:r,message:s,clientAuthPubKey:t.publicKey,encryptedShares:[n]}});f=await this.cipher.decrypt({cipherText:i.encryptedSeed,decryptionKey:h})}if(!f)throw new V({message:"Seed phrase could not be reconstructed from the provided shares",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});return{authentication:p,seedPhrase:f}}catch(e){throw pe.error("SDK::WalletService::convertToPasskey::error",e),t||await this.localStorageService.delete(exports.V2KeyNames.CredentialConversionInProgress),e}}async assertRoundTrip(e,t,r){try{await this.cipher.decrypt({cipherText:e,decryptionKey:t})}catch(e){throw new V({message:`Re-wrap validation failed for ${r}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}}bd.RATE_LIMIT_MAX=5,bd.RATE_LIMIT_WINDOW_MS=18e5,e._([Sd("create"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"create",null),e._([Sd("import"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"import",null),e._([Sd("credential-rewrap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"changePassword",null),e._([Sd("migrateToV2"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"handleUpdateToV2",null),e._([Sd("credential-rewrap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"convertToPasskey",null);class Id extends dd{constructor(e,t={}){super(e,t),this.userId=e.userId,this.walletService=new bd(e,t)}validateWalletAddressInfo(e,t){return e.some((e=>e.chainName===t))}async getTokenBalance({address:e,assetSymbol:t,tokenStandard:r,chainName:s}){try{if(!e||!t||!s&&!r)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.getTokenBalance,{payload:{address:e,assetSymbol:t,chainName:s,tokenStandard:r}})}catch(e){throw pe.error("SDK::WalletDataService::getTokenBalance::error",e),e}}async getMultiTokenBalances({walletId:e,tokensAndAddressesList:t}){try{if(!t.length)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.getMultiTokenBalances,{payload:{assets:t,walletId:e}})}catch(e){throw pe.error("SDK::WalletDataService::getMultiTokenBalances::error",e),e}}async getWalletBalances({walletId:e}){try{if(!e)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.getWalletBalances,{payload:{walletId:e}})}catch(e){throw pe.error("SDK::WalletDataService::getWalletBalances::error",e),e}}async getUserAssets({userId:e,queryOptions:t}){try{if(!e)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.getUserAssets,{payload:{userId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getUserAssets::error",e),e}}async getUserWallets({userId:e,queryOptions:t}){try{return await this.request(ld.getUserWallets,{payload:{userId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getUserWallets::error",e),e}}async getWalletAssets({walletId:e,queryOptions:t}){try{if(void 0!==(null==t?void 0:t.search)&&t.search.length<3)throw new V({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(ld.getWalletAssets,{payload:{walletId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getWalletAssets::error",e),e}}async addTokenToWallet({assetConfigId:e,walletId:t,userId:r,config:s,authenticationOptions:a}){try{if(!t)throw new V({message:"Wallet ID is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!e&&!s)throw new V({message:"Either assetConfigId or config must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});let n={};if(a){const e=await this.walletService.prepareWalletOperationAuth({walletId:t,authenticationOptions:a});n={message:e.signatureMessage.message,clientAuthPubKey:e.deviceAuthPublicKey,signature:e.signatureMessage.signature,encryptedSeed:e.readyForTransportSeedPhrase,encryptedShares:e.sharesEncryptedWithWallabyPubKey}}return await this.request(ld.addTokenToWallet,{payload:Object.assign({assetConfigId:e,walletId:t,userId:r||void 0,config:s},n)})}catch(e){throw pe.error("SDK::WalletDataService::addTokenToWallet::error",e),e}}async addNewChainAndTokenToWallet(e){const{authenticationOptions:t,walletId:r,userId:s,assetConfigId:a,blockchainName:n}=e;if(!(t&&r&&s&&a&&n))throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&t.password&&await this.walletService.migrateToV2Safe({password:t.password,walletId:r});try{const t=await this.walletService.generateWalletAddresses({walletId:e.walletId,authenticationOptions:e.authenticationOptions});if(this.validateWalletAddressInfo(t.walletAddressesInfo,n)){const t=(await this.getWalletAssets({walletId:r})).assets.find((e=>e.configId===a));if(t)return{asset:t};return await this.addTokenToWallet({assetConfigId:a,walletId:r,userId:s,authenticationOptions:e.authenticationOptions})}throw new V({message:`Wallet address is not present for blockchain: ${n}`,statusCode:400,errorCode:"sdk_wallet_address_not_found"})}catch(e){throw pe.error("SDK::WalletDataService::addNewChainAndTokenToWallet::error",e),e}}async updateAsset(t){var{configId:r,walletId:s}=t,a=e.b(t,["configId","walletId"]);try{if(!r||!s)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.updateAsset,{payload:Object.assign({configId:r,walletId:s},a)})}catch(e){throw pe.error("SDK::WalletDataService::updateAsset::error",e),e}}}class Pd extends dd{constructor(e,t={}){super(e,t),this.getDecryptedPrivateKey=async e=>{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return""!==r?r:void 0},this.decryptDevicePrivateKey=({encryptedPrivateKey:e,password:t})=>{const r=a.AES.decrypt(e,t).toString(a.enc.Utf8);return""!==r?r:void 0},this.auth=new _d(e,t)}async decryptSeedPhrase({password:e}){var t;const r=await this.auth.getUserSalt();if(!r)throw new Error("Salt could not be found");const s=`${r}${e}`,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase);if(!n)throw new Error("Seed phrase could not be found");const i=_a(a.AES.decrypt(n,s).toString(a.enc.Utf8)),o=this.decryptDevicePrivateKey({encryptedPrivateKey:null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey))&&void 0!==t?t:"",password:e});if(!o)throw pe.error("SDK::Utils::decryptSeedPhrase::devicePrivateKey: Device private key could not be decrypted"),new Error("Device private key could not be decrypted");return await wa(o,i)}async fetchFromEndpoint({endpoint:e,method:t,requiresAccessToken:r,payload:s}){try{const a=new RegExp("https?://[^/]*.?wallaby.cash/api/v1","i"),n={fullPath:e.replace(a,""),method:t,requiresAccessToken:null!=r&&r};return await this.request(n,{payload:s})}catch(e){return pe.error("SDK::Utils::fetchFromEndpoint::error",e),Promise.reject(e)}}async validatePassword({password:e}){const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return{valid:!1,message:"Could not locate client keys or seed phrase on this device."};try{const r=await this.auth.getUserSalt(),s=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:r});return await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:s.privateKey})?{valid:!0}:{valid:!1,message:"Password is incorrect"}}catch(e){return pe.error("SDK::Utils::validatePassword::error",e),{valid:!1,message:"Password is incorrect."}}}}class Td extends dd{constructor(e,t={}){super(e,t)}}class kd extends dd{constructor(e,t={}){super(e,t),this.authService=new _d(e,t),this.walletService=new bd(e,t)}async getQuote(e){try{const{walletId:t,fromAssetConfigId:r,toAssetConfigId:s,fromAmount:a,toAmount:n,slippage:i}=e;if(!t||!r||!s)throw new V({message:"Missing required parameters: walletId, fromAssetConfigId, and toAssetConfigId",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!a&&!n)throw new V({message:"Either fromAmount or toAmount must be provided",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(a&&n)throw new V({message:"Only one of fromAmount or toAmount may be provided, not both",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const o={walletId:t},c=Object.assign(Object.assign(Object.assign({fromAssetConfigId:r,toAssetConfigId:s},a&&{fromAmount:a}),n&&{toAmount:n}),null!=i&&{slippage:i});return await this.request(Object.assign(Object.assign({},pd.getQuote),{fullPath:pd.getQuote.fullPath(o)}),{payload:c})}catch(e){throw pe.error("SDK::Swap::getQuote::error",e),e}}async executeSwap({walletId:e,quoteId:t,authenticationOptions:r}){try{this.deviceAuthType===exports.AuthType.Password&&r.password&&await this.walletService.migrateToV2Safe({password:r.password,walletId:e});const{deviceAuthPublicKey:s,signatureMessage:a,readyForTransportSeedPhrase:n,sharesEncryptedWithWallabyPubKey:i,hasShares:o}=await this.prepareSwapAuth(r,e);let c;if(n)c=await this.request(Object.assign(Object.assign({},pd.executeSwap),{fullPath:pd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedSeed:n}});else{if(!o)throw new V({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});c=await this.request(Object.assign(Object.assign({},pd.executeSwap),{fullPath:pd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedShares:i}})}return c}catch(e){throw pe.error("SDK::Swap::executeSwap::error",e),e}}async getSwaps({walletId:e,queryParams:t}){try{if(!e)throw new V({message:"Missing required parameter: walletId",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const r={walletId:e};return await this.request(Object.assign(Object.assign({},pd.getSwaps),{fullPath:pd.getSwaps.fullPath(r)}),{queryParams:t})}catch(e){throw pe.error("SDK::Swap::getSwaps::error",e),e}}async prepareSwapAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!i)throw new V({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:o}),d=await this.cipher.decrypt({cipherText:JSON.parse(i),decryptionKey:c.privateKey});if(!d)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ms(d),h=await this.authService.getSignature({deviceAuthKeys:{publicKey:l,privateKey:d},passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0,walletId:t}),u=h.wallabyAuthPubKey;if(!u)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const p=[];let y;const f=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(f){const e=_a(f),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}});p.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to sign the transaction.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const a=_a(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:p,hasShares:p.length>0})}}e._([Sd("executeSwap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],kd.prototype,"executeSwap",null);class Cd extends dd{constructor(e,t={}){super(e,t)}async getSupportedBlockchains(e){try{return(await this.request(hd.getSupportedBlockchains,{queryParams:void 0!==(null==e?void 0:e.supportSwaps)?{supportSwaps:e.supportSwaps}:void 0})).chains}catch(e){throw pe.error("SDK::System::getSupportedBlockchains::error",e),e}}validateContractAddress({blockchain:e,contractAddress:t,suiObjectId:r}){switch(e){case exports.BlockchainName.Algorand:case exports.BlockchainName.Bitcoin:throw new V({message:`${e} does not support contract addresses.`,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});case exports.BlockchainName.Sui:if(r&&t)throw new V({message:"You can only provide either suiObjectId or contractAddress",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(t)throw new V({message:"You can only provide suiObjectId for SUI blockchain",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(!r)throw new V({message:"You must provide suiObjectId for SUI blockchain",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return(e=>{if(!e)throw new Error("Sui object ID is required");if(!e.startsWith("0x"))throw new Error("Invalid Sui object ID");return e.includes("::")?e.split("::")[0]:e})(r);default:if(!t)throw new V({message:"You must provide contractAddress for non-SUI blockchains",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return t}}async fetchTokenInfo({blockchain:e,contractAddress:t,suiObjectId:r,assetSymbol:s}){try{const a=this.validateContractAddress({blockchain:e,contractAddress:t,suiObjectId:r}),n=null!=s?s:e===exports.BlockchainName.Sui?(e=>{var t;if(!e||!e.includes("::"))return;const r=e.split("::");return(null===(t=r[r.length-1])||void 0===t?void 0:t.trim())||void 0})(r):void 0;return await this.request(hd.fetchTokenInfo,{queryParams:Object.assign({chainName:e,tokenContractAddress:a},n?{assetSymbol:n}:{})})}catch(e){throw pe.error("SDK::Wallet::fetchTokenInfo::error",e),e}}async getSupportedTokens(e){try{if(void 0!==(null==e?void 0:e.search)&&e.search.length<3)throw new V({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(hd.getSupportedTokens,{queryParams:e})}catch(e){throw pe.error("SDK::System::getSupportedTokens::error",e),e}}async getUserData(e){try{return(await this.request(hd.getUserData,{payload:{userId:e}})).user}catch(e){throw pe.error("SDK::System::getUserData::error",e),e}}async getUserByExternalUserId(e){try{return(await this.request(hd.getUserByExternalUserId,{payload:{externalUserId:e}})).user}catch(e){throw pe.error("SDK::System::getUserByExternalUserId::error",e),e}}}class xd extends dd{constructor(e,t={}){super(e,t),this.authService=new _d(e,t),this.walletService=new bd(e,t),this.userId=e.userId}async estimateFee({originAddress:e,recipientAddress:t,amount:r,transactionType:s,token:a}){try{return await this.request(ud.estimateFee,{queryParams:Object.assign({chainName:a.chainName,originAddress:e,recipientAddress:t,amount:r,assetSymbol:a.symbol,transactionType:s},a.tokenStandard&&{tokenStandard:a.tokenStandard})})}catch(e){throw pe.error("SDK::Transactions::estimateFee::error",e),e}}async getTransactionStatus({transactionHash:e,reference:t,blockchain:r}){try{return await this.request(ud.getTransaction,{payload:{transactionHash:e,transactionReference:t,chain:r.toString().toUpperCase()}})}catch(e){throw pe.error("SDK::Transactions::getTransactionStatus::error",e),e}}async getTransactions(e){try{return await this.request(ud.getTransactions,{queryParams:e})}catch(e){throw pe.error("SDK::Transactions::getTransactions::error",e),e}}async getRestriction(e){try{const t=Boolean(e.assetId),r=Boolean(e.contractAddress&&e.blockchainName);if(!t&&!r)throw new V({message:"Either assetId or both contractAddress and blockchainName must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ud.restriction,{queryParams:Object.assign(Object.assign(Object.assign({fromAddress:e.fromAddress,toAddress:e.toAddress,amount:e.amount},e.assetId&&{assetId:e.assetId}),e.contractAddress&&{contractAddress:e.contractAddress}),e.blockchainName&&{blockchainName:e.blockchainName})})}catch(e){throw pe.error("SDK::Transactions::getRestriction::error",e),e}}async transfer({originAddress:e,recipientAddress:t,amount:s,assetId:a,walletId:n,reference:i,authenticationOptions:o,memo:c,transactionType:d}){try{this.deviceAuthType===exports.AuthType.Password&&o.password&&await this.walletService.migrateToV2Safe({password:o.password,walletId:n});const{deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:u,sharesEncryptedWithWallabyPubKey:p,hasShares:y}=await this.prepareTransactionAuth(o,n);let f;if(u)f=await this.request(ud.transfer,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedSeed:u,originAddress:e,recipientAddress:t,assetId:a,amount:s,reference:i||r.v4(),memo:c,transactionType:d}});else{if(!y)throw new V({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});f=await this.request(ud.transferWithShares,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedShares:p,originAddress:e,recipientAddress:t,assetId:a,amount:s,reference:i||r.v4(),memo:c,transactionType:d}})}return f}catch(e){throw pe.error("SDK::Transactions::transfer::error",e),e}}async createAllowance({authenticationOptions:e,walletId:t,ownerAddress:r,spenderAddress:s,amount:a,assetId:n,suiObjectId:i,contractAddress:o,chainName:c,assetSymbol:d,reference:l,memo:h,transactionType:u}){try{if(!(i||o||n||d||c))throw new V({message:"AssetId, asset symbol, chain name or contract address must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(d&&!c||!d&&c)throw new V({message:"Asset symbol and chain name must be provided when asset is not in user wallet.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&e.password&&await this.walletService.migrateToV2Safe({password:e.password,walletId:t});const{deviceAuthPublicKey:p,signatureMessage:y,readyForTransportSeedPhrase:f,sharesEncryptedWithWallabyPubKey:g,hasShares:w}=await this.prepareTransactionAuth(e,t),{message:m,signature:v}=y;if(!f&&!w)throw new Error("No valid seed option found on this device.");const S=Object.assign({message:m,signature:v,walletId:t,clientAuthPubKey:p,ownerAddress:r,spenderAddress:s,chainName:c,assetSymbol:d,amount:a,assetId:n,contractAddress:null!=o?o:i,reference:l,memo:h,transactionType:u},w?{encryptedShares:g}:{encryptedSeed:f});return await this.request(ud.createAllowance,{payload:S})}catch(e){throw pe.error("SDK::Transactions::createAllowance::error",e),e}}async getPendingTransactions({walletId:e,chainName:t}){try{return await this.request(ud.getPendingTransactions,{queryParams:{walletId:e,chainName:t}})}catch(e){throw pe.error("SDK::Transactions::getPendingTransactions::error",e),e}}async resolvePendingTransaction({id:e,choice:t,symbol:r,chainName:s,walletId:a,authenticationOptions:n}){try{this.deviceAuthType===exports.AuthType.Password&&n.password&&await this.walletService.migrateToV2Safe({password:n.password,walletId:a});const{deviceAuthPublicKey:i,signatureMessage:o,readyForTransportSeedPhrase:c,sharesEncryptedWithWallabyPubKey:d,hasShares:l}=await this.prepareTransactionAuth(n,a);if(!c&&!l)throw new Error("No valid seed option found on this device.");return await this.request(ud.confirmPendingTransaction,{payload:{message:o.message,signature:o.signature,clientAuthPubKey:i,encryptedShares:d,encryptedSeed:c,id:e,choice:t,symbol:r,chainName:s,walletId:a}})}catch(e){throw pe.error("SDK::Transactions::transfer::error",e),e}}async prepareTransactionAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!i)throw new V({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:o}),d=await this.cipher.decrypt({cipherText:JSON.parse(i),decryptionKey:c.privateKey});if(!d)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ms(d),h=await this.authService.getSignature({deviceAuthKeys:{publicKey:l,privateKey:d},walletId:t,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),u=h.wallabyAuthPubKey;if(!u)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const p=[];let y;const f=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(f){const e=_a(f),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}});p.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to sign the transaction.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const a=_a(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:p,hasShares:p.length>0})}}e._([Sd("transaction-restriction-message"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],xd.prototype,"getRestriction",null),e._([Sd("transfer"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],xd.prototype,"transfer",null),e._([Sd("createAllowance"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],xd.prototype,"createAllowance",null),e._([Sd("confirmPendingTransaction"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],xd.prototype,"resolvePendingTransaction",null);const Kd={mainnet:{genesisHash:"0x6fbd74e5e1d0a61d52ccfe9d4adaed16dd3a7caa37c6bc4d0c2fa12e8b2f4063",specVersion:7003003,transactionVersion:7,ss58Format:12,balanceDecimals:6},testnet:{genesisHash:"0x2ace05e703aa50b48c0ccccfc8b424f7aab9a1e2c424ed12e45d20b1e8ffd0d6",specVersion:7003003,transactionVersion:7,ss58Format:42,balanceDecimals:6}};function Od(e){return"mainnet"===e||"testnet"===e}class Nd extends Error{constructor(e,t,r){super(r),this.name=e,this.reason=t}}class Rd extends Nd{constructor(e,t){super("PolymeshDecodeError",e,t),this.reason=e}}class Dd extends Nd{constructor(e,t){super("PolymeshVerifyError",e,t),this.reason=e}}const Ld=/^[0-9a-fA-F]*$/;function Ud(e){return"0x"+Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Bd(...e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}const qd=c.Bytes(32),Vd=c.Bytes(32),Md=c.Bytes(16),Wd=c.Bytes(32),Fd=c.u64,Gd=c.Enum({Id:qd},[0]),jd=c.Enum({Default:c._void,User:c.u64},[0,1]),Hd=c.Struct({did:Vd,kind:jd}),$d=c.Enum({SettleOnAffirmation:c._void},[0]),Yd=c.Enum({Fungible:c.Struct({sender:Hd,receiver:Hd,assetId:Md,amount:c.u128})},[0]),zd=c.Struct({fungible:c.u32,nonFungible:c.u32,offChain:c.u32}),Jd=c.Struct({senderAssetCount:zd,receiverAssetCount:zd,offchainCount:c.u32});function Xd(e){return e.replace(/^0x/i,"").toLowerCase()}const Zd={"5:1":{variant:"balances.transferWithMemo",codec:c.Struct({dest:Gd,value:c.compact,memo:c.Option(Wd)})},"37:20":{variant:"settlement.addAndAffirmWithMediators",codec:c.Struct({venueId:c.Option(c.u64),settlementType:$d,tradeDate:c.Option(c.u64),valueDate:c.Option(c.u64),legs:c.Vector(Yd),portfolios:c.Vector(Hd),instructionMemo:c.Option(Wd),mediators:c.Vector(Vd)})},"37:16":{variant:"settlement.affirmInstruction",codec:c.Struct({id:Fd,portfolios:c.Vector(Hd),numberOfAssets:c.Option(Jd)})},"37:11":{variant:"settlement.affirmInstruction",codec:c.Struct({id:Fd,portfolios:c.Vector(Hd)})},"37:17":{variant:"settlement.rejectInstruction",codec:c.Struct({id:Fd,portfolio:Hd,numberOfAssets:c.Option(zd)})},"37:13":{variant:"settlement.rejectInstruction",codec:c.Struct({id:Fd,portfolio:Hd})}};function Qd(e,t,r){if(!t.genesisHash)throw new Rd("context-not-pinned","Polymesh chain context has no pinned genesisHash — see context.ts before using this in production");if(!r.genesisHash)throw new Rd("genesis-hash-mismatch","No genesisHash was observed on the transaction under verification — cannot confirm which chain this call targets");if(Xd(r.genesisHash)!==Xd(t.genesisHash))throw new Rd("genesis-hash-mismatch",`Observed genesisHash ${r.genesisHash} does not match the pinned genesisHash ${t.genesisHash} for this network`);if(r.specVersion!==t.specVersion)throw new Rd("spec-version-mismatch",`Observed specVersion ${r.specVersion} does not match the pinned specVersion ${t.specVersion} this decoder was validated against`);if(void 0!==r.transactionVersion&&r.transactionVersion!==t.transactionVersion)throw new Rd("transaction-version-mismatch",`Observed transactionVersion ${r.transactionVersion} does not match the pinned transactionVersion ${t.transactionVersion} this decoder was validated against`);let s;try{s=function(e){const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0)throw new Error("hexToU8a: hex string must have an even number of digits");if(!Ld.test(t))throw new Error("hexToU8a: invalid hex string");const r=new Uint8Array(t.length/2);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}(e)}catch(e){throw new Rd("malformed",`Call bytes are not valid hex: ${e.message}`)}if(s.length<2)throw new Rd("malformed","Call bytes are too short to contain a pallet/call index");const[a,n]=s,i=Zd[`${a}:${n}`];if(!i)throw new Rd("unrecognized-call",`Unrecognized or unsupported Polymesh call (pallet=${a}, call=${n})`);const o=s.slice(2);let c,d;try{c=i.codec.dec(o)}catch(e){throw new Rd("malformed",`Failed to decode ${i.variant} args: ${e.message}`)}try{d=i.codec.enc(c)}catch(e){throw new Rd("malformed",`Failed to re-encode decoded ${i.variant} args: ${e.message}`)}if(!function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(d,o))throw new Rd("trailing-bytes",`Decoded ${i.variant} args do not round-trip to the original bytes — unrecognized trailing data`);return{variant:i.variant,args:c}}const el=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),tl=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),rl=new Uint32Array(32);function sl(e,t,r,s,a,n){const i=a[n],o=a[n+1];let c=rl[2*e],d=rl[2*e+1],l=rl[2*t],h=rl[2*t+1],u=rl[2*r],p=rl[2*r+1],y=rl[2*s],f=rl[2*s+1],g=nr(c,l,i);var w,m;d=ir(g,d,h,o),c=0|g,({Dh:f,Dl:y}={Dh:f^d,Dl:y^c}),({Dh:f,Dl:y}={Dh:(m=y,m),Dl:(w=f,w)}),({h:p,l:u}=ar(p,u,f,y)),({Bh:h,Bl:l}={Bh:h^p,Bl:l^u}),({Bh:h,Bl:l}={Bh:er(h,l,24),Bl:tr(h,l,24)}),rl[2*e]=c,rl[2*e+1]=d,rl[2*t]=l,rl[2*t+1]=h,rl[2*r]=u,rl[2*r+1]=p,rl[2*s]=y,rl[2*s+1]=f}function al(e,t,r,s,a,n){const i=a[n],o=a[n+1];let c=rl[2*e],d=rl[2*e+1],l=rl[2*t],h=rl[2*t+1],u=rl[2*r],p=rl[2*r+1],y=rl[2*s],f=rl[2*s+1],g=nr(c,l,i);d=ir(g,d,h,o),c=0|g,({Dh:f,Dl:y}={Dh:f^d,Dl:y^c}),({Dh:f,Dl:y}={Dh:er(f,y,16),Dl:tr(f,y,16)}),({h:p,l:u}=ar(p,u,f,y)),({Bh:h,Bl:l}={Bh:h^p,Bl:l^u}),({Bh:h,Bl:l}={Bh:rr(h,l,63),Bl:sr(h,l,63)}),rl[2*e]=c,rl[2*e+1]=d,rl[2*t]=l,rl[2*t+1]=h,rl[2*r]=u,rl[2*r+1]=p,rl[2*s]=y,rl[2*s+1]=f}class nl extends Ze{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Pe(e),Pe(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=Ke(this.buffer)}update(e){Ce(this),Te(e=Je(e));const{blockLen:t,buffer:r,buffer32:s}=this,a=e.length,n=e.byteOffset,i=e.buffer;for(let o=0;o<a;){this.pos===t&&(Be(s),this.compress(s,0,!1),Be(s),this.pos=0);const c=Math.min(t-this.pos,a-o),d=n+o;if(c!==t||d%4||!(o+c<a))r.set(e.subarray(o,o+c),this.pos),this.pos+=c,this.length+=c,o+=c;else{const e=new Uint32Array(i,d,Math.floor((a-o)/4));Be(e);for(let r=0;o+t<a;r+=s.length,o+=t)this.length+=t,this.compress(e,r,!1);Be(e)}}return this}digestInto(e){Ce(this),xe(e,this);const{pos:t,buffer32:r}=this;this.finished=!0,Oe(this.buffer.subarray(t)),Be(r),this.compress(r,0,!0),Be(r);const s=Ke(e);this.get().forEach(((e,t)=>s[t]=Ue(e)))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){const{buffer:t,length:r,finished:s,destroyed:a,outputLen:n,pos:i}=this;return e||(e=new this.constructor({dkLen:n})),e.set(...this.get()),e.buffer.set(t),e.destroyed=a,e.finished=s,e.length=r,e.pos=i,e.outputLen=n,e}clone(){return this._cloneInto()}}class il extends nl{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|tl[0],this.v0h=0|tl[1],this.v1l=0|tl[2],this.v1h=0|tl[3],this.v2l=0|tl[4],this.v2h=0|tl[5],this.v3l=0|tl[6],this.v3h=0|tl[7],this.v4l=0|tl[8],this.v4h=0|tl[9],this.v5l=0|tl[10],this.v5h=0|tl[11],this.v6l=0|tl[12],this.v6h=0|tl[13],this.v7l=0|tl[14],this.v7h=0|tl[15],function(e,t={},r,s,a){if(Pe(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");const{key:n,salt:i,personalization:o}=t;if(void 0!==n&&(n.length<1||n.length>r))throw new Error("key length must be undefined or 1.."+r);if(void 0!==i&&i.length!==s)throw new Error("salt must be undefined or "+s);if(void 0!==o&&o.length!==a)throw new Error("personalization must be undefined or "+a)}(t,e,64,16,16);let{key:r,personalization:s,salt:a}=e,n=0;if(void 0!==r&&(r=Je(r),n=r.length),this.v0l^=this.outputLen|n<<8|65536|1<<24,void 0!==a){a=Je(a);const e=Ke(a);this.v4l^=Ue(e[0]),this.v4h^=Ue(e[1]),this.v5l^=Ue(e[2]),this.v5h^=Ue(e[3])}if(void 0!==s){s=Je(s);const e=Ke(s);this.v6l^=Ue(e[0]),this.v6h^=Ue(e[1]),this.v7l^=Ue(e[2]),this.v7h^=Ue(e[3])}if(void 0!==r){const e=new Uint8Array(this.blockLen);e.set(r),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:r,v1h:s,v2l:a,v2h:n,v3l:i,v3h:o,v4l:c,v4h:d,v5l:l,v5h:h,v6l:u,v6h:p,v7l:y,v7h:f}=this;return[e,t,r,s,a,n,i,o,c,d,l,h,u,p,y,f]}set(e,t,r,s,a,n,i,o,c,d,l,h,u,p,y,f){this.v0l=0|e,this.v0h=0|t,this.v1l=0|r,this.v1h=0|s,this.v2l=0|a,this.v2h=0|n,this.v3l=0|i,this.v3h=0|o,this.v4l=0|c,this.v4h=0|d,this.v5l=0|l,this.v5h=0|h,this.v6l=0|u,this.v6h=0|p,this.v7l=0|y,this.v7h=0|f}compress(e,t,r){this.get().forEach(((e,t)=>rl[t]=e)),rl.set(tl,16);let{h:s,l:a}=Jt(BigInt(this.length));rl[24]=tl[8]^a,rl[25]=tl[9]^s,r&&(rl[28]=~rl[28],rl[29]=~rl[29]);let n=0;const i=el;for(let r=0;r<12;r++)sl(0,4,8,12,e,t+2*i[n++]),al(0,4,8,12,e,t+2*i[n++]),sl(1,5,9,13,e,t+2*i[n++]),al(1,5,9,13,e,t+2*i[n++]),sl(2,6,10,14,e,t+2*i[n++]),al(2,6,10,14,e,t+2*i[n++]),sl(3,7,11,15,e,t+2*i[n++]),al(3,7,11,15,e,t+2*i[n++]),sl(0,5,10,15,e,t+2*i[n++]),al(0,5,10,15,e,t+2*i[n++]),sl(1,6,11,12,e,t+2*i[n++]),al(1,6,11,12,e,t+2*i[n++]),sl(2,7,8,13,e,t+2*i[n++]),al(2,7,8,13,e,t+2*i[n++]),sl(3,4,9,14,e,t+2*i[n++]),al(3,4,9,14,e,t+2*i[n++]);this.v0l^=rl[0]^rl[16],this.v0h^=rl[1]^rl[17],this.v1l^=rl[2]^rl[18],this.v1h^=rl[3]^rl[19],this.v2l^=rl[4]^rl[20],this.v2h^=rl[5]^rl[21],this.v3l^=rl[6]^rl[22],this.v3h^=rl[7]^rl[23],this.v4l^=rl[8]^rl[24],this.v4h^=rl[9]^rl[25],this.v5l^=rl[10]^rl[26],this.v5h^=rl[11]^rl[27],this.v6l^=rl[12]^rl[28],this.v6h^=rl[13]^rl[29],this.v7l^=rl[14]^rl[30],this.v7h^=rl[15]^rl[31],Oe(rl)}destroy(){this.destroyed=!0,Oe(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const ol=et((e=>new il(e))),cl="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const dl=(new TextEncoder).encode("SS58PRE");function ll(e,t){if(32!==e.length)throw new Error("encodeAccountId32: expected a 32-byte public key");if(t<0||t>=64)throw new Error("encodeAccountId32: only single-byte ss58Format prefixes (0-63) are supported");const r=Bd(new Uint8Array([t]),e),s=function(e){return ol(Bd(dl,e),{dkLen:64}).slice(0,2)}(r);return function(e){let t=0;for(;t<e.length&&0===e[t];)t++;const r=[];for(let s=t;s<e.length;s++){let t=e[s];for(let e=0;e<r.length;e++)t+=r[e]<<8,r[e]=t%58,t=Math.floor(t/58);for(;t>0;)r.push(t%58),t=Math.floor(t/58)}let s=cl[0].repeat(t);for(let e=r.length-1;e>=0;e--)s+=cl[r[e]];return s}(Bd(r,s))}const hl=/^\d+$/,ul=/^\d+(?:\.\d+)?$/;function pl(e){return e.replace(/^0x/i,"").replace(/-/g,"").toLowerCase()}function yl(e,t,r="amount"){if("string"!=typeof e||!ul.test(e))throw new Dd("intent-field-malformed",`intent.${r} must be a non-negative decimal string in human-readable units (e.g. "1.5"), got ${JSON.stringify(e)}`);const[s,a=""]=e.split(".");if(a.length>t)throw new Dd("intent-field-malformed",`intent.${r} "${e}" has ${a.length} decimal places, more than this chain's ${t} — refusing to round a verification input`);return BigInt(s+a.padEnd(t,"0"))}function fl(e,t,r){const s=e[t];if(!s)throw new Dd("intent-field-missing",`${r}: intent.${String(t)} is required to verify this call — refusing to report a call as verified with this field unchecked`);return s}function gl(e,t,r){const s=[],{ss58Format:a,balanceDecimals:n}=r;switch(e.variant){case"balances.transferWithMemo":{const{args:r}=e,i=fl(t,"recipientAddress",e.variant),o=ll(r.dest.value,a);s.push({field:"destination",enforced:!0,matched:o===i,expected:t.recipientAddress,actual:o});const c=yl(fl(t,"amount",e.variant),n);s.push({field:"amount",enforced:!0,matched:BigInt(r.value)===c,expected:c.toString(),actual:String(r.value)});const d=fl(t,"assetSymbol",e.variant),l="POLYX";s.push({field:"asset",enforced:!0,matched:d.toUpperCase()===l,expected:d,actual:l});break}case"settlement.addAndAffirmWithMediators":{const{args:r}=e;if(1!==r.legs.length)throw new Dd("unsupported-call-shape",`settlement.addAndAffirmWithMediators carries ${r.legs.length} legs; an Intent describes a single transfer, so this call shape cannot be verified`);const a=r.legs[0].value;s.push({field:"destination",enforced:!1,actual:`did:${Ud(a.receiver.did)}`});const i=yl(fl(t,"amount",e.variant),n);s.push({field:"amount",enforced:!0,matched:BigInt(a.amount)===i,expected:i.toString(),actual:String(a.amount)});const o=fl(t,"assetId",e.variant),c=Ud(a.assetId);s.push({field:"asset",enforced:!0,matched:pl(c)===pl(o),expected:o,actual:c});break}case"settlement.affirmInstruction":case"settlement.rejectInstruction":{const{args:r}=e,a=function(e,t){if("string"!=typeof e||!hl.test(e))throw new Dd("intent-field-malformed",`intent.${t} must be a plain base-10 integer string, got ${JSON.stringify(e)}`);return BigInt(e)}(fl(t,"instructionId",e.variant),"instructionId");s.push({field:"instructionId",enforced:!0,matched:BigInt(r.id)===a,expected:a.toString(),actual:String(r.id)});const n=fl(t,"instructionDecision",e.variant),i="settlement.affirmInstruction"===e.variant?"approve":"deny";s.push({field:"instructionDecision",enforced:!0,matched:i===n,expected:n,actual:i});break}default:throw new Dd("unsupported-call-shape",`No verification rules are defined for Polymesh call variant "${e.variant}"`)}const i=s.filter((e=>e.enforced));if(0===i.length)throw new Dd("no-enforced-fields",`${e.variant} produced no enforced fields — refusing to report a call as verified with nothing checked`);return{chainName:exports.BlockchainName.Polymesh,callVariant:e.variant,fields:s,verified:i.every((e=>!0===e.matched))}}function wl(e,t,r,s){if(!Od(r))throw new Dd("intent-field-malformed",`Unknown Polymesh network ${JSON.stringify(r)} — expected "mainnet" or "testnet"`);const a=Kd[r];return gl(Qd(e,a,s),t,a)}const ml=Object.freeze(Object.defineProperty({__proto__:null,POLYMESH_CONTEXT:Kd,PolymeshDecodeError:Rd,PolymeshVerificationError:Nd,PolymeshVerifyError:Dd,decimalAmountToBaseUnits:yl,decodePolymeshCall:Qd,isPolymeshNetwork:Od,verifyPolymeshCallAgainstIntent:wl,verifyPolymeshIntent:gl},Symbol.toStringTag,{value:"Module"}));exports.WallabyApiClient=e.A,exports.WallabyHttpClient=e.H,exports.AndroidVersionNotSupportedError=F,exports.AuthenticatorGeneralError=se,exports.AuthenticatorMissingDiscoverableCredentialSupportError=ae,exports.AuthenticatorMissingUserVerificationSupportError=ne,exports.AuthenticatorNoSupportedPubKeyCredParamsAlgError=ce,exports.AuthenticatorNotRegisteredError={error:"ERROR_AUTHENTICATOR_NOT_REGISTERED",message:"Authenticator is not registered."},exports.AuthenticatorPreviouslyRegisteredError=ie,exports.AutoRegisterUserVerificationFailureError=de,exports.BadConfiguration=Y,exports.CeremonyAbortedError=Z,exports.IOSVersionNotSupportedError=W,exports.InterruptedError=J,exports.InvalidChallengeError=H,exports.InvalidDomainError=Q,exports.InvalidRpIdError=ee,exports.InvalidStateError=oe,exports.InvalidUserIdError=$,exports.InvalidUserIdLengthError=te,exports.MalformedPubKeyCredParamsError=re,exports.NativeError=(e="An unknown error occurred")=>({error:"Unknown",message:e}),exports.NoCredentialsError=z,exports.NotAllowedError={error:"NotAllowedError",message:"CredentialContainer request is not allowed."},exports.PasskeyErrorCodes=he,exports.PassthroughSeeCausePropertyError=le,exports.RequestFailedError=G,exports.TimeoutError=X,exports.UnknownError=M,exports.UserCancelledError=j,exports.Wallaby=class{constructor(e,t={}){this.wallet=new bd(e,t),this.walletData=new Id(e,t),this.utils=new Pd(e,t),this.auth=new _d(e,t),this.system=new Cd(e,t),this.transactions=new xd(e,t),this.swap=new kd(e,t),this.httpApi=new Td(e,t)}get version(){return _e}},exports.WallabyError=V,exports.createIdentity=Ls,exports.decryptWithPrivateKey=wa,exports.encryptWithPublicKey=ga,exports.hash=Sa,exports.isValidSeedPhrase=Ma,exports.keccak256=ma,exports.normalizeSeedPhrase=Va,exports.publicKeyByPrivateKey=ms,exports.recoverPublicKey=(e,t)=>{const r=qt(e),s=r.substring(0,r.length-2),a="1c"===r.slice(-2)?1:0;let n=Me(va(Ut(s),a,Ut(qt(t)),!1));return n=n.slice(2),n},exports.sign=Us,exports.verification=ml,exports.verifyCallAgainstIntent=function(e,t,r,s,a){if(r.chainName!==e)throw new Error(`verifyCallAgainstIntent: intent is for chain "${r.chainName}" but the call is for "${e}" — refusing to verify across chains`);if(e===exports.BlockchainName.Polymesh)return wl(t,r,s,a);throw new Error(`verifyCallAgainstIntent: no verifier registered for chain "${e}"`)};//# sourceMappingURL=index.cjs.map