wallaby-cash 3.8.0 → 3.9.0

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.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("bip39"),t=require("uuid"),r=require("loglevel"),s=require("crypto-js"),a=require("jwt-decode"),n=require("@simplewebauthn/browser"),o=require("js-base64"),i=e=>e&&"object"==typeof e&&"default"in e?e:{default:e};function c(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 d=c(e),l=i(r),h=c(n);function p(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(s=Object.getOwnPropertySymbols(e);a<s.length;a++)t.indexOf(s[a])<0&&Object.prototype.propertyIsEnumerable.call(e,s[a])&&(r[s[a]]=e[s[a]])}return r}function u(e,t,r,s){var a,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var i=e.length-1;i>=0;i--)(a=e[i])&&(o=(n<3?a(o):n>3?a(t,r,o):a(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o}function y(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}var g,f,m,w,v,S,A,b,E,_,T,P,I,k,C,O,K,x,R,N,D,L,q,U,j,B;"function"==typeof SuppressedError&&SuppressedError,exports.PasskeyChallengeType=void 0,(g=exports.PasskeyChallengeType||(exports.PasskeyChallengeType={})).REGISTRATION="webauthn.create",g.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,(m=exports.TransportEnum||(exports.TransportEnum={})).Usb="usb",m.Nfc="nfc",m.Ble="ble",m.Internal="internal",m.Hybrid="hybrid";class M extends Error{constructor(e){var t;const{message:r,statusCode:s,errorCode:a,kind:n,data:o,cause:i,onError:c}=e;super(r),this.name="WallabyError",this.status=s,this.errorCode=a,this.kind=null!=n?n:M.inferKind(s,a),this.cause=i,this.onError=c,this.data=o,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 M}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,(v=exports.AssetConfigStatus||(exports.AssetConfigStatus={})).Active="active",v.Inactive="inactive",exports.AssetType=void 0,(S=exports.AssetType||(exports.AssetType={})).Coin="COIN",S.Token="TOKEN",exports.OwnershipType=void 0,(A=exports.OwnershipType||(exports.OwnershipType={})).SingleOwner="SINGLE_OWNER",A.MultiSig="MULTI_SIG",exports.TokenStandard=void 0,(b=exports.TokenStandard||(exports.TokenStandard={})).Erc20="ERC_20",b.Erc1404="ERC_1404",b.Arc20="ARC_20",b.Arc1404="ARC_1404",b.Mrc20="MRC_20",b.Bep20="BEP_20",b.AlgoStandard="ALGO_STANDARD",b.AlgoApp="ALGO_APP",b.TokenFactory="TOKEN_FACTORY",b.SeiErc20="SEI_ERC_20",b.AptFA="APT_FUNGIBLE_ASSET",exports.AddressType=void 0,(E=exports.AddressType||(exports.AddressType={})).Segwit="SEGWIT",E.Legacy="LEGACY",E.Default="DEFAULT",exports.BlockchainStatus=void 0,(_=exports.BlockchainStatus||(exports.BlockchainStatus={})).Up="UP",_.Down="DOWN",exports.BlockchainSlip44=void 0,(T=exports.BlockchainSlip44||(exports.BlockchainSlip44={}))[T.BTC=0]="BTC",T[T.ETH=60]="ETH",T[T.ALGO=283]="ALGO",T[T.AVAX=9e3]="AVAX",T[T.MATIC=966]="MATIC",T[T.BSC=519]="BSC",T[T.BASE=8453]="BASE",T[T.SUI=784]="SUI",T[T.INJ=2525]="INJ",T[T.SEI=19000118]="SEI",T[T.APT=637]="APT",T[T.HBAR=3030]="HBAR",T[T.POLYX=595]="POLYX",exports.BlockchainName=void 0,(P=exports.BlockchainName||(exports.BlockchainName={})).Algorand="ALGORAND",P.Aptos="APTOS",P.Avalanche="AVALANCHE",P.Base="BASE",P.Bitcoin="BITCOIN",P.Bsc="BSC",P.Canton="CANTON",P.Ethereum="ETHEREUM",P.Hedera="HEDERA",P.Injective="INJECTIVE",P.Polygon="POLYGON",P.Polymesh="POLYMESH",P.Sei="SEI",P.Sui="SUI",P.Solana="SOLANA",exports.RequestMethod=void 0,(I=exports.RequestMethod||(exports.RequestMethod={})).Post="POST",I.Get="GET",I.Put="PUT",I.Delete="DELETE",exports.ApiKeyStatus=void 0,(k=exports.ApiKeyStatus||(exports.ApiKeyStatus={})).Active="active",k.Inactive="inactive",exports.TransactionEntryType=void 0,(C=exports.TransactionEntryType||(exports.TransactionEntryType={})).INCOMING="INCOMING",C.OUTGOING="OUTGOING",C.UNKNOWN="UNKNOWN",exports.KeyTypeName=void 0,(O=exports.KeyTypeName||(exports.KeyTypeName={})).WallabyShare="wallaby_share",O.OwnerMainDeviceShare="owner_main_device_share",O.OwnerBackupDeviceShare="owner_backup_device_share",exports.SeedPhraseType=void 0,(K=exports.SeedPhraseType||(exports.SeedPhraseType={})).Standard="standard",K.Algorand="algorand",exports.WalletAddressTypeName=void 0,(x=exports.WalletAddressTypeName||(exports.WalletAddressTypeName={})).BTC_MAINNET_SEGWIT="BTC:MAINNET:SEGWIT",x.BTC_MAINNET_LEGACY="BTC:MAINNET:LEGACY",x.BTC_TESTNET_SEGWIT="BTC:TESTNET:SEGWIT",x.BTC_TESTNET_LEGACY="BTC:TESTNET:LEGACY",x.ETH="ETH:ALL:DEFAULT",x.ALGO="ALGO:ALL:DEFAULT",x.SUI="SUI:ALL:DEFAULT",x.INJ="INJ:ALL:DEFAULT",x.APT="APT:ALL:DEFAULT",x.POLYX="POLYX:ALL:DEFAULT",x.BSC="BSC:ALL:DEFAULT",x.AVAX="AVAX:ALL:DEFAULT",x.MATIC="MATIC:ALL:DEFAULT",x.BASE="BASE:ALL:DEFAULT",x.SEI="SEI:ALL:DEFAULT",x.HBAR="HBAR:ALL:DEFAULT",x.CC="CC:ALL:DEFAULT",exports.ReturnWalletOption=void 0,(R=exports.ReturnWalletOption||(exports.ReturnWalletOption={})).ReturnOnlyEncryptedShares="RETURN_ONLY_ENCRYPTED_SHARES",R.ReturnOnlyEncryptedSeedPhrase="RETURN_ONLY_ENCRYPTED_SEED_PHRASE",R.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,(D=exports.AuthType||(exports.AuthType={})).Password="password",D.Passkey="passkey",exports.LocalStorageItems=void 0,(L=exports.LocalStorageItems||(exports.LocalStorageItems={})).AccessToken="access-token",L.RefreshToken="refresh-token",L.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",L.EncryptedKeyShares="encrypted-key-shares",L.PrimaryDeviceKeyShare="primary-device-key-share",L.BackupDeviceKeyShare="backup-device-key-share",L.EncryptedShare="encrypted-share",L.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",L.EncryptedDevicePrivateKey="encrypted-private-key",L.ClientAuthPublicKey="client-auth-pub-key",L.ClientAuthToken="republic-jwt",L.PasskeyCredential="pass-key-credential",L.Blob="blob",exports.LegacyKeyNames=void 0,(q=exports.LegacyKeyNames||(exports.LegacyKeyNames={})).EncryptedPrivateKey="encryptedPrivateKey",q.WallabyAuthPubKey="wallabyAuthPubKey",q.EncryptedAlgorandSeed="encryptedAlgorandSeed",q.EncryptedSeed="encryptedSeed",q.ClientAuthToken="republic_jwt",q.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,(j=exports.V2KeyNames||(exports.V2KeyNames={})).AccessToken="access-token",j.RefreshToken="refresh-token",j.BackupDeviceKeyShare="backup-device-key-share",j.ClientAuthPublicKey="client-auth-pub-key",j.ClientAuthToken="republic-jwt",j.EncryptedDevicePrivateKey="encrypted-private-key",j.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",j.PasskeyCredential="pass-key-credential",j.PrimaryDeviceKeyShare="primary-device-key-share",j.WallabyAuthPubKey="wallaby-auth-pub-key",j.MigrationVersion="wsdk_migrated_with_version",j.LastMigratedAt="wsdk_last_migrated_at",j.PasswordResetAttempts="wsdk_password_reset_attempts",j.MigrationAttempts="wsdk_migration_attempts",j.CredentialConversionInProgress="credential-conversion-in-progress",j.PendingCommit="pending-commit",exports.ErrorResponseCodes=void 0,(B=exports.ErrorResponseCodes||(exports.ErrorResponseCodes={})).request_payload_missing="request_payload_missing",B.request_payload_wrong_format="request_payload_wrong_format",B.auth_api_key_invalid="auth_api_key_invalid",B.auth_api_key_not_active="auth_api_key_not_active",B.auth_api_key_pub_key_not_set="auth_api_key_pub_key_not_set",B.auth_api_key_not_provided="auth_api_key_not_provided",B.auth_api_key_not_found="auth_api_key_not_found",B.auth_origin_not_allowed="auth_origin_not_allowed",B.auth_api_jwt_invalid="auth_api_jwt_invalid",B.auth_api_jwt_not_active="auth_api_jwt_not_active",B.auth_api_jwt_not_provided="auth_api_jwt_not_provided",B.auth_api_jwt_expired="auth_api_jwt_expired",B.auth_api_unauthorized="auth_api_unauthorized",B.auth_refresh_token_not_found="auth_refresh_token_not_found",B.auth_refresh_token_expired="auth_refresh_token_expired",B.auth_refresh_token_reuse_detected="auth_refresh_token_reuse_detected",B.auth_client_jwt_invalid="auth_client_jwt_invalid",B.auth_client_jwt_missing_external_id_payload="auth_client_jwt_missing_external_id_payload",B.auth_client_jwt_missing_exp_payload="auth_client_jwt_missing_exp_payload",B.auth_client_jwt_external_id_not_match="auth_client_jwt_external_id_not_match",B.auth_client_jwt_expired="auth_client_jwt_expired",B.auth_client_jwt_not_provided="auth_client_jwt_not_provided",B.auth_client_jwt_invalid_auth_type="auth_client_jwt_invalid_auth_type",B.auth_client_jwt_invalid_passkey="auth_client_jwt_invalid_passkey",B.auth_client_pub_key_and_message_not_match="auth_client_pub_key_and_message_not_match",B.auth_client_pub_key_and_message_expired="auth_client_pub_key_and_message_expired",B.auth_client_pub_key_and_message_signature_failed="auth_client_pub_key_and_message_signature_failed",B.auth_client_pub_key_not_found="auth_client_pub_key_not_found",B.auth_user_not_allowed_to_perform_the_action="auth_user_not_allowed_to_perform_the_action",B.multisig_participant_not_found="multisig_participant_not_found",B.wallet_not_found="wallet_not_found",B.asset_not_found="asset_not_found",B.seedphrase_could_not_be_decrypted="seedphrase_could_not_be_decrypted",B.user_already_exists="user_already_exists",B.user_not_found="user_not_found",B.otp_code_invalid="otp_code_invalid",B.otp_code_expired="otp_code_expired",B.merchant_not_found="merchant_not_found",B.sdk_jwt_invalid="sdk_jwt_invalid",B.sdk_jwt_expired="sdk_jwt_expired",B.sdk_unknown_error="sdk_unknown_error",B.sdk_too_many_requests="sdk_too_many_requests",B.sdk_seed_phrase_decryption_failed="sdk_seed_phrase_decryption_failed",B.sdk_key_shares_not_found="sdk_key_shares_not_found",B.sdk_key_share_decryption_failed="sdk_key_share_decryption_failed",B.sdk_seed_phrase_not_found="sdk_seed_phrase_not_found",B.sdk_private_key_decryption_failed="sdk_private_key_decryption_failed",B.sdk_private_key_not_found="sdk_private_key_not_found",B.sdk_device_key_missing_with_existing_data="sdk_device_key_missing_with_existing_data",B.sdk_refresh_token_missing="sdk_refresh_token_missing",B.sdk_missing_parameter="sdk_missing_parameter",B.sdk_invalid_parameter="sdk_invalid_parameter",B.sdk_invalid_response="sdk_invalid_response",B.sdk_wrong_password="sdk_wrong_password",B.sdk_no_valid_seed_option="sdk_no_valid_seed_option",B.sdk_passkey_prf_not_available="sdk_passkey_prf_not_available",B.sdk_passkey_challenge_unavailable="sdk_passkey_challenge_unavailable",B.sdk_passkey_authentication_failed="sdk_passkey_authentication_failed",B.sdk_passkey_registration_failed="sdk_passkey_registration_failed";const W={error:"UnknownError",message:"An unknown error occurred"},V={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."},H={error:"UserCancelled",message:"The user cancelled the request."},$={error:"InvalidChallenge",message:"The provided challenge was invalid"},J={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."},Z={error:"Interrupted",message:"The operation was interrupted and may be retried."},X={error:"TimedOut",message:"The operation timed out."},Q={error:"ERROR_CEREMONY_ABORTED",message:"User did not complete the request in time."},ee={error:"ERROR_INVALID_DOMAIN",message:"Invalid domain."},te={error:"ERROR_INVALID_RP_ID",message:"Invalid Relying Party ID."},re={error:"ERROR_INVALID_USER_ID_LENGTH",message:"Invalid user ID length."},se={error:"ERROR_MALFORMED_PUBKEYCREDPARAMS",message:"Malformed public key credential parameters."},ae={error:"ERROR_AUTHENTICATOR_GENERAL_ERROR",message:"Authenticator encountered a general error."},ne={error:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",message:"Authenticator does not support discoverable credentials."},oe={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."},ce={error:"InvalidStateError",message:"The authenticator was previously registered"},de={error:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",message:"Authenticator does not support any of the provided public key credential parameters algorithms."},le={error:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",message:"User verification failed during auto-registration."},he={error:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",message:"An error occurred. See the cause property for more details."},pe=[W,V,F,G,H,$,J,Y,z,Z,X,Q,ee,te,re,se,ae,ne,oe,ie,de,le,he];let ue=!1;"undefined"!=typeof window&&window.localStorage&&(ue="true"===window.localStorage.getItem("wsdk:enable_logging")),ue&&l.default.setLevel("trace");const ye=l.default;var ge,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 me=null!==(ge={env:{}}.env.NODE_ENV)&&void 0!==ge?ge:"development",we="testnet",ve="9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe75d907fe6db9e4c";exports.PublicKeyCredentialAlgorithm.RS256,exports.PublicKeyCredentialAlgorithm.ES256;const Se="undefined"!=typeof window&&"undefined"!=typeof document,Ae={platform:"web",isNative:!Se,isWeb:Se},be="3.8.0",Ee=e=>e.replace(/:/g,"_"),_e="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Te(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Pe(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("bip39"),t=require("uuid"),r=require("loglevel"),s=require("crypto-js"),a=require("jwt-decode"),n=require("@simplewebauthn/browser"),o=require("js-base64"),i=e=>e&&"object"==typeof e&&"default"in e?e:{default:e};function c(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 d=c(e),l=i(r),h=c(n);function p(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(s=Object.getOwnPropertySymbols(e);a<s.length;a++)t.indexOf(s[a])<0&&Object.prototype.propertyIsEnumerable.call(e,s[a])&&(r[s[a]]=e[s[a]])}return r}function u(e,t,r,s){var a,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var i=e.length-1;i>=0;i--)(a=e[i])&&(o=(n<3?a(o):n>3?a(t,r,o):a(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o}function y(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}var g,f,m,w,v,S,A,b,E,_,T,P,I,k,C,O,K,x,R,N,D,L,q,U,j,B;"function"==typeof SuppressedError&&SuppressedError,exports.PasskeyChallengeType=void 0,(g=exports.PasskeyChallengeType||(exports.PasskeyChallengeType={})).REGISTRATION="webauthn.create",g.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,(m=exports.TransportEnum||(exports.TransportEnum={})).Usb="usb",m.Nfc="nfc",m.Ble="ble",m.Internal="internal",m.Hybrid="hybrid";class M extends Error{constructor(e){var t;const{message:r,statusCode:s,errorCode:a,kind:n,data:o,cause:i,onError:c}=e;super(r),this.name="WallabyError",this.status=s,this.errorCode=a,this.kind=null!=n?n:M.inferKind(s,a),this.cause=i,this.onError=c,this.data=o,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 M}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,(v=exports.AssetConfigStatus||(exports.AssetConfigStatus={})).Active="active",v.Inactive="inactive",exports.AssetType=void 0,(S=exports.AssetType||(exports.AssetType={})).Coin="COIN",S.Token="TOKEN",exports.OwnershipType=void 0,(A=exports.OwnershipType||(exports.OwnershipType={})).SingleOwner="SINGLE_OWNER",A.MultiSig="MULTI_SIG",exports.TokenStandard=void 0,(b=exports.TokenStandard||(exports.TokenStandard={})).Erc20="ERC_20",b.Erc1404="ERC_1404",b.Arc20="ARC_20",b.Arc1404="ARC_1404",b.Mrc20="MRC_20",b.Bep20="BEP_20",b.AlgoStandard="ALGO_STANDARD",b.AlgoApp="ALGO_APP",b.TokenFactory="TOKEN_FACTORY",b.SeiErc20="SEI_ERC_20",b.AptFA="APT_FUNGIBLE_ASSET",exports.AddressType=void 0,(E=exports.AddressType||(exports.AddressType={})).Segwit="SEGWIT",E.Legacy="LEGACY",E.Default="DEFAULT",exports.BlockchainStatus=void 0,(_=exports.BlockchainStatus||(exports.BlockchainStatus={})).Up="UP",_.Down="DOWN",exports.BlockchainSlip44=void 0,(T=exports.BlockchainSlip44||(exports.BlockchainSlip44={}))[T.BTC=0]="BTC",T[T.ETH=60]="ETH",T[T.ALGO=283]="ALGO",T[T.AVAX=9e3]="AVAX",T[T.MATIC=966]="MATIC",T[T.BSC=519]="BSC",T[T.BASE=8453]="BASE",T[T.SUI=784]="SUI",T[T.INJ=2525]="INJ",T[T.SEI=19000118]="SEI",T[T.APT=637]="APT",T[T.HBAR=3030]="HBAR",T[T.POLYX=595]="POLYX",exports.BlockchainName=void 0,(P=exports.BlockchainName||(exports.BlockchainName={})).Algorand="ALGORAND",P.Aptos="APTOS",P.Avalanche="AVALANCHE",P.Base="BASE",P.Bitcoin="BITCOIN",P.Bsc="BSC",P.Canton="CANTON",P.Ethereum="ETHEREUM",P.Hedera="HEDERA",P.Injective="INJECTIVE",P.Polygon="POLYGON",P.Polymesh="POLYMESH",P.Sei="SEI",P.Sui="SUI",P.Solana="SOLANA",exports.RequestMethod=void 0,(I=exports.RequestMethod||(exports.RequestMethod={})).Post="POST",I.Get="GET",I.Put="PUT",I.Delete="DELETE",exports.ApiKeyStatus=void 0,(k=exports.ApiKeyStatus||(exports.ApiKeyStatus={})).Active="active",k.Inactive="inactive",exports.TransactionEntryType=void 0,(C=exports.TransactionEntryType||(exports.TransactionEntryType={})).INCOMING="INCOMING",C.OUTGOING="OUTGOING",C.UNKNOWN="UNKNOWN",exports.KeyTypeName=void 0,(O=exports.KeyTypeName||(exports.KeyTypeName={})).WallabyShare="wallaby_share",O.OwnerMainDeviceShare="owner_main_device_share",O.OwnerBackupDeviceShare="owner_backup_device_share",exports.SeedPhraseType=void 0,(K=exports.SeedPhraseType||(exports.SeedPhraseType={})).Standard="standard",K.Algorand="algorand",exports.WalletAddressTypeName=void 0,(x=exports.WalletAddressTypeName||(exports.WalletAddressTypeName={})).BTC_MAINNET_SEGWIT="BTC:MAINNET:SEGWIT",x.BTC_MAINNET_LEGACY="BTC:MAINNET:LEGACY",x.BTC_TESTNET_SEGWIT="BTC:TESTNET:SEGWIT",x.BTC_TESTNET_LEGACY="BTC:TESTNET:LEGACY",x.ETH="ETH:ALL:DEFAULT",x.ALGO="ALGO:ALL:DEFAULT",x.SUI="SUI:ALL:DEFAULT",x.INJ="INJ:ALL:DEFAULT",x.APT="APT:ALL:DEFAULT",x.POLYX="POLYX:ALL:DEFAULT",x.BSC="BSC:ALL:DEFAULT",x.AVAX="AVAX:ALL:DEFAULT",x.MATIC="MATIC:ALL:DEFAULT",x.BASE="BASE:ALL:DEFAULT",x.SEI="SEI:ALL:DEFAULT",x.HBAR="HBAR:ALL:DEFAULT",x.CC="CC:ALL:DEFAULT",exports.ReturnWalletOption=void 0,(R=exports.ReturnWalletOption||(exports.ReturnWalletOption={})).ReturnOnlyEncryptedShares="RETURN_ONLY_ENCRYPTED_SHARES",R.ReturnOnlyEncryptedSeedPhrase="RETURN_ONLY_ENCRYPTED_SEED_PHRASE",R.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,(D=exports.AuthType||(exports.AuthType={})).Password="password",D.Passkey="passkey",exports.LocalStorageItems=void 0,(L=exports.LocalStorageItems||(exports.LocalStorageItems={})).AccessToken="access-token",L.RefreshToken="refresh-token",L.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",L.EncryptedKeyShares="encrypted-key-shares",L.PrimaryDeviceKeyShare="primary-device-key-share",L.BackupDeviceKeyShare="backup-device-key-share",L.EncryptedShare="encrypted-share",L.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",L.EncryptedDevicePrivateKey="encrypted-private-key",L.ClientAuthPublicKey="client-auth-pub-key",L.ClientAuthToken="republic-jwt",L.PasskeyCredential="pass-key-credential",L.Blob="blob",exports.LegacyKeyNames=void 0,(q=exports.LegacyKeyNames||(exports.LegacyKeyNames={})).EncryptedPrivateKey="encryptedPrivateKey",q.WallabyAuthPubKey="wallabyAuthPubKey",q.EncryptedAlgorandSeed="encryptedAlgorandSeed",q.EncryptedSeed="encryptedSeed",q.ClientAuthToken="republic_jwt",q.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,(j=exports.V2KeyNames||(exports.V2KeyNames={})).AccessToken="access-token",j.RefreshToken="refresh-token",j.BackupDeviceKeyShare="backup-device-key-share",j.ClientAuthPublicKey="client-auth-pub-key",j.ClientAuthToken="republic-jwt",j.EncryptedDevicePrivateKey="encrypted-private-key",j.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",j.PasskeyCredential="pass-key-credential",j.PrimaryDeviceKeyShare="primary-device-key-share",j.WallabyAuthPubKey="wallaby-auth-pub-key",j.MigrationVersion="wsdk_migrated_with_version",j.LastMigratedAt="wsdk_last_migrated_at",j.PasswordResetAttempts="wsdk_password_reset_attempts",j.MigrationAttempts="wsdk_migration_attempts",j.CredentialConversionInProgress="credential-conversion-in-progress",j.PendingCommit="pending-commit",exports.ErrorResponseCodes=void 0,(B=exports.ErrorResponseCodes||(exports.ErrorResponseCodes={})).request_payload_missing="request_payload_missing",B.request_payload_wrong_format="request_payload_wrong_format",B.auth_api_key_invalid="auth_api_key_invalid",B.auth_api_key_not_active="auth_api_key_not_active",B.auth_api_key_pub_key_not_set="auth_api_key_pub_key_not_set",B.auth_api_key_not_provided="auth_api_key_not_provided",B.auth_api_key_not_found="auth_api_key_not_found",B.auth_origin_not_allowed="auth_origin_not_allowed",B.auth_api_jwt_invalid="auth_api_jwt_invalid",B.auth_api_jwt_not_active="auth_api_jwt_not_active",B.auth_api_jwt_not_provided="auth_api_jwt_not_provided",B.auth_api_jwt_expired="auth_api_jwt_expired",B.auth_api_unauthorized="auth_api_unauthorized",B.auth_refresh_token_not_found="auth_refresh_token_not_found",B.auth_refresh_token_expired="auth_refresh_token_expired",B.auth_refresh_token_reuse_detected="auth_refresh_token_reuse_detected",B.auth_client_jwt_invalid="auth_client_jwt_invalid",B.auth_client_jwt_missing_external_id_payload="auth_client_jwt_missing_external_id_payload",B.auth_client_jwt_missing_exp_payload="auth_client_jwt_missing_exp_payload",B.auth_client_jwt_external_id_not_match="auth_client_jwt_external_id_not_match",B.auth_client_jwt_expired="auth_client_jwt_expired",B.auth_client_jwt_not_provided="auth_client_jwt_not_provided",B.auth_client_jwt_invalid_auth_type="auth_client_jwt_invalid_auth_type",B.auth_client_jwt_invalid_passkey="auth_client_jwt_invalid_passkey",B.auth_client_pub_key_and_message_not_match="auth_client_pub_key_and_message_not_match",B.auth_client_pub_key_and_message_expired="auth_client_pub_key_and_message_expired",B.auth_client_pub_key_and_message_signature_failed="auth_client_pub_key_and_message_signature_failed",B.auth_client_pub_key_not_found="auth_client_pub_key_not_found",B.auth_user_not_allowed_to_perform_the_action="auth_user_not_allowed_to_perform_the_action",B.multisig_participant_not_found="multisig_participant_not_found",B.wallet_not_found="wallet_not_found",B.asset_not_found="asset_not_found",B.seedphrase_could_not_be_decrypted="seedphrase_could_not_be_decrypted",B.user_already_exists="user_already_exists",B.user_not_found="user_not_found",B.otp_code_invalid="otp_code_invalid",B.otp_code_expired="otp_code_expired",B.merchant_not_found="merchant_not_found",B.sdk_jwt_invalid="sdk_jwt_invalid",B.sdk_jwt_expired="sdk_jwt_expired",B.sdk_unknown_error="sdk_unknown_error",B.sdk_too_many_requests="sdk_too_many_requests",B.sdk_seed_phrase_decryption_failed="sdk_seed_phrase_decryption_failed",B.sdk_key_shares_not_found="sdk_key_shares_not_found",B.sdk_key_share_decryption_failed="sdk_key_share_decryption_failed",B.sdk_seed_phrase_not_found="sdk_seed_phrase_not_found",B.sdk_private_key_decryption_failed="sdk_private_key_decryption_failed",B.sdk_private_key_not_found="sdk_private_key_not_found",B.sdk_device_key_missing_with_existing_data="sdk_device_key_missing_with_existing_data",B.sdk_refresh_token_missing="sdk_refresh_token_missing",B.sdk_missing_parameter="sdk_missing_parameter",B.sdk_invalid_parameter="sdk_invalid_parameter",B.sdk_invalid_response="sdk_invalid_response",B.sdk_wrong_password="sdk_wrong_password",B.sdk_no_valid_seed_option="sdk_no_valid_seed_option",B.sdk_passkey_prf_not_available="sdk_passkey_prf_not_available",B.sdk_passkey_challenge_unavailable="sdk_passkey_challenge_unavailable",B.sdk_passkey_authentication_failed="sdk_passkey_authentication_failed",B.sdk_passkey_registration_failed="sdk_passkey_registration_failed";const W={error:"UnknownError",message:"An unknown error occurred"},V={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."},H={error:"UserCancelled",message:"The user cancelled the request."},$={error:"InvalidChallenge",message:"The provided challenge was invalid"},J={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."},Z={error:"Interrupted",message:"The operation was interrupted and may be retried."},X={error:"TimedOut",message:"The operation timed out."},Q={error:"ERROR_CEREMONY_ABORTED",message:"User did not complete the request in time."},ee={error:"ERROR_INVALID_DOMAIN",message:"Invalid domain."},te={error:"ERROR_INVALID_RP_ID",message:"Invalid Relying Party ID."},re={error:"ERROR_INVALID_USER_ID_LENGTH",message:"Invalid user ID length."},se={error:"ERROR_MALFORMED_PUBKEYCREDPARAMS",message:"Malformed public key credential parameters."},ae={error:"ERROR_AUTHENTICATOR_GENERAL_ERROR",message:"Authenticator encountered a general error."},ne={error:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",message:"Authenticator does not support discoverable credentials."},oe={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."},ce={error:"InvalidStateError",message:"The authenticator was previously registered"},de={error:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",message:"Authenticator does not support any of the provided public key credential parameters algorithms."},le={error:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",message:"User verification failed during auto-registration."},he={error:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",message:"An error occurred. See the cause property for more details."},pe=[W,V,F,G,H,$,J,Y,z,Z,X,Q,ee,te,re,se,ae,ne,oe,ie,de,le,he];let ue=!1;"undefined"!=typeof window&&window.localStorage&&(ue="true"===window.localStorage.getItem("wsdk:enable_logging")),ue&&l.default.setLevel("trace");const ye=l.default;var ge,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 me=null!==(ge={env:{}}.env.NODE_ENV)&&void 0!==ge?ge:"development",we="testnet",ve="9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe75d907fe6db9e4c";exports.PublicKeyCredentialAlgorithm.RS256,exports.PublicKeyCredentialAlgorithm.ES256;const Se="undefined"!=typeof window&&"undefined"!=typeof document,Ae={platform:"web",isNative:!Se,isWeb:Se},be="3.9.0",Ee=e=>e.replace(/:/g,"_"),_e="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Te(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Pe(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 Ie(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Te(e.outputLen),Te(e.blockLen)}function ke(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 Ce(e,t){Pe(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Oe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ke(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function xe(e,t){return e<<32-t|e>>>t}const Re=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let r=0;r<e.length;r++)e[r]=(t=e[r])<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var t;return e},Ne=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),De=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Le(e){if(Pe(e),Ne)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=De[e[r]];return t}const qe=48,Ue=57,je=65,Be=70,Me=97,We=102;function Ve(e){return e>=qe&&e<=Ue?e-qe:e>=je&&e<=Be?e-(je-10):e>=Me&&e<=We?e-(Me-10):void 0}function Fe(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Ge(e){return"string"==typeof e&&(e=Fe(e)),Pe(e),e}function He(e){return"string"==typeof e&&(e=Fe(e)),Pe(e),e}class $e{}function Je(e){const t=t=>e().update(Ge(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Ye(e=32){if(_e&&"function"==typeof _e.getRandomValues)return _e.getRandomValues(new Uint8Array(e));if(_e&&"function"==typeof _e.randomBytes)return Uint8Array.from(_e.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function ze(e){return Ye(e)}
4
4
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ze=BigInt(0),Xe=BigInt(1);function Qe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function et(e){if(!Qe(e))throw new Error("Uint8Array expected")}function tt(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function rt(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function st(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Ze:BigInt("0x"+e)}const at="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,nt=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function ot(e){if(et(e),at)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=nt[e[r]];return t}const it=48,ct=57,dt=65,lt=70,ht=97,pt=102;function ut(e){return e>=it&&e<=ct?e-it:e>=dt&&e<=lt?e-(dt-10):e>=ht&&e<=pt?e-(ht-10):void 0}function yt(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(at)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=ut(e.charCodeAt(a)),n=ut(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 gt(e){return st(ot(e))}function ft(e){return et(e),st(ot(Uint8Array.from(e).reverse()))}function mt(e,t){return yt(e.toString(16).padStart(2*t,"0"))}function wt(e,t){return mt(e,t).reverse()}function vt(e,t,r){let s;if("string"==typeof t)try{s=yt(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Qe(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 St(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];et(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 At=e=>"bigint"==typeof e&&Ze<=e;function bt(e,t,r){return At(e)&&At(t)&&At(r)&&t<=e&&e<r}function Et(e,t,r,s){if(!bt(t,r,s))throw new Error("expected valid "+e+": "+r+" <= n < "+s+", got "+t)}const _t=e=>(Xe<<BigInt(e))-Xe,Tt=e=>new Uint8Array(e),Pt=e=>Uint8Array.from(e);const It={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||Qe(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 kt(e,t,r={}){const s=(t,r,s)=>{const a=It[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 Ct(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 Ot=Pe;function Kt(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Ne)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=Ve(e.charCodeAt(a)),n=Ve(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 xt(e){return t=>(Ot(t),e(t))}const Rt=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},Nt=e=>e.startsWith("0x")?e:"0x"+e,Dt=e=>{let t=e;return 64===Kt(e).length&&(t="04"+e),t.substring(2)},Lt=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},qt=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 Ut(e,t,r){return e&t^e&r^t&r}class jt extends $e{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=Ke(this.buffer)}update(e){ke(this),Pe(e=Ge(e));const{view:t,buffer:r,blockLen:s}=this,a=e.length;for(let n=0;n<a;){const o=Math.min(s-this.pos,a-n);if(o!==s)r.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=Ke(e);for(;s<=a-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){ke(this),Ce(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),o=Number(r>>a&n),i=Number(r&n),c=s?4:0,d=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+d,i,s)}(r,s-8,BigInt(8*this.length),a),this.process(r,0);const o=Ke(e),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=i/4,d=this.get();if(c>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.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:o}=this;return e.destroyed=n,e.finished=a,e.length=s,e.pos=o,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Bt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Wt=BigInt(2**32-1),Vt=BigInt(32);function Ft(e,t=!1){return t?{h:Number(e&Wt),l:Number(e>>Vt&Wt)}:{h:0|Number(e>>Vt&Wt),l:0|Number(e&Wt)}}function Gt(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:o}=Ft(e[n],t);[s[n],a[n]]=[r,o]}return[s,a]}const Ht=(e,t,r)=>e>>>r,$t=(e,t,r)=>e<<32-r|t>>>r,Jt=(e,t,r)=>e>>>r|t<<32-r,Yt=(e,t,r)=>e<<32-r|t>>>r,zt=(e,t,r)=>e<<64-r|t>>>r-32,Zt=(e,t,r)=>e>>>r-32|t<<64-r;function Xt(e,t,r,s){const a=(t>>>0)+(s>>>0);return{h:e+r+(a/2**32|0)|0,l:0|a}}const Qt=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),er=(e,t,r,s)=>t+r+s+(e/2**32|0)|0,tr=(e,t,r,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),rr=(e,t,r,s,a)=>t+r+s+a+(e/2**32|0)|0,sr=(e,t,r,s,a)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0)+(a>>>0),ar=(e,t,r,s,a,n)=>t+r+s+a+n+(e/2**32|0)|0,nr=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]),or=new Uint32Array(64);class ir extends jt{constructor(e=32){super(64,e,8,!1),this.A=0|Bt[0],this.B=0|Bt[1],this.C=0|Bt[2],this.D=0|Bt[3],this.E=0|Bt[4],this.F=0|Bt[5],this.G=0|Bt[6],this.H=0|Bt[7]}get(){const{A:e,B:t,C:r,D:s,E:a,F:n,G:o,H:i}=this;return[e,t,r,s,a,n,o,i]}set(e,t,r,s,a,n,o,i){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|o,this.H=0|i}process(e,t){for(let r=0;r<16;r++,t+=4)or[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=or[e-15],r=or[e-2],s=xe(t,7)^xe(t,18)^t>>>3,a=xe(r,17)^xe(r,19)^r>>>10;or[e]=a+or[e-7]+s+or[e-16]|0}let{A:r,B:s,C:a,D:n,E:o,F:i,G:c,H:d}=this;for(let e=0;e<64;e++){const t=d+(xe(o,6)^xe(o,11)^xe(o,25))+((l=o)&i^~l&c)+nr[e]+or[e]|0,h=(xe(r,2)^xe(r,13)^xe(r,22))+Ut(r,s,a)|0;d=c,c=i,i=o,o=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,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,s,a,n,o,i,c,d)}roundClean(){Oe(or)}destroy(){this.set(0,0,0,0,0,0,0,0),Oe(this.buffer)}}const cr=(()=>Gt(["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)))))(),dr=(()=>cr[0])(),lr=(()=>cr[1])(),hr=new Uint32Array(80),pr=new Uint32Array(80);class ur extends jt{constructor(e=64){super(128,e,16,!1),this.Ah=0|Mt[0],this.Al=0|Mt[1],this.Bh=0|Mt[2],this.Bl=0|Mt[3],this.Ch=0|Mt[4],this.Cl=0|Mt[5],this.Dh=0|Mt[6],this.Dl=0|Mt[7],this.Eh=0|Mt[8],this.El=0|Mt[9],this.Fh=0|Mt[10],this.Fl=0|Mt[11],this.Gh=0|Mt[12],this.Gl=0|Mt[13],this.Hh=0|Mt[14],this.Hl=0|Mt[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:s,Ch:a,Cl:n,Dh:o,Dl:i,Eh:c,El:d,Fh:l,Fl:h,Gh:p,Gl:u,Hh:y,Hl:g}=this;return[e,t,r,s,a,n,o,i,c,d,l,h,p,u,y,g]}set(e,t,r,s,a,n,o,i,c,d,l,h,p,u,y,g){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|o,this.Dl=0|i,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|g}process(e,t){for(let r=0;r<16;r++,t+=4)hr[r]=e.getUint32(t),pr[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|hr[e-15],r=0|pr[e-15],s=Jt(t,r,1)^Jt(t,r,8)^Ht(t,0,7),a=Yt(t,r,1)^Yt(t,r,8)^$t(t,r,7),n=0|hr[e-2],o=0|pr[e-2],i=Jt(n,o,19)^zt(n,o,61)^Ht(n,0,6),c=Yt(n,o,19)^Zt(n,o,61)^$t(n,o,6),d=tr(a,c,pr[e-7],pr[e-16]),l=rr(d,s,i,hr[e-7],hr[e-16]);hr[e]=0|l,pr[e]=0|d}let{Ah:r,Al:s,Bh:a,Bl:n,Ch:o,Cl:i,Dh:c,Dl:d,Eh:l,El:h,Fh:p,Fl:u,Gh:y,Gl:g,Hh:f,Hl:m}=this;for(let e=0;e<80;e++){const t=Jt(l,h,14)^Jt(l,h,18)^zt(l,h,41),w=Yt(l,h,14)^Yt(l,h,18)^Zt(l,h,41),v=l&p^~l&y,S=sr(m,w,h&u^~h&g,lr[e],pr[e]),A=ar(S,f,t,v,dr[e],hr[e]),b=0|S,E=Jt(r,s,28)^zt(r,s,34)^zt(r,s,39),_=Yt(r,s,28)^Zt(r,s,34)^Zt(r,s,39),T=r&a^r&o^a&o,P=s&n^s&i^n&i;f=0|y,m=0|g,y=0|p,g=0|u,p=0|l,u=0|h,({h:l,l:h}=Xt(0|c,0|d,0|A,0|b)),c=0|o,d=0|i,o=0|a,i=0|n,a=0|r,n=0|s;const I=Qt(b,_,P);r=er(I,A,E,T),s=0|I}({h:r,l:s}=Xt(0|this.Ah,0|this.Al,0|r,0|s)),({h:a,l:n}=Xt(0|this.Bh,0|this.Bl,0|a,0|n)),({h:o,l:i}=Xt(0|this.Ch,0|this.Cl,0|o,0|i)),({h:c,l:d}=Xt(0|this.Dh,0|this.Dl,0|c,0|d)),({h:l,l:h}=Xt(0|this.Eh,0|this.El,0|l,0|h)),({h:p,l:u}=Xt(0|this.Fh,0|this.Fl,0|p,0|u)),({h:y,l:g}=Xt(0|this.Gh,0|this.Gl,0|y,0|g)),({h:f,l:m}=Xt(0|this.Hh,0|this.Hl,0|f,0|m)),this.set(r,s,a,n,o,i,c,d,l,h,p,u,y,g,f,m)}roundClean(){Oe(hr,pr)}destroy(){Oe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const yr=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class gr extends ur{constructor(){super(32),this.Ah=0|yr[0],this.Al=0|yr[1],this.Bh=0|yr[2],this.Bl=0|yr[3],this.Ch=0|yr[4],this.Cl=0|yr[5],this.Dh=0|yr[6],this.Dl=0|yr[7],this.Eh=0|yr[8],this.El=0|yr[9],this.Fh=0|yr[10],this.Fl=0|yr[11],this.Gh=0|yr[12],this.Gl=0|yr[13],this.Hh=0|yr[14],this.Hl=0|yr[15]}}const fr=Je((()=>new ir)),mr=Je((()=>new ur)),wr=Je((()=>new gr));class vr extends $e{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ie(e);const r=Ge(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 ke(this),this.iHash.update(e),this}digestInto(e){ke(this),Pe(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:o}=this;return e.finished=s,e.destroyed=a,e.blockLen=n,e.outputLen=o,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 Sr=(e,t,r)=>new vr(e,t).update(r).digest();Sr.create=(e,t)=>new vr(e,t)
@@ -10,4 +10,4 @@ const jr=BigInt(0),Br=BigInt(1);function Mr(e,t){const r=t.negate();return e?r:t
10
10
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
11
  const ns=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),os=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),is=BigInt(1),cs=BigInt(2),ds=(e,t)=>(e+t/cs)/t;const ls=Lr(ns,void 0,void 0,{sqrt:function(e){const t=ns,r=BigInt(3),s=BigInt(6),a=BigInt(11),n=BigInt(22),o=BigInt(23),i=BigInt(44),c=BigInt(88),d=e*e*e%t,l=d*d*e%t,h=Cr(l,r,t)*l%t,p=Cr(h,r,t)*l%t,u=Cr(p,cs,t)*d%t,y=Cr(u,a,t)*u%t,g=Cr(y,n,t)*y%t,f=Cr(g,i,t)*g%t,m=Cr(f,c,t)*f%t,w=Cr(m,i,t)*g%t,v=Cr(w,r,t)*l%t,S=Cr(v,o,t)*y%t,A=Cr(S,s,t)*d%t,b=Cr(A,cs,t);if(!ls.eql(ls.sqr(b),e))throw new Error("Cannot find square root");return b}}),hs=function(e,t){const r=t=>ss({...e,...as(t)});return{...r(t),create:r}}({a:BigInt(0),b:BigInt(7),Fp:ls,n:os,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=os,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),s=-is*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=r,o=BigInt("0x100000000000000000000000000000000"),i=ds(n*e,t),c=ds(-s*e,t);let d=kr(e-i*r-c*a,t),l=kr(-i*s-c*n,t);const h=d>o,p=l>o;if(h&&(d=t-d),p&&(l=t-l),d>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:d,k2neg:p,k2:l}}}},fr);BigInt(0),hs.ProjectivePoint;const ps=e=>{const t=Rt(e),r=hs.getPublicKey(t),s=hs.ProjectivePoint.fromHex(r);return Dt(Le(s.toRawBytes(!1)))},us=BigInt(0),ys=BigInt(1),gs=BigInt(2),fs=BigInt(7),ms=BigInt(256),ws=BigInt(113),vs=[],Ss=[],As=[];for(let e=0,t=ys,r=1,s=0;e<24;e++){[r,s]=[s,(2*r+3*s)%5],vs.push(2*(5*s+r)),Ss.push((e+1)*(e+2)/2%64);let a=us;for(let e=0;e<7;e++)t=(t<<ys^(t>>fs)*ws)%ms,t&gs&&(a^=ys<<(ys<<BigInt(e))-ys);As.push(a)}const bs=Gt(As,!0),Es=bs[0],_s=bs[1],Ts=(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),Ps=(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 Is extends $e{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,Te(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var n;this.state=new Uint8Array(200),this.state32=(n=this.state,new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)))}clone(){return this._cloneInto()}keccak(){Re(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],o=r[a+1],i=Ts(n,o,1)^r[s],c=Ps(n,o,1)^r[s+1];for(let r=0;r<50;r+=10)e[t+r]^=i,e[t+r+1]^=c}let t=e[2],a=e[3];for(let r=0;r<24;r++){const s=Ss[r],n=Ts(t,a,s),o=Ps(t,a,s),i=vs[r];t=e[i],a=e[i+1],e[i]=n,e[i+1]=o}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]^=Es[s],e[1]^=_s[s]}Oe(r)}(this.state32,this.rounds),Re(this.state32),this.posOut=0,this.pos=0}update(e){ke(this),Pe(e=Ge(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){ke(this,!1),Pe(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 Te(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ce(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 Is(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 ks=(()=>{return e=1,t=136,r=32,Je((()=>new Is(t,e,r)));var e,t,r})(),Cs=(()=>{const e=xt(ks);return e.create=ks.create,e})(),Os=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=Cs(e);return Nt(Le(r))}{const e=Cs(Lt([ze(32),ze(32)])),t=Lt([Lt([ze(32),e]),ze(32)]),r=Cs(t);return Nt(Le(r))}})(e),r=ps(t);return{privateKey:t,publicKey:Rt(r)}},Ks=(e,t)=>{const r=Nt(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=hs.sign(Kt(Rt(t)),Kt(Rt(e))),n=1===a.recovery?"1c":"1b";return"0x"+a.toCompactHex()+n},xs=(e,t)=>Sr(fr,e,t),Rs=xt(mr);function Ns(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 Ds(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ls(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const qs=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Us(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(Ns(r),!qs)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?Ns(t):Ns(t,e.nonceLength)}const a=e.tagLength;a&&void 0!==s[1]&&Ns(s[1]);const n=t(r,...s),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Ns(t)}};let i=!1;const c={encrypt(e,t){if(i)throw new Error("cannot encrypt() twice with same key + nonce");return i=!0,Ns(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(Ns(e),a&&e.length<a)throw new Error("invalid ciphertext length: smaller than tagLength="+a);return o(n.decrypt.length,t),n.decrypt(e,t)}};return c}return Object.assign(r,e),r};function Bs(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&&!Ms(t))throw new Error("invalid output, must be aligned");return t}function Ms(e){return e.byteOffset%4==0}function Ws(e){return Uint8Array.from(e)}const Vs=16;function Fs(e){return e<<1^283&-(e>>7)}function Gs(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Fs(e);return r}const Hs=(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Fs(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 Ls(e),t})(),$s=Hs.map(((e,t)=>Hs.indexOf(t))),Js=e=>e<<8|e>>>24;function Ys(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(Js),a=s.map(Js),n=a.map(Js),o=new Uint32Array(65536),i=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;o[l]=r[t]^s[d],i[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:o,T23:i}}const zs=Ys(Hs,(e=>Gs(e,3)<<24|e<<16|e<<8|Gs(e,2))),Zs=Ys($s,(e=>Gs(e,11)<<24|Gs(e,13)<<16|Gs(e,9)<<8|Gs(e,14))),Xs=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Fs(r))e[t]=r;return e})();function Qs(e){Ns(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}=zs,s=[];Ms(e)||s.push(e=Ws(e));const a=Ds(e),n=a.length,o=e=>ta(r,e,e,e,e),i=new Uint32Array(t+28);i.set(a);for(let e=n;e<i.length;e++){let t=i[e-1];e%n==0?t=o((c=t)<<24|c>>>8)^Xs[e/n-1]:n>6&&e%n==4&&(t=o(t)),i[e]=i[e-n]^t}var c;return Ls(...s),i}function ea(e,t,r,s,a,n){return e[r<<8&65280|s>>>8&255]^t[a>>>8&65280|n>>>24&255]}function ta(e,t,r,s,a){return e[255&t|65280&r]|e[s>>>16&255|a>>>16&65280]<<16}function ra(e,t,r,s,a){const{sbox2:n,T01:o,T23:i}=zs;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++]^ea(o,i,t,r,s,a),d=e[c++]^ea(o,i,r,s,a,t),l=e[c++]^ea(o,i,s,a,t,r),h=e[c++]^ea(o,i,a,t,r,s);t=n,r=d,s=l,a=h}return{s0:e[c++]^ta(n,t,r,s,a),s1:e[c++]^ta(n,r,s,a,t),s2:e[c++]^ta(n,s,a,t,r),s3:e[c++]^ta(n,a,t,r,s)}}function sa(e,t,r,s,a){const{sbox2:n,T01:o,T23:i}=Zs;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++]^ea(o,i,t,a,s,r),d=e[c++]^ea(o,i,r,t,a,s),l=e[c++]^ea(o,i,s,r,t,a),h=e[c++]^ea(o,i,a,s,r,t);t=n,r=d,s=l,a=h}return{s0:e[c++]^ta(n,t,a,s,r),s1:e[c++]^ta(n,r,t,a,s),s2:e[c++]^ta(n,s,r,t,a),s3:e[c++]^ta(n,a,s,r,t)}}function aa(e,t,r,s){Ns(t,Vs),Ns(r);const a=r.length;Us(r,s=Bs(a,s));const n=t,o=Ds(n);let{s0:i,s1:c,s2:d,s3:l}=ra(e,o[0],o[1],o[2],o[3]);const h=Ds(r),p=Ds(s);for(let t=0;t+4<=h.length;t+=4){p[t+0]=h[t+0]^i,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:i,s1:c,s2:d,s3:l}=ra(e,o[0],o[1],o[2],o[3]))}const u=Vs*Math.floor(h.length/4);if(u<a){const e=new Uint32Array([i,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];Ls(e)}var y;return s}const na=js({blockSize:16,nonceLength:16},(function(e,t){function r(r,s){if(Ns(r),void 0!==s&&(Ns(s),!Ms(s)))throw new Error("unaligned destination");const a=Qs(e),n=Ws(t),o=[a,n];Ms(r)||o.push(r=Ws(r));const i=aa(a,n,r,s);return Ls(...o),i}return{encrypt:(e,t)=>r(e,t),decrypt:(e,t)=>r(e,t)}}));const oa=js({blockSize:16,nonceLength:16},(function(e,t,r={}){const s=!r.disablePadding;return{encrypt(r,a){const n=Qs(e),{b:o,o:i,out:c}=function(e,t,r){Ns(e);let s=e.length;const a=s%Vs;if(!t&&0!==a)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Ms(e)||(e=Ws(e));const n=Ds(e);if(t){let e=Vs-a;e||(e=Vs),s+=e}return Us(e,r=Bs(s,r)),{b:n,o:Ds(r),out:r}}(r,s,a);let d=t;const l=[n];Ms(d)||l.push(d=Ws(d));const h=Ds(d);let p=h[0],u=h[1],y=h[2],g=h[3],f=0;for(;f+4<=o.length;)p^=o[f+0],u^=o[f+1],y^=o[f+2],g^=o[f+3],({s0:p,s1:u,s2:y,s3:g}=ra(n,p,u,y,g)),i[f++]=p,i[f++]=u,i[f++]=y,i[f++]=g;if(s){const e=function(e){const t=new Uint8Array(16),r=Ds(t);t.set(e);const s=Vs-e.length;for(let e=Vs-s;e<Vs;e++)t[e]=s;return r}(r.subarray(4*f));p^=e[0],u^=e[1],y^=e[2],g^=e[3],({s0:p,s1:u,s2:y,s3:g}=ra(n,p,u,y,g)),i[f++]=p,i[f++]=u,i[f++]=y,i[f++]=g}return Ls(...l),c},decrypt(r,a){!function(e){if(Ns(e),e.length%Vs!=0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size 16")}(r);const n=function(e){const t=Qs(e),r=t.slice(),s=t.length,{sbox2:a}=zs,{T0:n,T1:o,T2:i,T3:c}=Zs;for(let e=0;e<s;e+=4)for(let a=0;a<4;a++)r[e+a]=t[s-e-4+a];Ls(t);for(let e=4;e<s-4;e++){const t=r[e],s=ta(a,t,t,t,t);r[e]=n[255&s]^o[s>>>8&255]^i[s>>>16&255]^c[s>>>24]}return r}(e);let o=t;const i=[n];Ms(o)||i.push(o=Ws(o));const c=Ds(o);a=Bs(r.length,a),Ms(r)||i.push(r=Ws(r)),Us(r,a);const d=Ds(r),l=Ds(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:o,s1:i,s2:c,s3:g}=sa(n,h,p,u,y);l[e++]=o^t,l[e++]=i^r,l[e++]=c^s,l[e++]=g^a}return Ls(...i),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 ia(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 oa(e,t,{disablePadding:!s});if(["aes-128-ctr","aes-256-ctr"].includes(r))return na(e,t);throw new Error("AES: unsupported mode")}const ca=(e,t,r)=>{const s=(null==r?void 0:r.ephemPrivateKey)?Kt(r.ephemPrivateKey):ze(32),a=ze(16),n=hs.getPublicKey(s),o=hs.ProjectivePoint.fromHex(n).toRawBytes(!1),i=hs.getSharedSecret(s,Kt(e),!0).slice(1),c=Rs(i),d=c.subarray(0,32),l=c.subarray(32),h=function(e,t,r,s="aes-128-ctr",a=!0){return ia(t,r,s,a).encrypt(e)}(qt(t),d,a,"aes-256-cbc"),p=Lt([a,o,h]),u=xs(l,p);return{iv:Le(a),ephemPublicKey:Le(o),ciphertext:Le(h),mac:Le(u)}},da=(e,t)=>{let r;try{r=hs.getSharedSecret(Kt(e),t.ephemPublicKey,!0).slice(1)}catch(e){throw new Error(`Invalid MAC: data integrity check failed: ${e}`)}const s=Rs(r),a=s.subarray(0,32),n=s.subarray(32),o=Kt(t.ciphertext),i=Kt(t.iv),c=Kt(t.ephemPublicKey),d=Kt(t.mac),l=Lt([i,c,o]);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}(xs(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 ia(t,r,s,a).decrypt(e)}(o,a,i,"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 la=(e,t,r)=>{const s=Dt(e);return ca("04"+s,t,r)},ha=(e,t)=>{const r=Rt(e);return da(r,t)},pa=e=>(e=>{const t=qt(e),r=Nt(Le(t)),s=Cs(Kt(r));return Nt(Le(s))})(e);function ua(e,t,r,s=!0,a){Ot(r,32),tt("compressed",s);const n=function(e){return Ot(e,64),hs.Signature.fromCompact(e)}(e);return function(e=e=>new Uint8Array(e),t,r){return"function"==typeof e&&(e=e(t)),Ot(e,t),r&&e.set(r),e}(a,s?33:65,n.addRecoveryBit(t).recoverPublicKey(r).toRawBytes(s))}hs.ProjectivePoint,hs.CURVE.n;const ya={keccak256:pa};function ga(e){if(!fa(e))throw new Error("Invalid JSON string");return JSON.parse(e)}function fa(e){if("string"!=typeof e)return!1;try{return JSON.parse(e),!0}catch(e){return!1}}function ma(e,t,r,s){Ie(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:o,asyncTick:i}=a;if(Te(n),Te(o),Te(i),n<1)throw new Error("iterations (c) should be >= 1");const c=He(t),d=He(r),l=new Uint8Array(o),h=Sr.create(e,c),p=h._cloneInto().update(d);return{c:n,dkLen:o,asyncTick:i,DK:l,PRF:h,PRFSalt:p}}function wa(e,t,r,s){const{c:a,dkLen:n,DK:o,PRF:i,PRFSalt:c}=ma(e,t,r,s);let d;const l=new Uint8Array(4),h=Ke(l),p=new Uint8Array(i.outputLen);for(let e=1,t=0;t<n;e++,t+=i.outputLen){const r=o.subarray(t,t+i.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++){i._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}(i,c,o,d,p)}const va="wsdkmk:v1:";function Sa(e){if(Fe(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 Aa({password:e,salt:t}){Sa(t);const r=function(e,t,r,s,a){if(!["sha256","sha512"].includes(a))throw new Error("Only sha256 and sha512 are supported");return Ot(e),Ot(t),wa(fr,e,t,{c:r,dkLen:s})}(Fe(e.normalize("NFKC").trim()),Fe(t),131072,32,"sha256");return Os(r)}function ba(e,t){return va+function(e,t){return s.AES.encrypt(e,t).toString()}("string"==typeof e?e:JSON.stringify(e),t)}function Ea(e,t){const r=function(e,t){return s.AES.decrypt(e,t).toString(s.enc.Utf8)}(e.startsWith(va)?e.slice(10):e,t);if(r)return fa(r)?ga(r):r}class _a{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(!hs.utils.isValidPrivateKey(e.slice(2)))throw new Error("Invalid private key: outside secp256k1 scalar range")}(e)}getMasterKey(){return{buffer:Fe(ve),key:ve}}encryptWithMasterKey({data:e}){return ba(e,this.getMasterKey().key)}isWrappedByMasterKey(e){return function(e){return e.startsWith(va)||e.startsWith("U2FsdGVkX1")}(e)}decryptWithMasterKey({cipherText:e}){try{const t=Ea(e,this.getMasterKey().key);if(void 0!==t)return t}catch(e){return void ye.error("Decryption failed with master key",e)}ye.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){Sa(e)}sign({message:e,signingKey:t}){try{this.validatePrivateKey(t);const r=pa(e);return{message:e,signature:Ks(t,r),hashedMessage:r}}catch(e){throw ye.error("SDK::Cipher::sign",e),new Error(`Error signing message: ${e}`)}}async encrypt({data:e,encryptionKey:t}){try{return this.validatePublicKey(t),await la(t,e)}catch(e){throw ye.error("Error encrypting data: ",e),new Error("Something happened during data encryption.")}}async decrypt({cipherText:e,decryptionKey:t}){try{this.validatePrivateKey(t);return await ha(t,(r=e,"string"==typeof r?JSON.parse(r):r))}catch(e){throw ye.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 ye.error("SDK::CipherService::getCredentialsKeyPair::error",e),Promise.reject(e)}}async prepareDataForTransport({data:e,wallabyPublicKey:t}){try{return la(t,e)}catch(e){throw ye.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 ye.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 ye.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 ye.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 o=await this.decrypt({cipherText:JSON.parse(n),decryptionKey:a});if(!o)throw new Error("That doesn’t seem right. Check your login details and try again.");return o}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 ye.error("SDK::CipherService::displayDataFromServer::error",e),e}}async deriveKeyPairFromPasskey({inputKeyMaterial:e}){return function({inputKeyMaterial:e}){return Os(e)}({inputKeyMaterial:e})}async deriveKeyPairFromPassword({password:e,salt:t}){return Aa({password:e,salt:t})}}class Ta{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:me,this.shortenedEnv=this.environment.slice(0,1),this.deviceLocalStorage=e,this.cipher=new _a}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=>{ye.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}`;Ae.isNative&&(s=Ee(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 ye.error(`Failed to decrypt item with key ${s}`)}return a}ye.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(Ae.isNative&&(s=Ee(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 Se?r:Ee(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=ga(t)}catch(t){return ye.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 Ae.isNative&&(r=Ee(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=s.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}ye.error("SDK::StorageService::getEncryptedPrivateKey: private key not found")}async getDecryptedV1PrivateKey(e){try{const t=await this.getV1EncryptedPrivateKey();if(!t)return;const r=s.AES.decrypt(t,e).toString(s.enc.Utf8);return r||void 0}catch(e){return void ye.error("SDK::StorageService::getDecryptedV1PrivateKey::error",e)}}async getDecryptedPrivateKey(e){try{const t=await this.getEncryptedPrivateKey();if(!t)return;const r=s.AES.decrypt(t,e).toString(s.enc.Utf8);return r||void 0}catch(e){return void ye.error("SDK::StorageService::getDecryptedPrivateKey::error",e)}}async setEncryptedSeedPhrase({decryptedSeedPhrase:e,seedPhraseType:t,password:r,deviceAuthPublicKey:a,getUserSalt:n,salt:o,walletId:i}){const c=await la(a,e),d=null!=o?o: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 s.AES.encrypt(JSON.stringify(c),l),p=this.getSeedPhraseV2KeyName(t);return await this.save(p,h.toString(),{walletId:i}),!0}async getEncryptedSeedPhrase(e,t){const r=this.getSeedPhraseV2KeyName(e),s=await this.fetch(r,{walletId:t});if(s)return s;let a;if(e===exports.SeedPhraseType.Standard&&(a=`encryptedSeed_${this.userId}`),a){const e=await this.getItem(a);if(e)return e}if(!s){const t=`${this.environment}-encrypted-${e}-seedPhrase-${this.userId}`,r=await this.getItem(t);if(r)return r}}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(),a=await this.getDecryptedV1PrivateKey(e);if(!r||!a)return;const n=`${t}${e}`,o=ga(s.AES.decrypt(r,n).toString(s.enc.Utf8));return await ha(a,o)}async getDecryptedSeedPhrase({password:e,seedPhraseType:t,getUserSalt:r,salt:a,walletId:n}){const o=await this.getEncryptedSeedPhrase(t,n),i=await this.getDecryptedPrivateKey(e);if(!o||!i)return;const c=`${null!=a?a:await r()}${e}`,d=ga(s.AES.decrypt(o,c).toString(s.enc.Utf8));return await ha(i,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))))}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 Pa(e,t=Date.now){return!e||ka(e,t)<=0}function Ia(e,t,r=Date.now){return!!e&&ka(e,r)<=1e3*t}function ka(e,t=Date.now){const r=a.jwtDecode(e).exp;return 1e3*(null!=r?r:0)-t()}const Ca={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 Oa(e){return/^[a-zA-Z0-9-_]+$/.test(e)}function Ka(e){const{apiKey:t,baseUrl:r,userId:s,clientAuthToken:n,options:o}=e;if("string"!=typeof t||!Oa(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||!Oa(s))throw new Error("Invalid or empty user ID provided.");if("string"!=typeof n||!function(e){if("string"!=typeof e)return!1;if(3!==e.split(".").length)return!1;try{return a.jwtDecode(e),!0}catch(e){return!1}}(n))throw new Error("Invalid or empty client auth token provided.");if(o&&"object"!=typeof o)throw new Error("Invalid options provided.");return Object.freeze({apiKey:t.trim(),baseUrl:r.trim(),userId:s.trim(),clientAuthToken:n.trim(),options:o?Object.freeze(Object.assign({},o)):void 0})}var xa;!function(e){e.Json="application/json",e.JsonApi="application/vnd.api+json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"}(xa||(xa={}));class Ra{constructor(e={}){this.baseUrl="https://dev-testnet.wallaby.cash",this.securityData=null,this.abortControllers=new Map,this.customFetch=(...e)=>fetch(...e),this.baseApiParams={credentials:"same-origin",headers:{},redirect:"follow",referrerPolicy:"no-referrer"},this.setSecurityData=e=>{this.securityData=e},this.contentFormatters={[xa.Json]:e=>null===e||"object"!=typeof e&&"string"!=typeof e?e:JSON.stringify(e),[xa.JsonApi]:e=>null===e||"object"!=typeof e&&"string"!=typeof e?e:JSON.stringify(e),[xa.Text]:e=>null!==e&&"string"!=typeof e?JSON.stringify(e):e,[xa.FormData]:e=>e instanceof FormData?e:Object.keys(e||{}).reduce(((t,r)=>{const s=e[r];return t.append(r,s instanceof Blob?s:"object"==typeof s&&null!==s?JSON.stringify(s):`${s}`),t}),new FormData),[xa.UrlEncoded]:e=>this.toQueryString(e)},this.createAbortSignal=e=>{if(this.abortControllers.has(e)){const t=this.abortControllers.get(e);return t?t.signal:void 0}const t=new AbortController;return this.abortControllers.set(e,t),t.signal},this.abortRequest=e=>{const t=this.abortControllers.get(e);t&&(t.abort(),this.abortControllers.delete(e))},this.request=async e=>{var{body:t,secure:r,path:s,type:a,query:n,format:o,baseUrl:i,cancelToken:c}=e,d=p(e,["body","secure","path","type","query","format","baseUrl","cancelToken"]);const l=("boolean"==typeof r?r:this.baseApiParams.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},h=this.mergeRequestParams(d,l),u=n&&this.toQueryString(n),y=this.contentFormatters[a||xa.Json],g=o||h.format;return this.customFetch(`${i||this.baseUrl||""}${s}${u?`?${u}`:""}`,Object.assign(Object.assign({},h),{headers:Object.assign(Object.assign({},h.headers||{}),a&&a!==xa.FormData?{"Content-Type":a}:{}),signal:(c?this.createAbortSignal(c):h.signal)||null,body:null==t?null:y(t)})).then((async e=>{const t=e;t.data=null,t.error=null;const r=g?await e[g]().then((e=>(t.ok?t.data=e:t.error=e,t))).catch((e=>(t.error=e,t))):t;if(c&&this.abortControllers.delete(c),!e.ok)throw r;return r.data}))},Object.assign(this,e)}encodeQueryParam(e,t){return`${encodeURIComponent(e)}=${encodeURIComponent("number"==typeof t?t:`${t}`)}`}addQueryParam(e,t){return this.encodeQueryParam(t,e[t])}addArrayQueryParam(e,t){return e[t].map((e=>this.encodeQueryParam(t,e))).join("&")}toQueryString(e){const t=e||{};return Object.keys(t).filter((e=>void 0!==t[e])).map((e=>Array.isArray(t[e])?this.addArrayQueryParam(t,e):this.addQueryParam(t,e))).join("&")}addQueryParams(e){const t=this.toQueryString(e);return t?`?${t}`:""}mergeRequestParams(e,t){return Object.assign(Object.assign(Object.assign(Object.assign({},this.baseApiParams),e),t||{}),{headers:Object.assign(Object.assign(Object.assign({},this.baseApiParams.headers||{}),e.headers||{}),t&&t.headers||{})})}}class Na{constructor(e){this.health={getHello:(e={})=>this.http.request(Object.assign({path:"/",method:"GET",secure:!0},e)),getHealthCheck:(e={})=>this.http.request(Object.assign({path:"/healthz",method:"GET",secure:!0},e))},this.auth={generateExternalSignatureMessage:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/signature-message/external",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),generateSignatureMessage:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/signature-message",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),signUp:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/sign-up",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),signUpExternal:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/sign-up/external",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),signIn:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/sign-in",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),issueJwtToken:(e={})=>this.http.request(Object.assign({path:"/api/v1/auth/issue-jwt-token",method:"POST",secure:!0,format:"json"},e)),refreshAccessToken:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/refresh-access-token",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),logout:(e={})=>this.http.request(Object.assign({path:"/api/v1/auth/logout",method:"POST",secure:!0,format:"json"},e)),changeAuthPublicKey:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/client-auth-pubkey",method:"PUT",body:e,secure:!0,type:xa.Json,format:"json"},t)),getWallabyAuthPubKey:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/wallaby-auth-pubkey",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getPasskeyCredentials:(e={})=>this.http.request(Object.assign({path:"/api/v1/auth/passkey-credentials",method:"GET",secure:!0,format:"json"},e))},this.chains={getAllChains:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/chains",method:"GET",query:e,secure:!0,format:"json"},t)),createChain:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/chains",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),updateChain:(e,t,r)=>{var{chainId:s}=e;return p(e,["chainId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/chains/${s}`,method:"PUT",body:t,secure:!0,type:xa.Json,format:"json"},r))}},this.assets={getAssetsConfigurations:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/assets/configurations",method:"GET",query:e,secure:!0,format:"json"},t)),createAssetConfig:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/assets/configurations",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getAssetConfigById:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}`,method:"GET",secure:!0,format:"json"},t))},updateAssetConfig:(e,t,r)=>{var{assetConfigId:s}=e;return p(e,["assetConfigId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${s}`,method:"PUT",body:t,secure:!0,type:xa.Json,format:"json"},r))},verifyAsset:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}/verify`,method:"POST",secure:!0,format:"json"},t))},unverifyAsset:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}/unverify`,method:"DELETE",secure:!0,format:"json"},t))},archiveAsset:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}/archive`,method:"POST",secure:!0,format:"json"},t))},unarchiveAsset:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}/unarchive`,method:"POST",secure:!0,format:"json"},t))}},this.merchants={getAllMerchants:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants",method:"GET",query:e,secure:!0,format:"json"},t)),createMerchant:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),updateMerchant:(e,t,r)=>{var{merchantId:s}=e;return p(e,["merchantId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/merchants/${s}`,method:"PUT",body:t,secure:!0,type:xa.Json,format:"json"},r))},getOneMerchant:(e,t)=>{var{merchantId:r}=e;return p(e,["merchantId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}`,method:"GET",secure:!0,format:"json"},t))},getMerchantAssets:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/assets`,method:"GET",query:s,secure:!0,format:"json"},t))},getMerchantUsers:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/users`,method:"GET",query:s,secure:!0,format:"json"},t))},getMerchantAdmins:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/admins`,method:"GET",query:s,secure:!0,format:"json"},t))},inviteMerchantAdmins:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/admins/invite",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),revokeMerchantAdmins:(e,t)=>{var{merchantId:r,userId:s}=e;return p(e,["merchantId","userId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/admins/${s}`,method:"DELETE",secure:!0,format:"json"},t))},getMerchantWallets:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/wallets`,method:"GET",query:s,secure:!0,format:"json"},t))},addMerchantWalletAssets:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/wallets/add-assets",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),addNewAsset:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/assets/add",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),removeAsset:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/assets/delete",method:"DELETE",body:e,secure:!0,type:xa.Json,format:"json"},t)),showMerchantAssetToWalletHolders:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/assets/update-visibility",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),changeMerchantAssetDefaultStatus:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/assets/update-default-status",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getMerchantApiKeys:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/api-keys`,method:"GET",query:s,secure:!0,format:"json"},t))},createApiKey:(e,t,r)=>{var{merchantId:s}=e;return p(e,["merchantId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/merchants/${s}/api-keys`,method:"POST",body:t,secure:!0,type:xa.Json,format:"json"},r))},getMerchantApiKeyOrigins:(e,t)=>{var{merchantId:r,apiKeyId:s}=e,a=p(e,["merchantId","apiKeyId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/api-keys/${s}/origins`,method:"GET",query:a,secure:!0,format:"json"},t))},whitelistApiKeyOrigins:(e,t,r)=>{var{merchantId:s,apiKeyId:a}=e;return p(e,["merchantId","apiKeyId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/merchants/${s}/api-keys/${a}/whitelist-origins`,method:"POST",body:t,secure:!0,type:xa.Json,format:"json"},r))},updateApiKeyPublicKey:(e,t,r)=>{var{merchantId:s,apiKeyId:a}=e;return p(e,["merchantId","apiKeyId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/merchants/${s}/api-keys/${a}`,method:"PUT",body:t,secure:!0,type:xa.Json,format:"json"},r))}},this.wallets={getAllWallets:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets",method:"GET",query:e,secure:!0,format:"json"},t)),createWallet:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/create",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),verifyAccess:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/verify-access",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),createAdminWallet:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/create-admin-server-wallet",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),createWalletV2:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/create-with-shares",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),importWalletSeedPhraseV2:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/create-shares-based-wallet-from-seed",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),addNewDevice:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/add-new-device",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),importWalletSeedPhrase:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/import-seed-phrase",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),generateMissingAddresses:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/generate-wallet-addresses",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getUserAssetsByWalletId:(e,t)=>{var{walletId:r}=e,s=p(e,["walletId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/wallets/${r}/assets`,method:"GET",query:s,secure:!0,format:"json"},t))},getWalletAddresses:(e,t)=>{var{walletId:r}=e,s=p(e,["walletId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/wallets/${r}/addresses`,method:"GET",query:s,secure:!0,format:"json"},t))},getUserAsset:(e,t,r={})=>this.http.request(Object.assign({path:"/api/v1/wallets/asset",method:"GET",query:e,body:t,secure:!0,type:xa.Json,format:"json"},r)),updateUserAsset:(e,t,r={})=>this.http.request(Object.assign({path:"/api/v1/wallets/asset/update",method:"PUT",query:e,body:t,secure:!0,type:xa.Json,format:"json"},r)),initiateWalletRecovery:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/recover/init",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),recoverWallet:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/recover",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),requestSwapQuote:(e,t,r)=>{var{walletId:s}=e;return p(e,["walletId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/wallets/${s}/swap/quote`,method:"POST",body:t,secure:!0,type:xa.Json,format:"json"},r))},getSwapHistory:(e,t)=>{var{walletId:r}=e,s=p(e,["walletId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/wallets/${r}/swaps`,method:"GET",query:s,secure:!0,format:"json"},t))},getSwapById:(e,t)=>{var{walletId:r,swapId:s}=e;return p(e,["walletId","swapId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/wallets/${r}/swaps/${s}`,method:"GET",secure:!0,format:"json"},t))},executeSwap:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/execute-swap",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t))},this.transactions={getTransactions:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions",method:"GET",query:e,secure:!0,format:"json"},t)),getPendingTransactions:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/pending",method:"GET",query:e,secure:!0,format:"json"},t)),resolvePendingTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/resolve",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),sendTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/transfer",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),sendV2Transaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/transfer-with-shares",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),assetOptInTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/asset-optin",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),appOptInTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/app-optin",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getEstimateFee:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/estimate-fee",method:"GET",query:e,secure:!0,format:"json"},t)),fetchTransactionByHashOrReference:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/status",method:"GET",query:e,secure:!0,format:"json"},t)),getDetailedRawTransactionDataByReference:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/raw-status",method:"GET",query:e,secure:!0,format:"json"},t)),detectTransferRestriction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/detect-transfers-restrictions",method:"GET",query:e,secure:!0,format:"json"},t)),fetchMessageForTransferRestriction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/transfer-restriction-message",method:"GET",query:e,secure:!0,format:"json"},t)),getRestriction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/restriction",method:"GET",query:e,secure:!0,format:"json"},t)),checkAssetOptinForAddress:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/check-asset-optin",method:"GET",query:e,secure:!0,format:"json"},t)),checkAppOptinForAddress:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/check-app-optin",method:"GET",query:e,secure:!0,format:"json"},t)),createAllowanceTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/create-allowance",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t))},this.query={fetchBalance:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/assets/balance",method:"GET",query:e,secure:!0,format:"json"},t)),fetchOnlyBalance:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/address/balance",method:"GET",query:e,secure:!0,format:"json"},t)),fetchBulkBalance:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/assets/bulk-balance",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),fetchWalletBulkBalance:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/assets/wallet-bulk-balance",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),fetchTransactions:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/transactions",method:"GET",query:e,secure:!0,format:"json"},t)),fetchEvmTokenAssetInfo:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/fetch-token-info",method:"GET",query:e,secure:!0,format:"json"},t)),fetchAssetPairPrice:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/get-asset-price",method:"GET",query:e,secure:!0,format:"json"},t))},this.mpc={reconstructSeedPhrase:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/mpc/reconstruct-seed-phrase",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t))},this.users={getAllUsers:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users",method:"GET",query:e,secure:!0,format:"json"},t)),updateProfile:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users/profile",method:"PUT",body:e,secure:!0,type:xa.Json,format:"json"},t)),getCurrentUser:(e={})=>this.http.request(Object.assign({path:"/api/v1/users/profile",method:"GET",secure:!0,format:"json"},e)),getCurrentUserSalt:(e={})=>this.http.request(Object.assign({path:"/api/v1/users/salt",method:"GET",secure:!0,format:"json"},e)),getAllWalletsFromUserId:(e,t)=>{var{userId:r}=e;return p(e,["userId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${r}/wallets`,method:"GET",secure:!0,format:"json"},t))},getCurrentUserMerchantAssets:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users/merchants/assets",method:"GET",query:e,secure:!0,format:"json"},t)),getCurrentUserMerchantAssetsUsersMerchantAssets:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users/merchant/assets",method:"GET",query:e,secure:!0,format:"json"},t)),getAssetsByUserId:(e,t)=>{var{userId:r}=e,s=p(e,["userId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${r}/assets`,method:"GET",query:s,secure:!0,format:"json"},t))},addAssetToUser:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users/assets/add",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),removeAssetFromUser:(e,t)=>{var{assetConfigId:r,walletId:s,userId:a}=e;return p(e,["assetConfigId","walletId","userId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${a}/wallets/${s}/assets/${r}`,method:"DELETE",secure:!0,format:"json"},t))},getUserByUserId:(e,t)=>{var{userId:r}=e;return p(e,["userId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${r}`,method:"GET",secure:!0,format:"json"},t))},getUserByExternalUserId:(e,t)=>{var{externalUserId:r}=e;return p(e,["externalUserId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${r}/externalUserId`,method:"GET",secure:!0,format:"json"},t))}},this.adminTransactions={createReleaseSchedule:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/release-schedule",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),viewReleaseSchedule:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/release-schedule",method:"GET",query:e,secure:!0,format:"json"},t)),mint:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/mint",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),burn:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/burn",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),executePurchase:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/execute-purchase",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),executePurchaseWithInterest:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/execute-purchase-with-interest",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),setIdentity:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/set-identity",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),forceClaim:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/force-claim",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),forceClaimPrincipal:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/force-claim-principal",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getCallbackPublicKey:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/callback_pk",method:"GET",query:e,secure:!0},t)),viewAdminTransaction:(e,t)=>{var{referenceId:r}=e;return p(e,["referenceId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/transactions/admin/${r}`,method:"GET",secure:!0,format:"json"},t))},upsideCallback:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/callback",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t))},this.dashboard={getDashboardData:(e={})=>this.http.request(Object.assign({path:"/api/v1/dashboard",method:"GET",secure:!0,format:"json"},e))},this.userActivity={getActivities:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users-activities",method:"GET",query:e,secure:!0,format:"json"},t))},this.http=e}}const Da={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function La(e){return Da}function qa(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 Ua(e,t,r,s,a){const n=a&&"input"in a?a.input:r.value,o=a?.expected??e.expects??null,i=a?.received??qa(n),c={kind:e.kind,type:e.type,input:n,expected:o,received:i,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${i}`,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 ja=new WeakMap;function Ba(e){let t=ja.get(e);return t||(t={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},La())},ja.set(e,t)),t}function Ma(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}function Wa(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function Va(e,t,r){return"function"==typeof e.fallback?e.fallback(t,r):e.fallback}function Fa(e,t,r){return"function"==typeof e.default?e.default(t,r):e.default}function Ga(){return{kind:"schema",type:"any",reference:Ga,expects:"any",async:!1,get"~standard"(){return Ba(this)},"~run":e=>(e.typed=!0,e)}}function Ha(e,t){return{kind:"schema",type:"array",reference:Ha,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return Ba(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 o={type:"array",origin:"value",input:r,key:s,value:a};for(const t of n.issues)t.path?t.path.unshift(o):t.path=[o],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 Ua(this,"type",e,t);return e}}}function $a(e){return{kind:"schema",type:"boolean",reference:$a,expects:"boolean",async:!1,message:e,get"~standard"(){return Ba(this)},"~run"(e,t){return"boolean"==typeof e.value?e.typed=!0:Ua(this,"type",e,t),e}}}function Ja(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=Ja(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=Ja(e[s],t[s]);if(a.issue)return a;r[s]=a.value}return{value:r}}}return{issue:!0}}function Ya(e,t){return{kind:"schema",type:"intersect",reference:Ya,expects:Wa(e.map((e=>e.expects)),"&"),async:!1,options:e,message:t,get"~standard"(){return Ba(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=Ja(e.value,s[r]);if(a.issue){Ua(this,"type",e,t,{received:"unknown"});break}e.value=a.value}}}else Ua(this,"type",e,t);return e}}}function za(e){return{kind:"schema",type:"lazy",reference:za,expects:"unknown",async:!1,getter:e,get"~standard"(){return Ba(this)},"~run"(e,t){return this.getter(e.value)["~run"](e,t)}}}function Za(e,t){return{kind:"schema",type:"nullable",reference:Za,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return Ba(this)},"~run"(e,t){return null===e.value&&(void 0!==this.default&&(e.value=Fa(this,e,t)),null===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function Xa(e){return{kind:"schema",type:"number",reference:Xa,expects:"number",async:!1,message:e,get"~standard"(){return Ba(this)},"~run"(e,t){return"number"!=typeof e.value||isNaN(e.value)?Ua(this,"type",e,t):e.typed=!0,e}}}function Qa(e,t){return{kind:"schema",type:"object",reference:Qa,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return Ba(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]:Fa(a),o=a["~run"]({value:n},t);if(o.issues){const a={type:"object",origin:"value",input:r,key:s,value:n};for(const t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=o.issues),t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[s]=o.value}else if(void 0!==a.fallback)e.value[s]=Va(a);else if("exact_optional"!==a.type&&"optional"!==a.type&&"nullish"!==a.type&&(Ua(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 Ua(this,"type",e,t);return e}}}function en(e,t){return{kind:"schema",type:"optional",reference:en,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return Ba(this)},"~run"(e,t){return void 0===e.value&&(void 0!==this.default&&(e.value=Fa(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function tn(e,t){return{kind:"schema",type:"picklist",reference:tn,expects:Wa(e.map(qa),"|"),async:!1,options:e,message:t,get"~standard"(){return Ba(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:Ua(this,"type",e,t),e}}}function rn(e,t,r){return{kind:"schema",type:"record",reference:rn,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return Ba(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in r)if(Ma(r,s)){const a=r[s],n=this.key["~run"]({value:s},t);if(n.issues){const o={type:"object",origin:"key",input:r,key:s,value:a};for(const t of n.issues)t.path=[o],e.issues?.push(t);if(e.issues||(e.issues=n.issues),t.abortEarly){e.typed=!1;break}}const o=this.value["~run"]({value:a},t);if(o.issues){const n={type:"object",origin:"value",input:r,key:s,value:a};for(const t of o.issues)t.path?t.path.unshift(n):t.path=[n],e.issues?.push(t);if(e.issues||(e.issues=o.issues),t.abortEarly){e.typed=!1;break}}n.typed&&o.typed||(e.typed=!1),n.typed&&(e.value[n.value]=o.value)}}else Ua(this,"type",e,t);return e}}}function sn(e){return{kind:"schema",type:"string",reference:sn,expects:"string",async:!1,message:e,get"~standard"(){return Ba(this)},"~run"(e,t){return"string"==typeof e.value?e.typed=!0:Ua(this,"type",e,t),e}}}function an(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 nn(e,t){return{kind:"schema",type:"union",reference:nn,expects:Wa(e.map((e=>e.expects)),"|"),async:!1,options:e,message:t,get"~standard"(){return Ba(this)},"~run"(e,t){let r,s,a;for(const n of this.options){const o=n["~run"]({value:e.value},t);if(o.typed){if(!o.issues){r=o;break}s?s.push(o):s=[o]}else a?a.push(o):a=[o]}if(r)return r;if(s){if(1===s.length)return s[0];Ua(this,"type",e,t,{issues:an(s)}),e.typed=!0}else{if(1===a?.length)return a[0];Ua(this,"type",e,t,{issues:an(a)})}return e}}}const on=Qa({clientAuthPubKey:sn(),passkeyChallengeType:en(tn(["webauthn.create","webauthn.get"])),walletId:en(sn())}),cn=Qa({message:sn(),wallabyAuthPubKey:sn(),foundDevicePublicKey:$a(),challenge:sn(),registrationOptions:en(rn(sn(),Ga())),authenticationOptions:en(rn(sn(),Ga()))}),dn=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),externalUserId:sn(),firstName:en(sn()),lastName:en(sn()),merchantId:en(sn()),passkeyRegistrationResponse:en(rn(sn(),Ga()))}),ln=Qa({id:sn(),firstName:en(sn()),externalUserId:sn(),role:en(tn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),clientSalt:en(sn()),clientAuthPubKey:sn()}),hn=Qa({accessToken:sn(),refreshToken:en(sn()),user:za((()=>ln))}),pn=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),externalUserId:sn(),firstName:en(sn()),lastName:en(sn()),merchantId:en(sn()),passkeyRegistrationResponse:en(rn(sn(),Ga()))}),un=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),passkeyRegistrationResponse:en(rn(sn(),Ga())),passkeyAuthenticationResponse:en(rn(sn(),Ga()))}),yn=Qa({id:sn(),externalUserId:sn(),clientSalt:sn()}),gn=Qa({accessToken:sn(),refreshToken:sn(),user:za((()=>yn))}),fn=Qa({refreshToken:sn()}),mn=Qa({accessToken:sn(),refreshToken:sn()}),wn=Qa({message:sn()}),vn=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),newClientAuthPubKey:sn()}),Sn=Qa({user:za((()=>ln))}),An=Qa({clientAuthPubKey:sn()}),bn=Qa({wallabyAuthPubKey:sn()}),En=Qa({id:sn(),externalUserId:sn(),merchantId:sn(),role:tn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]),firstName:sn(),walletsCount:Xa(),latestWallabyAuthPubKey:sn(),latestWallabyAuthPubKeyVersion:sn(),portalInvitationStatus:en(Za(tn(["pending","accepted","rejected"]))),createdAt:sn(),updatedAt:sn(),hasFullPermissions:$a()}),_n=Qa({id:sn(),userId:sn(),publicKey:sn(),status:tn(["active","invalidated"]),createdAt:sn(),updatedAt:sn()}),Tn=Qa({id:sn(),authenticatorGlobalId:sn(),credentialID:sn(),publicKey:sn(),authPublicKeyId:sn(),counter:Xa(),transports:sn(),credentialDeviceType:sn(),credentialBackedUp:$a(),user:Ya([za((()=>En))]),authPublicKeys:Ha(za((()=>_n))),userId:sn(),externalUserId:sn(),createdAt:sn(),updatedAt:sn(),authenticatorName:sn()}),Pn=Qa({credentials:Ha(za((()=>Tn)))}),In=Qa({totalRecords:Xa(),currentPage:Xa(),totalPages:Xa(),nextPage:Za(Xa()),previousPage:Za(Xa()),pageSize:Xa()}),kn=Qa({address:sn(),publicKey:en(sn()),type:en(tn(["SEGWIT","LEGACY","DEFAULT"]))}),Cn=Qa({id:sn(),name:sn(),nameSlugify:sn(),verified:$a(),status:tn(["active","inactive","invalidated"])}),On=Qa({id:sn(),userId:sn(),merchantId:sn(),chainId:sn(),userAssetAddress:sn(),walletId:sn(),configId:sn(),assetName:sn(),assetSymbol:sn(),balance:Za(sn()),balanceUpdatedAt:Za(sn()),claimableBalance:en(Za(sn())),claimableBalanceUpdatedAt:en(Za(sn())),claimablePaymentTokenContractAddress:en(Za(sn())),claimablePaymentTokenAssetConfigId:en(Za(sn())),lockedTokenBalance:Za(sn()),lockedTokenBalanceUpdatedAt:Za(sn()),mainnetBalance:Za(sn()),mainnetBalanceUpdatedAt:Za(sn()),testnetBalance:Za(sn()),testnetBalanceUpdatedAt:Za(sn()),mainnetLockedBalance:Za(sn()),mainnetLockedBalanceUpdatedAt:Za(sn()),testnetLockedBalance:Za(sn()),testnetLockedBalanceUpdatedAt:Za(sn()),defaultAddress:sn(),isVisible:$a(),source:tn(["merchant","user","republic"]),addresses:Ha(za((()=>kn))),ownershipType:sn(),priceConversion:en(sn()),changePercentageLast24h:en(sn()),createdAt:sn(),updatedAt:sn(),merchant:Ya([za((()=>Cn))])}),Kn=Qa({id:sn(),name:sn(),nameSlugify:sn()}),xn=Qa({address:sn(),topics:Ha(sn()),data:sn(),transactionIndex:Xa()}),Rn=Qa({event:sn(),args:rn(sn(),nn([sn(),Xa(),$a()]))}),Nn=Qa({message:Za(sn()),txLogs:Za(Ha(za((()=>xn)))),txLogsDecoded:Za(Ha(za((()=>Rn)))),reqSignature:sn(),reason:Za(sn()),requestId:Za(sn()),signatureUsed:$a()}),Dn=Qa({id:sn(),reference:Za(sn()),hash:en(Za(sn())),merchantId:sn(),userEmail:sn(),chainId:sn(),chainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:Xa(),fromWalletId:sn(),fromAddress:sn(),toWalletId:sn(),toAddress:sn(),assetId:sn(),assetSymbol:sn(),tokenType:tn(["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:sn(),fee:sn(),note:sn(),nonce:Xa(),gasPrice:Xa(),submitter:sn(),status:tn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:Za(tn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:tn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:sn(),networkEnvironment:Za(tn(["mainnet","testnet"])),statusCheckAttempts:Xa(),statusCheckedAt:Za(sn()),createdAt:sn(),updatedAt:sn(),asset:Ya([za((()=>Gn))]),merchant:Ya([za((()=>Hn))]),adminTransactions:Ha(za((()=>Nn))),user:za((()=>En)),chain:za((()=>eo)),splitCoins:sn(),transferObjects:sn()}),Ln=Qa({id:Xa(),contractTypeName:sn(),assetContracts:Ha(za((()=>qn)))}),qn=Qa({configId:sn(),contractTypeId:Xa(),contractAddress:sn(),assetConfig:Ya([za((()=>Gn))]),contractType:Ya([za((()=>Ln))])}),Un=Qa({id:sn(),merchantId:sn(),configId:sn(),chainId:sn(),chainName:sn(),assetName:sn(),assetSymbol:sn(),isVisible:$a(),isDefault:$a(),createdAt:sn(),updatedAt:sn(),merchant:Ya([za((()=>Hn))]),config:Ya([za((()=>Gn))]),chain:Ya([za((()=>eo))])}),jn=Qa({id:sn(),typeName:sn(),createdAt:sn(),updatedAt:sn()}),Bn=Qa({id:sn(),objectId:sn(),packageId:sn(),moduleName:sn(),structName:sn(),coinType:sn(),createdAt:Ya([za((()=>jn))]),updatedAt:sn()}),Mn=Qa({id:sn(),chainId:sn(),swapProviderId:sn(),providerChainIdentifier:sn(),chain:Ya([za((()=>eo))]),swapProvider:Ya([za((()=>Wn))]),providerAssets:Ha(za((()=>Vn))),createdAt:sn(),updatedAt:sn()}),Wn=Qa({id:sn(),name:sn(),explorerBaseUrl:sn(),isActive:$a(),chainMappings:Ha(za((()=>Mn))),providerAssets:Ha(za((()=>Vn))),createdAt:sn(),updatedAt:sn()}),Vn=Qa({id:sn(),assetConfigId:sn(),swapProviderId:sn(),chainProviderMappingId:sn(),providerAssetIdentifier:sn(),lastSynced:en(sn()),isEnabled:$a(),assetConfig:Ya([za((()=>Gn))]),swapProvider:Ya([za((()=>Wn))]),chainProviderMapping:Ya([za((()=>Mn))]),createdAt:sn(),updatedAt:sn()}),Fn=Qa({id:sn(),config:za((()=>Gn)),configId:sn(),timestamp:sn(),createdAt:sn()}),Gn=Qa({id:sn(),chainId:sn(),merchantId:en(Za(sn())),chainName:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),name:sn(),symbol:sn(),verified:en($a()),isOffChain:en($a()),decimals:Xa(),iconUrl:en(sn()),ticker:en(Za(sn())),type:en(tn(["COIN","TOKEN","OBJECT"])),tokenStandard:en(Za(tn(["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:en(Za(Xa())),contractAddress:Za(sn()),description:en(Za(sn())),ownershipType:en(tn(["SINGLE_OWNER","MULTI_SIG"])),ownerAddresses:en(Za(Ha(sn()))),status:en(tn(["active","inactive","archived"])),createdByUserId:en(Za(sn())),createdByMerchantId:en(Za(sn())),relayerAddress:en(sn()),contractVersion:en(sn()),chain:en(za((()=>eo))),createdByMerchant:en(Ya([za((()=>Kn))])),usersAssets:en(Ha(za((()=>On)))),transactions:en(Ha(za((()=>Dn)))),assetContracts:en(Ha(za((()=>qn)))),merchantAssets:en(Ha(za((()=>Un)))),createdByUser:en(za((()=>En))),suiConfig:en(za((()=>Bn))),isAssetReady:en($a()),extendedConfiguration:en(rn(sn(),Ga())),requiresKyc:en($a()),swapProviderAssets:en(Ha(za((()=>Vn)))),tokenDistributions:en(Ha(za((()=>Fn))))}),Hn=Qa({id:sn(),name:sn(),nameSlugify:sn(),verified:$a(),contactEmail:sn(),contactPhoneNumber:sn(),usersCount:Xa(),assetsCount:Xa(),tokensCount:Xa(),coinsCount:Xa(),walletsCount:Xa(),status:tn(["active","inactive","invalidated"]),createdAt:sn(),updatedAt:sn(),createdAssets:Ha(za((()=>Gn))),merchantAssets:en(Ha(za((()=>Un))))}),$n=Qa({id:Xa(),name:tn(["wallaby_share","owner_main_device_share","owner_backup_device_share"]),keyShares:Ha(za((()=>Jn)))}),Jn=Qa({id:sn(),user:za((()=>En)),wallet:za((()=>Zn)),encryptedKey:sn(),type:za((()=>$n)),createdAt:sn(),updatedAt:sn(),migratedWallabyShareAt:en(Za(sn())),wrappingPublicKey:sn(),migrationStatus:tn(["not_required","pending","migrated","failed"]),migrationErrorMessage:en(Za(sn()))}),Yn=Qa({id:Xa(),roles:Ha(tn(["single_sig","shares_single_owner","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),wallets:Ha(za((()=>Zn)))}),zn=Qa({id:sn(),walletId:sn(),userId:sn(),shareCount:Xa(),createdAt:sn(),updatedAt:sn()}),Zn=Qa({id:sn(),userId:sn(),merchantId:sn(),revisionId:sn(),revisionName:sn(),hashedSeedPhraseSalt:sn(),hashedEthAddressSalt:sn(),recoveryCount:Xa(),assetsCount:Xa(),createdAt:sn(),updatedAt:sn(),lastVerifiedAt:Za(sn()),userAssets:Ha(za((()=>On))),merchant:za((()=>Hn)),keyShares:Ha(za((()=>Jn))),type:za((()=>Yn)),creationType:en(Za(tn(["user_imported","user_created"]))),keyMigrationStatus:tn(["not_required","pending","migrated","failed"]),migrationErrorMessage:en(Za(sn())),walletAddresses:Ha(za((()=>Qn))),walletKeks:Ha(za((()=>zn)))}),Xn=Qa({id:Xa(),name:tn(["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:za((()=>Qn))}),Qn=Qa({id:sn(),walletId:sn(),wallet:za((()=>Zn)),chain:za((()=>eo)),typeId:Xa(),type:za((()=>Xn)),address:sn(),publicKey:sn(),createdAt:sn(),updatedAt:sn()}),eo=Qa({id:sn(),name:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),isEvm:$a(),iconUrl:en(Za(sn())),mainnetId:en(sn()),mainnetIndexUrl:en(Za(sn())),mainnetExplorerUrl:en(sn()),testnetId:en(sn()),testnetExplorerUrl:en(Za(sn())),testnetIndexUrl:en(Za(sn())),derivationPath:en(Za(sn())),addressRegex:en(Za(sn())),slip44:tn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767]),signatureScheme:en(tn(["secp256k1","ed25519","sr25519"])),status:en(tn(["UP","DOWN"])),search:en(sn()),createdAt:sn(),updatedAt:sn(),walletAddresses:en(Ha(za((()=>Qn)))),isChainReady:en($a()),supportsSwaps:en($a()),swapChainMappings:en(Ha(za((()=>Mn)))),indexUrl:en(Za(sn())),chainId:en(sn())}),to=Qa({pagination:Ya([za((()=>In))]),chains:Ha(za((()=>eo)))}),ro=Qa({name:sn(),isEvm:$a(),mainnetRpcUrl:sn(),mainnetIndexUrl:en(sn()),testnetId:en(sn()),testnetRpcUrl:sn(),testnetIndexUrl:sn(),derivationPath:sn(),addressRegex:en(sn()),slip44:Xa(),signatureScheme:tn(["secp256k1","ed25519","sr25519"])}),so=Qa({chain:za((()=>eo))}),ao=Qa({name:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),isEvm:$a(),mainnetId:en(sn()),mainnetRpcUrl:en(sn()),mainnetIndexUrl:en(sn()),testnetId:en(sn()),testnetRpcUrl:en(sn()),testnetIndexUrl:en(sn()),derivationPath:en(sn()),addressRegex:en(sn()),slip44:tn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767]),signatureScheme:en(tn(["secp256k1","ed25519","sr25519"])),supportSwaps:en($a())}),no=Qa({chain:za((()=>eo))}),oo=Qa({pagination:Ya([za((()=>In))]),assets:Ha(za((()=>Gn)))}),io=Qa({asset:za((()=>Gn))}),co=Qa({chainId:sn(),name:sn(),symbol:sn(),verified:$a(),isOffChain:$a(),decimals:Xa(),iconUrl:en(sn()),ticker:sn(),type:tn(["COIN","TOKEN","OBJECT"]),tokenStandard:en(tn(["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:Xa(),contractAddress:en(sn()),description:en(sn()),createdByUserId:en(sn()),createdByMerchantId:en(sn()),suiObjectId:en(sn())}),lo=Qa({asset:za((()=>Gn))}),ho=Qa({name:en(sn()),symbol:en(sn()),isOffChain:en($a()),decimals:en(Xa()),iconUrl:en(sn()),ticker:en(sn()),type:en(tn(["COIN","TOKEN","OBJECT"])),tokenStandard:en(tn(["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:en(Xa()),contractAddress:en(sn()),relayerAddress:en(sn()),description:en(sn()),suiObjectId:en(sn())}),po=Qa({asset:za((()=>Gn))}),uo=Qa({message:sn()}),yo=Qa({pagination:Ya([za((()=>In))]),merchants:Ha(za((()=>Hn)))}),go=Qa({name:sn(),contactEmail:sn(),contactPhoneNumber:en(sn()),status:en(tn(["active","inactive","invalidated"]))}),fo=Qa({name:en(sn()),contactEmail:en(sn()),contactPhoneNumber:en(sn()),status:tn(["active","inactive","invalidated"])}),mo=Qa({merchant:za((()=>Hn))}),wo=Qa({merchant:za((()=>Hn))}),vo=Qa({pagination:Ya([za((()=>In))]),merchant:za((()=>Hn)),assets:Ha(za((()=>Un))),merchantAssets:Ha(za((()=>Un)))}),So=Qa({id:sn(),externalUserId:sn(),walletsCount:Xa(),createdAt:sn(),updatedAt:sn(),merchantId:en(sn()),firstName:en(sn()),email:en(sn()),role:en(tn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),polymeshDID:en(sn())}),Ao=Qa({pagination:Ya([za((()=>In))]),merchant:za((()=>Hn)),users:Ha(za((()=>So)))}),bo=Qa({merchantId:sn(),email:sn(),firstName:sn(),lastName:sn(),role:sn()}),Eo=Qa({message:en(sn()),user:za((()=>So))}),_o=Qa({message:en(sn()),user:za((()=>So))}),To=Qa({pagination:Ya([za((()=>In))]),merchant:za((()=>Hn)),wallets:Ha(za((()=>Zn)))}),Po=Qa({assetConfigId:sn(),userId:sn(),walletId:sn()}),Io=Qa({merchantId:sn(),assets:Ha(za((()=>Po))),updateExistingWallets:en($a())}),ko=Qa({message:en(sn())}),Co=Qa({merchantId:sn(),assetConfigId:en(sn()),isDefault:en($a()),addToExistingWallets:en($a()),addToWallets:en(Ha(sn())),config:en(za((()=>Gn)))}),Oo=Qa({message:en(sn()),merchantAsset:za((()=>Un))}),Ko=Qa({merchantId:sn(),assetConfigId:sn()}),xo=Qa({message:en(sn())}),Ro=Qa({merchantId:sn(),assetConfigId:sn(),isVisible:en($a())}),No=Qa({message:en(sn()),merchantAsset:za((()=>Un))}),Do=Qa({merchantId:sn(),assetConfigId:sn(),isDefault:en($a())}),Lo=Qa({message:en(sn()),merchantAsset:za((()=>Un))}),qo=Qa({iv:sn(),ephemPublicKey:sn(),ciphertext:sn(),mac:sn()}),Uo=Qa({id:sn(),merchantId:sn(),appName:sn(),ipAddresses:Ha(sn()),domainNames:Ha(sn()),status:tn(["active","inactive"]),clientJWTPubKey:sn(),usersCount:Xa(),requestsCount:Xa(),totalRequestSizeInKb:Xa(),totalResponseSizeInKb:Xa(),totalResponseTimeInKb:Xa(),lastRequestAt:Za(sn()),onlyDashboardAccess:$a(),allowMobileAccess:$a(),createdAt:sn(),updatedAt:sn(),merchant:za((()=>Hn)),origins:Ha(za((()=>jo)))}),jo=Qa({id:sn(),merchantId:sn(),apiKeyId:sn(),origin:sn(),createdAt:sn(),updatedAt:sn(),merchant:za((()=>Hn)),apiKey:za((()=>Uo))}),Bo=Qa({id:sn(),merchantId:sn(),appName:sn(),apiKey:za((()=>qo)),status:tn(["active","inactive"]),clientJWTPubKey:sn(),allowMobileAccess:$a(),createdAt:sn(),updatedAt:sn(),origins:en(Ha(za((()=>jo))))}),Mo=Qa({pagination:Ya([za((()=>In))]),apiKeys:Ha(za((()=>Bo)))}),Wo=Qa({pagination:Ya([za((()=>In))]),apiKeyOrigins:Ha(za((()=>jo)))}),Vo=Qa({clientJWTPubKey:en(sn()),wrappingPublicKey:en(sn()),allowMobileAccess:en($a()),appName:sn()}),Fo=Qa({message:en(sn()),apiKey:za((()=>Bo)),clientJWTPrivKey:en(Ya([za((()=>qo))]))}),Go=Qa({merchantId:sn(),apiKeyId:sn(),origins:Ha(sn())}),Ho=Qa({message:en(sn()),apiKeyOrigins:Ha(za((()=>jo)))}),$o=Qa({clientJWTPubKey:en(sn()),wrappingPublicKey:sn(),appName:en(sn()),status:en(tn(["active","inactive"])),allowMobileAccess:en($a())}),Jo=Qa({message:en(sn()),apiKey:za((()=>Bo))}),Yo=Qa({pagination:Ya([za((()=>In))]),wallets:Ha(za((()=>Zn)))}),zo=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn()}),Zo=Qa({id:sn(),userId:sn(),merchantId:sn(),chainId:sn(),userAssetAddress:sn(),walletId:sn(),configId:sn(),assetName:sn(),assetSymbol:sn(),balance:Za(sn()),balanceUpdatedAt:Za(sn()),claimableBalance:en(Za(sn())),claimableBalanceUpdatedAt:en(Za(sn())),claimablePaymentTokenContractAddress:en(Za(sn())),claimablePaymentTokenAssetConfigId:en(Za(sn())),lockedTokenBalance:Za(sn()),lockedTokenBalanceUpdatedAt:Za(sn()),mainnetBalance:Za(sn()),mainnetBalanceUpdatedAt:Za(sn()),testnetBalance:Za(sn()),testnetBalanceUpdatedAt:Za(sn()),mainnetLockedBalance:Za(sn()),mainnetLockedBalanceUpdatedAt:Za(sn()),testnetLockedBalance:Za(sn()),testnetLockedBalanceUpdatedAt:Za(sn()),defaultAddress:sn(),isVisible:$a(),source:tn(["merchant","user","republic"]),addresses:Ha(za((()=>kn))),ownershipType:sn(),priceConversion:en(sn()),changePercentageLast24h:en(sn()),createdAt:sn(),updatedAt:sn(),merchant:Ya([za((()=>Cn))]),config:za((()=>Gn))}),Xo=Qa({id:sn(),userId:sn(),revisionName:sn()}),Qo=Qa({iv:sn(),ephemPublicKey:sn(),ciphertext:sn(),mac:sn()}),ei=Qa({encrypted:Ya([za((()=>Qo))]),wrappingPublicKey:sn(),type:tn(["wallaby_share","owner_main_device_share","owner_backup_device_share"])}),ti=Qa({v:Xa(),iv:sn(),ciphertext:sn(),tag:sn()}),ri=Qa({address:sn(),type:tn(["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:sn(),chainName:sn()}),si=Qa({wallabyAuthPubKey:sn(),assets:Ha(za((()=>Zo))),encryptedSeed:en(nn([za((()=>Qo)),za((()=>ti))])),wallet:Ya([za((()=>Xo))]),shares:en(Ha(za((()=>ei)))),encryptedBackupShare:en(Ya([za((()=>ti))])),reference:sn(),encryptedSeedForSharesSplit:en(za((()=>Qo))),walletAddressesInfo:Ha(za((()=>ri)))}),ai=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),encryptedShares:en(Ha(za((()=>Qo)))),encryptedSeed:en(Ya([za((()=>Qo))])),walletId:sn()}),ni=Qa({isAccessVerified:$a()}),oi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),adminWalletTypes:Ha(tn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]))}),ii=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),returnWalletOption:tn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:sn(),numShares:en(Xa()),threshold:en(Xa()),wallabyKeepsOne:$a(),backupDevicePublicKey:en(sn()),walletOwnershipType:tn(["SINGLE_OWNER"])}),ci=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),encryptedSeed:Ya([za((()=>Qo))]),walletId:en(sn()),returnWalletOption:tn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:sn(),numShares:en(Xa()),threshold:en(Xa()),wallabyKeepsOne:$a(),backupDevicePublicKey:en(sn()),walletOwnershipType:tn(["SINGLE_OWNER"])}),di=Qa({clientAuthPubKey:sn(),walletId:sn(),encryptedBackupShare:nn([za((()=>ti)),za((()=>qo))])}),li=Qa({reference:sn(),share:Ya([za((()=>ei))])}),hi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),encryptedSeed:Ya([za((()=>Qo))]),walletId:sn()}),pi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo)))),chainName:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]))}),ui=Qa({id:sn(),walletId:sn(),typeId:Xa(),type:za((()=>Xn)),address:sn(),publicKey:sn()}),yi=Qa({walletAddressesInfo:Ha(za((()=>ri))),walletAddresses:Ha(za((()=>ui)))}),gi=Qa({pagination:Ya([za((()=>In))]),assets:Ha(za((()=>Zo))),groupedAssets:en(rn(sn(),Ha(za((()=>Zo))))),walletAddressesInfo:Ha(za((()=>ri)))}),fi=Qa({pagination:Ya([za((()=>In))]),addresses:Ha(za((()=>ri)))}),mi=Qa({assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])}),wi=Qa({configId:sn(),assetName:en(sn()),assetSymbol:en(sn()),isVisible:en($a()),walletId:sn()}),vi=Qa({userAsset:Ya([za((()=>Zo))]),message:sn()}),Si=Qa({externalUserId:sn(),clientAuthPubKey:sn()}),Ai=Qa({signatureMessage:sn(),wallabyAuthPubKey:sn()}),bi=Qa({walletId:en(sn()),externalUserId:sn(),clientAuthPubKey:sn(),message:sn(),signature:sn(),encryptedSeed:Ya([za((()=>Qo))])}),Ei=Qa({id:sn(),externalUserId:sn()}),_i=Qa({user:Ya([za((()=>Ei))]),wallet:Ya([za((()=>Zn))])}),Ti=Qa({fromAssetConfigId:sn(),toAssetConfigId:sn(),fromAmount:en(sn()),toAmount:en(sn()),slippage:en(Xa())}),Pi=Qa({amount:sn(),amountUSD:en(Za(sn())),symbol:en(sn()),icon:en(sn())}),Ii=Qa({id:sn(),gasFee:en(Ha(za((()=>Pi)))),providerFee:en(Ha(za((()=>Pi)))),republicFee:en(Ha(za((()=>Pi)))),allowanceFee:en(Ha(za((()=>Pi)))),fromAssetConfigId:sn(),fromAssetSymbol:sn(),fromAssetChain:sn(),toAssetConfigId:sn(),toAssetSymbol:sn(),toAssetChain:sn(),fromAmount:sn(),fromAddress:sn(),toAmount:sn(),toAddress:sn(),slippage:Xa(),expiresAt:en(sn())}),ki=Qa({id:sn(),fromAssetSymbol:sn(),fromAssetChainName:sn(),toAssetSymbol:sn(),toAssetChainName:sn(),fromAddress:sn(),toAddress:sn(),fromAmount:sn(),toAmount:sn(),slippage:Xa(),gasFee:en(Ha(za((()=>Pi)))),providerFee:en(Ha(za((()=>Pi)))),republicFee:en(Ha(za((()=>Pi)))),allowanceFee:en(Ha(za((()=>Pi)))),status:tn(["quote","executing","in_progress","completed","failed","abandoned","execution_failed","invalid"]),executedAt:Za(sn()),completedAt:Za(sn()),transactionId:Za(sn()),transactionHash:Za(sn()),explorerLink:Za(sn())}),Ci=Qa({pagination:Ya([za((()=>In))]),swaps:Ha(za((()=>ki)))}),Oi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),quoteId:sn(),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo))))}),Ki=Qa({swapQuoteId:sn(),status:sn(),explorerLink:sn(),transactionHash:sn()}),xi=Qa({id:sn(),reference:Za(sn()),hash:en(Za(sn())),merchantId:sn(),userEmail:sn(),chainId:sn(),chainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:Xa(),fromWalletId:sn(),fromAddress:sn(),toWalletId:sn(),toAddress:sn(),assetId:sn(),assetSymbol:sn(),tokenType:tn(["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:sn(),fee:sn(),note:sn(),nonce:Xa(),gasPrice:Xa(),submitter:sn(),status:tn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:Za(tn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:tn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:sn(),networkEnvironment:Za(tn(["mainnet","testnet"])),statusCheckAttempts:Xa(),statusCheckedAt:Za(sn()),createdAt:sn(),updatedAt:sn(),asset:Ya([za((()=>Gn))]),merchant:Ya([za((()=>Hn))]),adminTransactions:Ha(za((()=>Nn))),user:za((()=>En)),chain:za((()=>eo)),splitCoins:sn(),transferObjects:sn(),type:en(tn(["INCOMING","OUTGOING","SWAP","UNKNOWN"])),entryType:en(tn(["INCOMING","OUTGOING","SWAP","UNKNOWN"]))}),Ri=Qa({pagination:Ya([za((()=>In))]),transactions:Ha(za((()=>xi)))}),Ni=Qa({id:sn(),amount:sn(),sender:sn(),asset:en(Ya([za((()=>Gn))])),expires:en(sn())}),Di=Qa({transactions:Ha(za((()=>Ni)))}),Li=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),id:sn(),choice:tn(["approve","deny"]),symbol:sn(),chainName:sn(),walletId:sn(),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo))))}),qi=Qa({id:sn(),status:tn(["confirmed","denied"]),hash:sn(),asset:Ya([za((()=>Gn))])}),Ui=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),originAddress:sn(),recipientAddress:sn(),assetId:sn(),amount:sn(),reference:sn(),encryptedSeed:Ya([za((()=>Qo))]),memo:sn(),transactionType:en(tn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"]))}),ji=Qa({transaction:Ya([za((()=>Dn))]),message:en(sn())}),Bi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),originAddress:sn(),recipientAddress:sn(),assetId:sn(),amount:sn(),reference:sn(),memo:sn(),transactionType:en(tn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"])),encryptedShares:Ha(za((()=>Qo)))}),Mi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),originAddress:sn(),reference:sn(),note:en(sn()),encryptedSeed:Ya([za((()=>Qo))]),assetIndex:Xa()}),Wi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),originAddress:sn(),reference:sn(),note:en(sn()),encryptedSeed:Ya([za((()=>Qo))]),appIndex:Xa()}),Vi=Qa({feePaymentSymbol:sn(),fee:sn(),lowestFee:en(sn()),highestFee:en(sn())}),Fi=Qa({address:Ha(sn()),amount:sn(),txId:sn()}),Gi=Qa({status:tn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionHash:sn(),reference:sn(),assetSymbol:sn(),transactionValue:sn(),fromAddress:sn(),toAddress:sn(),chain:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),fee:sn(),nonce:en(Xa()),timestamp:en(Xa()),blockNumber:en(Xa()),memo:en(sn()),origins:en(Ha(za((()=>Fi)))),recipients:en(Ha(za((()=>Fi))))}),Hi=Qa({canTransfer:$a(),restrictionCode:sn(),tokenContractAddress:sn(),fromAddress:sn(),toAddress:sn(),value:sn(),assetId:sn()}),$i=Qa({restrictionCode:Xa(),restrictionCodeMessage:sn()}),Ji=Qa({canTransfer:$a(),message:sn(),restrictionCode:sn()}),Yi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),ownerAddress:sn(),spenderAddress:sn(),amount:sn(),reference:sn(),memo:sn(),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo)))),chainName:sn(),assetSymbol:sn(),assetId:sn(),contractAddress:en(sn())}),zi=Qa({transaction:Ya([za((()=>Dn))])}),Zi=Qa({paymentTokenContractAddress:sn(),assetConfigId:sn(),balance:sn()}),Xi=Qa({address:sn(),assetSymbol:sn(),tokenStandard:en(tn(["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:en(tn(["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:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:en(sn()),balance:sn(),claimable:Ya([za((()=>Zi))]),lockedTokenBalance:en(sn()),unlockedTokenBalance:en(sn()),stakedBalance:en(sn()),claimableBalance:en(sn()),assetConfigId:sn(),balanceUpdatedAt:en(sn())}),Qi=Qa({address:sn(),assetSymbol:sn(),tokenStandard:en(tn(["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:en(tn(["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:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:en(sn())}),ec=Qa({assets:Ha(za((()=>Qi)))}),tc=Qa({balances:Ha(za((()=>Xi)))}),rc=Qa({walletId:sn()}),sc=Qa({address:sn(),transactions:Ha(za((()=>Dn)))}),ac=Qa({decimals:Xa(),symbol:sn(),name:sn(),tokenContractAddress:sn()}),nc=Qa({symbol:sn(),price:sn(),changePercentageLast24h:sn()}),oc=Qa({data:Ha(za((()=>nc)))}),ic=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),encryptedShares:Ha(za((()=>Qo))),recoveryPubKey:en(sn()),walletId:en(sn())}),cc=Qa({encryptedSeed:Ya([za((()=>Qo))])}),dc=Qa({pagination:Ya([za((()=>In))]),users:Ha(za((()=>So)))}),lc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),email:sn(),firstName:sn(),lastName:sn()}),hc=Qa({message:sn(),user:Ya([za((()=>En))])}),pc=Qa({user:Ya([za((()=>So))])}),uc=Qa({clientSalt:sn()}),yc=Qa({wallets:Ha(za((()=>Zn)))}),gc=Qa({pagination:Ya([za((()=>In))]),assets:Ha(za((()=>On))),groupedAssets:en(rn(sn(),Ha(za((()=>On)))))}),fc=Qa({name:sn(),symbol:sn(),decimals:Xa(),contractAddress:sn(),chainId:en(sn()),chainName:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),tokenStandard:en(tn(["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:en(sn()),iconUrl:en(sn())}),mc=Qa({assetConfigId:en(sn()),walletId:sn(),userId:sn(),config:en(Ya([za((()=>fc))])),message:en(sn()),clientAuthPubKey:en(sn()),signature:en(sn()),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo))))}),wc=Qa({asset:Ya([za((()=>On))])}),vc=Qa({message:sn()}),Sc=Qa({user:Ya([za((()=>So))])}),Ac=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:sn(),releaseCount:Xa(),delayUntilFirstReleaseInSeconds:Xa(),initialReleasePortionInBips:Xa(),periodBetweenReleasesInSeconds:Xa(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),bc=Qa({reference:sn()}),Ec=Qa({address:sn(),amount:sn(),commencementTimestamp:Xa(),scheduleId:Xa(),cancelableBy:Ha(sn())}),_c=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:sn(),mints:Ha(za((()=>Ec))),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),Tc=Qa({references:Ha(za((()=>bc)))}),Pc=Qa({address:sn(),amount:sn(),commencementTimestamp:Xa(),scheduleId:Xa(),timelockIndex:Xa(),reclaimTokenTo:sn()}),Ic=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:sn(),burns:Ha(za((()=>Pc))),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),kc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:sn(),payerAddress:sn(),tokenRecipientAddress:sn(),originatorPurchaseAmount:sn(),mintAmount:sn(),adminFeeAmount:sn(),totalAmount:sn(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),Cc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:sn(),payerAddress:sn(),tokenRecipientAddress:sn(),originatorPurchaseAmount:sn(),mintAmount:sn(),prefundedInterestAmount:sn(),adminFeeExcludingPrefundedInterestAmount:sn(),totalAmount:sn(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),Oc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),owner:sn(),regions:Ha(sn()),accreditationType:Xa(),lastAmlKycChangeTimestamp:Xa(),lastAccreditationChangeTimestamp:Xa(),amlKycPassed:$a(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),Kc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),wallet:sn(),amount:sn(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),xc=Qa({assetSymbol:sn(),blockchainName:sn(),releaseCount:Xa(),delayUntilFirstReleaseInSeconds:Xa(),initialReleasePortionInBips:Xa(),periodBetweenReleasesInSeconds:Xa(),scheduleId:Xa()}),Rc=Qa({adminTransaction:Ya([za((()=>Nn))])}),Nc=Qa({status:tn(["QUEUED","PENDING","SUCCESS","FAILED"]),message:en(sn()),txHash:en(sn()),txLogs:Ha(za((()=>xn))),txLogsDecoded:Ha(za((()=>Rn))),reqSignature:en(sn()),clientRequestSignature:en(sn()),requestId:en(sn()),reason:en(sn()),txId:en(sn())}),Dc=Qa({message:sn()}),Lc=Qa({chainsCount:Xa(),chains:Ha(za((()=>eo))),merchantsCount:Xa(),merchants:Ha(za((()=>Hn))),assetsCount:Xa(),usersCount:Xa(),users:Ha(za((()=>So))),adminsCount:Xa(),walletsCount:Xa()}),qc=Qa({id:sn(),userId:sn(),merchantId:sn(),action:en(Za(tn(["logged_in","logged_out","created_wallet","updated_wallet","deleted_wallet","created_merchant","updated_merchant","deleted_merchant"]))),requestUrl:sn(),requestMethod:sn(),createdAt:sn(),updatedAt:sn(),merchant:za((()=>Hn))}),Uc=Qa({pagination:Ya([za((()=>In))]),activities:Ha(za((()=>qc)))}),jc=[{method:"POST",path:"/auth/signature-message/external",request:za((()=>on)),response:za((()=>cn))},{method:"POST",path:"/auth/signature-message",request:za((()=>on)),response:za((()=>cn))},{method:"POST",path:"/auth/sign-up",request:za((()=>dn)),response:za((()=>hn))},{method:"POST",path:"/auth/sign-up/external",request:za((()=>pn)),response:za((()=>hn))},{method:"POST",path:"/auth/sign-in",request:za((()=>un)),response:za((()=>hn))},{method:"POST",path:"/auth/issue-jwt-token",response:za((()=>gn))},{method:"POST",path:"/auth/refresh-access-token",request:za((()=>fn)),response:za((()=>mn))},{method:"POST",path:"/auth/logout",response:za((()=>wn))},{method:"PUT",path:"/auth/client-auth-pubkey",request:za((()=>vn)),response:za((()=>Sn))},{method:"POST",path:"/auth/wallaby-auth-pubkey",request:za((()=>An)),response:za((()=>bn))},{method:"GET",path:"/auth/passkey-credentials",response:za((()=>Pn))},{method:"GET",path:"/chains",response:za((()=>to))},{method:"POST",path:"/chains",request:za((()=>ro)),response:za((()=>so))},{method:"PUT",path:"/chains/{chainId}",request:za((()=>ao)),response:za((()=>no))},{method:"GET",path:"/assets/configurations",response:za((()=>oo))},{method:"POST",path:"/assets/configurations",request:za((()=>co)),response:za((()=>lo))},{method:"GET",path:"/assets/configurations/{assetConfigId}",response:za((()=>io))},{method:"PUT",path:"/assets/configurations/{assetConfigId}",request:za((()=>ho)),response:za((()=>po))},{method:"POST",path:"/assets/configurations/{assetConfigId}/verify",response:za((()=>uo))},{method:"DELETE",path:"/assets/configurations/{assetConfigId}/unverify",response:za((()=>uo))},{method:"POST",path:"/assets/configurations/{assetConfigId}/archive",response:za((()=>uo))},{method:"POST",path:"/assets/configurations/{assetConfigId}/unarchive",response:za((()=>uo))},{method:"GET",path:"/merchants",response:za((()=>yo))},{method:"POST",path:"/merchants",request:za((()=>go)),response:za((()=>go))},{method:"PUT",path:"/merchants/{merchantId}",request:za((()=>fo)),response:za((()=>mo))},{method:"GET",path:"/merchants/{merchantId}",response:za((()=>wo))},{method:"GET",path:"/merchants/{merchantId}/assets",response:za((()=>vo))},{method:"GET",path:"/merchants/{merchantId}/users",response:za((()=>Ao))},{method:"GET",path:"/merchants/{merchantId}/admins",response:za((()=>Ao))},{method:"POST",path:"/merchants/admins/invite",request:za((()=>bo)),response:za((()=>Eo))},{method:"DELETE",path:"/merchants/{merchantId}/admins/{userId}",response:za((()=>_o))},{method:"GET",path:"/merchants/{merchantId}/wallets",response:za((()=>To))},{method:"POST",path:"/merchants/wallets/add-assets",request:za((()=>Io)),response:za((()=>ko))},{method:"POST",path:"/merchants/assets/add",request:za((()=>Co)),response:za((()=>Oo))},{method:"DELETE",path:"/merchants/assets/delete",request:za((()=>Ko)),response:za((()=>xo))},{method:"POST",path:"/merchants/assets/update-visibility",request:za((()=>Ro)),response:za((()=>No))},{method:"POST",path:"/merchants/assets/update-default-status",request:za((()=>Do)),response:za((()=>Lo))},{method:"GET",path:"/merchants/{merchantId}/api-keys",response:za((()=>Mo))},{method:"POST",path:"/merchants/{merchantId}/api-keys",request:za((()=>Vo)),response:za((()=>Fo))},{method:"GET",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/origins",response:za((()=>Wo))},{method:"POST",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/whitelist-origins",request:za((()=>Go)),response:za((()=>Ho))},{method:"PUT",path:"/merchants/{merchantId}/api-keys/{apiKeyId}",request:za((()=>$o)),response:za((()=>Jo))},{method:"GET",path:"/wallets",response:za((()=>Yo))},{method:"POST",path:"/wallets/create",request:za((()=>zo)),response:za((()=>si))},{method:"POST",path:"/wallets/verify-access",request:za((()=>ai)),response:za((()=>ni))},{method:"POST",path:"/wallets/create-admin-server-wallet",request:za((()=>oi)),response:za((()=>si))},{method:"POST",path:"/wallets/create-with-shares",request:za((()=>ii)),response:za((()=>si))},{method:"POST",path:"/wallets/create-shares-based-wallet-from-seed",request:za((()=>ci)),response:za((()=>si))},{method:"POST",path:"/wallets/add-new-device",request:za((()=>di)),response:za((()=>li))},{method:"POST",path:"/wallets/import-seed-phrase",request:za((()=>hi)),response:za((()=>si))},{method:"POST",path:"/wallets/generate-wallet-addresses",request:za((()=>pi)),response:za((()=>yi))},{method:"GET",path:"/wallets/{walletId}/assets",response:za((()=>gi))},{method:"GET",path:"/wallets/{walletId}/addresses",response:za((()=>fi))},{method:"GET",path:"/wallets/asset",request:za((()=>mi)),response:za((()=>Zo))},{method:"PUT",path:"/wallets/asset/update",request:za((()=>wi)),response:za((()=>vi))},{method:"POST",path:"/wallets/recover/init",request:za((()=>Si)),response:za((()=>Ai))},{method:"POST",path:"/wallets/recover",request:za((()=>bi)),response:za((()=>_i))},{method:"POST",path:"/wallets/{walletId}/swap/quote",request:za((()=>Ti)),response:za((()=>Ii))},{method:"GET",path:"/wallets/{walletId}/swaps",response:za((()=>Ci))},{method:"GET",path:"/wallets/{walletId}/swaps/{swapId}",response:za((()=>ki))},{method:"POST",path:"/wallets/execute-swap",request:za((()=>Oi)),response:za((()=>Ki))},{method:"GET",path:"/transactions",response:za((()=>Ri))},{method:"GET",path:"/transactions/pending",response:za((()=>Di))},{method:"POST",path:"/transactions/resolve",request:za((()=>Li)),response:za((()=>qi))},{method:"POST",path:"/transactions/transfer",request:za((()=>Ui)),response:za((()=>ji))},{method:"POST",path:"/transactions/transfer-with-shares",request:za((()=>Bi)),response:za((()=>ji))},{method:"POST",path:"/transactions/asset-optin",request:za((()=>Mi)),response:za((()=>ji))},{method:"POST",path:"/transactions/app-optin",request:za((()=>Wi)),response:za((()=>ji))},{method:"GET",path:"/transactions/estimate-fee",response:za((()=>Vi))},{method:"GET",path:"/transactions/status",response:za((()=>Gi))},{method:"GET",path:"/transactions/raw-status",response:za((()=>Dn))},{method:"GET",path:"/transactions/detect-transfers-restrictions",response:za((()=>Hi))},{method:"GET",path:"/transactions/transfer-restriction-message",response:za((()=>$i))},{method:"GET",path:"/transactions/restriction",response:za((()=>Ji))},{method:"GET",path:"/transactions/check-asset-optin",response:Ha(rn(sn(),Ga()))},{method:"GET",path:"/transactions/check-app-optin",response:Ha(rn(sn(),Ga()))},{method:"POST",path:"/transactions/create-allowance",request:za((()=>Yi)),response:za((()=>zi))},{method:"GET",path:"/query/assets/balance",response:za((()=>Xi))},{method:"GET",path:"/query/address/balance",response:za((()=>Xi))},{method:"POST",path:"/query/assets/bulk-balance",request:za((()=>ec)),response:za((()=>tc))},{method:"POST",path:"/query/assets/wallet-bulk-balance",request:za((()=>rc)),response:za((()=>tc))},{method:"GET",path:"/query/transactions",response:za((()=>sc))},{method:"GET",path:"/query/fetch-token-info",response:za((()=>ac))},{method:"GET",path:"/query/get-asset-price",response:za((()=>oc))},{method:"POST",path:"/mpc/reconstruct-seed-phrase",request:za((()=>ic)),response:za((()=>cc))},{method:"GET",path:"/users",response:za((()=>dc))},{method:"PUT",path:"/users/profile",request:za((()=>lc)),response:za((()=>hc))},{method:"GET",path:"/users/profile",response:za((()=>pc))},{method:"GET",path:"/users/salt",response:za((()=>uc))},{method:"GET",path:"/users/{userId}/wallets",response:za((()=>yc))},{method:"GET",path:"/users/merchants/assets",response:za((()=>vo))},{method:"GET",path:"/users/merchant/assets",response:za((()=>vo))},{method:"GET",path:"/users/{userId}/assets",response:za((()=>gc))},{method:"POST",path:"/users/assets/add",request:za((()=>mc)),response:za((()=>wc))},{method:"DELETE",path:"/users/{userId}/wallets/{walletId}/assets/{assetConfigId}",response:za((()=>vc))},{method:"GET",path:"/users/{userId}",response:za((()=>pc))},{method:"GET",path:"/users/{externalUserId}/externalUserId",response:za((()=>Sc))},{method:"POST",path:"/transactions/admin/release-schedule",request:za((()=>Ac)),response:za((()=>bc))},{method:"GET",path:"/transactions/admin/release-schedule",response:za((()=>xc))},{method:"POST",path:"/transactions/admin/mint",request:za((()=>_c)),response:za((()=>Tc))},{method:"POST",path:"/transactions/admin/burn",request:za((()=>Ic)),response:za((()=>Tc))},{method:"POST",path:"/transactions/admin/execute-purchase",request:za((()=>kc)),response:za((()=>bc))},{method:"POST",path:"/transactions/admin/execute-purchase-with-interest",request:za((()=>Cc)),response:za((()=>bc))},{method:"POST",path:"/transactions/admin/set-identity",request:za((()=>Oc)),response:za((()=>bc))},{method:"POST",path:"/transactions/admin/force-claim",request:za((()=>Kc)),response:za((()=>bc))},{method:"POST",path:"/transactions/admin/force-claim-principal",request:za((()=>Kc)),response:za((()=>bc))},{method:"GET",path:"/transactions/admin/{referenceId}",response:za((()=>Rc))},{method:"POST",path:"/transactions/admin/callback",request:za((()=>Nc)),response:za((()=>Dc))},{method:"GET",path:"/dashboard",response:za((()=>Lc))},{method:"GET",path:"/users-activities",response:za((()=>Uc))}],Bc=new Map,Mc=[];for(const e of jc)if(e.path.includes("{")){const t=e.path.replace(/\{[^/]+\}/g,"[^/]+");Mc.push({method:e.method,regex:new RegExp(`^${t}$`),entry:e})}else Bc.set(`${e.method} ${e.path}`,e);const Wc={response:{statusCode:200,errorCode:exports.ErrorResponseCodes.sdk_invalid_response,tag:"InvalidResponse"},request:{statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter,tag:"InvalidRequest"}};function Vc(e,t,r,s,a){var n;if("off"===a)return;const o=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=Bc.get(`${r} ${s}`);if(a)return{request:a.request,response:a.response};const n=Mc.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(!o)return;const i=function(e,t){const r=e["~run"]({value:t},La());return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}(o,s);if(i.success)return;const c=`${t} ${r}: ${d=i.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}=Wc[e];if("throw"===a)throw new M({kind:"validation",message:c,statusCode:l,errorCode:h,data:{method:t,path:r,issues:i.issues}});ye.warn(`SDK::ApiValidation::${p} ${c}`)}function Fc({method:e,path:t,data:r,mode:s}){Vc("response",e,t,r,s)}function Gc({method:e,path:t,body:r,mode:s}){Vc("request",e,t,r,s)}const Hc=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]),$c=new Set([exports.ErrorResponseCodes.auth_refresh_token_not_found,exports.ErrorResponseCodes.auth_refresh_token_expired,exports.ErrorResponseCodes.auth_refresh_token_reuse_detected]);function Jc(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 Yc(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 zc(e){if(401!==Jc(e))return!1;const t=Yc(e);return!t||Hc.has(t)}const Zc=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()}},Xc=new class{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()}};class Qc{constructor(e,t={}){var r,s,a,n,o;const i=Ka(e);this.apiKey=i.apiKey,this.baseUrl=i.baseUrl,this.userId=i.userId,this.options=i.options,(null===(r=this.options)||void 0===r?void 0:r.platform)&&(Ae.platform=this.options.platform,Ae.isNative="ios"===this.options.platform||"android"===this.options.platform,Ae.isWeb=!Ae.isNative),this.cipher=null!==(s=t.cipher)&&void 0!==s?s:new _a,this.transport=null!==(a=t.transport)&&void 0!==a?a:(...e)=>fetch(...e),this.clock=null!==(n=t.clock)&&void 0!==n?n:{now:()=>Date.now()},this.lockManager=Xc,this._initializeClientAuthToken(i.clientAuthToken),this.request=this.request.bind(this);const c=new Ra({baseUrl:this.baseUrl.replace(/\/api\/v1\/?$/,""),baseApiParams:{secure:!0},securityWorker:this.securityWorker.bind(this),customFetch:this.transport}),d=c.request.bind(c);c.request=async e=>{const t=async r=>{try{Gc({method:e.method,path:e.path,body:e.body,mode:this.validationMode});const t=await d(e);return Fc({method:e.method,path:e.path,data:t,mode:this.validationMode}),t}catch(e){if(!r&&zc(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 M)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 Na(c),this.api.http.setSecurityData(Object.assign({"x-api-key":e.apiKey,"x-client-jwt":e.clientAuthToken},null===(o=this.options)||void 0===o?void 0:o.headers))}set setClientAuthToken(e){this._initializeClientAuthToken(e)}get version(){const e=be;return ye.log(`wsdk is running v${e}`),e}_initializeClientAuthToken(e){if(t=e,r=this.userId,!t||!r||a.jwtDecode(t).externalUserId!==r)throw new M({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 a.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 M({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:me,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 M({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 Ta({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 Zc.withDedupe(t,(async()=>{var t;const r=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(r)try{const s=await this.request(Ca.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=Jc(e),r=Yc(e);return 401===t||!!r&&$c.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 M(e);try{null===(r=null===(t=this.options)||void 0===t?void 0:t.onError)||void 0===r||r.call(t,s)}catch(e){ye.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 M(e):this.toWallabyError(e);if(e!==Ca.refreshAccessToken&&!r){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(e&&Ia(e,60,this.clock.now))try{await this._performTokenRefresh({silent:!0})}catch(e){}}let o="string"==typeof e.fullPath?e.fullPath:e.fullPath(null==t?void 0:t.payload);(null==t?void 0:t.queryParams)&&(o+=`?${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 i=`${this.baseUrl}${o}`,c=Object.assign(Object.assign({},await this._getRequestHeaders()),null===(a=this.options)||void 0===a?void 0:a.headers);try{Gc({method:e.method,path:o,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)),ye.debug(`SDK::Base::${e.method}::Request`,{path:i,payload:null==t?void 0:t.payload});const a=await this.transport(i,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(ye.debug(`SDK::Base::${e.method}::Response`,{status:a.status,statusText:a.statusText,data:l}),!a.ok){if(!r&&e!==Ca.refreshAccessToken&&zc({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 Fc({method:e.method,path:o,data:l,mode:this.validationMode}),l}catch(t){if(t instanceof M)throw t;if(null==t?void 0:t.error){ye.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 ye.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(Pa(this.clientAuthToken,this.clock.now))throw new M({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};return e&&(t.Authorization="Bearer "+e),t}async securityWorker(e){try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&Ia(e,60,this.clock.now)&&await this._performTokenRefresh({silent:!0})}catch(e){}const t=Object.assign({"Content-Type":"application/json"},e||{});try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&(t.Authorization=`Bearer ${e}`)}catch(e){}return{headers:t}}}const ed={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},initRecoveryFlow:{fullPath:"/wallets/recover/init",method:exports.RequestMethod.Post,requiresAccessToken:!1},recover:{fullPath:"/wallets/recover",method:exports.RequestMethod.Post,requiresAccessToken:!1},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}},td={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}},rd={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}},sd={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 ad(e,t){if(!e)return{};const r=new Set(t);return Object.fromEntries(Object.entries(e).filter((([e])=>!r.has(e))))}class nd{constructor(){}async register({optionsJSON:e}){if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new M({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await h.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 M({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await h.startAuthentication({optionsJSON:Object.assign(Object.assign({},e),{userVerification:r?"discouraged":e.userVerification}),useBrowserAutofill:t})}catch(e){throw this.handlePasskeyError(e),e}}handlePasskeyError(e){return ye.error("SDK::Authenticator::handlePasskeyError",e),this.throwPasskeyError(this.classifyPasskeyError(e),e)}classifyPasskeyError(e){return e instanceof h.WebAuthnError?(ye.debug("SDK::Authenticator::handlePasskeyError - WebAuthnError",e),{errorCode:e.code}):e instanceof Error?(ye.debug("SDK::Authenticator::handlePasskeyError - Error",e),{errorMessage:e.message}):null!==e&&"object"==typeof e&&e.error&&e.message?(ye.debug("SDK::Authenticator::handlePasskeyError - Object",e),{errorCode:e.error,errorMessage:e.message}):"string"==typeof e?(ye.debug("SDK::Authenticator::handlePasskeyError - String",e),{errorMessage:e}):(ye.debug("SDK::Authenticator::handlePasskeyError - Unknown",e),{})}throwPasskeyError({errorCode:e,errorMessage:t},r){var s,a,n;ye.error("SDK::Authenticator::throwPasskeyError",e);const o=pe.find((t=>t.error===e));throw ye.error("SDK::Authenticator::error",o),new M({message:null!==(a=null!==(s=null==o?void 0:o.message)&&void 0!==s?s:t)&&void 0!==a?a:W.message,statusCode:400,errorCode:null!==(n=null==o?void 0:o.error)&&void 0!==n?n:e,cause:r})}}function od(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");return t.padEnd(t.length+(4-t.length%4)%4,"=")}function id(e){try{return o.toUint8Array(e)}catch(r){return t=e,o.toUint8Array(od(t))}var t}function cd(e){const t=od(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 dd{constructor(e,t,r,s=new _a){this.cipher=s,this.localStorageService=t,this.userId=e,this.request=r,this.authenticator=new nd}preparePasskeyRequestOptions(e){var t,r,s,a,n,o,i,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?cd(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===(o=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===o?void 0:o.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===(i=e.extensions)||void 0===i?void 0:i.prf)&&void 0!==c?c:{}})});return ye.log("SDK::PasskeyService::preparePasskeyRequestOptions::parsedOptions",!!l),l}preparePasskeyCreationOptions(e){var t,r,s,a,n,o,i,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?cd(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===(o=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===o?void 0:o.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===(i=e.extensions)||void 0===i?void 0:i.prf)&&void 0!==c?c:{}})});return ye.log("SDK::PasskeyService::preparePasskeyCreationOptions::parsedOptions",!!l),l}async addNewPasskey({deviceKeyPair:e,getSignature:t}){try{let r,s;ye.log("SDK::PasskeyService::addNewPasskey: start adding new passkey");try{const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});if(!a.registrationOptions)throw new M({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);ye.log("SDK::PasskeyService::addNewPasskey: about to register passkey credential"),r=await this.authenticator.register({optionsJSON:n}),ye.log("SDK::PasskeyService::addNewPasskey: finished registering passkey credential");const o=await this.handleCredentialsCreationFromPrfExtension(r);ye.log("SDK::PasskeyService::addNewPasskey:: finished deriving credentials key pair",o.publicKey),s=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyRegistrationResponse:r}}),ye.log("SDK::PasskeyService::addNewPasskey:: signInResponse",s);const i=await this.cipher.encrypt({data:e.privateKey,encryptionKey:o.publicKey});return await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:i},passkeyCredential:r}),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:o.prfValue})}catch(a){if(ye.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 M({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);ye.log("SDK::PasskeyService::addNewPasskey::catch: about to authenticate with passkey"),r=await this.authenticator.authenticate({optionsJSON:n}),ye.log("SDK::PasskeyService::addNewPasskey::catch: finished authenticating with passkey"),s=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyAuthenticationResponse:r}}),ye.log("SDK::PasskeyService::addNewPasskey::catch: finished signing in with passkey",{signInResponse:s});const o=await this.handleCredentialsCreationFromPrfExtension(r);ye.log("SDK::PasskeyService::addNewPasskey::catch: finished deriving credentials key pair",o.publicKey);const i=await this.cipher.encrypt({data:e.privateKey,encryptionKey:o.publicKey});return ye.log("SDK::PasskeyService::addNewPasskey::catch: about to store data"),await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:i},passkeyCredential:r}),ye.log("SDK::PasskeyService::addNewPasskey::catch: finished storing data"),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:o.prfValue})}throw a}}catch(e){if(e instanceof M)throw e;throw this.authenticator.handlePasskeyError(e)}}async authenticate({deviceKeyPair:e,challengeResponse:t}){var r,s;try{if(!t.authenticationOptions)throw new M({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,o=Object.assign(Object.assign({},t.authenticationOptions),{extensions:Object.assign(Object.assign({},ad(a.extensions,["credProps"])),{prf:{eval:{first:n}}})}),i=await this.authenticator.authenticate({optionsJSON:o}),c=await this.handleCredentialsCreationFromPrfExtension(i),d=t.signature?t.signature:await this.getDeviceSignature({message:t.message,credentialsKeyPair:c,deviceKeyPair:e}),l=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:t.message,clientAuthPubKey:e.publicKey,signature:d,passkeyAuthenticationResponse:i}}),h=e.decryptedPrivateKey?e.decryptedPrivateKey:e.encryptedDevicePrivateKey?await this.cipher.decrypt({cipherText:e.encryptedDevicePrivateKey,decryptionKey:c.privateKey}):void 0;if(!h)throw new M({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:i}),Object.freeze(Object.assign(Object.assign({},l),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(e instanceof M)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 M({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 M({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});ye.log("SDK::PasskeyService::register:: got challenge",{registrationOptions:t.registrationOptions});const s=this.preparePasskeyCreationOptions(t.registrationOptions);ye.log("SDK::PasskeyService::register:: registering passkey",{parsedOptions:s});const a=await this.authenticator.register({optionsJSON:s});if(ye.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 M({message:"Device is not compatible with this feature. Try using a different authentication method.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});ye.log("SDK::PasskeyService::register:: getting signature",{message:t.message});const{signature:n,message:o}=await this.cipher.sign({message:t.message,signingKey:e.privateKey}),i=await this.request(Ca.signUp,{payload:{externalUserId:this.userId,message:o,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:i,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:d},passkeyCredential:a}),Object.freeze(Object.assign(Object.assign({},i),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(ye.log("SDK::PasskeyService::register::error",{error:e,errorCode:e.code,errorMessage:e.message}),e instanceof M)throw ye.log("SDK::PasskeyService::register::API error detected",{error:e}),e;if(e&&e.code===ie.error||e.code===ce.error||"The authenticator was previously registered."===e.message)throw ye.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 ye.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 o=e.clientExtensionResults;if(ye.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::extensions",o),!(null===(t=o.prf)||void 0===t?void 0:t.enabled)&&!(null===(s=null===(r=o.prf)||void 0===r?void 0:r.results)||void 0===s?void 0:s.first))throw new M({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(ye.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prf is enabled",o.prf.enabled),!(null===(a=o.prf.results)||void 0===a?void 0:a.first))throw new M({message:"PRF extension did not return any results. Cannot proceed with authentication.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});const i=null===(n=o.prf.results)||void 0===n?void 0:n.first;let c;if("string"==typeof i)c=id(i);else if(i instanceof Uint8Array)c=i;else if(i instanceof ArrayBuffer)c=new Uint8Array(i);else if(ArrayBuffer.isView(i))c=new Uint8Array(i.buffer);else if(Array.isArray(i))c=new Uint8Array(i);else{if(!i||"object"!=typeof i)throw new M({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});{const e=i.data;if(Array.isArray(e))c=new Uint8Array(e);else{const e=Object.values(i);if(!e.length||!e.every((e=>"number"==typeof e)))throw new M({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});c=new Uint8Array(e)}}}ye.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prfValue",c);const d=await this.cipher.getCredentialsKeyPair({prfValue:c,authType:exports.AuthType.Passkey});return ye.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::credentials key pair was created",!!d),Object.assign(Object.assign({},d),{prfValue:c})}catch(e){if(e instanceof M)throw e;if(e instanceof Error)throw new M({message:e.message,statusCode:400,errorCode:"sdk_passkey_prf_handling_failed",data:e,cause:e.cause});throw this.authenticator.handlePasskeyError(e)}}}function ld(e){return function(t,r,s){if(!s.value)return;const a=s.value;return s.value=async function(...s){var n,o,i,c,d;const l=this.lockManager,h=e||`${t.constructor.name}:${r}`,p=null!==(o=null===(n=this.options)||void 0===n?void 0:n.environment)&&void 0!==o?o:me,u=null!==(c=null===(i=this.options)||void 0===i?void 0:i.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 hd extends Qc{constructor(e,t={}){super(e,t),this.getUserSalt=this.getUserSalt.bind(this),this.passkeyService=new dd(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&&!Pa(e)||!!t}async refreshAuthTokens(){if(!await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken))throw new M({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 M({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 M({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){ye.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 ye.error("SDK::AuthService::getUserSalt::error",e),e}}async getSignature({deviceAuthKeys:e,walletId:t,passkeyChallengeType:r}){try{ye.debug("SDK::AuthService::getSignature::authType",this.deviceAuthType);const s=this.deviceAuthType===exports.AuthType.Passkey?null!=r?r:exports.PasskeyChallengeType.REGISTRATION:void 0;ye.debug("SDK::AuthService::getSignature::challengeType",s);const a=await this.request(Ca.signatureMessage,{payload:{walletId:t,clientAuthPubKey:e.publicKey,passkeyChallengeType:s}}),{signature:n,hashedMessage:o}=await this.cipher.sign({message:a.message,signingKey:e.privateKey});return Object.freeze(Object.assign(Object.assign({},a),{signature:n,hashedMessage:o}))}catch(e){throw ye.error("SDK::AuthService::getSignatureMessage::error",e),e}}async signUp(e){ye.info("starting signup");const t=Os();let r;ye.info("key pair generated",!!t);try{const s=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});switch(ye.info("signature has been generated",!!s),this.deviceAuthType){case exports.AuthType.Passkey:ye.info("registering a new passkey"),r=await this.passkeyService.register({deviceKeyPair:t,challengeResponse:s});break;case exports.AuthType.Password:ye.info("signing up with password"),r=await this.handleSignUpWithPassword({signatureMessage:s,deviceKeyPair:t,input:e});break;default:throw new M({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(ye.error("SDK::AuthService::signUp::error",e),e&&e.error===ce.error||e.code===ie.error){ye.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 M({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 ye.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 M({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 ye.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password, please try again."),new M({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(t){const e=ga(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 ye.error("SDK::AuthService::handleSignInWithPassword::error","Device key missing but wallet data exists"),new M({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});ye.info("No device data found, treating as a fresh device and creating a new key pair");n=Os().privateKey}if(!n)throw ye.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new M({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const o=ps(n);await this.storeDeviceKeyPair({deviceAuthKeyPair:{publicKey:o,privateKey:n},credentialsKeyPair:a});const i=await this.getSignature({deviceAuthKeys:{publicKey:o,privateKey:n}}),c=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:i.message,signature:i.signature,clientAuthPubKey:o}});return Object.assign(Object.assign({},c),{signatureMessageResponse:i,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){ye.debug("SDK::AuthService::handleSignInWithPasskey:: using existing key pair");const e=await this.request(Ca.signatureMessage,{payload:{clientAuthPubKey:a,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}});t=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:a,encryptedDevicePrivateKey:ga(s)},challengeResponse:e}),ye.debug("SDK::AuthService::handleSignInWithPasskey:: passkey authentication finished",!!t)}else{if(a||s)throw ye.error("SDK::AuthService::handleSignInWithPasskey::error","Passkey credential missing but device data exists"),new M({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=Os(),t=await this.passkeyService.addNewPasskey({deviceKeyPair:n,getSignature:this.getSignature.bind(this)}),ye.debug("SDK::AuthService::handleSignInWithPasskey:: passkey registration finished",t)}return Object.assign(Object.assign(Object.assign({},t),{prfValue:t.prfValue}),e)}catch(e){throw ye.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 M({message:"Password is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const s=await this.validatePasswordStrength(t.password);if(!s.valid)throw new M({message:s.message||"Invalid password",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const a=await this.request(Ca.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(ye.error("SDK::AuthService::getPasskeyCredentials::error",e),"string"==typeof e)throw new M({message:e,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});if(e&&"object"==typeof e&&"message"in e)throw new M({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(Ca.issueJwtToken);return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,e.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,e.refreshToken),e}catch(e){throw ye.error("SDK::Auth::exchangeClientToken::error",e),e}}}u([ld("signUp"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],hd.prototype,"signUp",null),u([ld("signIn"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],hd.prototype,"signIn",null),u([ld("storeDeviceKeyPair"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],hd.prototype,"storeDeviceKeyPair",null);class pd extends Qc{constructor(e,t={}){super(e,t),this.authService=new hd(e,t),this.userId=e.userId}async handleImportWallet(e,t){var r,s,a,n,o;try{const{signature:o,message:i,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((t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||t.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!t.keyShareOptions)throw new M({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 M({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:t.seedPhrase,encryptionKey:c}),p={reference:t.reference,walletId:t.walletId,message:i,signature:o,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(ed.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 M({message:null!==(o=e.message)&&void 0!==o?o:"Failed to handle importing the wallet",statusCode:e.statusCode,errorCode:e.errorCode,data:e.data,cause:e.cause})}}async handleWalletCreation(e,r){var s,a,n,o,i,c;try{const{signature:i,message:c,hashedMessage:d}=await this.authService.getSignature({deviceAuthKeys:{publicKey:e.publicKey,privateKey:e.privateKey},passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if((r.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||r.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!r.keyShareOptions)throw new M({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=r.keyShareOptions)&&void 0!==s?s:{};if(h&&l&&l<h)throw new M({message:"Number of shares must be greater than or equal to the threshold",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const p={reference:t.v4(),message:c,signature:i,hashedMessage:d,clientAuthPubKey:e.publicKey,returnWalletOption:r.returnWalletOption,numShares:l,threshold:h,wallabyKeepsOne:null!==(n=null===(a=r.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n,walletOwnershipType:null!==(o=r.walletOwnershipType)&&void 0!==o?o:exports.WalletOwnershipType.SingleOwner},u=await this.request(ed.createWithKeyShares,{payload:p});let y;const g=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:r.authenticationOptions.user.clientSalt,password:r.authenticationOptions.password,prfValue:r.authenticationOptions.prfValue});return u.encryptedSeed&&(y=await this.handleSeedPhraseFromResponse({walletId:u.wallet.id,encryptedSeed:u.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:r.storeSeedPhrase,credentialsKeyPair:g})),u.shares&&u.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:u.wallet.id,shares:u.shares,credentialsKeyPair:g,encryptedBackupShare:u.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign(Object.assign({},u),{standardSeedPhrase:y})}catch(e){throw ye.error("SDK::handleWalletCreation::error",e),new M({message:null!==(i=e.message)&&void 0!==i?i:"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 M({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 M({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}),o=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:o,walletId:e}]),[n,o]}catch(e){throw ye.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=ps(r),a=await this.cipher.encrypt({data:n,encryptionKey:t}),o=await this.cipher.encrypt({data:JSON.stringify(a),encryptionKey:s.publicKey});await this.localStorageService.save(exports.V2KeyNames.EncryptedStandardSeedPhrase,o,{walletId:e})}return n}catch(e){throw ye.error("SDK::handleSeedPhraseFromResponse::error",e),e}}async handleRecoverFromSeedPhrase({encryptedSeedPhrase:e,deviceAuthKeys:t}){var r;try{const r=await this.api.wallets.initiateWalletRecovery({externalUserId:this.userId,clientAuthPubKey:t.publicKey}),{signature:s,message:a}=await this.cipher.sign({message:r.signatureMessage,signingKey:t.privateKey});return await this.request(ed.recover,{payload:{externalUserId:this.userId,signature:s,message:a,clientAuthPubKey:t.publicKey,encryptedSeed:e}})}catch(e){throw ye.error("SDK::handleRecoverFromSeedPhrase::error",e),new M({message:null!==(r=e.message)&&void 0!==r?r:"Failed to recover wallet from seed phrase",statusCode:e.statusCode,errorCode:e.errorCode,data:e,cause:e.cause})}}}function ud(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 yd extends Qc{constructor(e,t={}){super(e,t),this.authService=new hd(e,t),this.handlers=new pd(e,t),this.userId=e.userId,this.passkeyService=new dd(e.userId,this.localStorageService,this.request,this.cipher)}async getRateState(e){const t=Date.now(),r=await this.localStorageService.fetch(e),s=r?ga(r):void 0;return!s||t-s.windowStart>yd.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>yd.RATE_LIMIT_MAX)throw new M({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 M({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 M({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const a=ps(s);return await this.handlers.handleWalletCreation({publicKey:a,privateKey:s},e)}catch(e){throw ye.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 M({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 o,i,c;if(!n)throw new M({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=ga(n),h=await this.cipher.decrypt({cipherText:l,decryptionKey:d.privateKey});if(!h)throw new M({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});if(r.keyShares){if(!a)throw new M({message:"You do not have any key shares stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const e=ga(a);o=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=ga(s);if(i=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(i),!c))throw new M({message:"Something went wrong decrypting algorand seed phrase.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed})}else{if(!a)throw new M({message:"You do not have a wallet stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const s=ga(a),n={publicKey:ps(h),privateKey:h},{signature:o,message:d,wallabyAuthPubKey:p}=await this.authService.getSignature({deviceAuthKeys:n,walletId:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),u=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:s,encryptedDevicePrivateKey:l,wallabyPublicKey:p||t.user.wallabyAuthPubKey,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),y=await this.request(ed.retrieveSeedPhrase,{payload:{walletId:e,signature:o,message:d,clientAuthPubKey:n.publicKey,recoveryPubKey:n.publicKey,encryptedShares:[u]}});i=await this.cipher.decrypt({cipherText:y.encryptedSeed,decryptionKey:h}),r.algorandSeedPhrase&&(c=this.getAlgorandSeedPhrase(i))}return{keyShares:r.keyShares&&o?o:void 0,standardSeedPhrase:r.standardSeedPhrase&&i?i:void 0,algorandSeedPhrase:r.algorandSeedPhrase&&c?c:void 0}}catch(e){throw ye.error("SDK::WalletService::export::error",e),e}}async import(e){var r;try{const s=null!==(r=e.reference)&&void 0!==r?r:t.v4(),a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new M({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=ga(a),o=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue}),i=await this.cipher.decrypt({cipherText:n,decryptionKey:o.privateKey});if(!i)throw new M({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ps(i);return await this.handlers.handleImportWallet({publicKey:c,privateKey:i},Object.assign(Object.assign({},e),{reference:s}))}catch(e){throw ye.error("SDK::WalletService::import::error",e),e}}async recover(e){try{const t=e.authenticationOptions.signatureMessageResponse.wallabyAuthPubKey||e.authenticationOptions.user.wallabyAuthPubKey,r=Os(),s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue});let a;if(e.seedPhrase){const n=await la(t,e.seedPhrase);return a=await this.handlers.handleRecoverFromSeedPhrase({encryptedSeedPhrase:n,deviceAuthKeys:{publicKey:r.publicKey,privateKey:r.privateKey}}),e.seedPhrase&&e.returnWalletOption!==exports.ReturnWalletOption.ReturnOnlyEncryptedShares&&await this.handlers.handleSeedPhraseFromResponse({walletId:a.wallet.id,encryptedSeed:la(r.publicKey,e.seedPhrase),devicePrivateKey:r.privateKey,credentialsKeyPair:s,storeSeedPhrase:!0}),a.shares&&a.encryptedBackupShare&&await this.handlers.handleKeySharesFromResponse({walletId:a.wallet.id,shares:a.shares,credentialsKeyPair:s,encryptedBackupShare:a.encryptedBackupShare,devicePrivateKey:r.privateKey}),await this.authService.storeDeviceKeyPair({deviceAuthKeyPair:r,credentialsKeyPair:s}),a}if(e.decryptedShares){if(!e.decryptedShares.length)throw new M({message:"Decrypted shares are required",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const{signature:n,message:o,wallabyAuthPubKey:i}=await this.authService.getSignature({deviceAuthKeys:r,walletId:e.walletId,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),c=i||e.authenticationOptions.user.wallabyAuthPubKey,d=await Promise.all(e.decryptedShares.map((async e=>await this.cipher.encrypt({data:e,encryptionKey:c})))),l=await this.request(ed.retrieveSeedPhrase,{payload:{walletId:e.walletId,signature:n,message:o,clientAuthPubKey:r.publicKey,recoveryPubKey:r.publicKey,encryptedShares:d}}),h=await this.cipher.flipEncryptedData({cipherText:l.encryptedSeed,decryptionKey:r.privateKey,encryptionKey:t});return a=await this.handlers.handleRecoverFromSeedPhrase({encryptedSeedPhrase:h,deviceAuthKeys:{publicKey:r.publicKey,privateKey:r.privateKey}}),a.encryptedSeed&&await this.handlers.handleSeedPhraseFromResponse({walletId:a.wallet.id,encryptedSeed:a.encryptedSeed,devicePrivateKey:r.privateKey,credentialsKeyPair:s,storeSeedPhrase:e.storeSeedPhrase}),a.shares&&a.encryptedBackupShare&&await this.handlers.handleKeySharesFromResponse({walletId:a.wallet.id,shares:a.shares,credentialsKeyPair:s,encryptedBackupShare:a.encryptedBackupShare,devicePrivateKey:r.privateKey}),await this.authService.storeDeviceKeyPair({deviceAuthKeyPair:r,credentialsKeyPair:s}),a}throw new M({message:"Decrypted seed phrase or shares are required to recover the wallet.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter})}catch(e){throw ye.error("SDK::Wallet::recover::error",e),e}}async changePassword({walletId:e,oldPassword:t,newPassword:r}){try{if(await this.recordRateAttempt(exports.V2KeyNames.PasswordResetAttempts)>yd.RATE_LIMIT_MAX)throw new M({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}),o=await this.localStorageService.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e});if(!s||"undefined"===s)throw new M({message:"Could not locate client keys on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=await this.authService.getUserSalt(),c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t,salt:i});if(!c.privateKey)throw new M({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:i});if(!d.publicKey||!d.privateKey)throw new M({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 M({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:ga(a),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,p=n?await this.cipher.flipEncryptedData({cipherText:ga(n),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,u=o?await this.cipher.flipEncryptedData({cipherText:ga(o),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 ye.error("SDK::Wallet::changePassword::error",e),e}}getAlgorandSeedPhrase(t){try{const r=d.mnemonicToSeedSync(t),s=function(t){if(32!==t.length)throw new Error(`Algorand seed must be 32 bytes, got ${t.length}`);const r=e.wordlists.english,s=ud(t).map((e=>r[e])),a=ud(wr(t).subarray(0,2))[0];return[...s,r[a]].join(" ")}(r.slice(0,32));return s}catch(e){throw ye.error("SDK::Wallet::getAlgorandSeedPhrase::error",e),new M({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 M({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=ga(a);this.deviceAuthType===exports.AuthType.Password&&e.authenticationOptions.password&&await this.migrateToV2Safe({password:e.authenticationOptions.password,walletId:e.walletId});const o=await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare,{walletId:t});if(!o)throw new M({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 i=ga(o),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 M({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});return{walletId:t,backupUrl:r,encryptedBackupShare:ga(await this.cipher.decrypt({cipherText:i,decryptionKey:c.privateKey}))}}async addNewDevice(e){var t;try{const r=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!r)throw new M({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 M({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:ps(a),o=await this.authService.getSignature({deviceAuthKeys:{privateKey:a,publicKey:n},walletId:e.walletId,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),i=await this.request(ed.addNewDevice,{payload:{walletId:e.walletId,clientAuthPubKey:n,signature:o.signature,message:o.message,wallabyAuthPubKey:o.wallabyAuthPubKey,encryptedBackupShare:e.encryptedBackupShare}});return await this.handlers.handleKeySharesFromResponse({walletId:e.walletId,shares:[i.share],credentialsKeyPair:s,encryptedBackupShare:e.encryptedBackupShare,devicePrivateKey:a}),{success:!0,reference:i.reference}}catch(e){throw ye.error("SDK::Wallet::backupKeyShare::error",e),e}}async generateWalletAddresses(e){const{walletId:t}=e;if(!t)throw new M({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(ed.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 ye.error("SDK::Wallet::generateWalletAddresses::error",e),e}}async migrateToV2Safe({password:e,walletId:t}){try{await this.handleUpdateToV2({password:e,walletId:t})}catch(e){throw ye.error("SDK::WalletService::migrateToV2Safe::error",e),new M({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 ye.error("SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material",e),new M({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 M({message:"Password is required for migration to v2",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const a=this.version,n=await this.localStorageService.fetch(exports.V2KeyNames.MigrationVersion),o=await this.localStorageService.fetch(exports.V2KeyNames.LastMigratedAt);if(ye.info("SDK::WalletService::handleUpdateToV2::starting migration check",{timestamp:new Date(r).toISOString(),walletId:t.substring(0,8)+"...",lastMigratedAt:o,currentSdkVersion:a,sdkMigrationVersion:n}),o&&"never"!==o&&n)return void ye.info("SDK::WalletService::handleUpdateToV2::Migration already completed successfully, skipping",{migratedVersion:n,migratedAt:o});const i=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(i&&(c||d))try{await this.cipher.decrypt({cipherText:ga(i),decryptionKey:h.privateKey});const t=c||d;return await this.cipher.displayStoredData({storedEncryptedData:ga(t),encryptedDevicePrivateKey:ga(i),options:{authType:exports.AuthType.Password,password:e,salt:l}}),ye.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,a)}catch(e){ye.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.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`),g=await this.localStorageService.getDecryptedV1PrivateKey(e);if(y&&g){this.assertValidDeviceKey(g),ye.info("SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration",{storageFormat:"legacy"});try{const t=ga(s.AES.decrypt(y,`${l}${e}`).toString(s.enc.Utf8));if(p=ha(g,t),u=g,!p)throw new M({message:"Failed to decrypt legacy seed phrase items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});ye.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted legacy items")}catch(e){throw ye.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt legacy items",e),new M({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)return ye.info("SDK::WalletService::handleUpdateToV2::No legacy or V1 items found to migrate"),void ye.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),ye.info("SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration",{storageFormat:"v1",validPrivateKey:!!u});try{if(ye.log("Attempting to decrypt V1 items during migration..."),ye.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 M({message:"Failed to decrypt V1 items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});ye.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted V1 items")}catch(e){throw ye.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt V1 items",e),new M({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}if(p&&u){ye.info("SDK::WalletService::handleUpdateToV2::Initiating wallet recovery for V2 migration"),ye.info("SDK::WalletService::handleUpdateToV2::Migration data prepared"),ye.info("SDK::WalletService::handleUpdateToV2::Seed phrase available:",!!p);const e=ps(u),s=await this.authService.getSignature({deviceAuthKeys:{publicKey:e,privateKey:u},walletId:t}),a=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:s.message,signature:s.signature,clientAuthPubKey:e}}),n=await this.cipher.encrypt({data:u,encryptionKey:h.publicKey}),o=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:o,walletId:t},{key:exports.V2KeyNames.EncryptedDevicePrivateKey,value:n}]),ye.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 M({message:"Decrypted data required for migration is missing, operation cannot be completed.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}catch(e){throw ye.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}),o=t&&!s;return await this.api.wallets.verifyAccess({message:a.message,signature:a.signature,clientAuthPubKey:n,encryptedSeed:o?t:void 0,encryptedShares:o?void 0:r,walletId:e.walletId})}catch(e){throw ye.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 M({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}),i=await this.cipher.decrypt({cipherText:JSON.parse(n),decryptionKey:o.privateKey});if(!i)throw new M({message:"Credentials are wrong, please pass the correct credentials.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ps(i),d=await this.authService.getSignature({deviceAuthKeys:{publicKey:c,privateKey:i},walletId:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),l=d.wallabyAuthPubKey||e.user.wallabyAuthPubKey,h=[];let p;const u=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(u){const e=ga(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 M({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 o=ga(e);p=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:o,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 r=!1;try{const s=await this.localStorageService.fetch(exports.V2KeyNames.CredentialConversionInProgress),a=s?ga(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&&ye.info("SDK::WalletService::convertToPasskey::resuming interrupted conversion");const n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),o=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:e.walletId}),i=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 ye.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password"),new M({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(n){ye.log("SDK::WalletService::convertToPasskey::Decrypting v2 device private key with password-derived key");const e=ga(n);h=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}else ye.log("SDK::WalletService::convertToPasskey::No encrypted device private key found, checking for v1 format"),h=await this.localStorageService.getDecryptedV1PrivateKey(e.password);if(!h)throw ye.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new M({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const p=ps(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)});r=!0;const y=u.prfValue;if(!(y&&y instanceof Uint8Array&&0!==y.length))throw ye.error("SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array"),new M({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 g,f,m;if(ye.log("SDK::WalletService::convertToPasskey::Received authentication response",!!u),o&&n)try{g=await this.cipher.displayStoredData({storedEncryptedData:ga(o),encryptedDevicePrivateKey:ga(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){ye.error("SDK::WalletService::convertToPasskey::seed_decryption_error",e)}if(!g)try{g=await this.localStorageService.getV1DecryptedSeedPhrase(e.password,d)}catch(e){ye.error("SDK::WalletService::convertToPasskey::v1_seed_decryption_error",e)}if(i&&n)try{const t=ga(i);f=await this.cipher.displayStoredData({storedEncryptedData:t,encryptedDevicePrivateKey:ga(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){ye.error("SDK::WalletService::convertToPasskey::primary_share_decryption_error",e)}if(c)try{const e=ga(c);m=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}catch(e){ye.error("SDK::WalletService::convertToPasskey::backup_share_decryption_error",e)}if(!g&&!(!!f||!!m))throw new M({message:"Seed phrase or key shares on this device could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});if(g&&!f)return ye.info("SDK::WalletService::convertToPasskey::No primary share found, importing wallet"),await this.handlers.handleImportWallet({publicKey:p,privateKey:h},{authenticationOptions:u,seedPhrase:g,storeSeedPhrase:!1,returnWalletOption:exports.ReturnWalletOption.ReturnOnlyEncryptedShares,walletId:e.walletId,reference:t.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}]),ye.info("SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed"),{authentication:u,seedPhrase:g};const w=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Passkey,prfValue:y}),v=[];if(f){const t=await this.cipher.doubleEncrypt({decryptedData:f,credentialsKeyPair:w,deviceKeyPair:{publicKey:p,privateKey:h}}),r=await this.cipher.decrypt({cipherText:t,decryptionKey:w.privateKey});if((r?await this.cipher.decrypt({cipherText:ga(r),decryptionKey:h}):null)!==f)throw new M({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(m){const t=await this.cipher.encrypt({data:m,encryptionKey:w.publicKey});v.push({key:exports.V2KeyNames.BackupDeviceKeyShare,value:t,walletId:e.walletId})}for(const e of v)await this.assertRoundTrip(e.value,w.privateKey,e.key);if(await this.localStorageService.commitBatch(v,[...o?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId}]:[],{key:exports.V2KeyNames.CredentialConversionInProgress}]),o&&ye.info("SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey"),!g&&f){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}),n=await this.cipher.encrypt({data:f,encryptionKey:a||u.user.wallabyAuthPubKey}),o=await this.request(ed.retrieveSeedPhrase,{payload:{walletId:e.walletId,signature:r,message:s,clientAuthPubKey:t.publicKey,recoveryPubKey:t.publicKey,encryptedShares:[n]}});g=await this.cipher.decrypt({cipherText:o.encryptedSeed,decryptionKey:h})}if(!g)throw new M({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:g}}catch(e){throw ye.error("SDK::WalletService::convertToPasskey::error",e),r||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 M({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})}}}yd.RATE_LIMIT_MAX=5,yd.RATE_LIMIT_WINDOW_MS=18e5,u([ld("create"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"create",null),u([ld("import"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"import",null),u([ld("recover"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"recover",null),u([ld("credential-rewrap"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"changePassword",null),u([ld("migrateToV2"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"handleUpdateToV2",null),u([ld("credential-rewrap"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"convertToPasskey",null);class gd extends Qc{constructor(e,t={}){super(e,t),this.userId=e.userId,this.walletService=new yd(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 M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.getTokenBalance,{payload:{address:e,assetSymbol:t,chainName:s,tokenStandard:r}})}catch(e){throw ye.error("SDK::WalletDataService::getTokenBalance::error",e),e}}async getMultiTokenBalances({walletId:e,tokensAndAddressesList:t}){try{if(!t.length)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.getMultiTokenBalances,{payload:{assets:t,walletId:e}})}catch(e){throw ye.error("SDK::WalletDataService::getMultiTokenBalances::error",e),e}}async getWalletBalances({walletId:e}){try{if(!e)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.getWalletBalances,{payload:{walletId:e}})}catch(e){throw ye.error("SDK::WalletDataService::getWalletBalances::error",e),e}}async getUserAssets({userId:e,queryOptions:t}){try{if(!e)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.getUserAssets,{payload:{userId:e},queryParams:t})}catch(e){throw ye.error("SDK::WalletDataService::getUserAssets::error",e),e}}async getUserWallets({userId:e,queryOptions:t}){try{return await this.request(ed.getUserWallets,{payload:{userId:e},queryParams:t})}catch(e){throw ye.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 M({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(ed.getWalletAssets,{payload:{walletId:e},queryParams:t})}catch(e){throw ye.error("SDK::WalletDataService::getWalletAssets::error",e),e}}async addTokenToWallet({assetConfigId:e,walletId:t,userId:r,config:s,authenticationOptions:a}){try{if(!t)throw new M({message:"Wallet ID is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!e&&!s)throw new M({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(ed.addTokenToWallet,{payload:Object.assign({assetConfigId:e,walletId:t,userId:r||void 0,config:s},n)})}catch(e){throw ye.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 M({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 M({message:`Wallet address is not present for blockchain: ${n}`,statusCode:400,errorCode:"sdk_wallet_address_not_found"})}catch(e){throw ye.error("SDK::WalletDataService::addNewChainAndTokenToWallet::error",e),e}}async updateAsset(e){var{configId:t,walletId:r}=e,s=p(e,["configId","walletId"]);try{if(!t||!r)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.updateAsset,{payload:Object.assign({configId:t,walletId:r},s)})}catch(e){throw ye.error("SDK::WalletDataService::updateAsset::error",e),e}}}class fd extends Qc{constructor(e,t={}){super(e,t),this.getDecryptedPrivateKey=async e=>{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return;const r=s.AES.decrypt(t,e).toString(s.enc.Utf8);return""!==r?r:void 0},this.decryptDevicePrivateKey=({encryptedPrivateKey:e,password:t})=>{const r=s.AES.decrypt(e,t).toString(s.enc.Utf8);return""!==r?r:void 0},this.auth=new hd(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 a=`${r}${e}`,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase);if(!n)throw new Error("Seed phrase could not be found");const o=ga(s.AES.decrypt(n,a).toString(s.enc.Utf8)),i=this.decryptDevicePrivateKey({encryptedPrivateKey:null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey))&&void 0!==t?t:"",password:e});if(!i)throw ye.error("SDK::Utils::decryptSeedPhrase::devicePrivateKey: Device private key could not be decrypted"),new Error("Device private key could not be decrypted");return await ha(i,o)}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 ye.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 ye.error("SDK::Utils::validatePassword::error",e),{valid:!1,message:"Password is incorrect."}}}}class md extends Qc{constructor(e,t={}){super(e,t)}}class wd extends Qc{constructor(e,t={}){super(e,t),this.authService=new hd(e,t),this.walletService=new yd(e,t)}async getQuote(e){try{const{walletId:t,fromAssetConfigId:r,toAssetConfigId:s,fromAmount:a,toAmount:n,slippage:o}=e;if(!t||!r||!s)throw new M({message:"Missing required parameters: walletId, fromAssetConfigId, and toAssetConfigId",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!a&&!n)throw new M({message:"Either fromAmount or toAmount must be provided",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(a&&n)throw new M({message:"Only one of fromAmount or toAmount may be provided, not both",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const i={walletId:t},c=Object.assign(Object.assign(Object.assign({fromAssetConfigId:r,toAssetConfigId:s},a&&{fromAmount:a}),n&&{toAmount:n}),null!=o&&{slippage:o});return await this.request(Object.assign(Object.assign({},sd.getQuote),{fullPath:sd.getQuote.fullPath(i)}),{payload:c})}catch(e){throw ye.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:o,hasShares:i}=await this.prepareSwapAuth(r,e);let c;if(n)c=await this.request(Object.assign(Object.assign({},sd.executeSwap),{fullPath:sd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedSeed:n}});else{if(!i)throw new M({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({},sd.executeSwap),{fullPath:sd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedShares:o}})}return c}catch(e){throw ye.error("SDK::Swap::executeSwap::error",e),e}}async getSwaps({walletId:e,queryParams:t}){try{if(!e)throw new M({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({},sd.getSwaps),{fullPath:sd.getSwaps.fullPath(r)}),{queryParams:t})}catch(e){throw ye.error("SDK::Swap::getSwaps::error",e),e}}async prepareSwapAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,o=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!o)throw new M({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:i}),d=await this.cipher.decrypt({cipherText:JSON.parse(o),decryptionKey:c.privateKey});if(!d)throw new M({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ps(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||e.user.wallabyAuthPubKey,u=[];let y;const g=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(g){const e=ga(g),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}});u.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new M({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=ga(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:u,hasShares:u.length>0})}}u([ld("executeSwap"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],wd.prototype,"executeSwap",null);class vd extends Qc{constructor(e,t={}){super(e,t)}async getSupportedBlockchains(e){try{return(await this.request(td.getSupportedBlockchains,{queryParams:void 0!==(null==e?void 0:e.supportSwaps)?{supportSwaps:e.supportSwaps}:void 0})).chains}catch(e){throw ye.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 M({message:`${e} does not support contract addresses.`,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});case exports.BlockchainName.Sui:if(r&&t)throw new M({message:"You can only provide either suiObjectId or contractAddress",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(t)throw new M({message:"You can only provide suiObjectId for SUI blockchain",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(!r)throw new M({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 M({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(td.fetchTokenInfo,{queryParams:Object.assign({chainName:e,tokenContractAddress:a},n?{assetSymbol:n}:{})})}catch(e){throw ye.error("SDK::Wallet::fetchTokenInfo::error",e),e}}async getSupportedTokens(e){try{const t={};if(void 0!==(null==e?void 0:e.supportsSwaps)&&(t.supportsSwaps=e.supportsSwaps),void 0!==(null==e?void 0:e.search)){if(e.search.length<3)throw new M({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});t.search=e.search}void 0!==(null==e?void 0:e.chainName)&&(t.chainName=e.chainName),void 0!==(null==e?void 0:e.contractAddress)&&(t.contractAddress=e.contractAddress);return(await this.request(td.getSupportedTokens,{queryParams:Object.keys(t).length>0?t:void 0})).assets}catch(e){throw ye.error("SDK::System::getSupportedTokens::error",e),e}}async getUserData(e){try{return(await this.request(td.getUserData,{payload:{userId:e}})).user}catch(e){throw ye.error("SDK::System::getUserData::error",e),e}}async getUserByExternalUserId(e){try{return(await this.request(td.getUserByExternalUserId,{payload:{externalUserId:e}})).user}catch(e){throw ye.error("SDK::System::getUserByExternalUserId::error",e),e}}}class Sd extends Qc{constructor(e,t={}){super(e,t),this.authService=new hd(e,t),this.walletService=new yd(e,t),this.userId=e.userId}async estimateFee({originAddress:e,recipientAddress:t,amount:r,transactionType:s,token:a}){try{return await this.request(rd.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 ye.error("SDK::Transactions::estimateFee::error",e),e}}async getTransactionStatus({transactionHash:e,reference:t,blockchain:r}){try{return await this.request(rd.getTransaction,{payload:{transactionHash:e,transactionReference:t,chain:r.toString().toUpperCase()}})}catch(e){throw ye.error("SDK::Transactions::getTransactionStatus::error",e),e}}async getTransactions(e){try{return await this.request(rd.getTransactions,{queryParams:e})}catch(e){throw ye.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 M({message:"Either assetId or both contractAddress and blockchainName must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(rd.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 ye.error("SDK::Transactions::getRestriction::error",e),e}}async transfer({originAddress:e,recipientAddress:r,amount:s,assetId:a,walletId:n,reference:o,authenticationOptions:i,memo:c,transactionType:d}){try{this.deviceAuthType===exports.AuthType.Password&&i.password&&await this.walletService.migrateToV2Safe({password:i.password,walletId:n});const{deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:p,sharesEncryptedWithWallabyPubKey:u,hasShares:y}=await this.prepareTransactionAuth(i,n);let g;if(p)g=await this.request(rd.transfer,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedSeed:p,originAddress:e,recipientAddress:r,assetId:a,amount:s,reference:o||t.v4(),memo:c,transactionType:d}});else{if(!y)throw new M({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});g=await this.request(rd.transferWithShares,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedShares:u,originAddress:e,recipientAddress:r,assetId:a,amount:s,reference:o||t.v4(),memo:c,transactionType:d}})}return g}catch(e){throw ye.error("SDK::Transactions::transfer::error",e),e}}async createAllowance({authenticationOptions:e,walletId:t,ownerAddress:r,spenderAddress:s,amount:a,assetId:n,suiObjectId:o,contractAddress:i,chainName:c,assetSymbol:d,reference:l,memo:h,transactionType:p}){try{if(!(o||i||n||d||c))throw new M({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 M({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:g,sharesEncryptedWithWallabyPubKey:f,hasShares:m}=await this.prepareTransactionAuth(e,t),{message:w,signature:v}=y;if(!g&&!m)throw new Error("No valid seed option found on this device.");const S=Object.assign({message:w,signature:v,walletId:t,clientAuthPubKey:u,ownerAddress:r,spenderAddress:s,chainName:c,assetSymbol:d,amount:a,assetId:n,contractAddress:null!=i?i:o,reference:l,memo:h,transactionType:p},m?{encryptedShares:f}:{encryptedSeed:g});return await this.request(rd.createAllowance,{payload:S})}catch(e){throw ye.error("SDK::Transactions::createAllowance::error",e),e}}async getPendingTransactions({walletId:e,chainName:t}){try{return await this.request(rd.getPendingTransactions,{queryParams:{walletId:e,chainName:t}})}catch(e){throw ye.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:o,signatureMessage:i,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(rd.confirmPendingTransaction,{payload:{message:i.message,signature:i.signature,clientAuthPubKey:o,encryptedShares:d,encryptedSeed:c,id:e,choice:t,symbol:r,chainName:s,walletId:a}})}catch(e){throw ye.error("SDK::Transactions::transfer::error",e),e}}async prepareTransactionAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,o=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!o)throw new M({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:i}),d=await this.cipher.decrypt({cipherText:JSON.parse(o),decryptionKey:c.privateKey});if(!d)throw new M({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ps(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||e.user.wallabyAuthPubKey,u=[];let y;const g=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(g){const e=ga(g),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}});u.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new M({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=ga(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:u,hasShares:u.length>0})}}u([ld("transaction-restriction-message"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],Sd.prototype,"getRestriction",null),u([ld("transfer"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],Sd.prototype,"transfer",null),u([ld("createAllowance"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],Sd.prototype,"createAllowance",null),u([ld("confirmPendingTransaction"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],Sd.prototype,"resolvePendingTransaction",null);exports.AndroidVersionNotSupportedError=F,exports.AuthenticatorGeneralError=ae,exports.AuthenticatorMissingDiscoverableCredentialSupportError=ne,exports.AuthenticatorMissingUserVerificationSupportError=oe,exports.AuthenticatorNoSupportedPubKeyCredParamsAlgError=de,exports.AuthenticatorNotRegisteredError={error:"ERROR_AUTHENTICATOR_NOT_REGISTERED",message:"Authenticator is not registered."},exports.AuthenticatorPreviouslyRegisteredError=ie,exports.AutoRegisterUserVerificationFailureError=le,exports.BadConfiguration=Y,exports.CeremonyAbortedError=Q,exports.IOSVersionNotSupportedError=V,exports.InterruptedError=Z,exports.InvalidChallengeError=$,exports.InvalidDomainError=ee,exports.InvalidRpIdError=te,exports.InvalidStateError=ce,exports.InvalidUserIdError=J,exports.InvalidUserIdLengthError=re,exports.MalformedPubKeyCredParamsError=se,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=pe,exports.PassthroughSeeCausePropertyError=he,exports.RequestFailedError=G,exports.TimeoutError=X,exports.UnknownError=W,exports.UserCancelledError=H,exports.Wallaby=class{constructor(e,t={}){this.wallet=new yd(e,t),this.walletData=new gd(e,t),this.utils=new fd(e,t),this.auth=new hd(e,t),this.system=new vd(e,t),this.transactions=new Sd(e,t),this.swap=new wd(e,t),this.httpApi=new md(e,t)}get version(){return be}},exports.WallabyApiClient=Na,exports.WallabyError=M,exports.WallabyHttpClient=Ra,exports.createIdentity=Os,exports.decryptWithPrivateKey=ha,exports.encryptWithPublicKey=la,exports.hash=ya,exports.keccak256=pa,exports.publicKeyByPrivateKey=ps,exports.recoverPublicKey=(e,t)=>{const r=Rt(e),s=r.substring(0,r.length-2),a="1c"===r.slice(-2)?1:0;let n=Le(ua(Kt(s),a,Kt(Rt(t)),!1));return n=n.slice(2),n},exports.sign=Ks;//# sourceMappingURL=index.cjs.js.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 Ds(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ls(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const qs=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Us(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(Ns(r),!qs)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?Ns(t):Ns(t,e.nonceLength)}const a=e.tagLength;a&&void 0!==s[1]&&Ns(s[1]);const n=t(r,...s),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Ns(t)}};let i=!1;const c={encrypt(e,t){if(i)throw new Error("cannot encrypt() twice with same key + nonce");return i=!0,Ns(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(Ns(e),a&&e.length<a)throw new Error("invalid ciphertext length: smaller than tagLength="+a);return o(n.decrypt.length,t),n.decrypt(e,t)}};return c}return Object.assign(r,e),r};function Bs(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&&!Ms(t))throw new Error("invalid output, must be aligned");return t}function Ms(e){return e.byteOffset%4==0}function Ws(e){return Uint8Array.from(e)}const Vs=16;function Fs(e){return e<<1^283&-(e>>7)}function Gs(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Fs(e);return r}const Hs=(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Fs(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 Ls(e),t})(),$s=Hs.map(((e,t)=>Hs.indexOf(t))),Js=e=>e<<8|e>>>24;function Ys(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(Js),a=s.map(Js),n=a.map(Js),o=new Uint32Array(65536),i=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;o[l]=r[t]^s[d],i[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:o,T23:i}}const zs=Ys(Hs,(e=>Gs(e,3)<<24|e<<16|e<<8|Gs(e,2))),Zs=Ys($s,(e=>Gs(e,11)<<24|Gs(e,13)<<16|Gs(e,9)<<8|Gs(e,14))),Xs=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Fs(r))e[t]=r;return e})();function Qs(e){Ns(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}=zs,s=[];Ms(e)||s.push(e=Ws(e));const a=Ds(e),n=a.length,o=e=>ta(r,e,e,e,e),i=new Uint32Array(t+28);i.set(a);for(let e=n;e<i.length;e++){let t=i[e-1];e%n==0?t=o((c=t)<<24|c>>>8)^Xs[e/n-1]:n>6&&e%n==4&&(t=o(t)),i[e]=i[e-n]^t}var c;return Ls(...s),i}function ea(e,t,r,s,a,n){return e[r<<8&65280|s>>>8&255]^t[a>>>8&65280|n>>>24&255]}function ta(e,t,r,s,a){return e[255&t|65280&r]|e[s>>>16&255|a>>>16&65280]<<16}function ra(e,t,r,s,a){const{sbox2:n,T01:o,T23:i}=zs;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++]^ea(o,i,t,r,s,a),d=e[c++]^ea(o,i,r,s,a,t),l=e[c++]^ea(o,i,s,a,t,r),h=e[c++]^ea(o,i,a,t,r,s);t=n,r=d,s=l,a=h}return{s0:e[c++]^ta(n,t,r,s,a),s1:e[c++]^ta(n,r,s,a,t),s2:e[c++]^ta(n,s,a,t,r),s3:e[c++]^ta(n,a,t,r,s)}}function sa(e,t,r,s,a){const{sbox2:n,T01:o,T23:i}=Zs;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++]^ea(o,i,t,a,s,r),d=e[c++]^ea(o,i,r,t,a,s),l=e[c++]^ea(o,i,s,r,t,a),h=e[c++]^ea(o,i,a,s,r,t);t=n,r=d,s=l,a=h}return{s0:e[c++]^ta(n,t,a,s,r),s1:e[c++]^ta(n,r,t,a,s),s2:e[c++]^ta(n,s,r,t,a),s3:e[c++]^ta(n,a,s,r,t)}}function aa(e,t,r,s){Ns(t,Vs),Ns(r);const a=r.length;Us(r,s=Bs(a,s));const n=t,o=Ds(n);let{s0:i,s1:c,s2:d,s3:l}=ra(e,o[0],o[1],o[2],o[3]);const h=Ds(r),p=Ds(s);for(let t=0;t+4<=h.length;t+=4){p[t+0]=h[t+0]^i,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:i,s1:c,s2:d,s3:l}=ra(e,o[0],o[1],o[2],o[3]))}const u=Vs*Math.floor(h.length/4);if(u<a){const e=new Uint32Array([i,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];Ls(e)}var y;return s}const na=js({blockSize:16,nonceLength:16},(function(e,t){function r(r,s){if(Ns(r),void 0!==s&&(Ns(s),!Ms(s)))throw new Error("unaligned destination");const a=Qs(e),n=Ws(t),o=[a,n];Ms(r)||o.push(r=Ws(r));const i=aa(a,n,r,s);return Ls(...o),i}return{encrypt:(e,t)=>r(e,t),decrypt:(e,t)=>r(e,t)}}));const oa=js({blockSize:16,nonceLength:16},(function(e,t,r={}){const s=!r.disablePadding;return{encrypt(r,a){const n=Qs(e),{b:o,o:i,out:c}=function(e,t,r){Ns(e);let s=e.length;const a=s%Vs;if(!t&&0!==a)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Ms(e)||(e=Ws(e));const n=Ds(e);if(t){let e=Vs-a;e||(e=Vs),s+=e}return Us(e,r=Bs(s,r)),{b:n,o:Ds(r),out:r}}(r,s,a);let d=t;const l=[n];Ms(d)||l.push(d=Ws(d));const h=Ds(d);let p=h[0],u=h[1],y=h[2],g=h[3],f=0;for(;f+4<=o.length;)p^=o[f+0],u^=o[f+1],y^=o[f+2],g^=o[f+3],({s0:p,s1:u,s2:y,s3:g}=ra(n,p,u,y,g)),i[f++]=p,i[f++]=u,i[f++]=y,i[f++]=g;if(s){const e=function(e){const t=new Uint8Array(16),r=Ds(t);t.set(e);const s=Vs-e.length;for(let e=Vs-s;e<Vs;e++)t[e]=s;return r}(r.subarray(4*f));p^=e[0],u^=e[1],y^=e[2],g^=e[3],({s0:p,s1:u,s2:y,s3:g}=ra(n,p,u,y,g)),i[f++]=p,i[f++]=u,i[f++]=y,i[f++]=g}return Ls(...l),c},decrypt(r,a){!function(e){if(Ns(e),e.length%Vs!=0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size 16")}(r);const n=function(e){const t=Qs(e),r=t.slice(),s=t.length,{sbox2:a}=zs,{T0:n,T1:o,T2:i,T3:c}=Zs;for(let e=0;e<s;e+=4)for(let a=0;a<4;a++)r[e+a]=t[s-e-4+a];Ls(t);for(let e=4;e<s-4;e++){const t=r[e],s=ta(a,t,t,t,t);r[e]=n[255&s]^o[s>>>8&255]^i[s>>>16&255]^c[s>>>24]}return r}(e);let o=t;const i=[n];Ms(o)||i.push(o=Ws(o));const c=Ds(o);a=Bs(r.length,a),Ms(r)||i.push(r=Ws(r)),Us(r,a);const d=Ds(r),l=Ds(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:o,s1:i,s2:c,s3:g}=sa(n,h,p,u,y);l[e++]=o^t,l[e++]=i^r,l[e++]=c^s,l[e++]=g^a}return Ls(...i),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 ia(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 oa(e,t,{disablePadding:!s});if(["aes-128-ctr","aes-256-ctr"].includes(r))return na(e,t);throw new Error("AES: unsupported mode")}const ca=(e,t,r)=>{const s=(null==r?void 0:r.ephemPrivateKey)?Kt(r.ephemPrivateKey):ze(32),a=ze(16),n=hs.getPublicKey(s),o=hs.ProjectivePoint.fromHex(n).toRawBytes(!1),i=hs.getSharedSecret(s,Kt(e),!0).slice(1),c=Rs(i),d=c.subarray(0,32),l=c.subarray(32),h=function(e,t,r,s="aes-128-ctr",a=!0){return ia(t,r,s,a).encrypt(e)}(qt(t),d,a,"aes-256-cbc"),p=Lt([a,o,h]),u=xs(l,p);return{iv:Le(a),ephemPublicKey:Le(o),ciphertext:Le(h),mac:Le(u)}},da=(e,t)=>{let r;try{r=hs.getSharedSecret(Kt(e),t.ephemPublicKey,!0).slice(1)}catch(e){throw new Error(`Invalid MAC: data integrity check failed: ${e}`)}const s=Rs(r),a=s.subarray(0,32),n=s.subarray(32),o=Kt(t.ciphertext),i=Kt(t.iv),c=Kt(t.ephemPublicKey),d=Kt(t.mac),l=Lt([i,c,o]);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}(xs(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 ia(t,r,s,a).decrypt(e)}(o,a,i,"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 la=(e,t,r)=>{const s=Dt(e);return ca("04"+s,t,r)},ha=(e,t)=>{const r=Rt(e);return da(r,t)},pa=e=>(e=>{const t=qt(e),r=Nt(Le(t)),s=Cs(Kt(r));return Nt(Le(s))})(e);function ua(e,t,r,s=!0,a){Ot(r,32),tt("compressed",s);const n=function(e){return Ot(e,64),hs.Signature.fromCompact(e)}(e);return function(e=e=>new Uint8Array(e),t,r){return"function"==typeof e&&(e=e(t)),Ot(e,t),r&&e.set(r),e}(a,s?33:65,n.addRecoveryBit(t).recoverPublicKey(r).toRawBytes(s))}hs.ProjectivePoint,hs.CURVE.n;const ya={keccak256:pa};function ga(e){if(!fa(e))throw new Error("Invalid JSON string");return JSON.parse(e)}function fa(e){if("string"!=typeof e)return!1;try{return JSON.parse(e),!0}catch(e){return!1}}function ma(e,t,r,s){Ie(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:o,asyncTick:i}=a;if(Te(n),Te(o),Te(i),n<1)throw new Error("iterations (c) should be >= 1");const c=He(t),d=He(r),l=new Uint8Array(o),h=Sr.create(e,c),p=h._cloneInto().update(d);return{c:n,dkLen:o,asyncTick:i,DK:l,PRF:h,PRFSalt:p}}function wa(e,t,r,s){const{c:a,dkLen:n,DK:o,PRF:i,PRFSalt:c}=ma(e,t,r,s);let d;const l=new Uint8Array(4),h=Ke(l),p=new Uint8Array(i.outputLen);for(let e=1,t=0;t<n;e++,t+=i.outputLen){const r=o.subarray(t,t+i.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++){i._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}(i,c,o,d,p)}const va="wsdkmk:v1:";function Sa(e){if(Fe(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 Aa({password:e,salt:t}){Sa(t);const r=function(e,t,r,s,a){if(!["sha256","sha512"].includes(a))throw new Error("Only sha256 and sha512 are supported");return Ot(e),Ot(t),wa(fr,e,t,{c:r,dkLen:s})}(Fe(e.normalize("NFKC").trim()),Fe(t),131072,32,"sha256");return Os(r)}function ba(e,t){return va+function(e,t){return s.AES.encrypt(e,t).toString()}("string"==typeof e?e:JSON.stringify(e),t)}function Ea(e,t){const r=function(e,t){return s.AES.decrypt(e,t).toString(s.enc.Utf8)}(e.startsWith(va)?e.slice(10):e,t);if(r)return fa(r)?ga(r):r}class _a{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(!hs.utils.isValidPrivateKey(e.slice(2)))throw new Error("Invalid private key: outside secp256k1 scalar range")}(e)}getMasterKey(){return{buffer:Fe(ve),key:ve}}encryptWithMasterKey({data:e}){return ba(e,this.getMasterKey().key)}isWrappedByMasterKey(e){return function(e){return e.startsWith(va)||e.startsWith("U2FsdGVkX1")}(e)}decryptWithMasterKey({cipherText:e}){try{const t=Ea(e,this.getMasterKey().key);if(void 0!==t)return t}catch(e){return void ye.error("Decryption failed with master key",e)}ye.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){Sa(e)}sign({message:e,signingKey:t}){try{this.validatePrivateKey(t);const r=pa(e);return{message:e,signature:Ks(t,r),hashedMessage:r}}catch(e){throw ye.error("SDK::Cipher::sign",e),new Error(`Error signing message: ${e}`)}}async encrypt({data:e,encryptionKey:t}){try{return this.validatePublicKey(t),await la(t,e)}catch(e){throw ye.error("Error encrypting data: ",e),new Error("Something happened during data encryption.")}}async decrypt({cipherText:e,decryptionKey:t}){try{this.validatePrivateKey(t);return await ha(t,(r=e,"string"==typeof r?JSON.parse(r):r))}catch(e){throw ye.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 ye.error("SDK::CipherService::getCredentialsKeyPair::error",e),Promise.reject(e)}}async prepareDataForTransport({data:e,wallabyPublicKey:t}){try{return la(t,e)}catch(e){throw ye.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 ye.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 ye.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 ye.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 o=await this.decrypt({cipherText:JSON.parse(n),decryptionKey:a});if(!o)throw new Error("That doesn’t seem right. Check your login details and try again.");return o}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 ye.error("SDK::CipherService::displayDataFromServer::error",e),e}}async deriveKeyPairFromPasskey({inputKeyMaterial:e}){return function({inputKeyMaterial:e}){return Os(e)}({inputKeyMaterial:e})}async deriveKeyPairFromPassword({password:e,salt:t}){return Aa({password:e,salt:t})}}class Ta{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:me,this.shortenedEnv=this.environment.slice(0,1),this.deviceLocalStorage=e,this.cipher=new _a}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=>{ye.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}`;Ae.isNative&&(s=Ee(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 ye.error(`Failed to decrypt item with key ${s}`)}return a}ye.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(Ae.isNative&&(s=Ee(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 Se?r:Ee(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=ga(t)}catch(t){return ye.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 Ae.isNative&&(r=Ee(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=s.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}ye.error("SDK::StorageService::getEncryptedPrivateKey: private key not found")}async getDecryptedV1PrivateKey(e){try{const t=await this.getV1EncryptedPrivateKey();if(!t)return;const r=s.AES.decrypt(t,e).toString(s.enc.Utf8);return r||void 0}catch(e){return void ye.error("SDK::StorageService::getDecryptedV1PrivateKey::error",e)}}async getDecryptedPrivateKey(e){try{const t=await this.getEncryptedPrivateKey();if(!t)return;const r=s.AES.decrypt(t,e).toString(s.enc.Utf8);return r||void 0}catch(e){return void ye.error("SDK::StorageService::getDecryptedPrivateKey::error",e)}}async setEncryptedSeedPhrase({decryptedSeedPhrase:e,seedPhraseType:t,password:r,deviceAuthPublicKey:a,getUserSalt:n,salt:o,walletId:i}){const c=await la(a,e),d=null!=o?o: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 s.AES.encrypt(JSON.stringify(c),l),p=this.getSeedPhraseV2KeyName(t);return await this.save(p,h.toString(),{walletId:i}),!0}async getEncryptedSeedPhrase(e,t){const r=this.getSeedPhraseV2KeyName(e),s=await this.fetch(r,{walletId:t});if(s)return s;let a;if(e===exports.SeedPhraseType.Standard&&(a=`encryptedSeed_${this.userId}`),a){const e=await this.getItem(a);if(e)return e}if(!s){const t=`${this.environment}-encrypted-${e}-seedPhrase-${this.userId}`,r=await this.getItem(t);if(r)return r}}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(),a=await this.getDecryptedV1PrivateKey(e);if(!r||!a)return;const n=`${t}${e}`,o=ga(s.AES.decrypt(r,n).toString(s.enc.Utf8));return await ha(a,o)}async getDecryptedSeedPhrase({password:e,seedPhraseType:t,getUserSalt:r,salt:a,walletId:n}){const o=await this.getEncryptedSeedPhrase(t,n),i=await this.getDecryptedPrivateKey(e);if(!o||!i)return;const c=`${null!=a?a:await r()}${e}`,d=ga(s.AES.decrypt(o,c).toString(s.enc.Utf8));return await ha(i,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))))}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 Pa(e,t=Date.now){return!e||ka(e,t)<=0}function Ia(e,t,r=Date.now){return!!e&&ka(e,r)<=1e3*t}function ka(e,t=Date.now){const r=a.jwtDecode(e).exp;return 1e3*(null!=r?r:0)-t()}const Ca={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 Oa(e){return/^[a-zA-Z0-9-_]+$/.test(e)}function Ka(e){const{apiKey:t,baseUrl:r,userId:s,clientAuthToken:n,options:o}=e;if("string"!=typeof t||!Oa(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||!Oa(s))throw new Error("Invalid or empty user ID provided.");if("string"!=typeof n||!function(e){if("string"!=typeof e)return!1;if(3!==e.split(".").length)return!1;try{return a.jwtDecode(e),!0}catch(e){return!1}}(n))throw new Error("Invalid or empty client auth token provided.");if(o&&"object"!=typeof o)throw new Error("Invalid options provided.");return Object.freeze({apiKey:t.trim(),baseUrl:r.trim(),userId:s.trim(),clientAuthToken:n.trim(),options:o?Object.freeze(Object.assign({},o)):void 0})}var xa;!function(e){e.Json="application/json",e.JsonApi="application/vnd.api+json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"}(xa||(xa={}));class Ra{constructor(e={}){this.baseUrl="https://dev-testnet.wallaby.cash",this.securityData=null,this.abortControllers=new Map,this.customFetch=(...e)=>fetch(...e),this.baseApiParams={credentials:"same-origin",headers:{},redirect:"follow",referrerPolicy:"no-referrer"},this.setSecurityData=e=>{this.securityData=e},this.contentFormatters={[xa.Json]:e=>null===e||"object"!=typeof e&&"string"!=typeof e?e:JSON.stringify(e),[xa.JsonApi]:e=>null===e||"object"!=typeof e&&"string"!=typeof e?e:JSON.stringify(e),[xa.Text]:e=>null!==e&&"string"!=typeof e?JSON.stringify(e):e,[xa.FormData]:e=>e instanceof FormData?e:Object.keys(e||{}).reduce(((t,r)=>{const s=e[r];return t.append(r,s instanceof Blob?s:"object"==typeof s&&null!==s?JSON.stringify(s):`${s}`),t}),new FormData),[xa.UrlEncoded]:e=>this.toQueryString(e)},this.createAbortSignal=e=>{if(this.abortControllers.has(e)){const t=this.abortControllers.get(e);return t?t.signal:void 0}const t=new AbortController;return this.abortControllers.set(e,t),t.signal},this.abortRequest=e=>{const t=this.abortControllers.get(e);t&&(t.abort(),this.abortControllers.delete(e))},this.request=async e=>{var{body:t,secure:r,path:s,type:a,query:n,format:o,baseUrl:i,cancelToken:c}=e,d=p(e,["body","secure","path","type","query","format","baseUrl","cancelToken"]);const l=("boolean"==typeof r?r:this.baseApiParams.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},h=this.mergeRequestParams(d,l),u=n&&this.toQueryString(n),y=this.contentFormatters[a||xa.Json],g=o||h.format;return this.customFetch(`${i||this.baseUrl||""}${s}${u?`?${u}`:""}`,Object.assign(Object.assign({},h),{headers:Object.assign(Object.assign({},h.headers||{}),a&&a!==xa.FormData?{"Content-Type":a}:{}),signal:(c?this.createAbortSignal(c):h.signal)||null,body:null==t?null:y(t)})).then((async e=>{const t=e;t.data=null,t.error=null;const r=g?await e[g]().then((e=>(t.ok?t.data=e:t.error=e,t))).catch((e=>(t.error=e,t))):t;if(c&&this.abortControllers.delete(c),!e.ok)throw r;return r.data}))},Object.assign(this,e)}encodeQueryParam(e,t){return`${encodeURIComponent(e)}=${encodeURIComponent("number"==typeof t?t:`${t}`)}`}addQueryParam(e,t){return this.encodeQueryParam(t,e[t])}addArrayQueryParam(e,t){return e[t].map((e=>this.encodeQueryParam(t,e))).join("&")}toQueryString(e){const t=e||{};return Object.keys(t).filter((e=>void 0!==t[e])).map((e=>Array.isArray(t[e])?this.addArrayQueryParam(t,e):this.addQueryParam(t,e))).join("&")}addQueryParams(e){const t=this.toQueryString(e);return t?`?${t}`:""}mergeRequestParams(e,t){return Object.assign(Object.assign(Object.assign(Object.assign({},this.baseApiParams),e),t||{}),{headers:Object.assign(Object.assign(Object.assign({},this.baseApiParams.headers||{}),e.headers||{}),t&&t.headers||{})})}}class Na{constructor(e){this.health={getHello:(e={})=>this.http.request(Object.assign({path:"/",method:"GET",secure:!0},e)),getHealthCheck:(e={})=>this.http.request(Object.assign({path:"/healthz",method:"GET",secure:!0},e))},this.auth={generateExternalSignatureMessage:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/signature-message/external",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),generateSignatureMessage:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/signature-message",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),signUp:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/sign-up",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),signUpExternal:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/sign-up/external",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),signIn:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/sign-in",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),issueJwtToken:(e={})=>this.http.request(Object.assign({path:"/api/v1/auth/issue-jwt-token",method:"POST",secure:!0,format:"json"},e)),refreshAccessToken:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/refresh-access-token",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),logout:(e={})=>this.http.request(Object.assign({path:"/api/v1/auth/logout",method:"POST",secure:!0,format:"json"},e)),changeAuthPublicKey:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/client-auth-pubkey",method:"PUT",body:e,secure:!0,type:xa.Json,format:"json"},t)),getWallabyAuthPubKey:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/auth/wallaby-auth-pubkey",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getPasskeyCredentials:(e={})=>this.http.request(Object.assign({path:"/api/v1/auth/passkey-credentials",method:"GET",secure:!0,format:"json"},e))},this.chains={getAllChains:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/chains",method:"GET",query:e,secure:!0,format:"json"},t)),createChain:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/chains",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),updateChain:(e,t,r)=>{var{chainId:s}=e;return p(e,["chainId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/chains/${s}`,method:"PUT",body:t,secure:!0,type:xa.Json,format:"json"},r))}},this.assets={getAssetsConfigurations:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/assets/configurations",method:"GET",query:e,secure:!0,format:"json"},t)),createAssetConfig:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/assets/configurations",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getAssetConfigById:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}`,method:"GET",secure:!0,format:"json"},t))},updateAssetConfig:(e,t,r)=>{var{assetConfigId:s}=e;return p(e,["assetConfigId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${s}`,method:"PUT",body:t,secure:!0,type:xa.Json,format:"json"},r))},verifyAsset:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}/verify`,method:"POST",secure:!0,format:"json"},t))},unverifyAsset:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}/unverify`,method:"DELETE",secure:!0,format:"json"},t))},archiveAsset:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}/archive`,method:"POST",secure:!0,format:"json"},t))},unarchiveAsset:(e,t)=>{var{assetConfigId:r}=e;return p(e,["assetConfigId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/assets/configurations/${r}/unarchive`,method:"POST",secure:!0,format:"json"},t))}},this.merchants={getAllMerchants:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants",method:"GET",query:e,secure:!0,format:"json"},t)),createMerchant:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),updateMerchant:(e,t,r)=>{var{merchantId:s}=e;return p(e,["merchantId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/merchants/${s}`,method:"PUT",body:t,secure:!0,type:xa.Json,format:"json"},r))},getOneMerchant:(e,t)=>{var{merchantId:r}=e;return p(e,["merchantId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}`,method:"GET",secure:!0,format:"json"},t))},getMerchantAssets:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/assets`,method:"GET",query:s,secure:!0,format:"json"},t))},getMerchantUsers:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/users`,method:"GET",query:s,secure:!0,format:"json"},t))},getMerchantAdmins:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/admins`,method:"GET",query:s,secure:!0,format:"json"},t))},inviteMerchantAdmins:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/admins/invite",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),revokeMerchantAdmins:(e,t)=>{var{merchantId:r,userId:s}=e;return p(e,["merchantId","userId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/admins/${s}`,method:"DELETE",secure:!0,format:"json"},t))},getMerchantWallets:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/wallets`,method:"GET",query:s,secure:!0,format:"json"},t))},addMerchantWalletAssets:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/wallets/add-assets",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),addNewAsset:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/assets/add",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),removeAsset:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/assets/delete",method:"DELETE",body:e,secure:!0,type:xa.Json,format:"json"},t)),showMerchantAssetToWalletHolders:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/assets/update-visibility",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),changeMerchantAssetDefaultStatus:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/merchants/assets/update-default-status",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getMerchantApiKeys:(e,t)=>{var{merchantId:r}=e,s=p(e,["merchantId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/api-keys`,method:"GET",query:s,secure:!0,format:"json"},t))},createApiKey:(e,t,r)=>{var{merchantId:s}=e;return p(e,["merchantId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/merchants/${s}/api-keys`,method:"POST",body:t,secure:!0,type:xa.Json,format:"json"},r))},getMerchantApiKeyOrigins:(e,t)=>{var{merchantId:r,apiKeyId:s}=e,a=p(e,["merchantId","apiKeyId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/merchants/${r}/api-keys/${s}/origins`,method:"GET",query:a,secure:!0,format:"json"},t))},whitelistApiKeyOrigins:(e,t,r)=>{var{merchantId:s,apiKeyId:a}=e;return p(e,["merchantId","apiKeyId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/merchants/${s}/api-keys/${a}/whitelist-origins`,method:"POST",body:t,secure:!0,type:xa.Json,format:"json"},r))},updateApiKeyPublicKey:(e,t,r)=>{var{merchantId:s,apiKeyId:a}=e;return p(e,["merchantId","apiKeyId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/merchants/${s}/api-keys/${a}`,method:"PUT",body:t,secure:!0,type:xa.Json,format:"json"},r))}},this.wallets={getAllWallets:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets",method:"GET",query:e,secure:!0,format:"json"},t)),createWallet:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/create",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),verifyAccess:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/verify-access",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),createAdminWallet:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/create-admin-server-wallet",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),createWalletV2:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/create-with-shares",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),importWalletSeedPhraseV2:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/create-shares-based-wallet-from-seed",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),addNewDevice:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/add-new-device",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),importWalletSeedPhrase:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/import-seed-phrase",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),generateMissingAddresses:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/generate-wallet-addresses",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getUserAssetsByWalletId:(e,t)=>{var{walletId:r}=e,s=p(e,["walletId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/wallets/${r}/assets`,method:"GET",query:s,secure:!0,format:"json"},t))},getWalletAddresses:(e,t)=>{var{walletId:r}=e,s=p(e,["walletId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/wallets/${r}/addresses`,method:"GET",query:s,secure:!0,format:"json"},t))},getUserAsset:(e,t,r={})=>this.http.request(Object.assign({path:"/api/v1/wallets/asset",method:"GET",query:e,body:t,secure:!0,type:xa.Json,format:"json"},r)),updateUserAsset:(e,t,r={})=>this.http.request(Object.assign({path:"/api/v1/wallets/asset/update",method:"PUT",query:e,body:t,secure:!0,type:xa.Json,format:"json"},r)),initiateWalletRecovery:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/recover/init",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),recoverWallet:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/recover",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),requestSwapQuote:(e,t,r)=>{var{walletId:s}=e;return p(e,["walletId"]),void 0===r&&(r={}),this.http.request(Object.assign({path:`/api/v1/wallets/${s}/swap/quote`,method:"POST",body:t,secure:!0,type:xa.Json,format:"json"},r))},getSwapHistory:(e,t)=>{var{walletId:r}=e,s=p(e,["walletId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/wallets/${r}/swaps`,method:"GET",query:s,secure:!0,format:"json"},t))},getSwapById:(e,t)=>{var{walletId:r,swapId:s}=e;return p(e,["walletId","swapId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/wallets/${r}/swaps/${s}`,method:"GET",secure:!0,format:"json"},t))},executeSwap:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/wallets/execute-swap",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t))},this.transactions={getTransactions:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions",method:"GET",query:e,secure:!0,format:"json"},t)),getPendingTransactions:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/pending",method:"GET",query:e,secure:!0,format:"json"},t)),resolvePendingTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/resolve",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),sendTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/transfer",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),sendV2Transaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/transfer-with-shares",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),assetOptInTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/asset-optin",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),appOptInTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/app-optin",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getEstimateFee:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/estimate-fee",method:"GET",query:e,secure:!0,format:"json"},t)),fetchTransactionByHashOrReference:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/status",method:"GET",query:e,secure:!0,format:"json"},t)),getDetailedRawTransactionDataByReference:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/raw-status",method:"GET",query:e,secure:!0,format:"json"},t)),detectTransferRestriction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/detect-transfers-restrictions",method:"GET",query:e,secure:!0,format:"json"},t)),fetchMessageForTransferRestriction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/transfer-restriction-message",method:"GET",query:e,secure:!0,format:"json"},t)),getRestriction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/restriction",method:"GET",query:e,secure:!0,format:"json"},t)),checkAssetOptinForAddress:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/check-asset-optin",method:"GET",query:e,secure:!0,format:"json"},t)),checkAppOptinForAddress:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/check-app-optin",method:"GET",query:e,secure:!0,format:"json"},t)),createAllowanceTransaction:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/create-allowance",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t))},this.query={fetchBalance:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/assets/balance",method:"GET",query:e,secure:!0,format:"json"},t)),fetchOnlyBalance:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/address/balance",method:"GET",query:e,secure:!0,format:"json"},t)),fetchBulkBalance:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/assets/bulk-balance",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),fetchWalletBulkBalance:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/assets/wallet-bulk-balance",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),fetchTransactions:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/transactions",method:"GET",query:e,secure:!0,format:"json"},t)),fetchEvmTokenAssetInfo:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/fetch-token-info",method:"GET",query:e,secure:!0,format:"json"},t)),fetchAssetPairPrice:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/query/get-asset-price",method:"GET",query:e,secure:!0,format:"json"},t))},this.mpc={reconstructSeedPhrase:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/mpc/reconstruct-seed-phrase",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t))},this.users={getAllUsers:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users",method:"GET",query:e,secure:!0,format:"json"},t)),updateProfile:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users/profile",method:"PUT",body:e,secure:!0,type:xa.Json,format:"json"},t)),getCurrentUser:(e={})=>this.http.request(Object.assign({path:"/api/v1/users/profile",method:"GET",secure:!0,format:"json"},e)),getCurrentUserSalt:(e={})=>this.http.request(Object.assign({path:"/api/v1/users/salt",method:"GET",secure:!0,format:"json"},e)),getAllWalletsFromUserId:(e,t)=>{var{userId:r}=e;return p(e,["userId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${r}/wallets`,method:"GET",secure:!0,format:"json"},t))},getCurrentUserMerchantAssets:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users/merchants/assets",method:"GET",query:e,secure:!0,format:"json"},t)),getCurrentUserMerchantAssetsUsersMerchantAssets:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users/merchant/assets",method:"GET",query:e,secure:!0,format:"json"},t)),getAssetsByUserId:(e,t)=>{var{userId:r}=e,s=p(e,["userId"]);return void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${r}/assets`,method:"GET",query:s,secure:!0,format:"json"},t))},addAssetToUser:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users/assets/add",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),removeAssetFromUser:(e,t)=>{var{assetConfigId:r,walletId:s,userId:a}=e;return p(e,["assetConfigId","walletId","userId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${a}/wallets/${s}/assets/${r}`,method:"DELETE",secure:!0,format:"json"},t))},getUserByUserId:(e,t)=>{var{userId:r}=e;return p(e,["userId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${r}`,method:"GET",secure:!0,format:"json"},t))},getUserByExternalUserId:(e,t)=>{var{externalUserId:r}=e;return p(e,["externalUserId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/users/${r}/externalUserId`,method:"GET",secure:!0,format:"json"},t))}},this.adminTransactions={createReleaseSchedule:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/release-schedule",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),viewReleaseSchedule:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/release-schedule",method:"GET",query:e,secure:!0,format:"json"},t)),mint:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/mint",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),burn:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/burn",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),executePurchase:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/execute-purchase",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),executePurchaseWithInterest:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/execute-purchase-with-interest",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),setIdentity:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/set-identity",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),forceClaim:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/force-claim",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),forceClaimPrincipal:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/force-claim-principal",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t)),getCallbackPublicKey:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/callback_pk",method:"GET",query:e,secure:!0},t)),viewAdminTransaction:(e,t)=>{var{referenceId:r}=e;return p(e,["referenceId"]),void 0===t&&(t={}),this.http.request(Object.assign({path:`/api/v1/transactions/admin/${r}`,method:"GET",secure:!0,format:"json"},t))},upsideCallback:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/transactions/admin/callback",method:"POST",body:e,secure:!0,type:xa.Json,format:"json"},t))},this.dashboard={getDashboardData:(e={})=>this.http.request(Object.assign({path:"/api/v1/dashboard",method:"GET",secure:!0,format:"json"},e))},this.userActivity={getActivities:(e,t={})=>this.http.request(Object.assign({path:"/api/v1/users-activities",method:"GET",query:e,secure:!0,format:"json"},t))},this.http=e}}const Da={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function La(e){return Da}function qa(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 Ua(e,t,r,s,a){const n=a&&"input"in a?a.input:r.value,o=a?.expected??e.expects??null,i=a?.received??qa(n),c={kind:e.kind,type:e.type,input:n,expected:o,received:i,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${i}`,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 ja=new WeakMap;function Ba(e){let t=ja.get(e);return t||(t={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},La())},ja.set(e,t)),t}function Ma(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}function Wa(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function Va(e,t,r){return"function"==typeof e.fallback?e.fallback(t,r):e.fallback}function Fa(e,t,r){return"function"==typeof e.default?e.default(t,r):e.default}function Ga(){return{kind:"schema",type:"any",reference:Ga,expects:"any",async:!1,get"~standard"(){return Ba(this)},"~run":e=>(e.typed=!0,e)}}function Ha(e,t){return{kind:"schema",type:"array",reference:Ha,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return Ba(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 o={type:"array",origin:"value",input:r,key:s,value:a};for(const t of n.issues)t.path?t.path.unshift(o):t.path=[o],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 Ua(this,"type",e,t);return e}}}function $a(e){return{kind:"schema",type:"boolean",reference:$a,expects:"boolean",async:!1,message:e,get"~standard"(){return Ba(this)},"~run"(e,t){return"boolean"==typeof e.value?e.typed=!0:Ua(this,"type",e,t),e}}}function Ja(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=Ja(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=Ja(e[s],t[s]);if(a.issue)return a;r[s]=a.value}return{value:r}}}return{issue:!0}}function Ya(e,t){return{kind:"schema",type:"intersect",reference:Ya,expects:Wa(e.map((e=>e.expects)),"&"),async:!1,options:e,message:t,get"~standard"(){return Ba(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=Ja(e.value,s[r]);if(a.issue){Ua(this,"type",e,t,{received:"unknown"});break}e.value=a.value}}}else Ua(this,"type",e,t);return e}}}function za(e){return{kind:"schema",type:"lazy",reference:za,expects:"unknown",async:!1,getter:e,get"~standard"(){return Ba(this)},"~run"(e,t){return this.getter(e.value)["~run"](e,t)}}}function Za(e,t){return{kind:"schema",type:"nullable",reference:Za,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return Ba(this)},"~run"(e,t){return null===e.value&&(void 0!==this.default&&(e.value=Fa(this,e,t)),null===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function Xa(e){return{kind:"schema",type:"number",reference:Xa,expects:"number",async:!1,message:e,get"~standard"(){return Ba(this)},"~run"(e,t){return"number"!=typeof e.value||isNaN(e.value)?Ua(this,"type",e,t):e.typed=!0,e}}}function Qa(e,t){return{kind:"schema",type:"object",reference:Qa,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return Ba(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]:Fa(a),o=a["~run"]({value:n},t);if(o.issues){const a={type:"object",origin:"value",input:r,key:s,value:n};for(const t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=o.issues),t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[s]=o.value}else if(void 0!==a.fallback)e.value[s]=Va(a);else if("exact_optional"!==a.type&&"optional"!==a.type&&"nullish"!==a.type&&(Ua(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 Ua(this,"type",e,t);return e}}}function en(e,t){return{kind:"schema",type:"optional",reference:en,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return Ba(this)},"~run"(e,t){return void 0===e.value&&(void 0!==this.default&&(e.value=Fa(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function tn(e,t){return{kind:"schema",type:"picklist",reference:tn,expects:Wa(e.map(qa),"|"),async:!1,options:e,message:t,get"~standard"(){return Ba(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:Ua(this,"type",e,t),e}}}function rn(e,t,r){return{kind:"schema",type:"record",reference:rn,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return Ba(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in r)if(Ma(r,s)){const a=r[s],n=this.key["~run"]({value:s},t);if(n.issues){const o={type:"object",origin:"key",input:r,key:s,value:a};for(const t of n.issues)t.path=[o],e.issues?.push(t);if(e.issues||(e.issues=n.issues),t.abortEarly){e.typed=!1;break}}const o=this.value["~run"]({value:a},t);if(o.issues){const n={type:"object",origin:"value",input:r,key:s,value:a};for(const t of o.issues)t.path?t.path.unshift(n):t.path=[n],e.issues?.push(t);if(e.issues||(e.issues=o.issues),t.abortEarly){e.typed=!1;break}}n.typed&&o.typed||(e.typed=!1),n.typed&&(e.value[n.value]=o.value)}}else Ua(this,"type",e,t);return e}}}function sn(e){return{kind:"schema",type:"string",reference:sn,expects:"string",async:!1,message:e,get"~standard"(){return Ba(this)},"~run"(e,t){return"string"==typeof e.value?e.typed=!0:Ua(this,"type",e,t),e}}}function an(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 nn(e,t){return{kind:"schema",type:"union",reference:nn,expects:Wa(e.map((e=>e.expects)),"|"),async:!1,options:e,message:t,get"~standard"(){return Ba(this)},"~run"(e,t){let r,s,a;for(const n of this.options){const o=n["~run"]({value:e.value},t);if(o.typed){if(!o.issues){r=o;break}s?s.push(o):s=[o]}else a?a.push(o):a=[o]}if(r)return r;if(s){if(1===s.length)return s[0];Ua(this,"type",e,t,{issues:an(s)}),e.typed=!0}else{if(1===a?.length)return a[0];Ua(this,"type",e,t,{issues:an(a)})}return e}}}const on=Qa({clientAuthPubKey:sn(),passkeyChallengeType:en(tn(["webauthn.create","webauthn.get"])),walletId:en(sn())}),cn=Qa({message:sn(),wallabyAuthPubKey:en(sn()),foundDevicePublicKey:$a(),challenge:sn(),registrationOptions:en(rn(sn(),Ga())),authenticationOptions:en(rn(sn(),Ga()))}),dn=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),externalUserId:sn(),firstName:en(sn()),lastName:en(sn()),merchantId:en(sn()),passkeyRegistrationResponse:en(rn(sn(),Ga()))}),ln=Qa({id:sn(),firstName:en(sn()),externalUserId:sn(),role:en(tn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),clientSalt:en(sn()),clientAuthPubKey:sn()}),hn=Qa({accessToken:sn(),refreshToken:en(sn()),user:za((()=>ln))}),pn=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),externalUserId:sn(),firstName:en(sn()),lastName:en(sn()),merchantId:en(sn()),passkeyRegistrationResponse:en(rn(sn(),Ga()))}),un=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),passkeyRegistrationResponse:en(rn(sn(),Ga())),passkeyAuthenticationResponse:en(rn(sn(),Ga()))}),yn=Qa({id:sn(),externalUserId:sn(),clientSalt:sn()}),gn=Qa({accessToken:sn(),refreshToken:sn(),user:za((()=>yn))}),fn=Qa({refreshToken:sn()}),mn=Qa({accessToken:sn(),refreshToken:sn()}),wn=Qa({message:sn()}),vn=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),newClientAuthPubKey:sn()}),Sn=Qa({user:za((()=>ln))}),An=Qa({clientAuthPubKey:sn()}),bn=Qa({wallabyAuthPubKey:sn()}),En=Qa({id:sn(),externalUserId:sn(),merchantId:sn(),role:tn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]),firstName:sn(),walletsCount:Xa(),latestWallabyAuthPubKey:sn(),latestWallabyAuthPubKeyVersion:sn(),portalInvitationStatus:en(Za(tn(["pending","accepted","rejected"]))),createdAt:sn(),updatedAt:sn(),hasFullPermissions:$a()}),_n=Qa({id:sn(),userId:sn(),publicKey:sn(),status:tn(["active","invalidated"]),createdAt:sn(),updatedAt:sn()}),Tn=Qa({id:sn(),authenticatorGlobalId:sn(),credentialID:sn(),publicKey:sn(),authPublicKeyId:sn(),counter:Xa(),transports:sn(),credentialDeviceType:sn(),credentialBackedUp:$a(),user:Ya([za((()=>En))]),authPublicKeys:Ha(za((()=>_n))),userId:sn(),externalUserId:sn(),createdAt:sn(),updatedAt:sn(),authenticatorName:sn()}),Pn=Qa({credentials:Ha(za((()=>Tn)))}),In=Qa({totalRecords:Xa(),currentPage:Xa(),totalPages:Xa(),nextPage:Za(Xa()),previousPage:Za(Xa()),pageSize:Xa()}),kn=Qa({address:sn(),publicKey:en(sn()),type:en(tn(["SEGWIT","LEGACY","DEFAULT"]))}),Cn=Qa({id:sn(),name:sn(),nameSlugify:sn(),verified:$a(),status:tn(["active","inactive","invalidated"])}),On=Qa({id:sn(),userId:sn(),merchantId:sn(),chainId:sn(),userAssetAddress:sn(),walletId:sn(),configId:sn(),assetName:sn(),assetSymbol:sn(),balance:Za(sn()),balanceUpdatedAt:Za(sn()),claimableBalance:en(Za(sn())),claimableBalanceUpdatedAt:en(Za(sn())),claimablePaymentTokenContractAddress:en(Za(sn())),claimablePaymentTokenAssetConfigId:en(Za(sn())),lockedTokenBalance:Za(sn()),lockedTokenBalanceUpdatedAt:Za(sn()),mainnetBalance:Za(sn()),mainnetBalanceUpdatedAt:Za(sn()),testnetBalance:Za(sn()),testnetBalanceUpdatedAt:Za(sn()),mainnetLockedBalance:Za(sn()),mainnetLockedBalanceUpdatedAt:Za(sn()),testnetLockedBalance:Za(sn()),testnetLockedBalanceUpdatedAt:Za(sn()),defaultAddress:sn(),isVisible:$a(),source:tn(["merchant","user","republic"]),addresses:Ha(za((()=>kn))),ownershipType:sn(),priceConversion:en(sn()),changePercentageLast24h:en(sn()),createdAt:sn(),updatedAt:sn(),merchant:Ya([za((()=>Cn))])}),Kn=Qa({id:sn(),name:sn(),nameSlugify:sn()}),xn=Qa({address:sn(),topics:Ha(sn()),data:sn(),transactionIndex:Xa()}),Rn=Qa({event:sn(),args:rn(sn(),nn([sn(),Xa(),$a()]))}),Nn=Qa({message:Za(sn()),txLogs:Za(Ha(za((()=>xn)))),txLogsDecoded:Za(Ha(za((()=>Rn)))),reqSignature:sn(),reason:Za(sn()),requestId:Za(sn()),signatureUsed:$a()}),Dn=Qa({id:sn(),reference:Za(sn()),hash:en(Za(sn())),merchantId:sn(),userEmail:sn(),chainId:sn(),chainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:Xa(),fromWalletId:sn(),fromAddress:sn(),toWalletId:sn(),toAddress:sn(),assetId:sn(),assetSymbol:sn(),tokenType:tn(["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:sn(),fee:sn(),note:sn(),nonce:Xa(),gasPrice:Xa(),submitter:sn(),status:tn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:Za(tn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:tn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:sn(),networkEnvironment:Za(tn(["mainnet","testnet"])),statusCheckAttempts:Xa(),statusCheckedAt:Za(sn()),createdAt:sn(),updatedAt:sn(),asset:Ya([za((()=>Gn))]),merchant:Ya([za((()=>Hn))]),adminTransactions:Ha(za((()=>Nn))),user:za((()=>En)),chain:za((()=>eo)),splitCoins:sn(),transferObjects:sn()}),Ln=Qa({id:Xa(),contractTypeName:sn(),assetContracts:Ha(za((()=>qn)))}),qn=Qa({configId:sn(),contractTypeId:Xa(),contractAddress:sn(),assetConfig:Ya([za((()=>Gn))]),contractType:Ya([za((()=>Ln))])}),Un=Qa({id:sn(),merchantId:sn(),configId:sn(),chainId:sn(),chainName:sn(),assetName:sn(),assetSymbol:sn(),isVisible:$a(),isDefault:$a(),createdAt:sn(),updatedAt:sn(),merchant:Ya([za((()=>Hn))]),config:Ya([za((()=>Gn))]),chain:Ya([za((()=>eo))])}),jn=Qa({id:sn(),typeName:sn(),createdAt:sn(),updatedAt:sn()}),Bn=Qa({id:sn(),objectId:sn(),packageId:sn(),moduleName:sn(),structName:sn(),coinType:sn(),createdAt:Ya([za((()=>jn))]),updatedAt:sn()}),Mn=Qa({id:sn(),chainId:sn(),swapProviderId:sn(),providerChainIdentifier:sn(),chain:Ya([za((()=>eo))]),swapProvider:Ya([za((()=>Wn))]),providerAssets:Ha(za((()=>Vn))),createdAt:sn(),updatedAt:sn()}),Wn=Qa({id:sn(),name:sn(),explorerBaseUrl:sn(),isActive:$a(),chainMappings:Ha(za((()=>Mn))),providerAssets:Ha(za((()=>Vn))),createdAt:sn(),updatedAt:sn()}),Vn=Qa({id:sn(),assetConfigId:sn(),swapProviderId:sn(),chainProviderMappingId:sn(),providerAssetIdentifier:sn(),lastSynced:en(sn()),isEnabled:$a(),assetConfig:Ya([za((()=>Gn))]),swapProvider:Ya([za((()=>Wn))]),chainProviderMapping:Ya([za((()=>Mn))]),createdAt:sn(),updatedAt:sn()}),Fn=Qa({id:sn(),config:za((()=>Gn)),configId:sn(),timestamp:sn(),createdAt:sn()}),Gn=Qa({id:sn(),chainId:sn(),merchantId:en(Za(sn())),chainName:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),name:sn(),symbol:sn(),verified:en($a()),isOffChain:en($a()),decimals:Xa(),iconUrl:en(sn()),ticker:en(Za(sn())),type:en(tn(["COIN","TOKEN","OBJECT"])),tokenStandard:en(Za(tn(["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:en(Za(Xa())),contractAddress:Za(sn()),description:en(Za(sn())),ownershipType:en(tn(["SINGLE_OWNER","MULTI_SIG"])),ownerAddresses:en(Za(Ha(sn()))),status:en(tn(["active","inactive","archived"])),createdByUserId:en(Za(sn())),createdByMerchantId:en(Za(sn())),relayerAddress:en(sn()),contractVersion:en(sn()),chain:en(za((()=>eo))),createdByMerchant:en(Ya([za((()=>Kn))])),usersAssets:en(Ha(za((()=>On)))),transactions:en(Ha(za((()=>Dn)))),assetContracts:en(Ha(za((()=>qn)))),merchantAssets:en(Ha(za((()=>Un)))),createdByUser:en(za((()=>En))),suiConfig:en(za((()=>Bn))),isAssetReady:en($a()),extendedConfiguration:en(rn(sn(),Ga())),requiresKyc:en($a()),swapProviderAssets:en(Ha(za((()=>Vn)))),tokenDistributions:en(Ha(za((()=>Fn))))}),Hn=Qa({id:sn(),name:sn(),nameSlugify:sn(),verified:$a(),contactEmail:sn(),contactPhoneNumber:sn(),usersCount:Xa(),assetsCount:Xa(),tokensCount:Xa(),coinsCount:Xa(),walletsCount:Xa(),status:tn(["active","inactive","invalidated"]),createdAt:sn(),updatedAt:sn(),createdAssets:Ha(za((()=>Gn))),merchantAssets:en(Ha(za((()=>Un))))}),$n=Qa({id:Xa(),name:tn(["wallaby_share","owner_main_device_share","owner_backup_device_share"]),keyShares:Ha(za((()=>Jn)))}),Jn=Qa({id:sn(),user:za((()=>En)),wallet:za((()=>Zn)),encryptedKey:sn(),type:za((()=>$n)),createdAt:sn(),updatedAt:sn(),migratedWallabyShareAt:en(Za(sn())),wrappingPublicKey:sn(),migrationStatus:tn(["not_required","pending","migrated","failed"]),migrationErrorMessage:en(Za(sn()))}),Yn=Qa({id:Xa(),roles:Ha(tn(["single_sig","shares_single_owner","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),wallets:Ha(za((()=>Zn)))}),zn=Qa({id:sn(),walletId:sn(),userId:sn(),shareCount:Xa(),createdAt:sn(),updatedAt:sn()}),Zn=Qa({id:sn(),userId:sn(),merchantId:sn(),revisionId:sn(),revisionName:sn(),hashedSeedPhraseSalt:sn(),hashedEthAddressSalt:sn(),recoveryCount:Xa(),assetsCount:Xa(),createdAt:sn(),updatedAt:sn(),lastVerifiedAt:Za(sn()),userAssets:Ha(za((()=>On))),merchant:za((()=>Hn)),keyShares:Ha(za((()=>Jn))),type:za((()=>Yn)),creationType:en(Za(tn(["user_imported","user_created"]))),keyMigrationStatus:tn(["not_required","pending","migrated","failed"]),migrationErrorMessage:en(Za(sn())),walletAddresses:Ha(za((()=>Qn))),walletKeks:Ha(za((()=>zn)))}),Xn=Qa({id:Xa(),name:tn(["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:za((()=>Qn))}),Qn=Qa({id:sn(),walletId:sn(),wallet:za((()=>Zn)),chain:za((()=>eo)),typeId:Xa(),type:za((()=>Xn)),address:sn(),publicKey:sn(),createdAt:sn(),updatedAt:sn()}),eo=Qa({id:sn(),name:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),isEvm:$a(),iconUrl:en(Za(sn())),mainnetId:en(sn()),mainnetIndexUrl:en(Za(sn())),mainnetExplorerUrl:en(sn()),testnetId:en(sn()),testnetExplorerUrl:en(Za(sn())),testnetIndexUrl:en(Za(sn())),derivationPath:en(Za(sn())),addressRegex:en(Za(sn())),slip44:tn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767]),signatureScheme:en(tn(["secp256k1","ed25519","sr25519"])),status:en(tn(["UP","DOWN"])),search:en(sn()),createdAt:sn(),updatedAt:sn(),walletAddresses:en(Ha(za((()=>Qn)))),isChainReady:en($a()),supportsSwaps:en($a()),swapChainMappings:en(Ha(za((()=>Mn)))),indexUrl:en(Za(sn())),chainId:en(sn())}),to=Qa({pagination:Ya([za((()=>In))]),chains:Ha(za((()=>eo)))}),ro=Qa({name:sn(),isEvm:$a(),mainnetRpcUrl:sn(),mainnetIndexUrl:en(sn()),testnetId:en(sn()),testnetRpcUrl:sn(),testnetIndexUrl:sn(),derivationPath:sn(),addressRegex:en(sn()),slip44:Xa(),signatureScheme:tn(["secp256k1","ed25519","sr25519"])}),so=Qa({chain:za((()=>eo))}),ao=Qa({name:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),isEvm:$a(),mainnetId:en(sn()),mainnetRpcUrl:en(sn()),mainnetIndexUrl:en(sn()),testnetId:en(sn()),testnetRpcUrl:en(sn()),testnetIndexUrl:en(sn()),derivationPath:en(sn()),addressRegex:en(sn()),slip44:tn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767]),signatureScheme:en(tn(["secp256k1","ed25519","sr25519"])),supportSwaps:en($a())}),no=Qa({chain:za((()=>eo))}),oo=Qa({pagination:Ya([za((()=>In))]),assets:Ha(za((()=>Gn)))}),io=Qa({asset:za((()=>Gn))}),co=Qa({chainId:sn(),name:sn(),symbol:sn(),verified:$a(),isOffChain:$a(),decimals:Xa(),iconUrl:en(sn()),ticker:sn(),type:tn(["COIN","TOKEN","OBJECT"]),tokenStandard:en(tn(["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:Xa(),contractAddress:en(sn()),description:en(sn()),createdByUserId:en(sn()),createdByMerchantId:en(sn()),suiObjectId:en(sn())}),lo=Qa({asset:za((()=>Gn))}),ho=Qa({name:en(sn()),symbol:en(sn()),isOffChain:en($a()),decimals:en(Xa()),iconUrl:en(sn()),ticker:en(sn()),type:en(tn(["COIN","TOKEN","OBJECT"])),tokenStandard:en(tn(["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:en(Xa()),contractAddress:en(sn()),relayerAddress:en(sn()),description:en(sn()),suiObjectId:en(sn())}),po=Qa({asset:za((()=>Gn))}),uo=Qa({message:sn()}),yo=Qa({pagination:Ya([za((()=>In))]),merchants:Ha(za((()=>Hn)))}),go=Qa({name:sn(),contactEmail:sn(),contactPhoneNumber:en(sn()),status:en(tn(["active","inactive","invalidated"]))}),fo=Qa({name:en(sn()),contactEmail:en(sn()),contactPhoneNumber:en(sn()),status:tn(["active","inactive","invalidated"])}),mo=Qa({merchant:za((()=>Hn))}),wo=Qa({merchant:za((()=>Hn))}),vo=Qa({pagination:Ya([za((()=>In))]),merchant:za((()=>Hn)),assets:Ha(za((()=>Un))),merchantAssets:Ha(za((()=>Un)))}),So=Qa({id:sn(),externalUserId:sn(),walletsCount:Xa(),createdAt:sn(),updatedAt:sn(),merchantId:en(sn()),firstName:en(sn()),email:en(sn()),role:en(tn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),polymeshDID:en(sn())}),Ao=Qa({pagination:Ya([za((()=>In))]),merchant:za((()=>Hn)),users:Ha(za((()=>So)))}),bo=Qa({merchantId:sn(),email:sn(),firstName:sn(),lastName:sn(),role:sn()}),Eo=Qa({message:en(sn()),user:za((()=>So))}),_o=Qa({message:en(sn()),user:za((()=>So))}),To=Qa({pagination:Ya([za((()=>In))]),merchant:za((()=>Hn)),wallets:Ha(za((()=>Zn)))}),Po=Qa({assetConfigId:sn(),userId:sn(),walletId:sn()}),Io=Qa({merchantId:sn(),assets:Ha(za((()=>Po))),updateExistingWallets:en($a())}),ko=Qa({message:en(sn())}),Co=Qa({merchantId:sn(),assetConfigId:en(sn()),isDefault:en($a()),addToExistingWallets:en($a()),addToWallets:en(Ha(sn())),config:en(za((()=>Gn)))}),Oo=Qa({message:en(sn()),merchantAsset:za((()=>Un))}),Ko=Qa({merchantId:sn(),assetConfigId:sn()}),xo=Qa({message:en(sn())}),Ro=Qa({merchantId:sn(),assetConfigId:sn(),isVisible:en($a())}),No=Qa({message:en(sn()),merchantAsset:za((()=>Un))}),Do=Qa({merchantId:sn(),assetConfigId:sn(),isDefault:en($a())}),Lo=Qa({message:en(sn()),merchantAsset:za((()=>Un))}),qo=Qa({iv:sn(),ephemPublicKey:sn(),ciphertext:sn(),mac:sn()}),Uo=Qa({id:sn(),merchantId:sn(),appName:sn(),ipAddresses:Ha(sn()),domainNames:Ha(sn()),status:tn(["active","inactive"]),clientJWTPubKey:sn(),usersCount:Xa(),requestsCount:Xa(),totalRequestSizeInKb:Xa(),totalResponseSizeInKb:Xa(),totalResponseTimeInKb:Xa(),lastRequestAt:Za(sn()),onlyDashboardAccess:$a(),allowMobileAccess:$a(),createdAt:sn(),updatedAt:sn(),merchant:za((()=>Hn)),origins:Ha(za((()=>jo)))}),jo=Qa({id:sn(),merchantId:sn(),apiKeyId:sn(),origin:sn(),createdAt:sn(),updatedAt:sn(),merchant:za((()=>Hn)),apiKey:za((()=>Uo))}),Bo=Qa({id:sn(),merchantId:sn(),appName:sn(),apiKey:za((()=>qo)),status:tn(["active","inactive"]),clientJWTPubKey:sn(),allowMobileAccess:$a(),createdAt:sn(),updatedAt:sn(),origins:en(Ha(za((()=>jo))))}),Mo=Qa({pagination:Ya([za((()=>In))]),apiKeys:Ha(za((()=>Bo)))}),Wo=Qa({pagination:Ya([za((()=>In))]),apiKeyOrigins:Ha(za((()=>jo)))}),Vo=Qa({clientJWTPubKey:en(sn()),wrappingPublicKey:en(sn()),allowMobileAccess:en($a()),appName:sn()}),Fo=Qa({message:en(sn()),apiKey:za((()=>Bo)),clientJWTPrivKey:en(Ya([za((()=>qo))]))}),Go=Qa({merchantId:sn(),apiKeyId:sn(),origins:Ha(sn())}),Ho=Qa({message:en(sn()),apiKeyOrigins:Ha(za((()=>jo)))}),$o=Qa({clientJWTPubKey:en(sn()),wrappingPublicKey:sn(),appName:en(sn()),status:en(tn(["active","inactive"])),allowMobileAccess:en($a())}),Jo=Qa({message:en(sn()),apiKey:za((()=>Bo))}),Yo=Qa({pagination:Ya([za((()=>In))]),wallets:Ha(za((()=>Zn)))}),zo=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn()}),Zo=Qa({id:sn(),userId:sn(),merchantId:sn(),chainId:sn(),userAssetAddress:sn(),walletId:sn(),configId:sn(),assetName:sn(),assetSymbol:sn(),balance:Za(sn()),balanceUpdatedAt:Za(sn()),claimableBalance:en(Za(sn())),claimableBalanceUpdatedAt:en(Za(sn())),claimablePaymentTokenContractAddress:en(Za(sn())),claimablePaymentTokenAssetConfigId:en(Za(sn())),lockedTokenBalance:Za(sn()),lockedTokenBalanceUpdatedAt:Za(sn()),mainnetBalance:Za(sn()),mainnetBalanceUpdatedAt:Za(sn()),testnetBalance:Za(sn()),testnetBalanceUpdatedAt:Za(sn()),mainnetLockedBalance:Za(sn()),mainnetLockedBalanceUpdatedAt:Za(sn()),testnetLockedBalance:Za(sn()),testnetLockedBalanceUpdatedAt:Za(sn()),defaultAddress:sn(),isVisible:$a(),source:tn(["merchant","user","republic"]),addresses:Ha(za((()=>kn))),ownershipType:sn(),priceConversion:en(sn()),changePercentageLast24h:en(sn()),createdAt:sn(),updatedAt:sn(),merchant:Ya([za((()=>Cn))]),config:za((()=>Gn))}),Xo=Qa({id:sn(),userId:sn(),revisionName:sn()}),Qo=Qa({iv:sn(),ephemPublicKey:sn(),ciphertext:sn(),mac:sn()}),ei=Qa({encrypted:Ya([za((()=>Qo))]),wrappingPublicKey:sn(),type:tn(["wallaby_share","owner_main_device_share","owner_backup_device_share"])}),ti=Qa({v:Xa(),iv:sn(),ciphertext:sn(),tag:sn()}),ri=Qa({address:sn(),type:tn(["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:sn(),chainName:sn()}),si=Qa({wallabyAuthPubKey:sn(),assets:Ha(za((()=>Zo))),encryptedSeed:en(nn([za((()=>Qo)),za((()=>ti))])),wallet:Ya([za((()=>Xo))]),shares:en(Ha(za((()=>ei)))),encryptedBackupShare:en(Ya([za((()=>ti))])),reference:sn(),encryptedSeedForSharesSplit:en(za((()=>Qo))),walletAddressesInfo:Ha(za((()=>ri)))}),ai=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),encryptedShares:en(Ha(za((()=>Qo)))),encryptedSeed:en(Ya([za((()=>Qo))])),walletId:sn()}),ni=Qa({isAccessVerified:$a()}),oi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),adminWalletTypes:Ha(tn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]))}),ii=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),returnWalletOption:tn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:sn(),numShares:en(Xa()),threshold:en(Xa()),wallabyKeepsOne:$a(),backupDevicePublicKey:en(sn()),walletOwnershipType:tn(["SINGLE_OWNER"])}),ci=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),encryptedSeed:Ya([za((()=>Qo))]),walletId:en(sn()),returnWalletOption:tn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:sn(),numShares:en(Xa()),threshold:en(Xa()),wallabyKeepsOne:$a(),backupDevicePublicKey:en(sn()),walletOwnershipType:tn(["SINGLE_OWNER"])}),di=Qa({clientAuthPubKey:sn(),walletId:sn(),encryptedBackupShare:nn([za((()=>ti)),za((()=>qo))])}),li=Qa({reference:sn(),share:Ya([za((()=>ei))])}),hi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),encryptedSeed:Ya([za((()=>Qo))]),walletId:sn()}),pi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo)))),chainName:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]))}),ui=Qa({id:sn(),walletId:sn(),typeId:Xa(),type:za((()=>Xn)),address:sn(),publicKey:sn()}),yi=Qa({walletAddressesInfo:Ha(za((()=>ri))),walletAddresses:Ha(za((()=>ui)))}),gi=Qa({pagination:Ya([za((()=>In))]),assets:Ha(za((()=>Zo))),groupedAssets:en(rn(sn(),Ha(za((()=>Zo))))),walletAddressesInfo:Ha(za((()=>ri)))}),fi=Qa({pagination:Ya([za((()=>In))]),addresses:Ha(za((()=>ri)))}),mi=Qa({assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])}),wi=Qa({configId:sn(),assetName:en(sn()),assetSymbol:en(sn()),isVisible:en($a()),walletId:sn()}),vi=Qa({userAsset:Ya([za((()=>Zo))]),message:sn()}),Si=Qa({externalUserId:sn(),clientAuthPubKey:sn()}),Ai=Qa({signatureMessage:sn(),wallabyAuthPubKey:sn()}),bi=Qa({walletId:en(sn()),externalUserId:sn(),clientAuthPubKey:sn(),message:sn(),signature:sn(),encryptedSeed:Ya([za((()=>Qo))])}),Ei=Qa({id:sn(),externalUserId:sn()}),_i=Qa({user:Ya([za((()=>Ei))]),wallet:Ya([za((()=>Zn))])}),Ti=Qa({fromAssetConfigId:sn(),toAssetConfigId:sn(),fromAmount:en(sn()),toAmount:en(sn()),slippage:en(Xa())}),Pi=Qa({amount:sn(),amountUSD:en(Za(sn())),symbol:en(sn()),icon:en(sn())}),Ii=Qa({id:sn(),gasFee:en(Ha(za((()=>Pi)))),providerFee:en(Ha(za((()=>Pi)))),republicFee:en(Ha(za((()=>Pi)))),allowanceFee:en(Ha(za((()=>Pi)))),fromAssetConfigId:sn(),fromAssetSymbol:sn(),fromAssetChain:sn(),toAssetConfigId:sn(),toAssetSymbol:sn(),toAssetChain:sn(),fromAmount:sn(),fromAddress:sn(),toAmount:sn(),toAddress:sn(),slippage:Xa(),expiresAt:en(sn())}),ki=Qa({id:sn(),fromAssetSymbol:sn(),fromAssetChainName:sn(),toAssetSymbol:sn(),toAssetChainName:sn(),fromAddress:sn(),toAddress:sn(),fromAmount:sn(),toAmount:sn(),slippage:Xa(),gasFee:en(Ha(za((()=>Pi)))),providerFee:en(Ha(za((()=>Pi)))),republicFee:en(Ha(za((()=>Pi)))),allowanceFee:en(Ha(za((()=>Pi)))),status:tn(["quote","executing","in_progress","completed","failed","abandoned","execution_failed","invalid"]),executedAt:Za(sn()),completedAt:Za(sn()),transactionId:Za(sn()),transactionHash:Za(sn()),explorerLink:Za(sn())}),Ci=Qa({pagination:Ya([za((()=>In))]),swaps:Ha(za((()=>ki)))}),Oi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),quoteId:sn(),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo))))}),Ki=Qa({swapQuoteId:sn(),status:sn(),explorerLink:sn(),transactionHash:sn()}),xi=Qa({id:sn(),reference:Za(sn()),hash:en(Za(sn())),merchantId:sn(),userEmail:sn(),chainId:sn(),chainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:Xa(),fromWalletId:sn(),fromAddress:sn(),toWalletId:sn(),toAddress:sn(),assetId:sn(),assetSymbol:sn(),tokenType:tn(["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:sn(),fee:sn(),note:sn(),nonce:Xa(),gasPrice:Xa(),submitter:sn(),status:tn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:Za(tn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:tn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:sn(),networkEnvironment:Za(tn(["mainnet","testnet"])),statusCheckAttempts:Xa(),statusCheckedAt:Za(sn()),createdAt:sn(),updatedAt:sn(),asset:Ya([za((()=>Gn))]),merchant:Ya([za((()=>Hn))]),adminTransactions:Ha(za((()=>Nn))),user:za((()=>En)),chain:za((()=>eo)),splitCoins:sn(),transferObjects:sn(),type:en(tn(["INCOMING","OUTGOING","SWAP","UNKNOWN"])),entryType:en(tn(["INCOMING","OUTGOING","SWAP","UNKNOWN"]))}),Ri=Qa({pagination:Ya([za((()=>In))]),transactions:Ha(za((()=>xi)))}),Ni=Qa({id:sn(),amount:sn(),sender:sn(),asset:en(Ya([za((()=>Gn))])),expires:en(sn())}),Di=Qa({transactions:Ha(za((()=>Ni)))}),Li=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),id:sn(),choice:tn(["approve","deny"]),symbol:sn(),chainName:sn(),walletId:sn(),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo))))}),qi=Qa({id:sn(),status:tn(["confirmed","denied"]),hash:sn(),asset:Ya([za((()=>Gn))])}),Ui=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),originAddress:sn(),recipientAddress:sn(),assetId:sn(),amount:sn(),reference:sn(),encryptedSeed:Ya([za((()=>Qo))]),memo:sn(),transactionType:en(tn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"]))}),ji=Qa({transaction:Ya([za((()=>Dn))]),message:en(sn())}),Bi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),originAddress:sn(),recipientAddress:sn(),assetId:sn(),amount:sn(),reference:sn(),memo:sn(),transactionType:en(tn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"])),encryptedShares:Ha(za((()=>Qo)))}),Mi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),originAddress:sn(),reference:sn(),note:en(sn()),encryptedSeed:Ya([za((()=>Qo))]),assetIndex:Xa()}),Wi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),originAddress:sn(),reference:sn(),note:en(sn()),encryptedSeed:Ya([za((()=>Qo))]),appIndex:Xa()}),Vi=Qa({feePaymentSymbol:sn(),fee:sn(),lowestFee:en(sn()),highestFee:en(sn())}),Fi=Qa({address:Ha(sn()),amount:sn(),txId:sn()}),Gi=Qa({status:tn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionHash:sn(),reference:sn(),assetSymbol:sn(),transactionValue:sn(),fromAddress:sn(),toAddress:sn(),chain:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),fee:sn(),nonce:en(Xa()),timestamp:en(Xa()),blockNumber:en(Xa()),memo:en(sn()),origins:en(Ha(za((()=>Fi)))),recipients:en(Ha(za((()=>Fi))))}),Hi=Qa({canTransfer:$a(),restrictionCode:sn(),tokenContractAddress:sn(),fromAddress:sn(),toAddress:sn(),value:sn(),assetId:sn()}),$i=Qa({restrictionCode:Xa(),restrictionCodeMessage:sn()}),Ji=Qa({canTransfer:$a(),message:sn(),restrictionCode:sn()}),Yi=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),walletId:sn(),ownerAddress:sn(),spenderAddress:sn(),amount:sn(),reference:sn(),memo:sn(),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo)))),chainName:sn(),assetSymbol:sn(),assetId:sn(),contractAddress:en(sn())}),zi=Qa({transaction:Ya([za((()=>Dn))])}),Zi=Qa({paymentTokenContractAddress:sn(),assetConfigId:sn(),balance:sn()}),Xi=Qa({address:sn(),assetSymbol:sn(),tokenStandard:en(tn(["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:en(tn(["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:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:en(sn()),balance:sn(),claimable:Ya([za((()=>Zi))]),lockedTokenBalance:en(sn()),unlockedTokenBalance:en(sn()),stakedBalance:en(sn()),claimableBalance:en(sn()),assetConfigId:sn(),balanceUpdatedAt:en(sn())}),Qi=Qa({address:sn(),assetSymbol:sn(),tokenStandard:en(tn(["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:en(tn(["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:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:en(sn())}),ec=Qa({assets:Ha(za((()=>Qi)))}),tc=Qa({balances:Ha(za((()=>Xi)))}),rc=Qa({walletId:sn()}),sc=Qa({address:sn(),transactions:Ha(za((()=>Dn)))}),ac=Qa({decimals:Xa(),symbol:sn(),name:sn(),tokenContractAddress:sn()}),nc=Qa({symbol:sn(),price:sn(),changePercentageLast24h:sn()}),oc=Qa({data:Ha(za((()=>nc)))}),ic=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),encryptedShares:Ha(za((()=>Qo))),recoveryPubKey:en(sn()),walletId:en(sn())}),cc=Qa({encryptedSeed:Ya([za((()=>Qo))])}),dc=Qa({pagination:Ya([za((()=>In))]),users:Ha(za((()=>So)))}),lc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),email:sn(),firstName:sn(),lastName:sn()}),hc=Qa({message:sn(),user:Ya([za((()=>En))])}),pc=Qa({user:Ya([za((()=>So))])}),uc=Qa({clientSalt:sn()}),yc=Qa({wallets:Ha(za((()=>Zn)))}),gc=Qa({pagination:Ya([za((()=>In))]),assets:Ha(za((()=>On))),groupedAssets:en(rn(sn(),Ha(za((()=>On)))))}),fc=Qa({name:sn(),symbol:sn(),decimals:Xa(),contractAddress:sn(),chainId:en(sn()),chainName:en(tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),tokenStandard:en(tn(["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:en(sn()),iconUrl:en(sn())}),mc=Qa({assetConfigId:en(sn()),walletId:sn(),userId:sn(),config:en(Ya([za((()=>fc))])),message:en(sn()),clientAuthPubKey:en(sn()),signature:en(sn()),encryptedSeed:en(Ya([za((()=>Qo))])),encryptedShares:en(Ha(za((()=>Qo))))}),wc=Qa({asset:Ya([za((()=>On))])}),vc=Qa({message:sn()}),Sc=Qa({user:Ya([za((()=>So))])}),Ac=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:sn(),releaseCount:Xa(),delayUntilFirstReleaseInSeconds:Xa(),initialReleasePortionInBips:Xa(),periodBetweenReleasesInSeconds:Xa(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),bc=Qa({reference:sn()}),Ec=Qa({address:sn(),amount:sn(),commencementTimestamp:Xa(),scheduleId:Xa(),cancelableBy:Ha(sn())}),_c=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:sn(),mints:Ha(za((()=>Ec))),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),Tc=Qa({references:Ha(za((()=>bc)))}),Pc=Qa({address:sn(),amount:sn(),commencementTimestamp:Xa(),scheduleId:Xa(),timelockIndex:Xa(),reclaimTokenTo:sn()}),Ic=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:sn(),burns:Ha(za((()=>Pc))),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),kc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:sn(),payerAddress:sn(),tokenRecipientAddress:sn(),originatorPurchaseAmount:sn(),mintAmount:sn(),adminFeeAmount:sn(),totalAmount:sn(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),Cc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:sn(),payerAddress:sn(),tokenRecipientAddress:sn(),originatorPurchaseAmount:sn(),mintAmount:sn(),prefundedInterestAmount:sn(),adminFeeExcludingPrefundedInterestAmount:sn(),totalAmount:sn(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),Oc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),owner:sn(),regions:Ha(sn()),accreditationType:Xa(),lastAmlKycChangeTimestamp:Xa(),lastAccreditationChangeTimestamp:Xa(),amlKycPassed:$a(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),Kc=Qa({message:sn(),clientAuthPubKey:sn(),signature:sn(),assetSymbol:sn(),blockchainName:tn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),wallet:sn(),amount:sn(),walletId:sn(),encryptedSeed:Ya([za((()=>ti))])}),xc=Qa({assetSymbol:sn(),blockchainName:sn(),releaseCount:Xa(),delayUntilFirstReleaseInSeconds:Xa(),initialReleasePortionInBips:Xa(),periodBetweenReleasesInSeconds:Xa(),scheduleId:Xa()}),Rc=Qa({adminTransaction:Ya([za((()=>Nn))])}),Nc=Qa({status:tn(["QUEUED","PENDING","SUCCESS","FAILED"]),message:en(sn()),txHash:en(sn()),txLogs:Ha(za((()=>xn))),txLogsDecoded:Ha(za((()=>Rn))),reqSignature:en(sn()),clientRequestSignature:en(sn()),requestId:en(sn()),reason:en(sn()),txId:en(sn())}),Dc=Qa({message:sn()}),Lc=Qa({chainsCount:Xa(),chains:Ha(za((()=>eo))),merchantsCount:Xa(),merchants:Ha(za((()=>Hn))),assetsCount:Xa(),usersCount:Xa(),users:Ha(za((()=>So))),adminsCount:Xa(),walletsCount:Xa()}),qc=Qa({id:sn(),userId:sn(),merchantId:sn(),action:en(Za(tn(["logged_in","logged_out","created_wallet","updated_wallet","deleted_wallet","created_merchant","updated_merchant","deleted_merchant"]))),requestUrl:sn(),requestMethod:sn(),createdAt:sn(),updatedAt:sn(),merchant:za((()=>Hn))}),Uc=Qa({pagination:Ya([za((()=>In))]),activities:Ha(za((()=>qc)))}),jc=[{method:"POST",path:"/auth/signature-message/external",request:za((()=>on)),response:za((()=>cn))},{method:"POST",path:"/auth/signature-message",request:za((()=>on)),response:za((()=>cn))},{method:"POST",path:"/auth/sign-up",request:za((()=>dn)),response:za((()=>hn))},{method:"POST",path:"/auth/sign-up/external",request:za((()=>pn)),response:za((()=>hn))},{method:"POST",path:"/auth/sign-in",request:za((()=>un)),response:za((()=>hn))},{method:"POST",path:"/auth/issue-jwt-token",response:za((()=>gn))},{method:"POST",path:"/auth/refresh-access-token",request:za((()=>fn)),response:za((()=>mn))},{method:"POST",path:"/auth/logout",response:za((()=>wn))},{method:"PUT",path:"/auth/client-auth-pubkey",request:za((()=>vn)),response:za((()=>Sn))},{method:"POST",path:"/auth/wallaby-auth-pubkey",request:za((()=>An)),response:za((()=>bn))},{method:"GET",path:"/auth/passkey-credentials",response:za((()=>Pn))},{method:"GET",path:"/chains",response:za((()=>to))},{method:"POST",path:"/chains",request:za((()=>ro)),response:za((()=>so))},{method:"PUT",path:"/chains/{chainId}",request:za((()=>ao)),response:za((()=>no))},{method:"GET",path:"/assets/configurations",response:za((()=>oo))},{method:"POST",path:"/assets/configurations",request:za((()=>co)),response:za((()=>lo))},{method:"GET",path:"/assets/configurations/{assetConfigId}",response:za((()=>io))},{method:"PUT",path:"/assets/configurations/{assetConfigId}",request:za((()=>ho)),response:za((()=>po))},{method:"POST",path:"/assets/configurations/{assetConfigId}/verify",response:za((()=>uo))},{method:"DELETE",path:"/assets/configurations/{assetConfigId}/unverify",response:za((()=>uo))},{method:"POST",path:"/assets/configurations/{assetConfigId}/archive",response:za((()=>uo))},{method:"POST",path:"/assets/configurations/{assetConfigId}/unarchive",response:za((()=>uo))},{method:"GET",path:"/merchants",response:za((()=>yo))},{method:"POST",path:"/merchants",request:za((()=>go)),response:za((()=>go))},{method:"PUT",path:"/merchants/{merchantId}",request:za((()=>fo)),response:za((()=>mo))},{method:"GET",path:"/merchants/{merchantId}",response:za((()=>wo))},{method:"GET",path:"/merchants/{merchantId}/assets",response:za((()=>vo))},{method:"GET",path:"/merchants/{merchantId}/users",response:za((()=>Ao))},{method:"GET",path:"/merchants/{merchantId}/admins",response:za((()=>Ao))},{method:"POST",path:"/merchants/admins/invite",request:za((()=>bo)),response:za((()=>Eo))},{method:"DELETE",path:"/merchants/{merchantId}/admins/{userId}",response:za((()=>_o))},{method:"GET",path:"/merchants/{merchantId}/wallets",response:za((()=>To))},{method:"POST",path:"/merchants/wallets/add-assets",request:za((()=>Io)),response:za((()=>ko))},{method:"POST",path:"/merchants/assets/add",request:za((()=>Co)),response:za((()=>Oo))},{method:"DELETE",path:"/merchants/assets/delete",request:za((()=>Ko)),response:za((()=>xo))},{method:"POST",path:"/merchants/assets/update-visibility",request:za((()=>Ro)),response:za((()=>No))},{method:"POST",path:"/merchants/assets/update-default-status",request:za((()=>Do)),response:za((()=>Lo))},{method:"GET",path:"/merchants/{merchantId}/api-keys",response:za((()=>Mo))},{method:"POST",path:"/merchants/{merchantId}/api-keys",request:za((()=>Vo)),response:za((()=>Fo))},{method:"GET",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/origins",response:za((()=>Wo))},{method:"POST",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/whitelist-origins",request:za((()=>Go)),response:za((()=>Ho))},{method:"PUT",path:"/merchants/{merchantId}/api-keys/{apiKeyId}",request:za((()=>$o)),response:za((()=>Jo))},{method:"GET",path:"/wallets",response:za((()=>Yo))},{method:"POST",path:"/wallets/create",request:za((()=>zo)),response:za((()=>si))},{method:"POST",path:"/wallets/verify-access",request:za((()=>ai)),response:za((()=>ni))},{method:"POST",path:"/wallets/create-admin-server-wallet",request:za((()=>oi)),response:za((()=>si))},{method:"POST",path:"/wallets/create-with-shares",request:za((()=>ii)),response:za((()=>si))},{method:"POST",path:"/wallets/create-shares-based-wallet-from-seed",request:za((()=>ci)),response:za((()=>si))},{method:"POST",path:"/wallets/add-new-device",request:za((()=>di)),response:za((()=>li))},{method:"POST",path:"/wallets/import-seed-phrase",request:za((()=>hi)),response:za((()=>si))},{method:"POST",path:"/wallets/generate-wallet-addresses",request:za((()=>pi)),response:za((()=>yi))},{method:"GET",path:"/wallets/{walletId}/assets",response:za((()=>gi))},{method:"GET",path:"/wallets/{walletId}/addresses",response:za((()=>fi))},{method:"GET",path:"/wallets/asset",request:za((()=>mi)),response:za((()=>Zo))},{method:"PUT",path:"/wallets/asset/update",request:za((()=>wi)),response:za((()=>vi))},{method:"POST",path:"/wallets/recover/init",request:za((()=>Si)),response:za((()=>Ai))},{method:"POST",path:"/wallets/recover",request:za((()=>bi)),response:za((()=>_i))},{method:"POST",path:"/wallets/{walletId}/swap/quote",request:za((()=>Ti)),response:za((()=>Ii))},{method:"GET",path:"/wallets/{walletId}/swaps",response:za((()=>Ci))},{method:"GET",path:"/wallets/{walletId}/swaps/{swapId}",response:za((()=>ki))},{method:"POST",path:"/wallets/execute-swap",request:za((()=>Oi)),response:za((()=>Ki))},{method:"GET",path:"/transactions",response:za((()=>Ri))},{method:"GET",path:"/transactions/pending",response:za((()=>Di))},{method:"POST",path:"/transactions/resolve",request:za((()=>Li)),response:za((()=>qi))},{method:"POST",path:"/transactions/transfer",request:za((()=>Ui)),response:za((()=>ji))},{method:"POST",path:"/transactions/transfer-with-shares",request:za((()=>Bi)),response:za((()=>ji))},{method:"POST",path:"/transactions/asset-optin",request:za((()=>Mi)),response:za((()=>ji))},{method:"POST",path:"/transactions/app-optin",request:za((()=>Wi)),response:za((()=>ji))},{method:"GET",path:"/transactions/estimate-fee",response:za((()=>Vi))},{method:"GET",path:"/transactions/status",response:za((()=>Gi))},{method:"GET",path:"/transactions/raw-status",response:za((()=>Dn))},{method:"GET",path:"/transactions/detect-transfers-restrictions",response:za((()=>Hi))},{method:"GET",path:"/transactions/transfer-restriction-message",response:za((()=>$i))},{method:"GET",path:"/transactions/restriction",response:za((()=>Ji))},{method:"GET",path:"/transactions/check-asset-optin",response:Ha(rn(sn(),Ga()))},{method:"GET",path:"/transactions/check-app-optin",response:Ha(rn(sn(),Ga()))},{method:"POST",path:"/transactions/create-allowance",request:za((()=>Yi)),response:za((()=>zi))},{method:"GET",path:"/query/assets/balance",response:za((()=>Xi))},{method:"GET",path:"/query/address/balance",response:za((()=>Xi))},{method:"POST",path:"/query/assets/bulk-balance",request:za((()=>ec)),response:za((()=>tc))},{method:"POST",path:"/query/assets/wallet-bulk-balance",request:za((()=>rc)),response:za((()=>tc))},{method:"GET",path:"/query/transactions",response:za((()=>sc))},{method:"GET",path:"/query/fetch-token-info",response:za((()=>ac))},{method:"GET",path:"/query/get-asset-price",response:za((()=>oc))},{method:"POST",path:"/mpc/reconstruct-seed-phrase",request:za((()=>ic)),response:za((()=>cc))},{method:"GET",path:"/users",response:za((()=>dc))},{method:"PUT",path:"/users/profile",request:za((()=>lc)),response:za((()=>hc))},{method:"GET",path:"/users/profile",response:za((()=>pc))},{method:"GET",path:"/users/salt",response:za((()=>uc))},{method:"GET",path:"/users/{userId}/wallets",response:za((()=>yc))},{method:"GET",path:"/users/merchants/assets",response:za((()=>vo))},{method:"GET",path:"/users/merchant/assets",response:za((()=>vo))},{method:"GET",path:"/users/{userId}/assets",response:za((()=>gc))},{method:"POST",path:"/users/assets/add",request:za((()=>mc)),response:za((()=>wc))},{method:"DELETE",path:"/users/{userId}/wallets/{walletId}/assets/{assetConfigId}",response:za((()=>vc))},{method:"GET",path:"/users/{userId}",response:za((()=>pc))},{method:"GET",path:"/users/{externalUserId}/externalUserId",response:za((()=>Sc))},{method:"POST",path:"/transactions/admin/release-schedule",request:za((()=>Ac)),response:za((()=>bc))},{method:"GET",path:"/transactions/admin/release-schedule",response:za((()=>xc))},{method:"POST",path:"/transactions/admin/mint",request:za((()=>_c)),response:za((()=>Tc))},{method:"POST",path:"/transactions/admin/burn",request:za((()=>Ic)),response:za((()=>Tc))},{method:"POST",path:"/transactions/admin/execute-purchase",request:za((()=>kc)),response:za((()=>bc))},{method:"POST",path:"/transactions/admin/execute-purchase-with-interest",request:za((()=>Cc)),response:za((()=>bc))},{method:"POST",path:"/transactions/admin/set-identity",request:za((()=>Oc)),response:za((()=>bc))},{method:"POST",path:"/transactions/admin/force-claim",request:za((()=>Kc)),response:za((()=>bc))},{method:"POST",path:"/transactions/admin/force-claim-principal",request:za((()=>Kc)),response:za((()=>bc))},{method:"GET",path:"/transactions/admin/{referenceId}",response:za((()=>Rc))},{method:"POST",path:"/transactions/admin/callback",request:za((()=>Nc)),response:za((()=>Dc))},{method:"GET",path:"/dashboard",response:za((()=>Lc))},{method:"GET",path:"/users-activities",response:za((()=>Uc))}],Bc=new Map,Mc=[];for(const e of jc)if(e.path.includes("{")){const t=e.path.replace(/\{[^/]+\}/g,"[^/]+");Mc.push({method:e.method,regex:new RegExp(`^${t}$`),entry:e})}else Bc.set(`${e.method} ${e.path}`,e);const Wc={response:{statusCode:200,errorCode:exports.ErrorResponseCodes.sdk_invalid_response,tag:"InvalidResponse"},request:{statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter,tag:"InvalidRequest"}};function Vc(e,t,r,s,a){var n;if("off"===a)return;const o=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=Bc.get(`${r} ${s}`);if(a)return{request:a.request,response:a.response};const n=Mc.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(!o)return;const i=function(e,t){const r=e["~run"]({value:t},La());return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}(o,s);if(i.success)return;const c=`${t} ${r}: ${d=i.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}=Wc[e];if("throw"===a)throw new M({kind:"validation",message:c,statusCode:l,errorCode:h,data:{method:t,path:r,issues:i.issues}});ye.warn(`SDK::ApiValidation::${p} ${c}`)}function Fc({method:e,path:t,data:r,mode:s}){Vc("response",e,t,r,s)}function Gc({method:e,path:t,body:r,mode:s}){Vc("request",e,t,r,s)}const Hc=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]),$c=new Set([exports.ErrorResponseCodes.auth_refresh_token_not_found,exports.ErrorResponseCodes.auth_refresh_token_expired,exports.ErrorResponseCodes.auth_refresh_token_reuse_detected]);function Jc(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 Yc(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 zc(e){if(401!==Jc(e))return!1;const t=Yc(e);return!t||Hc.has(t)}const Zc=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()}},Xc=new class{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()}};class Qc{constructor(e,t={}){var r,s,a,n,o;const i=Ka(e);this.apiKey=i.apiKey,this.baseUrl=i.baseUrl,this.userId=i.userId,this.options=i.options,(null===(r=this.options)||void 0===r?void 0:r.platform)&&(Ae.platform=this.options.platform,Ae.isNative="ios"===this.options.platform||"android"===this.options.platform,Ae.isWeb=!Ae.isNative),this.cipher=null!==(s=t.cipher)&&void 0!==s?s:new _a,this.transport=null!==(a=t.transport)&&void 0!==a?a:(...e)=>fetch(...e),this.clock=null!==(n=t.clock)&&void 0!==n?n:{now:()=>Date.now()},this.lockManager=Xc,this._initializeClientAuthToken(i.clientAuthToken),this.request=this.request.bind(this);const c=new Ra({baseUrl:this.baseUrl.replace(/\/api\/v1\/?$/,""),baseApiParams:{secure:!0},securityWorker:this.securityWorker.bind(this),customFetch:this.transport}),d=c.request.bind(c);c.request=async e=>{const t=async r=>{try{Gc({method:e.method,path:e.path,body:e.body,mode:this.validationMode});const t=await d(e);return Fc({method:e.method,path:e.path,data:t,mode:this.validationMode}),t}catch(e){if(!r&&zc(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 M)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 Na(c),this.api.http.setSecurityData(Object.assign({"x-api-key":e.apiKey,"x-client-jwt":e.clientAuthToken},null===(o=this.options)||void 0===o?void 0:o.headers))}set setClientAuthToken(e){this._initializeClientAuthToken(e)}get version(){const e=be;return ye.log(`wsdk is running v${e}`),e}_initializeClientAuthToken(e){if(t=e,r=this.userId,!t||!r||a.jwtDecode(t).externalUserId!==r)throw new M({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 a.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 M({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:me,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 M({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 Ta({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 Zc.withDedupe(t,(async()=>{var t;const r=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(r)try{const s=await this.request(Ca.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=Jc(e),r=Yc(e);return 401===t||!!r&&$c.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 M(e);try{null===(r=null===(t=this.options)||void 0===t?void 0:t.onError)||void 0===r||r.call(t,s)}catch(e){ye.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 M(e):this.toWallabyError(e);if(e!==Ca.refreshAccessToken&&!r){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(e&&Ia(e,60,this.clock.now))try{await this._performTokenRefresh({silent:!0})}catch(e){}}let o="string"==typeof e.fullPath?e.fullPath:e.fullPath(null==t?void 0:t.payload);(null==t?void 0:t.queryParams)&&(o+=`?${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 i=`${this.baseUrl}${o}`,c=Object.assign(Object.assign({},await this._getRequestHeaders()),null===(a=this.options)||void 0===a?void 0:a.headers);try{Gc({method:e.method,path:o,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)),ye.debug(`SDK::Base::${e.method}::Request`,{path:i,payload:null==t?void 0:t.payload});const a=await this.transport(i,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(ye.debug(`SDK::Base::${e.method}::Response`,{status:a.status,statusText:a.statusText,data:l}),!a.ok){if(!r&&e!==Ca.refreshAccessToken&&zc({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 Fc({method:e.method,path:o,data:l,mode:this.validationMode}),l}catch(t){if(t instanceof M)throw t;if(null==t?void 0:t.error){ye.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 ye.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(Pa(this.clientAuthToken,this.clock.now))throw new M({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};return e&&(t.Authorization="Bearer "+e),t}async securityWorker(e){try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&Ia(e,60,this.clock.now)&&await this._performTokenRefresh({silent:!0})}catch(e){}const t=Object.assign({"Content-Type":"application/json"},e||{});try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&(t.Authorization=`Bearer ${e}`)}catch(e){}return{headers:t}}}const ed={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},initRecoveryFlow:{fullPath:"/wallets/recover/init",method:exports.RequestMethod.Post,requiresAccessToken:!1},recover:{fullPath:"/wallets/recover",method:exports.RequestMethod.Post,requiresAccessToken:!1},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}},td={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}},rd={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}},sd={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 ad(e,t){if(!e)return{};const r=new Set(t);return Object.fromEntries(Object.entries(e).filter((([e])=>!r.has(e))))}class nd{constructor(){}async register({optionsJSON:e}){if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new M({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await h.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 M({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await h.startAuthentication({optionsJSON:Object.assign(Object.assign({},e),{userVerification:r?"discouraged":e.userVerification}),useBrowserAutofill:t})}catch(e){throw this.handlePasskeyError(e),e}}handlePasskeyError(e){return ye.error("SDK::Authenticator::handlePasskeyError",e),this.throwPasskeyError(this.classifyPasskeyError(e),e)}classifyPasskeyError(e){return e instanceof h.WebAuthnError?(ye.debug("SDK::Authenticator::handlePasskeyError - WebAuthnError",e),{errorCode:e.code}):e instanceof Error?(ye.debug("SDK::Authenticator::handlePasskeyError - Error",e),{errorMessage:e.message}):null!==e&&"object"==typeof e&&e.error&&e.message?(ye.debug("SDK::Authenticator::handlePasskeyError - Object",e),{errorCode:e.error,errorMessage:e.message}):"string"==typeof e?(ye.debug("SDK::Authenticator::handlePasskeyError - String",e),{errorMessage:e}):(ye.debug("SDK::Authenticator::handlePasskeyError - Unknown",e),{})}throwPasskeyError({errorCode:e,errorMessage:t},r){var s,a,n;ye.error("SDK::Authenticator::throwPasskeyError",e);const o=pe.find((t=>t.error===e));throw ye.error("SDK::Authenticator::error",o),new M({message:null!==(a=null!==(s=null==o?void 0:o.message)&&void 0!==s?s:t)&&void 0!==a?a:W.message,statusCode:400,errorCode:null!==(n=null==o?void 0:o.error)&&void 0!==n?n:e,cause:r})}}function od(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");return t.padEnd(t.length+(4-t.length%4)%4,"=")}function id(e){try{return o.toUint8Array(e)}catch(r){return t=e,o.toUint8Array(od(t))}var t}function cd(e){const t=od(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 dd{constructor(e,t,r,s=new _a){this.cipher=s,this.localStorageService=t,this.userId=e,this.request=r,this.authenticator=new nd}preparePasskeyRequestOptions(e){var t,r,s,a,n,o,i,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?cd(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===(o=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===o?void 0:o.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===(i=e.extensions)||void 0===i?void 0:i.prf)&&void 0!==c?c:{}})});return ye.log("SDK::PasskeyService::preparePasskeyRequestOptions::parsedOptions",!!l),l}preparePasskeyCreationOptions(e){var t,r,s,a,n,o,i,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?cd(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===(o=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===o?void 0:o.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===(i=e.extensions)||void 0===i?void 0:i.prf)&&void 0!==c?c:{}})});return ye.log("SDK::PasskeyService::preparePasskeyCreationOptions::parsedOptions",!!l),l}async addNewPasskey({deviceKeyPair:e,getSignature:t}){try{let r,s;ye.log("SDK::PasskeyService::addNewPasskey: start adding new passkey");try{const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});if(!a.registrationOptions)throw new M({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);ye.log("SDK::PasskeyService::addNewPasskey: about to register passkey credential"),r=await this.authenticator.register({optionsJSON:n}),ye.log("SDK::PasskeyService::addNewPasskey: finished registering passkey credential");const o=await this.handleCredentialsCreationFromPrfExtension(r);ye.log("SDK::PasskeyService::addNewPasskey:: finished deriving credentials key pair",o.publicKey),s=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyRegistrationResponse:r}}),ye.log("SDK::PasskeyService::addNewPasskey:: signInResponse",s);const i=await this.cipher.encrypt({data:e.privateKey,encryptionKey:o.publicKey});return await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:i},passkeyCredential:r}),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:o.prfValue})}catch(a){if(ye.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 M({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);ye.log("SDK::PasskeyService::addNewPasskey::catch: about to authenticate with passkey"),r=await this.authenticator.authenticate({optionsJSON:n}),ye.log("SDK::PasskeyService::addNewPasskey::catch: finished authenticating with passkey"),s=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyAuthenticationResponse:r}}),ye.log("SDK::PasskeyService::addNewPasskey::catch: finished signing in with passkey",{signInResponse:s});const o=await this.handleCredentialsCreationFromPrfExtension(r);ye.log("SDK::PasskeyService::addNewPasskey::catch: finished deriving credentials key pair",o.publicKey);const i=await this.cipher.encrypt({data:e.privateKey,encryptionKey:o.publicKey});return ye.log("SDK::PasskeyService::addNewPasskey::catch: about to store data"),await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:i},passkeyCredential:r}),ye.log("SDK::PasskeyService::addNewPasskey::catch: finished storing data"),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:o.prfValue})}throw a}}catch(e){if(e instanceof M)throw e;throw this.authenticator.handlePasskeyError(e)}}async authenticate({deviceKeyPair:e,challengeResponse:t}){var r,s;try{if(!t.authenticationOptions)throw new M({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,o=Object.assign(Object.assign({},t.authenticationOptions),{extensions:Object.assign(Object.assign({},ad(a.extensions,["credProps"])),{prf:{eval:{first:n}}})}),i=await this.authenticator.authenticate({optionsJSON:o}),c=await this.handleCredentialsCreationFromPrfExtension(i),d=t.signature?t.signature:await this.getDeviceSignature({message:t.message,credentialsKeyPair:c,deviceKeyPair:e}),l=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:t.message,clientAuthPubKey:e.publicKey,signature:d,passkeyAuthenticationResponse:i}}),h=e.decryptedPrivateKey?e.decryptedPrivateKey:e.encryptedDevicePrivateKey?await this.cipher.decrypt({cipherText:e.encryptedDevicePrivateKey,decryptionKey:c.privateKey}):void 0;if(!h)throw new M({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:i}),Object.freeze(Object.assign(Object.assign({},l),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(e instanceof M)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 M({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 M({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});ye.log("SDK::PasskeyService::register:: got challenge",{registrationOptions:t.registrationOptions});const s=this.preparePasskeyCreationOptions(t.registrationOptions);ye.log("SDK::PasskeyService::register:: registering passkey",{parsedOptions:s});const a=await this.authenticator.register({optionsJSON:s});if(ye.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 M({message:"Device is not compatible with this feature. Try using a different authentication method.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});ye.log("SDK::PasskeyService::register:: getting signature",{message:t.message});const{signature:n,message:o}=await this.cipher.sign({message:t.message,signingKey:e.privateKey}),i=await this.request(Ca.signUp,{payload:{externalUserId:this.userId,message:o,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:i,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:d},passkeyCredential:a}),Object.freeze(Object.assign(Object.assign({},i),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(ye.log("SDK::PasskeyService::register::error",{error:e,errorCode:e.code,errorMessage:e.message}),e instanceof M)throw ye.log("SDK::PasskeyService::register::API error detected",{error:e}),e;if(e&&e.code===ie.error||e.code===ce.error||"The authenticator was previously registered."===e.message)throw ye.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 ye.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 o=e.clientExtensionResults;if(ye.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::extensions",o),!(null===(t=o.prf)||void 0===t?void 0:t.enabled)&&!(null===(s=null===(r=o.prf)||void 0===r?void 0:r.results)||void 0===s?void 0:s.first))throw new M({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(ye.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prf is enabled",o.prf.enabled),!(null===(a=o.prf.results)||void 0===a?void 0:a.first))throw new M({message:"PRF extension did not return any results. Cannot proceed with authentication.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});const i=null===(n=o.prf.results)||void 0===n?void 0:n.first;let c;if("string"==typeof i)c=id(i);else if(i instanceof Uint8Array)c=i;else if(i instanceof ArrayBuffer)c=new Uint8Array(i);else if(ArrayBuffer.isView(i))c=new Uint8Array(i.buffer);else if(Array.isArray(i))c=new Uint8Array(i);else{if(!i||"object"!=typeof i)throw new M({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});{const e=i.data;if(Array.isArray(e))c=new Uint8Array(e);else{const e=Object.values(i);if(!e.length||!e.every((e=>"number"==typeof e)))throw new M({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});c=new Uint8Array(e)}}}ye.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prfValue",c);const d=await this.cipher.getCredentialsKeyPair({prfValue:c,authType:exports.AuthType.Passkey});return ye.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::credentials key pair was created",!!d),Object.assign(Object.assign({},d),{prfValue:c})}catch(e){if(e instanceof M)throw e;if(e instanceof Error)throw new M({message:e.message,statusCode:400,errorCode:"sdk_passkey_prf_handling_failed",data:e,cause:e.cause});throw this.authenticator.handlePasskeyError(e)}}}function ld(e){return function(t,r,s){if(!s.value)return;const a=s.value;return s.value=async function(...s){var n,o,i,c,d;const l=this.lockManager,h=e||`${t.constructor.name}:${r}`,p=null!==(o=null===(n=this.options)||void 0===n?void 0:n.environment)&&void 0!==o?o:me,u=null!==(c=null===(i=this.options)||void 0===i?void 0:i.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 hd extends Qc{constructor(e,t={}){super(e,t),this.getUserSalt=this.getUserSalt.bind(this),this.passkeyService=new dd(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&&!Pa(e)||!!t}async refreshAuthTokens(){if(!await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken))throw new M({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 M({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 M({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){ye.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 ye.error("SDK::AuthService::getUserSalt::error",e),e}}async getSignature({deviceAuthKeys:e,walletId:t,passkeyChallengeType:r}){try{ye.debug("SDK::AuthService::getSignature::authType",this.deviceAuthType);const s=this.deviceAuthType===exports.AuthType.Passkey?null!=r?r:exports.PasskeyChallengeType.REGISTRATION:void 0;ye.debug("SDK::AuthService::getSignature::challengeType",s);const a=await this.request(Ca.signatureMessage,{payload:{walletId:t,clientAuthPubKey:e.publicKey,passkeyChallengeType:s}}),{signature:n,hashedMessage:o}=await this.cipher.sign({message:a.message,signingKey:e.privateKey});return Object.freeze(Object.assign(Object.assign({},a),{signature:n,hashedMessage:o,authenticationOptions:a.authenticationOptions,registrationOptions:a.registrationOptions}))}catch(e){throw ye.error("SDK::AuthService::getSignatureMessage::error",e),e}}async signUp(e){ye.info("starting signup");const t=Os();let r;ye.info("key pair generated",!!t);try{const s=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});switch(ye.info("signature has been generated",!!s),this.deviceAuthType){case exports.AuthType.Passkey:ye.info("registering a new passkey"),r=await this.passkeyService.register({deviceKeyPair:t,challengeResponse:s});break;case exports.AuthType.Password:ye.info("signing up with password"),r=await this.handleSignUpWithPassword({signatureMessage:s,deviceKeyPair:t,input:e});break;default:throw new M({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(ye.error("SDK::AuthService::signUp::error",e),e&&e.error===ce.error||e.code===ie.error){ye.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 M({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 ye.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 M({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 ye.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password, please try again."),new M({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(t){const e=ga(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 ye.error("SDK::AuthService::handleSignInWithPassword::error","Device key missing but wallet data exists"),new M({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});ye.info("No device data found, treating as a fresh device and creating a new key pair");n=Os().privateKey}if(!n)throw ye.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new M({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const o=ps(n);await this.storeDeviceKeyPair({deviceAuthKeyPair:{publicKey:o,privateKey:n},credentialsKeyPair:a});const i=await this.getSignature({deviceAuthKeys:{publicKey:o,privateKey:n}}),c=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:i.message,signature:i.signature,clientAuthPubKey:o}});return Object.assign(Object.assign({},c),{signatureMessageResponse:i,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){ye.debug("SDK::AuthService::handleSignInWithPasskey:: using existing key pair");const e=await this.request(Ca.signatureMessage,{payload:{clientAuthPubKey:a,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}});t=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:a,encryptedDevicePrivateKey:ga(s)},challengeResponse:e}),ye.debug("SDK::AuthService::handleSignInWithPasskey:: passkey authentication finished",!!t)}else{if(a||s)throw ye.error("SDK::AuthService::handleSignInWithPasskey::error","Passkey credential missing but device data exists"),new M({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=Os(),t=await this.passkeyService.addNewPasskey({deviceKeyPair:n,getSignature:this.getSignature.bind(this)}),ye.debug("SDK::AuthService::handleSignInWithPasskey:: passkey registration finished",t)}return Object.assign(Object.assign(Object.assign({},t),{prfValue:t.prfValue}),e)}catch(e){throw ye.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 M({message:"Password is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const s=await this.validatePasswordStrength(t.password);if(!s.valid)throw new M({message:s.message||"Invalid password",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const a=await this.request(Ca.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(ye.error("SDK::AuthService::getPasskeyCredentials::error",e),"string"==typeof e)throw new M({message:e,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});if(e&&"object"==typeof e&&"message"in e)throw new M({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(Ca.issueJwtToken);return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,e.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,e.refreshToken),e}catch(e){throw ye.error("SDK::Auth::exchangeClientToken::error",e),e}}}u([ld("signUp"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],hd.prototype,"signUp",null),u([ld("signIn"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],hd.prototype,"signIn",null),u([ld("storeDeviceKeyPair"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],hd.prototype,"storeDeviceKeyPair",null);class pd extends Qc{constructor(e,t={}){super(e,t),this.authService=new hd(e,t),this.userId=e.userId}async handleImportWallet(e,t){var r,s,a,n,o;try{const{signature:o,message:i,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 M({message:"Failed to obtain wallaby auth public key.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if((t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||t.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!t.keyShareOptions)throw new M({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 M({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:t.seedPhrase,encryptionKey:c}),p={reference:t.reference,walletId:t.walletId,message:i,signature:o,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(ed.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 M({message:null!==(o=e.message)&&void 0!==o?o:"Failed to handle importing the wallet",statusCode:e.statusCode,errorCode:e.errorCode,data:e.data,cause:e.cause})}}async handleWalletCreation(e,r){var s,a,n,o,i,c;try{const{signature:i,message:c,hashedMessage:d}=await this.authService.getSignature({deviceAuthKeys:{publicKey:e.publicKey,privateKey:e.privateKey},passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if((r.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||r.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!r.keyShareOptions)throw new M({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=r.keyShareOptions)&&void 0!==s?s:{};if(h&&l&&l<h)throw new M({message:"Number of shares must be greater than or equal to the threshold",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const p={reference:t.v4(),message:c,signature:i,hashedMessage:d,clientAuthPubKey:e.publicKey,returnWalletOption:r.returnWalletOption,numShares:l,threshold:h,wallabyKeepsOne:null!==(n=null===(a=r.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n,walletOwnershipType:null!==(o=r.walletOwnershipType)&&void 0!==o?o:exports.WalletOwnershipType.SingleOwner},u=await this.request(ed.createWithKeyShares,{payload:p});let y;const g=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:r.authenticationOptions.user.clientSalt,password:r.authenticationOptions.password,prfValue:r.authenticationOptions.prfValue});return u.encryptedSeed&&(y=await this.handleSeedPhraseFromResponse({walletId:u.wallet.id,encryptedSeed:u.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:r.storeSeedPhrase,credentialsKeyPair:g})),u.shares&&u.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:u.wallet.id,shares:u.shares,credentialsKeyPair:g,encryptedBackupShare:u.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign(Object.assign({},u),{standardSeedPhrase:y})}catch(e){throw ye.error("SDK::handleWalletCreation::error",e),new M({message:null!==(i=e.message)&&void 0!==i?i:"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 M({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 M({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}),o=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:o,walletId:e}]),[n,o]}catch(e){throw ye.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=ps(r),a=await this.cipher.encrypt({data:n,encryptionKey:t}),o=await this.cipher.encrypt({data:JSON.stringify(a),encryptionKey:s.publicKey});await this.localStorageService.save(exports.V2KeyNames.EncryptedStandardSeedPhrase,o,{walletId:e})}return n}catch(e){throw ye.error("SDK::handleSeedPhraseFromResponse::error",e),e}}async handleRecoverFromSeedPhrase({encryptedSeedPhrase:e,deviceAuthKeys:t}){var r;try{const r=await this.api.wallets.initiateWalletRecovery({externalUserId:this.userId,clientAuthPubKey:t.publicKey}),{signature:s,message:a}=await this.cipher.sign({message:r.signatureMessage,signingKey:t.privateKey});return await this.request(ed.recover,{payload:{externalUserId:this.userId,signature:s,message:a,clientAuthPubKey:t.publicKey,encryptedSeed:e}})}catch(e){throw ye.error("SDK::handleRecoverFromSeedPhrase::error",e),new M({message:null!==(r=e.message)&&void 0!==r?r:"Failed to recover wallet from seed phrase",statusCode:e.statusCode,errorCode:e.errorCode,data:e,cause:e.cause})}}}function ud(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 yd extends Qc{constructor(e,t={}){super(e,t),this.authService=new hd(e,t),this.handlers=new pd(e,t),this.userId=e.userId,this.passkeyService=new dd(e.userId,this.localStorageService,this.request,this.cipher)}async getRateState(e){const t=Date.now(),r=await this.localStorageService.fetch(e),s=r?ga(r):void 0;return!s||t-s.windowStart>yd.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>yd.RATE_LIMIT_MAX)throw new M({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 M({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 M({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const a=ps(s);return await this.handlers.handleWalletCreation({publicKey:a,privateKey:s},e)}catch(e){throw ye.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 M({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 o,i,c;if(!n)throw new M({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=ga(n),h=await this.cipher.decrypt({cipherText:l,decryptionKey:d.privateKey});if(!h)throw new M({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});if(r.keyShares){if(!a)throw new M({message:"You do not have any key shares stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const e=ga(a);o=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=ga(s);if(i=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(i),!c))throw new M({message:"Something went wrong decrypting algorand seed phrase.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed})}else{if(!a)throw new M({message:"You do not have a wallet stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const s=ga(a),n={publicKey:ps(h),privateKey:h},{signature:o,message:d,wallabyAuthPubKey:p}=await this.authService.getSignature({deviceAuthKeys:n,walletId:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),u=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:s,encryptedDevicePrivateKey:l,wallabyPublicKey:p||t.user.wallabyAuthPubKey,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),y=await this.request(ed.retrieveSeedPhrase,{payload:{walletId:e,signature:o,message:d,clientAuthPubKey:n.publicKey,recoveryPubKey:n.publicKey,encryptedShares:[u]}});i=await this.cipher.decrypt({cipherText:y.encryptedSeed,decryptionKey:h}),r.algorandSeedPhrase&&(c=this.getAlgorandSeedPhrase(i))}return{keyShares:r.keyShares&&o?o:void 0,standardSeedPhrase:r.standardSeedPhrase&&i?i:void 0,algorandSeedPhrase:r.algorandSeedPhrase&&c?c:void 0}}catch(e){throw ye.error("SDK::WalletService::export::error",e),e}}async import(e){var r;try{const s=null!==(r=e.reference)&&void 0!==r?r:t.v4(),a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new M({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=ga(a),o=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue}),i=await this.cipher.decrypt({cipherText:n,decryptionKey:o.privateKey});if(!i)throw new M({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ps(i);return await this.handlers.handleImportWallet({publicKey:c,privateKey:i},Object.assign(Object.assign({},e),{reference:s}))}catch(e){throw ye.error("SDK::WalletService::import::error",e),e}}async recover(e){try{const t=e.authenticationOptions.signatureMessageResponse.wallabyAuthPubKey||e.authenticationOptions.user.wallabyAuthPubKey,r=Os(),s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue});let a;if(e.seedPhrase){const n=await la(t,e.seedPhrase);return a=await this.handlers.handleRecoverFromSeedPhrase({encryptedSeedPhrase:n,deviceAuthKeys:{publicKey:r.publicKey,privateKey:r.privateKey}}),e.seedPhrase&&e.returnWalletOption!==exports.ReturnWalletOption.ReturnOnlyEncryptedShares&&await this.handlers.handleSeedPhraseFromResponse({walletId:a.wallet.id,encryptedSeed:la(r.publicKey,e.seedPhrase),devicePrivateKey:r.privateKey,credentialsKeyPair:s,storeSeedPhrase:!0}),a.shares&&a.encryptedBackupShare&&await this.handlers.handleKeySharesFromResponse({walletId:a.wallet.id,shares:a.shares,credentialsKeyPair:s,encryptedBackupShare:a.encryptedBackupShare,devicePrivateKey:r.privateKey}),await this.authService.storeDeviceKeyPair({deviceAuthKeyPair:r,credentialsKeyPair:s}),a}if(e.decryptedShares){if(!e.decryptedShares.length)throw new M({message:"Decrypted shares are required",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const{signature:n,message:o,wallabyAuthPubKey:i}=await this.authService.getSignature({deviceAuthKeys:r,walletId:e.walletId,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),c=i||e.authenticationOptions.user.wallabyAuthPubKey,d=await Promise.all(e.decryptedShares.map((async e=>await this.cipher.encrypt({data:e,encryptionKey:c})))),l=await this.request(ed.retrieveSeedPhrase,{payload:{walletId:e.walletId,signature:n,message:o,clientAuthPubKey:r.publicKey,recoveryPubKey:r.publicKey,encryptedShares:d}}),h=await this.cipher.flipEncryptedData({cipherText:l.encryptedSeed,decryptionKey:r.privateKey,encryptionKey:t});return a=await this.handlers.handleRecoverFromSeedPhrase({encryptedSeedPhrase:h,deviceAuthKeys:{publicKey:r.publicKey,privateKey:r.privateKey}}),a.encryptedSeed&&await this.handlers.handleSeedPhraseFromResponse({walletId:a.wallet.id,encryptedSeed:a.encryptedSeed,devicePrivateKey:r.privateKey,credentialsKeyPair:s,storeSeedPhrase:e.storeSeedPhrase}),a.shares&&a.encryptedBackupShare&&await this.handlers.handleKeySharesFromResponse({walletId:a.wallet.id,shares:a.shares,credentialsKeyPair:s,encryptedBackupShare:a.encryptedBackupShare,devicePrivateKey:r.privateKey}),await this.authService.storeDeviceKeyPair({deviceAuthKeyPair:r,credentialsKeyPair:s}),a}throw new M({message:"Decrypted seed phrase or shares are required to recover the wallet.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter})}catch(e){throw ye.error("SDK::Wallet::recover::error",e),e}}async changePassword({walletId:e,oldPassword:t,newPassword:r}){try{if(await this.recordRateAttempt(exports.V2KeyNames.PasswordResetAttempts)>yd.RATE_LIMIT_MAX)throw new M({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}),o=await this.localStorageService.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e});if(!s||"undefined"===s)throw new M({message:"Could not locate client keys on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=await this.authService.getUserSalt(),c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t,salt:i});if(!c.privateKey)throw new M({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:i});if(!d.publicKey||!d.privateKey)throw new M({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 M({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:ga(a),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,p=n?await this.cipher.flipEncryptedData({cipherText:ga(n),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,u=o?await this.cipher.flipEncryptedData({cipherText:ga(o),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 ye.error("SDK::Wallet::changePassword::error",e),e}}getAlgorandSeedPhrase(t){try{const r=d.mnemonicToSeedSync(t),s=function(t){if(32!==t.length)throw new Error(`Algorand seed must be 32 bytes, got ${t.length}`);const r=e.wordlists.english,s=ud(t).map((e=>r[e])),a=ud(wr(t).subarray(0,2))[0];return[...s,r[a]].join(" ")}(r.slice(0,32));return s}catch(e){throw ye.error("SDK::Wallet::getAlgorandSeedPhrase::error",e),new M({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 M({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=ga(a);this.deviceAuthType===exports.AuthType.Password&&e.authenticationOptions.password&&await this.migrateToV2Safe({password:e.authenticationOptions.password,walletId:e.walletId});const o=await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare,{walletId:t});if(!o)throw new M({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 i=ga(o),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 M({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});return{walletId:t,backupUrl:r,encryptedBackupShare:ga(await this.cipher.decrypt({cipherText:i,decryptionKey:c.privateKey}))}}async addNewDevice(e){var t;try{const r=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!r)throw new M({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 M({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:ps(a),o=await this.authService.getSignature({deviceAuthKeys:{privateKey:a,publicKey:n},walletId:e.walletId,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),i=await this.request(ed.addNewDevice,{payload:{walletId:e.walletId,clientAuthPubKey:n,signature:o.signature,message:o.message,wallabyAuthPubKey:o.wallabyAuthPubKey,encryptedBackupShare:e.encryptedBackupShare}});return await this.handlers.handleKeySharesFromResponse({walletId:e.walletId,shares:[i.share],credentialsKeyPair:s,encryptedBackupShare:e.encryptedBackupShare,devicePrivateKey:a}),{success:!0,reference:i.reference}}catch(e){throw ye.error("SDK::Wallet::backupKeyShare::error",e),e}}async generateWalletAddresses(e){const{walletId:t}=e;if(!t)throw new M({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(ed.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 ye.error("SDK::Wallet::generateWalletAddresses::error",e),e}}async migrateToV2Safe({password:e,walletId:t}){try{await this.handleUpdateToV2({password:e,walletId:t})}catch(e){throw ye.error("SDK::WalletService::migrateToV2Safe::error",e),new M({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 ye.error("SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material",e),new M({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 M({message:"Password is required for migration to v2",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const a=this.version,n=await this.localStorageService.fetch(exports.V2KeyNames.MigrationVersion),o=await this.localStorageService.fetch(exports.V2KeyNames.LastMigratedAt);if(ye.info("SDK::WalletService::handleUpdateToV2::starting migration check",{timestamp:new Date(r).toISOString(),walletId:t.substring(0,8)+"...",lastMigratedAt:o,currentSdkVersion:a,sdkMigrationVersion:n}),o&&"never"!==o&&n)return void ye.info("SDK::WalletService::handleUpdateToV2::Migration already completed successfully, skipping",{migratedVersion:n,migratedAt:o});const i=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(i&&(c||d))try{await this.cipher.decrypt({cipherText:ga(i),decryptionKey:h.privateKey});const t=c||d;return await this.cipher.displayStoredData({storedEncryptedData:ga(t),encryptedDevicePrivateKey:ga(i),options:{authType:exports.AuthType.Password,password:e,salt:l}}),ye.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,a)}catch(e){ye.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.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`),g=await this.localStorageService.getDecryptedV1PrivateKey(e);if(y&&g){this.assertValidDeviceKey(g),ye.info("SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration",{storageFormat:"legacy"});try{const t=ga(s.AES.decrypt(y,`${l}${e}`).toString(s.enc.Utf8));if(p=ha(g,t),u=g,!p)throw new M({message:"Failed to decrypt legacy seed phrase items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});ye.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted legacy items")}catch(e){throw ye.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt legacy items",e),new M({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)return ye.info("SDK::WalletService::handleUpdateToV2::No legacy or V1 items found to migrate"),void ye.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),ye.info("SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration",{storageFormat:"v1",validPrivateKey:!!u});try{if(ye.log("Attempting to decrypt V1 items during migration..."),ye.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 M({message:"Failed to decrypt V1 items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});ye.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted V1 items")}catch(e){throw ye.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt V1 items",e),new M({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}if(p&&u){ye.info("SDK::WalletService::handleUpdateToV2::Initiating wallet recovery for V2 migration"),ye.info("SDK::WalletService::handleUpdateToV2::Migration data prepared"),ye.info("SDK::WalletService::handleUpdateToV2::Seed phrase available:",!!p);const e=ps(u),s=await this.authService.getSignature({deviceAuthKeys:{publicKey:e,privateKey:u},walletId:t}),a=await this.request(Ca.signIn,{payload:{externalUserId:this.userId,message:s.message,signature:s.signature,clientAuthPubKey:e}}),n=await this.cipher.encrypt({data:u,encryptionKey:h.publicKey}),o=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:o,walletId:t},{key:exports.V2KeyNames.EncryptedDevicePrivateKey,value:n}]),ye.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 M({message:"Decrypted data required for migration is missing, operation cannot be completed.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}catch(e){throw ye.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}),o=t&&!s;return await this.api.wallets.verifyAccess({message:a.message,signature:a.signature,clientAuthPubKey:n,encryptedSeed:o?t:void 0,encryptedShares:o?void 0:r,walletId:e.walletId})}catch(e){throw ye.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 M({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}),i=await this.cipher.decrypt({cipherText:JSON.parse(n),decryptionKey:o.privateKey});if(!i)throw new M({message:"Credentials are wrong, please pass the correct credentials.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ps(i),d=await this.authService.getSignature({deviceAuthKeys:{publicKey:c,privateKey:i},walletId:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),l=d.wallabyAuthPubKey||e.user.wallabyAuthPubKey,h=[];let p;const u=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(u){const e=ga(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 M({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 o=ga(e);p=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:o,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 r=!1;try{const s=await this.localStorageService.fetch(exports.V2KeyNames.CredentialConversionInProgress),a=s?ga(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&&ye.info("SDK::WalletService::convertToPasskey::resuming interrupted conversion");const n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),o=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:e.walletId}),i=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 ye.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password"),new M({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(n){ye.log("SDK::WalletService::convertToPasskey::Decrypting v2 device private key with password-derived key");const e=ga(n);h=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}else ye.log("SDK::WalletService::convertToPasskey::No encrypted device private key found, checking for v1 format"),h=await this.localStorageService.getDecryptedV1PrivateKey(e.password);if(!h)throw ye.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new M({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const p=ps(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)});r=!0;const y=u.prfValue;if(!(y&&y instanceof Uint8Array&&0!==y.length))throw ye.error("SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array"),new M({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 g,f,m;if(ye.log("SDK::WalletService::convertToPasskey::Received authentication response",!!u),o&&n)try{g=await this.cipher.displayStoredData({storedEncryptedData:ga(o),encryptedDevicePrivateKey:ga(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){ye.error("SDK::WalletService::convertToPasskey::seed_decryption_error",e)}if(!g)try{g=await this.localStorageService.getV1DecryptedSeedPhrase(e.password,d)}catch(e){ye.error("SDK::WalletService::convertToPasskey::v1_seed_decryption_error",e)}if(i&&n)try{const t=ga(i);f=await this.cipher.displayStoredData({storedEncryptedData:t,encryptedDevicePrivateKey:ga(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){ye.error("SDK::WalletService::convertToPasskey::primary_share_decryption_error",e)}if(c)try{const e=ga(c);m=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}catch(e){ye.error("SDK::WalletService::convertToPasskey::backup_share_decryption_error",e)}if(!g&&!(!!f||!!m))throw new M({message:"Seed phrase or key shares on this device could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});if(g&&!f)return ye.info("SDK::WalletService::convertToPasskey::No primary share found, importing wallet"),await this.handlers.handleImportWallet({publicKey:p,privateKey:h},{authenticationOptions:u,seedPhrase:g,storeSeedPhrase:!1,returnWalletOption:exports.ReturnWalletOption.ReturnOnlyEncryptedShares,walletId:e.walletId,reference:t.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}]),ye.info("SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed"),{authentication:u,seedPhrase:g};const w=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Passkey,prfValue:y}),v=[];if(f){const t=await this.cipher.doubleEncrypt({decryptedData:f,credentialsKeyPair:w,deviceKeyPair:{publicKey:p,privateKey:h}}),r=await this.cipher.decrypt({cipherText:t,decryptionKey:w.privateKey});if((r?await this.cipher.decrypt({cipherText:ga(r),decryptionKey:h}):null)!==f)throw new M({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(m){const t=await this.cipher.encrypt({data:m,encryptionKey:w.publicKey});v.push({key:exports.V2KeyNames.BackupDeviceKeyShare,value:t,walletId:e.walletId})}for(const e of v)await this.assertRoundTrip(e.value,w.privateKey,e.key);if(await this.localStorageService.commitBatch(v,[...o?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId}]:[],{key:exports.V2KeyNames.CredentialConversionInProgress}]),o&&ye.info("SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey"),!g&&f){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}),n=await this.cipher.encrypt({data:f,encryptionKey:a||u.user.wallabyAuthPubKey}),o=await this.request(ed.retrieveSeedPhrase,{payload:{walletId:e.walletId,signature:r,message:s,clientAuthPubKey:t.publicKey,recoveryPubKey:t.publicKey,encryptedShares:[n]}});g=await this.cipher.decrypt({cipherText:o.encryptedSeed,decryptionKey:h})}if(!g)throw new M({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:g}}catch(e){throw ye.error("SDK::WalletService::convertToPasskey::error",e),r||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 M({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})}}}yd.RATE_LIMIT_MAX=5,yd.RATE_LIMIT_WINDOW_MS=18e5,u([ld("create"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"create",null),u([ld("import"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"import",null),u([ld("recover"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"recover",null),u([ld("credential-rewrap"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"changePassword",null),u([ld("migrateToV2"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"handleUpdateToV2",null),u([ld("credential-rewrap"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],yd.prototype,"convertToPasskey",null);class gd extends Qc{constructor(e,t={}){super(e,t),this.userId=e.userId,this.walletService=new yd(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 M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.getTokenBalance,{payload:{address:e,assetSymbol:t,chainName:s,tokenStandard:r}})}catch(e){throw ye.error("SDK::WalletDataService::getTokenBalance::error",e),e}}async getMultiTokenBalances({walletId:e,tokensAndAddressesList:t}){try{if(!t.length)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.getMultiTokenBalances,{payload:{assets:t,walletId:e}})}catch(e){throw ye.error("SDK::WalletDataService::getMultiTokenBalances::error",e),e}}async getWalletBalances({walletId:e}){try{if(!e)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.getWalletBalances,{payload:{walletId:e}})}catch(e){throw ye.error("SDK::WalletDataService::getWalletBalances::error",e),e}}async getUserAssets({userId:e,queryOptions:t}){try{if(!e)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.getUserAssets,{payload:{userId:e},queryParams:t})}catch(e){throw ye.error("SDK::WalletDataService::getUserAssets::error",e),e}}async getUserWallets({userId:e,queryOptions:t}){try{return await this.request(ed.getUserWallets,{payload:{userId:e},queryParams:t})}catch(e){throw ye.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 M({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(ed.getWalletAssets,{payload:{walletId:e},queryParams:t})}catch(e){throw ye.error("SDK::WalletDataService::getWalletAssets::error",e),e}}async addTokenToWallet({assetConfigId:e,walletId:t,userId:r,config:s,authenticationOptions:a}){try{if(!t)throw new M({message:"Wallet ID is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!e&&!s)throw new M({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(ed.addTokenToWallet,{payload:Object.assign({assetConfigId:e,walletId:t,userId:r||void 0,config:s},n)})}catch(e){throw ye.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 M({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 M({message:`Wallet address is not present for blockchain: ${n}`,statusCode:400,errorCode:"sdk_wallet_address_not_found"})}catch(e){throw ye.error("SDK::WalletDataService::addNewChainAndTokenToWallet::error",e),e}}async updateAsset(e){var{configId:t,walletId:r}=e,s=p(e,["configId","walletId"]);try{if(!t||!r)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ed.updateAsset,{payload:Object.assign({configId:t,walletId:r},s)})}catch(e){throw ye.error("SDK::WalletDataService::updateAsset::error",e),e}}}class fd extends Qc{constructor(e,t={}){super(e,t),this.getDecryptedPrivateKey=async e=>{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return;const r=s.AES.decrypt(t,e).toString(s.enc.Utf8);return""!==r?r:void 0},this.decryptDevicePrivateKey=({encryptedPrivateKey:e,password:t})=>{const r=s.AES.decrypt(e,t).toString(s.enc.Utf8);return""!==r?r:void 0},this.auth=new hd(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 a=`${r}${e}`,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase);if(!n)throw new Error("Seed phrase could not be found");const o=ga(s.AES.decrypt(n,a).toString(s.enc.Utf8)),i=this.decryptDevicePrivateKey({encryptedPrivateKey:null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey))&&void 0!==t?t:"",password:e});if(!i)throw ye.error("SDK::Utils::decryptSeedPhrase::devicePrivateKey: Device private key could not be decrypted"),new Error("Device private key could not be decrypted");return await ha(i,o)}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 ye.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 ye.error("SDK::Utils::validatePassword::error",e),{valid:!1,message:"Password is incorrect."}}}}class md extends Qc{constructor(e,t={}){super(e,t)}}class wd extends Qc{constructor(e,t={}){super(e,t),this.authService=new hd(e,t),this.walletService=new yd(e,t)}async getQuote(e){try{const{walletId:t,fromAssetConfigId:r,toAssetConfigId:s,fromAmount:a,toAmount:n,slippage:o}=e;if(!t||!r||!s)throw new M({message:"Missing required parameters: walletId, fromAssetConfigId, and toAssetConfigId",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!a&&!n)throw new M({message:"Either fromAmount or toAmount must be provided",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(a&&n)throw new M({message:"Only one of fromAmount or toAmount may be provided, not both",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const i={walletId:t},c=Object.assign(Object.assign(Object.assign({fromAssetConfigId:r,toAssetConfigId:s},a&&{fromAmount:a}),n&&{toAmount:n}),null!=o&&{slippage:o});return await this.request(Object.assign(Object.assign({},sd.getQuote),{fullPath:sd.getQuote.fullPath(i)}),{payload:c})}catch(e){throw ye.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:o,hasShares:i}=await this.prepareSwapAuth(r,e);let c;if(n)c=await this.request(Object.assign(Object.assign({},sd.executeSwap),{fullPath:sd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedSeed:n}});else{if(!i)throw new M({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({},sd.executeSwap),{fullPath:sd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedShares:o}})}return c}catch(e){throw ye.error("SDK::Swap::executeSwap::error",e),e}}async getSwaps({walletId:e,queryParams:t}){try{if(!e)throw new M({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({},sd.getSwaps),{fullPath:sd.getSwaps.fullPath(r)}),{queryParams:t})}catch(e){throw ye.error("SDK::Swap::getSwaps::error",e),e}}async prepareSwapAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,o=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!o)throw new M({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:i}),d=await this.cipher.decrypt({cipherText:JSON.parse(o),decryptionKey:c.privateKey});if(!d)throw new M({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ps(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||e.user.wallabyAuthPubKey,u=[];let y;const g=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(g){const e=ga(g),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}});u.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new M({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=ga(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:u,hasShares:u.length>0})}}u([ld("executeSwap"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],wd.prototype,"executeSwap",null);class vd extends Qc{constructor(e,t={}){super(e,t)}async getSupportedBlockchains(e){try{return(await this.request(td.getSupportedBlockchains,{queryParams:void 0!==(null==e?void 0:e.supportSwaps)?{supportSwaps:e.supportSwaps}:void 0})).chains}catch(e){throw ye.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 M({message:`${e} does not support contract addresses.`,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});case exports.BlockchainName.Sui:if(r&&t)throw new M({message:"You can only provide either suiObjectId or contractAddress",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(t)throw new M({message:"You can only provide suiObjectId for SUI blockchain",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(!r)throw new M({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 M({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(td.fetchTokenInfo,{queryParams:Object.assign({chainName:e,tokenContractAddress:a},n?{assetSymbol:n}:{})})}catch(e){throw ye.error("SDK::Wallet::fetchTokenInfo::error",e),e}}async getSupportedTokens(e){try{const t={};if(void 0!==(null==e?void 0:e.supportsSwaps)&&(t.supportsSwaps=e.supportsSwaps),void 0!==(null==e?void 0:e.search)){if(e.search.length<3)throw new M({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});t.search=e.search}void 0!==(null==e?void 0:e.chainName)&&(t.chainName=e.chainName),void 0!==(null==e?void 0:e.contractAddress)&&(t.contractAddress=e.contractAddress);return(await this.request(td.getSupportedTokens,{queryParams:Object.keys(t).length>0?t:void 0})).assets}catch(e){throw ye.error("SDK::System::getSupportedTokens::error",e),e}}async getUserData(e){try{return(await this.request(td.getUserData,{payload:{userId:e}})).user}catch(e){throw ye.error("SDK::System::getUserData::error",e),e}}async getUserByExternalUserId(e){try{return(await this.request(td.getUserByExternalUserId,{payload:{externalUserId:e}})).user}catch(e){throw ye.error("SDK::System::getUserByExternalUserId::error",e),e}}}class Sd extends Qc{constructor(e,t={}){super(e,t),this.authService=new hd(e,t),this.walletService=new yd(e,t),this.userId=e.userId}async estimateFee({originAddress:e,recipientAddress:t,amount:r,transactionType:s,token:a}){try{return await this.request(rd.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 ye.error("SDK::Transactions::estimateFee::error",e),e}}async getTransactionStatus({transactionHash:e,reference:t,blockchain:r}){try{return await this.request(rd.getTransaction,{payload:{transactionHash:e,transactionReference:t,chain:r.toString().toUpperCase()}})}catch(e){throw ye.error("SDK::Transactions::getTransactionStatus::error",e),e}}async getTransactions(e){try{return await this.request(rd.getTransactions,{queryParams:e})}catch(e){throw ye.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 M({message:"Either assetId or both contractAddress and blockchainName must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(rd.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 ye.error("SDK::Transactions::getRestriction::error",e),e}}async transfer({originAddress:e,recipientAddress:r,amount:s,assetId:a,walletId:n,reference:o,authenticationOptions:i,memo:c,transactionType:d}){try{this.deviceAuthType===exports.AuthType.Password&&i.password&&await this.walletService.migrateToV2Safe({password:i.password,walletId:n});const{deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:p,sharesEncryptedWithWallabyPubKey:u,hasShares:y}=await this.prepareTransactionAuth(i,n);let g;if(p)g=await this.request(rd.transfer,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedSeed:p,originAddress:e,recipientAddress:r,assetId:a,amount:s,reference:o||t.v4(),memo:c,transactionType:d}});else{if(!y)throw new M({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});g=await this.request(rd.transferWithShares,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedShares:u,originAddress:e,recipientAddress:r,assetId:a,amount:s,reference:o||t.v4(),memo:c,transactionType:d}})}return g}catch(e){throw ye.error("SDK::Transactions::transfer::error",e),e}}async createAllowance({authenticationOptions:e,walletId:t,ownerAddress:r,spenderAddress:s,amount:a,assetId:n,suiObjectId:o,contractAddress:i,chainName:c,assetSymbol:d,reference:l,memo:h,transactionType:p}){try{if(!(o||i||n||d||c))throw new M({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 M({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:g,sharesEncryptedWithWallabyPubKey:f,hasShares:m}=await this.prepareTransactionAuth(e,t),{message:w,signature:v}=y;if(!g&&!m)throw new Error("No valid seed option found on this device.");const S=Object.assign({message:w,signature:v,walletId:t,clientAuthPubKey:u,ownerAddress:r,spenderAddress:s,chainName:c,assetSymbol:d,amount:a,assetId:n,contractAddress:null!=i?i:o,reference:l,memo:h,transactionType:p},m?{encryptedShares:f}:{encryptedSeed:g});return await this.request(rd.createAllowance,{payload:S})}catch(e){throw ye.error("SDK::Transactions::createAllowance::error",e),e}}async getPendingTransactions({walletId:e,chainName:t}){try{return await this.request(rd.getPendingTransactions,{queryParams:{walletId:e,chainName:t}})}catch(e){throw ye.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:o,signatureMessage:i,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(rd.confirmPendingTransaction,{payload:{message:i.message,signature:i.signature,clientAuthPubKey:o,encryptedShares:d,encryptedSeed:c,id:e,choice:t,symbol:r,chainName:s,walletId:a}})}catch(e){throw ye.error("SDK::Transactions::transfer::error",e),e}}async prepareTransactionAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,o=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!o)throw new M({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:i}),d=await this.cipher.decrypt({cipherText:JSON.parse(o),decryptionKey:c.privateKey});if(!d)throw new M({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ps(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||e.user.wallabyAuthPubKey,u=[];let y;const g=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(g){const e=ga(g),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}});u.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new M({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=ga(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:p,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:u,hasShares:u.length>0})}}u([ld("transaction-restriction-message"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],Sd.prototype,"getRestriction",null),u([ld("transfer"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],Sd.prototype,"transfer",null),u([ld("createAllowance"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],Sd.prototype,"createAllowance",null),u([ld("confirmPendingTransaction"),y("design:type",Function),y("design:paramtypes",[Object]),y("design:returntype",Promise)],Sd.prototype,"resolvePendingTransaction",null);exports.AndroidVersionNotSupportedError=F,exports.AuthenticatorGeneralError=ae,exports.AuthenticatorMissingDiscoverableCredentialSupportError=ne,exports.AuthenticatorMissingUserVerificationSupportError=oe,exports.AuthenticatorNoSupportedPubKeyCredParamsAlgError=de,exports.AuthenticatorNotRegisteredError={error:"ERROR_AUTHENTICATOR_NOT_REGISTERED",message:"Authenticator is not registered."},exports.AuthenticatorPreviouslyRegisteredError=ie,exports.AutoRegisterUserVerificationFailureError=le,exports.BadConfiguration=Y,exports.CeremonyAbortedError=Q,exports.IOSVersionNotSupportedError=V,exports.InterruptedError=Z,exports.InvalidChallengeError=$,exports.InvalidDomainError=ee,exports.InvalidRpIdError=te,exports.InvalidStateError=ce,exports.InvalidUserIdError=J,exports.InvalidUserIdLengthError=re,exports.MalformedPubKeyCredParamsError=se,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=pe,exports.PassthroughSeeCausePropertyError=he,exports.RequestFailedError=G,exports.TimeoutError=X,exports.UnknownError=W,exports.UserCancelledError=H,exports.Wallaby=class{constructor(e,t={}){this.wallet=new yd(e,t),this.walletData=new gd(e,t),this.utils=new fd(e,t),this.auth=new hd(e,t),this.system=new vd(e,t),this.transactions=new Sd(e,t),this.swap=new wd(e,t),this.httpApi=new md(e,t)}get version(){return be}},exports.WallabyApiClient=Na,exports.WallabyError=M,exports.WallabyHttpClient=Ra,exports.createIdentity=Os,exports.decryptWithPrivateKey=ha,exports.encryptWithPublicKey=la,exports.hash=ya,exports.keccak256=pa,exports.publicKeyByPrivateKey=ps,exports.recoverPublicKey=(e,t)=>{const r=Rt(e),s=r.substring(0,r.length-2),a="1c"===r.slice(-2)?1:0;let n=Le(ua(Kt(s),a,Kt(Rt(t)),!1));return n=n.slice(2),n},exports.sign=Ks;//# sourceMappingURL=index.cjs.js.map