wallaby-cash 3.15.2 → 3.16.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/api.cjs +1 -1
- package/dist/api.js +1 -1
- package/dist/api.mjs +1 -1
- package/dist/eth-crypto-utils/util.d.ts +6 -0
- package/dist/generated/api.d.ts +114 -15
- package/dist/helpers/bytes.d.ts +37 -0
- package/dist/helpers/pem-to-der.d.ts +1 -0
- package/dist/index.cjs +12 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +12 -10
- package/dist/index.mjs.map +1 -1
- package/dist/lib/attestation/aws-root-cert.d.ts +19 -0
- package/dist/lib/attestation/cbor.d.ts +106 -0
- package/dist/lib/attestation/cose.d.ts +70 -0
- package/dist/lib/attestation/crypto.d.ts +36 -0
- package/dist/lib/attestation/errors.d.ts +44 -0
- package/dist/lib/attestation/index.d.ts +7 -0
- package/dist/lib/attestation/pinned-measurements.d.ts +37 -0
- package/dist/lib/attestation/verify.d.ts +29 -0
- package/dist/lib/attestation/x509.d.ts +78 -0
- package/dist/package.json +6 -4
- package/dist/r/oci-DzAn0PLg.js +1 -0
- package/dist/r/oci-DzAn0PLg.js.map +1 -0
- package/dist/r/oci-DzAn0PLg.mjs +1 -0
- package/dist/r/oci-DzAn0PLg.mjs.map +1 -0
- package/dist/r/oci-al0xoD5i.cjs +1 -0
- package/dist/r/oci-al0xoD5i.cjs.map +1 -0
- package/dist/routes/auth.d.ts +10 -0
- package/dist/types/attestation.d.ts +58 -0
- package/dist/types/index.d.ts +1 -0
- package/package.json +6 -4
- package/dist/r/oci-3T3HuAKO.cjs +0 -1
- package/dist/r/oci-3T3HuAKO.cjs.map +0 -1
- package/dist/r/oci-DsJU4c2w.js +0 -1
- package/dist/r/oci-DsJU4c2w.js.map +0 -1
- package/dist/r/oci-DsJU4c2w.mjs +0 -1
- package/dist/r/oci-DsJU4c2w.mjs.map +0 -1
- package/dist/verification/polymesh/bytes.d.ts +0 -4
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./r/oci-3T3HuAKO.cjs"),t=require("bip39"),r=require("uuid"),s=require("loglevel"),a=require("crypto-js"),n=require("jwt-decode"),i=require("@simplewebauthn/browser"),o=require("js-base64"),c=require("scale-ts"),d=e=>e&&"object"==typeof e&&"default"in e?e:{default:e};function l(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const h=l(t),u=d(s),p=l(i);var y,f,g,w,m,v,S,_,A,E,b,I,P,T,k,C,x,K,O,N,R,D,L,U,B,q;exports.PasskeyChallengeType=void 0,(y=exports.PasskeyChallengeType||(exports.PasskeyChallengeType={})).REGISTRATION="webauthn.create",y.AUTHENTICATION="webauthn.get",exports.PublicKeyCredentialAlgorithm=void 0,(f=exports.PublicKeyCredentialAlgorithm||(exports.PublicKeyCredentialAlgorithm={}))[f.RS256=-257]="RS256",f[f.ES256=-7]="ES256",exports.TransportEnum=void 0,(g=exports.TransportEnum||(exports.TransportEnum={})).Usb="usb",g.Nfc="nfc",g.Ble="ble",g.Internal="internal",g.Hybrid="hybrid";class V extends Error{constructor(e){var t;const{message:r,statusCode:s,errorCode:a,kind:n,data:i,cause:o,onError:c}=e;super(r),this.name="WallabyError",this.status=s,this.errorCode=a,this.kind=null!=n?n:V.inferKind(s,a),this.cause=o,this.onError=c,this.data=i,Object.setPrototypeOf(this,new.target.prototype),null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,new.target)}static isWallabyError(e){return e instanceof V}static inferKind(e,t){return 0===e?"network":"device_storage_unsupported"===t||(null==t?void 0:t.startsWith("sdk_"))?"sdk":"api"}toJSON(){return{name:this.name,message:this.message,kind:this.kind,status:this.status,errorCode:this.errorCode,data:this.data}}}exports.UserAssetSource=void 0,(w=exports.UserAssetSource||(exports.UserAssetSource={})).Merchant="merchant",w.User="user",w.republic="republic",exports.AssetConfigStatus=void 0,(m=exports.AssetConfigStatus||(exports.AssetConfigStatus={})).Active="active",m.Inactive="inactive",exports.AssetType=void 0,(v=exports.AssetType||(exports.AssetType={})).Coin="COIN",v.Token="TOKEN",exports.OwnershipType=void 0,(S=exports.OwnershipType||(exports.OwnershipType={})).SingleOwner="SINGLE_OWNER",S.MultiSig="MULTI_SIG",exports.TokenStandard=void 0,(_=exports.TokenStandard||(exports.TokenStandard={})).Erc20="ERC_20",_.Erc1404="ERC_1404",_.Arc20="ARC_20",_.Arc1404="ARC_1404",_.Mrc20="MRC_20",_.Bep20="BEP_20",_.AlgoStandard="ALGO_STANDARD",_.AlgoApp="ALGO_APP",_.TokenFactory="TOKEN_FACTORY",_.SeiErc20="SEI_ERC_20",_.AptFA="APT_FUNGIBLE_ASSET",exports.AddressType=void 0,(A=exports.AddressType||(exports.AddressType={})).Segwit="SEGWIT",A.Legacy="LEGACY",A.Default="DEFAULT",exports.BlockchainStatus=void 0,(E=exports.BlockchainStatus||(exports.BlockchainStatus={})).Up="UP",E.Down="DOWN",exports.BlockchainSlip44=void 0,(b=exports.BlockchainSlip44||(exports.BlockchainSlip44={}))[b.BTC=0]="BTC",b[b.ETH=60]="ETH",b[b.ALGO=283]="ALGO",b[b.AVAX=9e3]="AVAX",b[b.MATIC=966]="MATIC",b[b.BSC=519]="BSC",b[b.BASE=8453]="BASE",b[b.SUI=784]="SUI",b[b.INJ=2525]="INJ",b[b.SEI=19000118]="SEI",b[b.APT=637]="APT",b[b.HBAR=3030]="HBAR",b[b.POLYX=595]="POLYX",exports.BlockchainName=void 0,(I=exports.BlockchainName||(exports.BlockchainName={})).Algorand="ALGORAND",I.Aptos="APTOS",I.Avalanche="AVALANCHE",I.Base="BASE",I.Bitcoin="BITCOIN",I.Bsc="BSC",I.Canton="CANTON",I.Ethereum="ETHEREUM",I.Hedera="HEDERA",I.Injective="INJECTIVE",I.Polygon="POLYGON",I.Polymesh="POLYMESH",I.Sei="SEI",I.Sui="SUI",I.Solana="SOLANA",exports.RequestMethod=void 0,(P=exports.RequestMethod||(exports.RequestMethod={})).Post="POST",P.Get="GET",P.Put="PUT",P.Delete="DELETE",exports.ApiKeyStatus=void 0,(T=exports.ApiKeyStatus||(exports.ApiKeyStatus={})).Active="active",T.Inactive="inactive",exports.TransactionEntryType=void 0,(k=exports.TransactionEntryType||(exports.TransactionEntryType={})).INCOMING="INCOMING",k.OUTGOING="OUTGOING",k.UNKNOWN="UNKNOWN",exports.KeyTypeName=void 0,(C=exports.KeyTypeName||(exports.KeyTypeName={})).WallabyShare="wallaby_share",C.OwnerMainDeviceShare="owner_main_device_share",C.OwnerBackupDeviceShare="owner_backup_device_share",exports.SeedPhraseType=void 0,(x=exports.SeedPhraseType||(exports.SeedPhraseType={})).Standard="standard",x.Algorand="algorand",exports.WalletAddressTypeName=void 0,(K=exports.WalletAddressTypeName||(exports.WalletAddressTypeName={})).BTC_MAINNET_SEGWIT="BTC:MAINNET:SEGWIT",K.BTC_MAINNET_LEGACY="BTC:MAINNET:LEGACY",K.BTC_TESTNET_SEGWIT="BTC:TESTNET:SEGWIT",K.BTC_TESTNET_LEGACY="BTC:TESTNET:LEGACY",K.ETH="ETH:ALL:DEFAULT",K.ALGO="ALGO:ALL:DEFAULT",K.SUI="SUI:ALL:DEFAULT",K.INJ="INJ:ALL:DEFAULT",K.APT="APT:ALL:DEFAULT",K.POLYX="POLYX:ALL:DEFAULT",K.BSC="BSC:ALL:DEFAULT",K.AVAX="AVAX:ALL:DEFAULT",K.MATIC="MATIC:ALL:DEFAULT",K.BASE="BASE:ALL:DEFAULT",K.SEI="SEI:ALL:DEFAULT",K.HBAR="HBAR:ALL:DEFAULT",K.CC="CC:ALL:DEFAULT",exports.ReturnWalletOption=void 0,(O=exports.ReturnWalletOption||(exports.ReturnWalletOption={})).ReturnOnlyEncryptedShares="RETURN_ONLY_ENCRYPTED_SHARES",O.ReturnOnlyEncryptedSeedPhrase="RETURN_ONLY_ENCRYPTED_SEED_PHRASE",O.ReturnBothEncryptedSharesAndSeed="RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED",exports.WalletOwnershipType=void 0,(N=exports.WalletOwnershipType||(exports.WalletOwnershipType={})).SingleOwner="SINGLE_OWNER",N.MultiOwner="MULTI_OWNER",exports.AuthType=void 0,(R=exports.AuthType||(exports.AuthType={})).Password="password",R.Passkey="passkey",exports.LocalStorageItems=void 0,(D=exports.LocalStorageItems||(exports.LocalStorageItems={})).AccessToken="access-token",D.RefreshToken="refresh-token",D.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",D.EncryptedKeyShares="encrypted-key-shares",D.PrimaryDeviceKeyShare="primary-device-key-share",D.BackupDeviceKeyShare="backup-device-key-share",D.EncryptedShare="encrypted-share",D.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",D.EncryptedDevicePrivateKey="encrypted-private-key",D.ClientAuthPublicKey="client-auth-pub-key",D.ClientAuthToken="republic-jwt",D.PasskeyCredential="pass-key-credential",D.Blob="blob",exports.LegacyKeyNames=void 0,(L=exports.LegacyKeyNames||(exports.LegacyKeyNames={})).EncryptedPrivateKey="encryptedPrivateKey",L.WallabyAuthPubKey="wallabyAuthPubKey",L.EncryptedAlgorandSeed="encryptedAlgorandSeed",L.EncryptedSeed="encryptedSeed",L.ClientAuthToken="republic_jwt",L.AccessToken="accessToken",exports.V1KeyNames=void 0,(U=exports.V1KeyNames||(exports.V1KeyNames={})).AccessToken="access-token",U.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",U.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",U.EncryptedDevicePrivateKey="encrypted-private-key",U.ClientAuthPublicKey="client-auth-pub-key",U.WallabyAuthPubKey="wallaby-auth-pub-key",U.ClientAuthToken="republic-jwt",exports.V2KeyNames=void 0,(B=exports.V2KeyNames||(exports.V2KeyNames={})).AccessToken="access-token",B.RefreshToken="refresh-token",B.BackupDeviceKeyShare="backup-device-key-share",B.ClientAuthPublicKey="client-auth-pub-key",B.ClientAuthToken="republic-jwt",B.EncryptedDevicePrivateKey="encrypted-private-key",B.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",B.PasskeyCredential="pass-key-credential",B.PrimaryDeviceKeyShare="primary-device-key-share",B.WallabyAuthPubKey="wallaby-auth-pub-key",B.MigrationVersion="wsdk_migrated_with_version",B.LastMigratedAt="wsdk_last_migrated_at",B.PasswordResetAttempts="wsdk_password_reset_attempts",B.MigrationAttempts="wsdk_migration_attempts",B.CredentialConversionInProgress="credential-conversion-in-progress",B.PendingCommit="pending-commit",B.LegacySeedClaimedWalletId="wsdk_legacy_seed_claimed_wallet_id",exports.ErrorResponseCodes=void 0,(q=exports.ErrorResponseCodes||(exports.ErrorResponseCodes={})).unknown_error="unknown_error",q.internal_server_error="internal_server_error",q.request_payload_missing="request_payload_missing",q.request_payload_wrong_format="request_payload_wrong_format",q.auth_api_key_invalid="auth_api_key_invalid",q.auth_api_key_not_active="auth_api_key_not_active",q.auth_api_key_pub_key_not_set="auth_api_key_pub_key_not_set",q.auth_api_key_pub_key_already_in_use="auth_api_key_pub_key_already_in_use",q.auth_api_key_not_provided="auth_api_key_not_provided",q.auth_api_key_not_found="auth_api_key_not_found",q.auth_origin_not_allowed="auth_origin_not_allowed",q.auth_api_jwt_invalid="auth_api_jwt_invalid",q.auth_api_jwt_not_active="auth_api_jwt_not_active",q.auth_api_jwt_not_provided="auth_api_jwt_not_provided",q.auth_api_jwt_expired="auth_api_jwt_expired",q.auth_api_unauthorized="auth_api_unauthorized",q.auth_client_jwt_invalid="auth_client_jwt_invalid",q.auth_client_jwt_missing_external_id_payload="auth_client_jwt_missing_external_id_payload",q.auth_client_jwt_missing_exp_payload="auth_client_jwt_missing_exp_payload",q.auth_client_jwt_external_id_not_match="auth_client_jwt_external_id_not_match",q.auth_client_jwt_expired="auth_client_jwt_expired",q.auth_client_jwt_not_provided="auth_client_jwt_not_provided",q.auth_client_jwt_invalid_auth_type="auth_client_jwt_invalid_auth_type",q.auth_client_jwt_invalid_passkey="auth_client_jwt_invalid_passkey",q.auth_client_pub_key_and_message_not_match="auth_client_pub_key_and_message_not_match",q.auth_client_pub_key_and_message_expired="auth_client_pub_key_and_message_expired",q.auth_client_pub_key_and_message_signature_failed="auth_client_pub_key_and_message_signature_failed",q.auth_client_pub_key_not_found="auth_client_pub_key_not_found",q.auth_client_pub_key_already_registered="auth_client_pub_key_already_registered",q.auth_user_not_allowed_to_perform_the_action="auth_user_not_allowed_to_perform_the_action",q.auth_upside_signature_not_provided="auth_upside_signature_not_provided",q.auth_upside_signature_invalid="auth_upside_signature_invalid",q.auth_upside_wrong_base64_signature="auth_upside_wrong_base64_signature",q.multisig_participant_not_found="multisig_participant_not_found",q.wallet_not_found="wallet_not_found",q.wallet_recovery_seed_mismatch="wallet_recovery_seed_mismatch",q.wallet_address_not_found="wallet_address_not_found",q.wallet_address_generation_failed="wallet_address_generation_failed",q.invalid_public_key="invalid_public_key",q.canton_registration_daily_limit_exceeded="canton_registration_daily_limit_exceeded",q.asset_not_found="asset_not_found",q.seedphrase_could_not_be_decrypted="seedphrase_could_not_be_decrypted",q.invalid_seed_phrase="invalid_seed_phrase",q.user_already_exists="user_already_exists",q.user_not_found="user_not_found",q.otp_code_invalid="otp_code_invalid",q.otp_code_expired="otp_code_expired",q.merchant_not_found="merchant_not_found",q.swap_provider_not_found="swap_provider_not_found",q.swap_chain_not_supported="swap_chain_not_supported",q.swap_asset_not_supported="swap_asset_not_supported",q.swap_quote_executing="swap_quote_executing",q.swap_quote_in_progress="swap_quote_in_progress",q.swap_quote_completed="swap_quote_completed",q.swap_quote_failed="swap_quote_failed",q.swap_quote_abandoned="swap_quote_abandoned",q.swap_quote_execution_failed="swap_quote_execution_failed",q.swap_quote_invalid="swap_quote_invalid",q.feature_not_enabled="feature_not_enabled",q.insufficient_balance="insufficient_balance",q.transaction_failed="transaction_failed",q.invalid_number_of_signatures="invalid_number_of_signatures",q.invalid_signature="invalid_signature",q.chain_adapter_not_found="chain_adapter_not_found",q.chain_not_found="chain_not_found",q.invalid_address="invalid_address",q.auth_refresh_token_not_found="auth_refresh_token_not_found",q.auth_refresh_token_expired="auth_refresh_token_expired",q.auth_refresh_token_reuse_detected="auth_refresh_token_reuse_detected",q.sdk_jwt_invalid="sdk_jwt_invalid",q.sdk_jwt_expired="sdk_jwt_expired",q.sdk_unknown_error="sdk_unknown_error",q.sdk_too_many_requests="sdk_too_many_requests",q.sdk_seed_phrase_decryption_failed="sdk_seed_phrase_decryption_failed",q.sdk_key_shares_not_found="sdk_key_shares_not_found",q.sdk_key_share_decryption_failed="sdk_key_share_decryption_failed",q.sdk_seed_phrase_not_found="sdk_seed_phrase_not_found",q.sdk_private_key_decryption_failed="sdk_private_key_decryption_failed",q.sdk_private_key_not_found="sdk_private_key_not_found",q.sdk_device_key_missing_with_existing_data="sdk_device_key_missing_with_existing_data",q.sdk_refresh_token_missing="sdk_refresh_token_missing",q.sdk_missing_parameter="sdk_missing_parameter",q.sdk_invalid_parameter="sdk_invalid_parameter",q.sdk_invalid_response="sdk_invalid_response",q.sdk_wrong_password="sdk_wrong_password",q.sdk_no_valid_seed_option="sdk_no_valid_seed_option",q.sdk_ambiguous_legacy_migration_data="sdk_ambiguous_legacy_migration_data",q.sdk_passkey_prf_not_available="sdk_passkey_prf_not_available",q.sdk_passkey_challenge_unavailable="sdk_passkey_challenge_unavailable",q.sdk_passkey_authentication_failed="sdk_passkey_authentication_failed",q.sdk_passkey_registration_failed="sdk_passkey_registration_failed";const M={error:"UnknownError",message:"An unknown error occurred"},W={error:"IOSVersionNotSupportedError",message:"Passkeys are not supported on this device. iOS 15 and above is required to use Passkeys"},F={error:"AndroidVersionNotSupportedError",message:"Passkeys are not supported on this device. Android 9 and above is required to use Passkeys"},G={error:"RequestFailed",message:"The request failed. No Credentials were returned."},j={error:"UserCancelled",message:"The user cancelled the request."},H={error:"InvalidChallenge",message:"The provided challenge was invalid"},$={error:"InvalidUserId",message:"The provided userId was invalid"},Y={error:"BadConfiguration",message:"Your app is not properly configured. Refer to the docs for help."},z={error:"NoCredentials",message:"No viable credential is available for the user."},J={error:"Interrupted",message:"The operation was interrupted and may be retried."},X={error:"TimedOut",message:"The operation timed out."},Z={error:"ERROR_CEREMONY_ABORTED",message:"User did not complete the request in time."},Q={error:"ERROR_INVALID_DOMAIN",message:"Invalid domain."},ee={error:"ERROR_INVALID_RP_ID",message:"Invalid Relying Party ID."},te={error:"ERROR_INVALID_USER_ID_LENGTH",message:"Invalid user ID length."},re={error:"ERROR_MALFORMED_PUBKEYCREDPARAMS",message:"Malformed public key credential parameters."},se={error:"ERROR_AUTHENTICATOR_GENERAL_ERROR",message:"Authenticator encountered a general error."},ae={error:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",message:"Authenticator does not support discoverable credentials."},ne={error:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",message:"Authenticator does not support user verification."},ie={error:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",message:"Authenticator was previously registered."},oe={error:"InvalidStateError",message:"The authenticator was previously registered"},ce={error:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",message:"Authenticator does not support any of the provided public key credential parameters algorithms."},de={error:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",message:"User verification failed during auto-registration."},le={error:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",message:"An error occurred. See the cause property for more details."},he=[M,W,F,G,j,H,$,Y,z,J,X,Z,Q,ee,te,re,se,ae,ne,ie,ce,de,le];let ue=!1;"undefined"!=typeof window&&window.localStorage&&(ue="true"===window.localStorage.getItem("wsdk:enable_logging")),ue&&u.default.setLevel("trace");const pe=u.default;var ye,fe=("undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}).performance||{};fe.now||fe.mozNow||fe.msNow||fe.oNow||fe.webkitNow;const ge=null!==(ye={env:{}}.env.NODE_ENV)&&void 0!==ye?ye:"development",we="testnet",me="9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe75d907fe6db9e4c";exports.PublicKeyCredentialAlgorithm.RS256,exports.PublicKeyCredentialAlgorithm.ES256;const ve="undefined"!=typeof window&&"undefined"!=typeof document,Se={platform:"web",isNative:!ve,isWeb:ve},_e="3.15.2",Ae="x-sdk-version",Ee=`wallaby-cash/${_e}`,be=e=>e.replace(/:/g,"_"),Ie="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Pe(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Te(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./r/oci-al0xoD5i.cjs"),t=require("bip39"),r=require("uuid"),s=require("loglevel"),a=require("crypto-js"),n=require("jwt-decode"),o=require("@simplewebauthn/browser"),i=require("js-base64"),c=require("scale-ts"),d=e=>e&&"object"==typeof e&&"default"in e?e:{default:e};function l(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const u=l(t),h=d(s),p=l(o);var f,y,g,w,m,v,S,A,b,E,_,k,I,T,P,C,x,K,O,N,R,D,L,B,U,q;exports.PasskeyChallengeType=void 0,(f=exports.PasskeyChallengeType||(exports.PasskeyChallengeType={})).REGISTRATION="webauthn.create",f.AUTHENTICATION="webauthn.get",exports.PublicKeyCredentialAlgorithm=void 0,(y=exports.PublicKeyCredentialAlgorithm||(exports.PublicKeyCredentialAlgorithm={}))[y.RS256=-257]="RS256",y[y.ES256=-7]="ES256",exports.TransportEnum=void 0,(g=exports.TransportEnum||(exports.TransportEnum={})).Usb="usb",g.Nfc="nfc",g.Ble="ble",g.Internal="internal",g.Hybrid="hybrid";class 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,(m=exports.AssetConfigStatus||(exports.AssetConfigStatus={})).Active="active",m.Inactive="inactive",exports.AssetType=void 0,(v=exports.AssetType||(exports.AssetType={})).Coin="COIN",v.Token="TOKEN",exports.OwnershipType=void 0,(S=exports.OwnershipType||(exports.OwnershipType={})).SingleOwner="SINGLE_OWNER",S.MultiSig="MULTI_SIG",exports.TokenStandard=void 0,(A=exports.TokenStandard||(exports.TokenStandard={})).Erc20="ERC_20",A.Erc1404="ERC_1404",A.Arc20="ARC_20",A.Arc1404="ARC_1404",A.Mrc20="MRC_20",A.Bep20="BEP_20",A.AlgoStandard="ALGO_STANDARD",A.AlgoApp="ALGO_APP",A.TokenFactory="TOKEN_FACTORY",A.SeiErc20="SEI_ERC_20",A.AptFA="APT_FUNGIBLE_ASSET",exports.AddressType=void 0,(b=exports.AddressType||(exports.AddressType={})).Segwit="SEGWIT",b.Legacy="LEGACY",b.Default="DEFAULT",exports.BlockchainStatus=void 0,(E=exports.BlockchainStatus||(exports.BlockchainStatus={})).Up="UP",E.Down="DOWN",exports.BlockchainSlip44=void 0,(_=exports.BlockchainSlip44||(exports.BlockchainSlip44={}))[_.BTC=0]="BTC",_[_.ETH=60]="ETH",_[_.ALGO=283]="ALGO",_[_.AVAX=9e3]="AVAX",_[_.MATIC=966]="MATIC",_[_.BSC=519]="BSC",_[_.BASE=8453]="BASE",_[_.SUI=784]="SUI",_[_.INJ=2525]="INJ",_[_.SEI=19000118]="SEI",_[_.APT=637]="APT",_[_.HBAR=3030]="HBAR",_[_.POLYX=595]="POLYX",exports.BlockchainName=void 0,(k=exports.BlockchainName||(exports.BlockchainName={})).Algorand="ALGORAND",k.Aptos="APTOS",k.Avalanche="AVALANCHE",k.Base="BASE",k.Bitcoin="BITCOIN",k.Bsc="BSC",k.Canton="CANTON",k.Ethereum="ETHEREUM",k.Hedera="HEDERA",k.Injective="INJECTIVE",k.Polygon="POLYGON",k.Polymesh="POLYMESH",k.Sei="SEI",k.Sui="SUI",k.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,(T=exports.ApiKeyStatus||(exports.ApiKeyStatus={})).Active="active",T.Inactive="inactive",exports.TransactionEntryType=void 0,(P=exports.TransactionEntryType||(exports.TransactionEntryType={})).INCOMING="INCOMING",P.OUTGOING="OUTGOING",P.UNKNOWN="UNKNOWN",exports.KeyTypeName=void 0,(C=exports.KeyTypeName||(exports.KeyTypeName={})).WallabyShare="wallaby_share",C.OwnerMainDeviceShare="owner_main_device_share",C.OwnerBackupDeviceShare="owner_backup_device_share",exports.SeedPhraseType=void 0,(x=exports.SeedPhraseType||(exports.SeedPhraseType={})).Standard="standard",x.Algorand="algorand",exports.WalletAddressTypeName=void 0,(K=exports.WalletAddressTypeName||(exports.WalletAddressTypeName={})).BTC_MAINNET_SEGWIT="BTC:MAINNET:SEGWIT",K.BTC_MAINNET_LEGACY="BTC:MAINNET:LEGACY",K.BTC_TESTNET_SEGWIT="BTC:TESTNET:SEGWIT",K.BTC_TESTNET_LEGACY="BTC:TESTNET:LEGACY",K.ETH="ETH:ALL:DEFAULT",K.ALGO="ALGO:ALL:DEFAULT",K.SUI="SUI:ALL:DEFAULT",K.INJ="INJ:ALL:DEFAULT",K.APT="APT:ALL:DEFAULT",K.POLYX="POLYX:ALL:DEFAULT",K.BSC="BSC:ALL:DEFAULT",K.AVAX="AVAX:ALL:DEFAULT",K.MATIC="MATIC:ALL:DEFAULT",K.BASE="BASE:ALL:DEFAULT",K.SEI="SEI:ALL:DEFAULT",K.HBAR="HBAR:ALL:DEFAULT",K.CC="CC:ALL:DEFAULT",exports.ReturnWalletOption=void 0,(O=exports.ReturnWalletOption||(exports.ReturnWalletOption={})).ReturnOnlyEncryptedShares="RETURN_ONLY_ENCRYPTED_SHARES",O.ReturnOnlyEncryptedSeedPhrase="RETURN_ONLY_ENCRYPTED_SEED_PHRASE",O.ReturnBothEncryptedSharesAndSeed="RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED",exports.WalletOwnershipType=void 0,(N=exports.WalletOwnershipType||(exports.WalletOwnershipType={})).SingleOwner="SINGLE_OWNER",N.MultiOwner="MULTI_OWNER",exports.AuthType=void 0,(R=exports.AuthType||(exports.AuthType={})).Password="password",R.Passkey="passkey",exports.LocalStorageItems=void 0,(D=exports.LocalStorageItems||(exports.LocalStorageItems={})).AccessToken="access-token",D.RefreshToken="refresh-token",D.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",D.EncryptedKeyShares="encrypted-key-shares",D.PrimaryDeviceKeyShare="primary-device-key-share",D.BackupDeviceKeyShare="backup-device-key-share",D.EncryptedShare="encrypted-share",D.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",D.EncryptedDevicePrivateKey="encrypted-private-key",D.ClientAuthPublicKey="client-auth-pub-key",D.ClientAuthToken="republic-jwt",D.PasskeyCredential="pass-key-credential",D.Blob="blob",exports.LegacyKeyNames=void 0,(L=exports.LegacyKeyNames||(exports.LegacyKeyNames={})).EncryptedPrivateKey="encryptedPrivateKey",L.WallabyAuthPubKey="wallabyAuthPubKey",L.EncryptedAlgorandSeed="encryptedAlgorandSeed",L.EncryptedSeed="encryptedSeed",L.ClientAuthToken="republic_jwt",L.AccessToken="accessToken",exports.V1KeyNames=void 0,(B=exports.V1KeyNames||(exports.V1KeyNames={})).AccessToken="access-token",B.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",B.EncryptedAlgorandSeedPhrase="encrypted-algorand-seedPhrase",B.EncryptedDevicePrivateKey="encrypted-private-key",B.ClientAuthPublicKey="client-auth-pub-key",B.WallabyAuthPubKey="wallaby-auth-pub-key",B.ClientAuthToken="republic-jwt",exports.V2KeyNames=void 0,(U=exports.V2KeyNames||(exports.V2KeyNames={})).AccessToken="access-token",U.RefreshToken="refresh-token",U.BackupDeviceKeyShare="backup-device-key-share",U.ClientAuthPublicKey="client-auth-pub-key",U.ClientAuthToken="republic-jwt",U.EncryptedDevicePrivateKey="encrypted-private-key",U.EncryptedStandardSeedPhrase="encrypted-standard-seedPhrase",U.PasskeyCredential="pass-key-credential",U.PrimaryDeviceKeyShare="primary-device-key-share",U.WallabyAuthPubKey="wallaby-auth-pub-key",U.MigrationVersion="wsdk_migrated_with_version",U.LastMigratedAt="wsdk_last_migrated_at",U.PasswordResetAttempts="wsdk_password_reset_attempts",U.MigrationAttempts="wsdk_migration_attempts",U.CredentialConversionInProgress="credential-conversion-in-progress",U.PendingCommit="pending-commit",U.LegacySeedClaimedWalletId="wsdk_legacy_seed_claimed_wallet_id",exports.ErrorResponseCodes=void 0,(q=exports.ErrorResponseCodes||(exports.ErrorResponseCodes={})).unknown_error="unknown_error",q.internal_server_error="internal_server_error",q.request_payload_missing="request_payload_missing",q.request_payload_wrong_format="request_payload_wrong_format",q.auth_api_key_invalid="auth_api_key_invalid",q.auth_api_key_not_active="auth_api_key_not_active",q.auth_api_key_pub_key_not_set="auth_api_key_pub_key_not_set",q.auth_api_key_pub_key_already_in_use="auth_api_key_pub_key_already_in_use",q.auth_api_key_not_provided="auth_api_key_not_provided",q.auth_api_key_not_found="auth_api_key_not_found",q.auth_origin_not_allowed="auth_origin_not_allowed",q.auth_api_jwt_invalid="auth_api_jwt_invalid",q.auth_api_jwt_not_active="auth_api_jwt_not_active",q.auth_api_jwt_not_provided="auth_api_jwt_not_provided",q.auth_api_jwt_expired="auth_api_jwt_expired",q.auth_api_unauthorized="auth_api_unauthorized",q.auth_client_jwt_invalid="auth_client_jwt_invalid",q.auth_client_jwt_missing_external_id_payload="auth_client_jwt_missing_external_id_payload",q.auth_client_jwt_missing_exp_payload="auth_client_jwt_missing_exp_payload",q.auth_client_jwt_external_id_not_match="auth_client_jwt_external_id_not_match",q.auth_client_jwt_expired="auth_client_jwt_expired",q.auth_client_jwt_not_provided="auth_client_jwt_not_provided",q.auth_client_jwt_invalid_auth_type="auth_client_jwt_invalid_auth_type",q.auth_client_jwt_invalid_passkey="auth_client_jwt_invalid_passkey",q.auth_client_pub_key_and_message_not_match="auth_client_pub_key_and_message_not_match",q.auth_client_pub_key_and_message_expired="auth_client_pub_key_and_message_expired",q.auth_client_pub_key_and_message_signature_failed="auth_client_pub_key_and_message_signature_failed",q.auth_client_pub_key_not_found="auth_client_pub_key_not_found",q.auth_client_pub_key_already_registered="auth_client_pub_key_already_registered",q.auth_user_not_allowed_to_perform_the_action="auth_user_not_allowed_to_perform_the_action",q.auth_upside_signature_not_provided="auth_upside_signature_not_provided",q.auth_upside_signature_invalid="auth_upside_signature_invalid",q.auth_upside_wrong_base64_signature="auth_upside_wrong_base64_signature",q.multisig_participant_not_found="multisig_participant_not_found",q.wallet_not_found="wallet_not_found",q.wallet_recovery_seed_mismatch="wallet_recovery_seed_mismatch",q.wallet_address_not_found="wallet_address_not_found",q.wallet_address_generation_failed="wallet_address_generation_failed",q.invalid_public_key="invalid_public_key",q.canton_registration_daily_limit_exceeded="canton_registration_daily_limit_exceeded",q.asset_not_found="asset_not_found",q.seedphrase_could_not_be_decrypted="seedphrase_could_not_be_decrypted",q.invalid_seed_phrase="invalid_seed_phrase",q.user_already_exists="user_already_exists",q.user_not_found="user_not_found",q.otp_code_invalid="otp_code_invalid",q.otp_code_expired="otp_code_expired",q.merchant_not_found="merchant_not_found",q.swap_provider_not_found="swap_provider_not_found",q.swap_chain_not_supported="swap_chain_not_supported",q.swap_asset_not_supported="swap_asset_not_supported",q.swap_quote_executing="swap_quote_executing",q.swap_quote_in_progress="swap_quote_in_progress",q.swap_quote_completed="swap_quote_completed",q.swap_quote_failed="swap_quote_failed",q.swap_quote_abandoned="swap_quote_abandoned",q.swap_quote_execution_failed="swap_quote_execution_failed",q.swap_quote_invalid="swap_quote_invalid",q.feature_not_enabled="feature_not_enabled",q.insufficient_balance="insufficient_balance",q.transaction_failed="transaction_failed",q.invalid_number_of_signatures="invalid_number_of_signatures",q.invalid_signature="invalid_signature",q.chain_adapter_not_found="chain_adapter_not_found",q.chain_not_found="chain_not_found",q.invalid_address="invalid_address",q.auth_refresh_token_not_found="auth_refresh_token_not_found",q.auth_refresh_token_expired="auth_refresh_token_expired",q.auth_refresh_token_reuse_detected="auth_refresh_token_reuse_detected",q.sdk_jwt_invalid="sdk_jwt_invalid",q.sdk_jwt_expired="sdk_jwt_expired",q.sdk_unknown_error="sdk_unknown_error",q.sdk_too_many_requests="sdk_too_many_requests",q.sdk_seed_phrase_decryption_failed="sdk_seed_phrase_decryption_failed",q.sdk_key_shares_not_found="sdk_key_shares_not_found",q.sdk_key_share_decryption_failed="sdk_key_share_decryption_failed",q.sdk_seed_phrase_not_found="sdk_seed_phrase_not_found",q.sdk_private_key_decryption_failed="sdk_private_key_decryption_failed",q.sdk_private_key_not_found="sdk_private_key_not_found",q.sdk_device_key_missing_with_existing_data="sdk_device_key_missing_with_existing_data",q.sdk_refresh_token_missing="sdk_refresh_token_missing",q.sdk_missing_parameter="sdk_missing_parameter",q.sdk_invalid_parameter="sdk_invalid_parameter",q.sdk_invalid_response="sdk_invalid_response",q.sdk_wrong_password="sdk_wrong_password",q.sdk_no_valid_seed_option="sdk_no_valid_seed_option",q.sdk_ambiguous_legacy_migration_data="sdk_ambiguous_legacy_migration_data",q.sdk_passkey_prf_not_available="sdk_passkey_prf_not_available",q.sdk_passkey_challenge_unavailable="sdk_passkey_challenge_unavailable",q.sdk_passkey_authentication_failed="sdk_passkey_authentication_failed",q.sdk_passkey_registration_failed="sdk_passkey_registration_failed";const V={error:"UnknownError",message:"An unknown error occurred"},F={error:"IOSVersionNotSupportedError",message:"Passkeys are not supported on this device. iOS 15 and above is required to use Passkeys"},$={error:"AndroidVersionNotSupportedError",message:"Passkeys are not supported on this device. Android 9 and above is required to use Passkeys"},W={error:"RequestFailed",message:"The request failed. No Credentials were returned."},j={error:"UserCancelled",message:"The user cancelled the request."},G={error:"InvalidChallenge",message:"The provided challenge was invalid"},H={error:"InvalidUserId",message:"The provided userId was invalid"},Y={error:"BadConfiguration",message:"Your app is not properly configured. Refer to the docs for help."},z={error:"NoCredentials",message:"No viable credential is available for the user."},J={error:"Interrupted",message:"The operation was interrupted and may be retried."},X={error:"TimedOut",message:"The operation timed out."},Z={error:"ERROR_CEREMONY_ABORTED",message:"User did not complete the request in time."},Q={error:"ERROR_INVALID_DOMAIN",message:"Invalid domain."},ee={error:"ERROR_INVALID_RP_ID",message:"Invalid Relying Party ID."},te={error:"ERROR_INVALID_USER_ID_LENGTH",message:"Invalid user ID length."},re={error:"ERROR_MALFORMED_PUBKEYCREDPARAMS",message:"Malformed public key credential parameters."},se={error:"ERROR_AUTHENTICATOR_GENERAL_ERROR",message:"Authenticator encountered a general error."},ae={error:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",message:"Authenticator does not support discoverable credentials."},ne={error:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",message:"Authenticator does not support user verification."},oe={error:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",message:"Authenticator was previously registered."},ie={error:"InvalidStateError",message:"The authenticator was previously registered"},ce={error:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",message:"Authenticator does not support any of the provided public key credential parameters algorithms."},de={error:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",message:"User verification failed during auto-registration."},le={error:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",message:"An error occurred. See the cause property for more details."},ue=[V,F,$,W,j,G,H,Y,z,J,X,Z,Q,ee,te,re,se,ae,ne,oe,ce,de,le];let he=!1;"undefined"!=typeof window&&window.localStorage&&(he="true"===window.localStorage.getItem("wsdk:enable_logging")),he&&h.default.setLevel("trace");const pe=h.default;var fe,ye=("undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}).performance||{};ye.now||ye.mozNow||ye.msNow||ye.oNow||ye.webkitNow;const ge=null!==(fe={env:{}}.env.NODE_ENV)&&void 0!==fe?fe:"development",we="testnet",me="9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe75d907fe6db9e4c";exports.PublicKeyCredentialAlgorithm.RS256,exports.PublicKeyCredentialAlgorithm.ES256;const ve="undefined"!=typeof window&&"undefined"!=typeof document,Se={platform:"web",isNative:!ve,isWeb:ve},Ae="3.16.0",be="x-sdk-version",Ee=`wallaby-cash/${Ae}`,_e=e=>e.replace(/:/g,"_"),ke="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Ie(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Te(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
|
|
2
2
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
|
-
var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function
|
|
4
|
-
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const st=BigInt(0),at=BigInt(1);function nt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function it(e){if(!nt(e))throw new Error("Uint8Array expected")}function ot(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function ct(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function dt(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?st:BigInt("0x"+e)}const lt="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,ht=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function ut(e){if(it(e),lt)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=ht[e[r]];return t}const pt=48,yt=57,ft=65,gt=70,wt=97,mt=102;function vt(e){return e>=pt&&e<=yt?e-pt:e>=ft&&e<=gt?e-(ft-10):e>=wt&&e<=mt?e-(wt-10):void 0}function St(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(lt)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){const r=vt(e.charCodeAt(a)),n=vt(e.charCodeAt(a+1));if(void 0===r||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[t]=16*r+n}return s}function _t(e){return dt(ut(e))}function At(e){return it(e),dt(ut(Uint8Array.from(e).reverse()))}function Et(e,t){return St(e.toString(16).padStart(2*t,"0"))}function bt(e,t){return Et(e,t).reverse()}function It(e,t,r){let s;if("string"==typeof t)try{s=St(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!nt(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const a=s.length;if("number"==typeof r&&a!==r)throw new Error(e+" of length "+r+" expected, got "+a);return s}function Pt(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];it(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const a=e[t];r.set(a,s),s+=a.length}return r}const Tt=e=>"bigint"==typeof e&&st<=e;function kt(e,t,r){return Tt(e)&&Tt(t)&&Tt(r)&&t<=e&&e<r}function Ct(e,t,r,s){if(!kt(t,r,s))throw new Error("expected valid "+e+": "+r+" <= n < "+s+", got "+t)}const xt=e=>(at<<BigInt(e))-at,Kt=e=>new Uint8Array(e),Ot=e=>Uint8Array.from(e);const Nt={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||nt(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Rt(e,t,r={}){const s=(t,r,s)=>{const a=Nt[r];if("function"!=typeof a)throw new Error("invalid validator function");const n=e[t];if(!(s&&void 0===n||a(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+r+", got "+n)};for(const[e,r]of Object.entries(t))s(e,r,!1);for(const[e,t]of Object.entries(r))s(e,t,!0);return e}function Dt(e){const t=new WeakMap;return(r,...s)=>{const a=t.get(r);if(void 0!==a)return a;const n=e(r,...s);return t.set(r,n),n}}const Lt=Te;function Ut(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(qe)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){const r=Ye(e.charCodeAt(a)),n=Ye(e.charCodeAt(a+1));if(void 0===r||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[t]=16*r+n}return s}(e.startsWith("0x")?e.substring(2):e)}function Bt(e){return t=>(Lt(t),e(t))}const qt=e=>{if("string"!=typeof e)throw new Error("[stripHexPrefix] input must be type 'string', received "+typeof e);return(e=>{if("string"!=typeof e)throw new Error("[isHexPrefixed] input must be type 'string', received type "+typeof e);return"0"===e[0]&&"x"===e[1]})(e)?e.slice(2):e},Vt=e=>e.startsWith("0x")?e:"0x"+e,Mt=e=>{let t=e;return 64===Ut(e).length&&(t="04"+e),t.substring(2)},Wt=e=>{const t=e.reduce(((e,t)=>e+t.byteLength),0),r=new Uint8Array(t);let s=0;return e.forEach((e=>{r.set(e,s),s+=e.byteLength})),r},Ft=e=>{if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);const t=[];for(let r=0;r<e.length;r++){const s=e.codePointAt(r);if(!s)throw new Error("Invalid code point");s<128?t.push(s):s<2048?t.push(192|s>>6,128|63&s):s<65536?t.push(224|s>>12,128|s>>6&63,128|63&s):(r++,t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s))}return new Uint8Array(t)};function Gt(e,t,r){return e&t^e&r^t&r}class jt extends Ze{constructor(e,t,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ne(this.buffer)}update(e){Ce(this),Te(e=Je(e));const{view:t,buffer:r,blockLen:s}=this,a=e.length;for(let n=0;n<a;){const i=Math.min(s-this.pos,a-n);if(i!==s)r.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=Ne(e);for(;s<=a-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ce(this),xe(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:a}=this;let{pos:n}=this;t[n++]=128,Oe(this.buffer.subarray(n)),this.padOffset>s-n&&(this.process(r,0),n=0);for(let e=n;e<s;e++)t[e]=0;!function(e,t,r,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,s);const a=BigInt(32),n=BigInt(4294967295),i=Number(r>>a&n),o=Number(r&n),c=s?4:0,d=s?0:4;e.setUint32(t+c,i,s),e.setUint32(t+d,o,s)}(r,s-8,BigInt(8*this.length),a),this.process(r,0);const i=Ne(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,d=this.get();if(c>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)i.setUint32(4*e,d[e],a)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:a,destroyed:n,pos:i}=this;return e.destroyed=n,e.finished=a,e.length=s,e.pos=i,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Ht=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$t=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Yt=BigInt(2**32-1),zt=BigInt(32);function Jt(e,t=!1){return t?{h:Number(e&Yt),l:Number(e>>zt&Yt)}:{h:0|Number(e>>zt&Yt),l:0|Number(e&Yt)}}function Xt(e,t=!1){const r=e.length;let s=new Uint32Array(r),a=new Uint32Array(r);for(let n=0;n<r;n++){const{h:r,l:i}=Jt(e[n],t);[s[n],a[n]]=[r,i]}return[s,a]}const Zt=(e,t,r)=>e>>>r,Qt=(e,t,r)=>e<<32-r|t>>>r,er=(e,t,r)=>e>>>r|t<<32-r,tr=(e,t,r)=>e<<32-r|t>>>r,rr=(e,t,r)=>e<<64-r|t>>>r-32,sr=(e,t,r)=>e>>>r-32|t<<64-r;function ar(e,t,r,s){const a=(t>>>0)+(s>>>0);return{h:e+r+(a/2**32|0)|0,l:0|a}}const nr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),ir=(e,t,r,s)=>t+r+s+(e/2**32|0)|0,or=(e,t,r,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),cr=(e,t,r,s,a)=>t+r+s+a+(e/2**32|0)|0,dr=(e,t,r,s,a)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0)+(a>>>0),lr=(e,t,r,s,a,n)=>t+r+s+a+n+(e/2**32|0)|0,hr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ur=new Uint32Array(64);class pr extends jt{constructor(e=32){super(64,e,8,!1),this.A=0|Ht[0],this.B=0|Ht[1],this.C=0|Ht[2],this.D=0|Ht[3],this.E=0|Ht[4],this.F=0|Ht[5],this.G=0|Ht[6],this.H=0|Ht[7]}get(){const{A:e,B:t,C:r,D:s,E:a,F:n,G:i,H:o}=this;return[e,t,r,s,a,n,i,o]}set(e,t,r,s,a,n,i,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|s,this.E=0|a,this.F=0|n,this.G=0|i,this.H=0|o}process(e,t){for(let r=0;r<16;r++,t+=4)ur[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=ur[e-15],r=ur[e-2],s=Re(t,7)^Re(t,18)^t>>>3,a=Re(r,17)^Re(r,19)^r>>>10;ur[e]=a+ur[e-7]+s+ur[e-16]|0}let{A:r,B:s,C:a,D:n,E:i,F:o,G:c,H:d}=this;for(let e=0;e<64;e++){const t=d+(Re(i,6)^Re(i,11)^Re(i,25))+((l=i)&o^~l&c)+hr[e]+ur[e]|0,h=(Re(r,2)^Re(r,13)^Re(r,22))+Gt(r,s,a)|0;d=c,c=o,o=i,i=n+t|0,n=a,a=s,s=r,r=t+h|0}var l;r=r+this.A|0,s=s+this.B|0,a=a+this.C|0,n=n+this.D|0,i=i+this.E|0,o=o+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,s,a,n,i,o,c,d)}roundClean(){Oe(ur)}destroy(){this.set(0,0,0,0,0,0,0,0),Oe(this.buffer)}}const yr=(()=>Xt(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),fr=(()=>yr[0])(),gr=(()=>yr[1])(),wr=new Uint32Array(80),mr=new Uint32Array(80);class vr extends jt{constructor(e=64){super(128,e,16,!1),this.Ah=0|$t[0],this.Al=0|$t[1],this.Bh=0|$t[2],this.Bl=0|$t[3],this.Ch=0|$t[4],this.Cl=0|$t[5],this.Dh=0|$t[6],this.Dl=0|$t[7],this.Eh=0|$t[8],this.El=0|$t[9],this.Fh=0|$t[10],this.Fl=0|$t[11],this.Gh=0|$t[12],this.Gl=0|$t[13],this.Hh=0|$t[14],this.Hl=0|$t[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:s,Ch:a,Cl:n,Dh:i,Dl:o,Eh:c,El:d,Fh:l,Fl:h,Gh:u,Gl:p,Hh:y,Hl:f}=this;return[e,t,r,s,a,n,i,o,c,d,l,h,u,p,y,f]}set(e,t,r,s,a,n,i,o,c,d,l,h,u,p,y,f){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|s,this.Ch=0|a,this.Cl=0|n,this.Dh=0|i,this.Dl=0|o,this.Eh=0|c,this.El=0|d,this.Fh=0|l,this.Fl=0|h,this.Gh=0|u,this.Gl=0|p,this.Hh=0|y,this.Hl=0|f}process(e,t){for(let r=0;r<16;r++,t+=4)wr[r]=e.getUint32(t),mr[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|wr[e-15],r=0|mr[e-15],s=er(t,r,1)^er(t,r,8)^Zt(t,0,7),a=tr(t,r,1)^tr(t,r,8)^Qt(t,r,7),n=0|wr[e-2],i=0|mr[e-2],o=er(n,i,19)^rr(n,i,61)^Zt(n,0,6),c=tr(n,i,19)^sr(n,i,61)^Qt(n,i,6),d=or(a,c,mr[e-7],mr[e-16]),l=cr(d,s,o,wr[e-7],wr[e-16]);wr[e]=0|l,mr[e]=0|d}let{Ah:r,Al:s,Bh:a,Bl:n,Ch:i,Cl:o,Dh:c,Dl:d,Eh:l,El:h,Fh:u,Fl:p,Gh:y,Gl:f,Hh:g,Hl:w}=this;for(let e=0;e<80;e++){const t=er(l,h,14)^er(l,h,18)^rr(l,h,41),m=tr(l,h,14)^tr(l,h,18)^sr(l,h,41),v=l&u^~l&y,S=dr(w,m,h&p^~h&f,gr[e],mr[e]),_=lr(S,g,t,v,fr[e],wr[e]),A=0|S,E=er(r,s,28)^rr(r,s,34)^rr(r,s,39),b=tr(r,s,28)^sr(r,s,34)^sr(r,s,39),I=r&a^r&i^a&i,P=s&n^s&o^n&o;g=0|y,w=0|f,y=0|u,f=0|p,u=0|l,p=0|h,({h:l,l:h}=ar(0|c,0|d,0|_,0|A)),c=0|i,d=0|o,i=0|a,o=0|n,a=0|r,n=0|s;const T=nr(A,b,P);r=ir(T,_,E,I),s=0|T}({h:r,l:s}=ar(0|this.Ah,0|this.Al,0|r,0|s)),({h:a,l:n}=ar(0|this.Bh,0|this.Bl,0|a,0|n)),({h:i,l:o}=ar(0|this.Ch,0|this.Cl,0|i,0|o)),({h:c,l:d}=ar(0|this.Dh,0|this.Dl,0|c,0|d)),({h:l,l:h}=ar(0|this.Eh,0|this.El,0|l,0|h)),({h:u,l:p}=ar(0|this.Fh,0|this.Fl,0|u,0|p)),({h:y,l:f}=ar(0|this.Gh,0|this.Gl,0|y,0|f)),({h:g,l:w}=ar(0|this.Hh,0|this.Hl,0|g,0|w)),this.set(r,s,a,n,i,o,c,d,l,h,u,p,y,f,g,w)}roundClean(){Oe(wr,mr)}destroy(){Oe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Sr=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class _r extends vr{constructor(){super(32),this.Ah=0|Sr[0],this.Al=0|Sr[1],this.Bh=0|Sr[2],this.Bl=0|Sr[3],this.Ch=0|Sr[4],this.Cl=0|Sr[5],this.Dh=0|Sr[6],this.Dl=0|Sr[7],this.Eh=0|Sr[8],this.El=0|Sr[9],this.Fh=0|Sr[10],this.Fl=0|Sr[11],this.Gh=0|Sr[12],this.Gl=0|Sr[13],this.Hh=0|Sr[14],this.Hl=0|Sr[15]}}const Ar=Qe((()=>new pr)),Er=Qe((()=>new vr)),br=Qe((()=>new _r));class Ir extends Ze{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ke(e);const r=Je(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,a=new Uint8Array(s);a.set(r.length>s?e.create().update(r).digest():r);for(let e=0;e<a.length;e++)a[e]^=54;this.iHash.update(a),this.oHash=e.create();for(let e=0;e<a.length;e++)a[e]^=106;this.oHash.update(a),Oe(a)}update(e){return Ce(this),this.iHash.update(e),this}digestInto(e){Ce(this),Te(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:a,blockLen:n,outputLen:i}=this;return e.finished=s,e.destroyed=a,e.blockLen=n,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Pr=(e,t,r)=>new Ir(e,t).update(r).digest();Pr.create=(e,t)=>new Ir(e,t)
|
|
5
|
-
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const
|
|
3
|
+
var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Pe(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Ie(e.outputLen),Ie(e.blockLen)}function Ce(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function xe(e,t){Te(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ke(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Oe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ne(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Re(e,t){return e<<32-t|e>>>t}const De=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Le(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Be=De?e=>e:e=>Le(e);const Ue=De?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Le(e[t]);return e},qe=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Me=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Ve(e){if(Te(e),qe)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Me[e[r]];return t}const Fe=48,$e=57,We=65,je=70,Ge=97,He=102;function Ye(e){return e>=Fe&&e<=$e?e-Fe:e>=We&&e<=je?e-(We-10):e>=Ge&&e<=He?e-(Ge-10):void 0}function ze(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Je(e){return"string"==typeof e&&(e=ze(e)),Te(e),e}function Xe(e){return"string"==typeof e&&(e=ze(e)),Te(e),e}class Ze{}function Qe(e){const t=t=>e().update(Je(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function et(e){const t=(t,r)=>e(r).update(Je(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}function tt(e=32){if(ke&&"function"==typeof ke.getRandomValues)return ke.getRandomValues(new Uint8Array(e));if(ke&&"function"==typeof ke.randomBytes)return Uint8Array.from(ke.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function rt(e){return tt(e)}
|
|
4
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const st=BigInt(0),at=BigInt(1);function nt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ot(e){if(!nt(e))throw new Error("Uint8Array expected")}function it(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function ct(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function dt(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?st:BigInt("0x"+e)}const lt="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,ut=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function ht(e){if(ot(e),lt)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=ut[e[r]];return t}const pt=48,ft=57,yt=65,gt=70,wt=97,mt=102;function vt(e){return e>=pt&&e<=ft?e-pt:e>=yt&&e<=gt?e-(yt-10):e>=wt&&e<=mt?e-(wt-10):void 0}function St(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(lt)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){const r=vt(e.charCodeAt(a)),n=vt(e.charCodeAt(a+1));if(void 0===r||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[t]=16*r+n}return s}function At(e){return dt(ht(e))}function bt(e){return ot(e),dt(ht(Uint8Array.from(e).reverse()))}function Et(e,t){return St(e.toString(16).padStart(2*t,"0"))}function _t(e,t){return Et(e,t).reverse()}function kt(e,t,r){let s;if("string"==typeof t)try{s=St(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!nt(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const a=s.length;if("number"==typeof r&&a!==r)throw new Error(e+" of length "+r+" expected, got "+a);return s}function It(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];ot(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const a=e[t];r.set(a,s),s+=a.length}return r}const Tt=e=>"bigint"==typeof e&&st<=e;function Pt(e,t,r){return Tt(e)&&Tt(t)&&Tt(r)&&t<=e&&e<r}function Ct(e,t,r,s){if(!Pt(t,r,s))throw new Error("expected valid "+e+": "+r+" <= n < "+s+", got "+t)}const xt=e=>(at<<BigInt(e))-at,Kt=e=>new Uint8Array(e),Ot=e=>Uint8Array.from(e);const Nt={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||nt(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Rt(e,t,r={}){const s=(t,r,s)=>{const a=Nt[r];if("function"!=typeof a)throw new Error("invalid validator function");const n=e[t];if(!(s&&void 0===n||a(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+r+", got "+n)};for(const[e,r]of Object.entries(t))s(e,r,!1);for(const[e,t]of Object.entries(r))s(e,t,!0);return e}function Dt(e){const t=new WeakMap;return(r,...s)=>{const a=t.get(r);if(void 0!==a)return a;const n=e(r,...s);return t.set(r,n),n}}const Lt=Te;function Bt(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(qe)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(r);for(let t=0,a=0;t<r;t++,a+=2){const r=Ye(e.charCodeAt(a)),n=Ye(e.charCodeAt(a+1));if(void 0===r||void 0===n){const t=e[a]+e[a+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+a)}s[t]=16*r+n}return s}(e.startsWith("0x")?e.substring(2):e)}function Ut(e){return t=>(Lt(t),e(t))}const qt=e=>{if("string"!=typeof e)throw new Error("[stripHexPrefix] input must be type 'string', received "+typeof e);return(e=>{if("string"!=typeof e)throw new Error("[isHexPrefixed] input must be type 'string', received type "+typeof e);return"0"===e[0]&&"x"===e[1]})(e)?e.slice(2):e},Mt=e=>e.startsWith("0x")?e:"0x"+e,Vt=e=>{let t=e;return 64===Bt(e).length&&(t="04"+e),t.substring(2)},Ft=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},$t=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 Wt(e,t,r){return e&t^e&r^t&r}class jt extends Ze{constructor(e,t,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ne(this.buffer)}update(e){Ce(this),Te(e=Je(e));const{view:t,buffer:r,blockLen:s}=this,a=e.length;for(let n=0;n<a;){const 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=Ne(e);for(;s<=a-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ce(this),xe(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:a}=this;let{pos:n}=this;t[n++]=128,Oe(this.buffer.subarray(n)),this.padOffset>s-n&&(this.process(r,0),n=0);for(let e=n;e<s;e++)t[e]=0;!function(e,t,r,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,s);const a=BigInt(32),n=BigInt(4294967295),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=Ne(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 Gt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ht=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Yt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),zt=BigInt(2**32-1),Jt=BigInt(32);function Xt(e,t=!1){return t?{h:Number(e&zt),l:Number(e>>Jt&zt)}:{h:0|Number(e>>Jt&zt),l:0|Number(e&zt)}}function Zt(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}=Xt(e[n],t);[s[n],a[n]]=[r,o]}return[s,a]}const Qt=(e,t,r)=>e>>>r,er=(e,t,r)=>e<<32-r|t>>>r,tr=(e,t,r)=>e>>>r|t<<32-r,rr=(e,t,r)=>e<<32-r|t>>>r,sr=(e,t,r)=>e<<64-r|t>>>r-32,ar=(e,t,r)=>e>>>r-32|t<<64-r;function nr(e,t,r,s){const a=(t>>>0)+(s>>>0);return{h:e+r+(a/2**32|0)|0,l:0|a}}const or=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),ir=(e,t,r,s)=>t+r+s+(e/2**32|0)|0,cr=(e,t,r,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),dr=(e,t,r,s,a)=>t+r+s+a+(e/2**32|0)|0,lr=(e,t,r,s,a)=>(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0)+(a>>>0),ur=(e,t,r,s,a,n)=>t+r+s+a+n+(e/2**32|0)|0,hr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),pr=new Uint32Array(64);class fr extends jt{constructor(e=32){super(64,e,8,!1),this.A=0|Gt[0],this.B=0|Gt[1],this.C=0|Gt[2],this.D=0|Gt[3],this.E=0|Gt[4],this.F=0|Gt[5],this.G=0|Gt[6],this.H=0|Gt[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)pr[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=pr[e-15],r=pr[e-2],s=Re(t,7)^Re(t,18)^t>>>3,a=Re(r,17)^Re(r,19)^r>>>10;pr[e]=a+pr[e-7]+s+pr[e-16]|0}let{A:r,B:s,C:a,D:n,E:o,F:i,G:c,H:d}=this;for(let e=0;e<64;e++){const t=d+(Re(o,6)^Re(o,11)^Re(o,25))+((l=o)&i^~l&c)+hr[e]+pr[e]|0,u=(Re(r,2)^Re(r,13)^Re(r,22))+Wt(r,s,a)|0;d=c,c=i,i=o,o=n+t|0,n=a,a=s,s=r,r=t+u|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(pr)}destroy(){this.set(0,0,0,0,0,0,0,0),Oe(this.buffer)}}const yr=(()=>Zt(["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)))))(),gr=(()=>yr[0])(),wr=(()=>yr[1])(),mr=new Uint32Array(80),vr=new Uint32Array(80);class Sr extends jt{constructor(e=64){super(128,e,16,!1),this.Ah=0|Yt[0],this.Al=0|Yt[1],this.Bh=0|Yt[2],this.Bl=0|Yt[3],this.Ch=0|Yt[4],this.Cl=0|Yt[5],this.Dh=0|Yt[6],this.Dl=0|Yt[7],this.Eh=0|Yt[8],this.El=0|Yt[9],this.Fh=0|Yt[10],this.Fl=0|Yt[11],this.Gh=0|Yt[12],this.Gl=0|Yt[13],this.Hh=0|Yt[14],this.Hl=0|Yt[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:u,Gh:h,Gl:p,Hh:f,Hl:y}=this;return[e,t,r,s,a,n,o,i,c,d,l,u,h,p,f,y]}set(e,t,r,s,a,n,o,i,c,d,l,u,h,p,f,y){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|u,this.Gh=0|h,this.Gl=0|p,this.Hh=0|f,this.Hl=0|y}process(e,t){for(let r=0;r<16;r++,t+=4)mr[r]=e.getUint32(t),vr[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|mr[e-15],r=0|vr[e-15],s=tr(t,r,1)^tr(t,r,8)^Qt(t,0,7),a=rr(t,r,1)^rr(t,r,8)^er(t,r,7),n=0|mr[e-2],o=0|vr[e-2],i=tr(n,o,19)^sr(n,o,61)^Qt(n,0,6),c=rr(n,o,19)^ar(n,o,61)^er(n,o,6),d=cr(a,c,vr[e-7],vr[e-16]),l=dr(d,s,i,mr[e-7],mr[e-16]);mr[e]=0|l,vr[e]=0|d}let{Ah:r,Al:s,Bh:a,Bl:n,Ch:o,Cl:i,Dh:c,Dl:d,Eh:l,El:u,Fh:h,Fl:p,Gh:f,Gl:y,Hh:g,Hl:w}=this;for(let e=0;e<80;e++){const t=tr(l,u,14)^tr(l,u,18)^sr(l,u,41),m=rr(l,u,14)^rr(l,u,18)^ar(l,u,41),v=l&h^~l&f,S=lr(w,m,u&p^~u&y,wr[e],vr[e]),A=ur(S,g,t,v,gr[e],mr[e]),b=0|S,E=tr(r,s,28)^sr(r,s,34)^sr(r,s,39),_=rr(r,s,28)^ar(r,s,34)^ar(r,s,39),k=r&a^r&o^a&o,I=s&n^s&i^n&i;g=0|f,w=0|y,f=0|h,y=0|p,h=0|l,p=0|u,({h:l,l:u}=nr(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 T=or(b,_,I);r=ir(T,A,E,k),s=0|T}({h:r,l:s}=nr(0|this.Ah,0|this.Al,0|r,0|s)),({h:a,l:n}=nr(0|this.Bh,0|this.Bl,0|a,0|n)),({h:o,l:i}=nr(0|this.Ch,0|this.Cl,0|o,0|i)),({h:c,l:d}=nr(0|this.Dh,0|this.Dl,0|c,0|d)),({h:l,l:u}=nr(0|this.Eh,0|this.El,0|l,0|u)),({h:h,l:p}=nr(0|this.Fh,0|this.Fl,0|h,0|p)),({h:f,l:y}=nr(0|this.Gh,0|this.Gl,0|f,0|y)),({h:g,l:w}=nr(0|this.Hh,0|this.Hl,0|g,0|w)),this.set(r,s,a,n,o,i,c,d,l,u,h,p,f,y,g,w)}roundClean(){Oe(mr,vr)}destroy(){Oe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Ar extends Sr{constructor(){super(48),this.Ah=0|Ht[0],this.Al=0|Ht[1],this.Bh=0|Ht[2],this.Bl=0|Ht[3],this.Ch=0|Ht[4],this.Cl=0|Ht[5],this.Dh=0|Ht[6],this.Dl=0|Ht[7],this.Eh=0|Ht[8],this.El=0|Ht[9],this.Fh=0|Ht[10],this.Fl=0|Ht[11],this.Gh=0|Ht[12],this.Gl=0|Ht[13],this.Hh=0|Ht[14],this.Hl=0|Ht[15]}}const br=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Er extends Sr{constructor(){super(32),this.Ah=0|br[0],this.Al=0|br[1],this.Bh=0|br[2],this.Bl=0|br[3],this.Ch=0|br[4],this.Cl=0|br[5],this.Dh=0|br[6],this.Dl=0|br[7],this.Eh=0|br[8],this.El=0|br[9],this.Fh=0|br[10],this.Fl=0|br[11],this.Gh=0|br[12],this.Gl=0|br[13],this.Hh=0|br[14],this.Hl=0|br[15]}}const _r=Qe((()=>new fr)),kr=Qe((()=>new Sr)),Ir=Qe((()=>new Ar)),Tr=Qe((()=>new Er));class Pr extends Ze{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Pe(e);const r=Je(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,a=new Uint8Array(s);a.set(r.length>s?e.create().update(r).digest():r);for(let e=0;e<a.length;e++)a[e]^=54;this.iHash.update(a),this.oHash=e.create();for(let e=0;e<a.length;e++)a[e]^=106;this.oHash.update(a),Oe(a)}update(e){return Ce(this),this.iHash.update(e),this}digestInto(e){Ce(this),Te(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:a,blockLen:n,outputLen: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 Cr=(e,t,r)=>new Pr(e,t).update(r).digest();Cr.create=(e,t)=>new Pr(e,t)
|
|
5
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const xr=BigInt(0),Kr=BigInt(1),Or=BigInt(2),Nr=BigInt(3),Rr=BigInt(4),Dr=BigInt(5),Lr=BigInt(8);function Br(e,t){const r=e%t;return r>=xr?r:t+r}function Ur(e,t,r){let s=e;for(;t-- >xr;)s*=s,s%=r;return s}function qr(e,t){if(e===xr)throw new Error("invert: expected non-zero number");if(t<=xr)throw new Error("invert: expected positive modulus, got "+t);let r=Br(e,t),s=t,a=xr,n=Kr;for(;r!==xr;){const e=s%r,t=a-n*(s/r);s=r,r=e,a=n,n=t}if(s!==Kr)throw new Error("invert: does not exist");return Br(a,t)}function Mr(e){return e%Rr===Nr?function(t,r){const s=(e+Kr)/Rr,a=t.pow(r,s);if(!t.eql(t.sqr(a),r))throw new Error("Cannot find square root");return a}:e%Lr===Dr?function(t,r){const s=t.mul(r,Or),a=(e-Dr)/Lr,n=t.pow(s,a),o=t.mul(r,n),i=t.mul(t.mul(o,Or),n),c=t.mul(o,t.sub(i,t.ONE));if(!t.eql(t.sqr(c),r))throw new Error("Cannot find square root");return c}:function(e){let t=e-Kr,r=0;for(;t%Or===xr;)t/=Or,r++;let s=Or;const a=jr(e);for(;s<e&&$r(a,s);)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r){const t=(e+Kr)/Rr;return function(e,r){const s=e.pow(r,t);if(!e.eql(e.sqr(s),r))throw new Error("Cannot find square root");return s}}const n=(t+Kr)/Or;return function(e,a){if(!$r(e,a))throw new Error("Cannot find square root");let o=r,i=e.pow(e.mul(e.ONE,s),t),c=e.pow(a,n),d=e.pow(a,t);for(;!e.eql(d,e.ONE);){if(e.eql(d,e.ZERO))return e.ZERO;let t=1;for(let r=e.sqr(d);t<o&&!e.eql(r,e.ONE);t++)r=e.sqr(r);const r=e.pow(i,Kr<<BigInt(o-t-1));i=e.sqr(r),c=e.mul(c,r),d=e.mul(d,i),o=t}return c}}(e)}const Vr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Fr(e,t,r=!1){const s=new Array(t.length).fill(r?e.ZERO:void 0),a=t.reduce(((t,r,a)=>e.is0(r)?t:(s[a]=t,e.mul(t,r))),e.ONE),n=e.inv(a);return t.reduceRight(((t,r,a)=>e.is0(r)?t:(s[a]=e.mul(t,s[a]),e.mul(t,r))),n),s}function $r(e,t){const r=function(e,t){const r=(e.ORDER-Kr)/Or,s=e.pow(t,r),a=e.eql(s,e.ONE),n=e.eql(s,e.ZERO),o=e.eql(s,e.neg(e.ONE));if(!a&&!n&&!o)throw new Error("Cannot find square root: probably non-prime P");return a?1:n?0:-1}(e,t);return 0===r||1===r}function Wr(e,t){void 0!==t&&Ie(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function jr(e,t,r=!1,s={}){if(e<=xr)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:a,nByteLength:n}=Wr(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const i=Object.freeze({ORDER:e,isLE:r,BITS:a,BYTES:n,MASK:xt(a),ZERO:xr,ONE:Kr,create:t=>Br(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return xr<=t&&t<e},is0:e=>e===xr,isOdd:e=>(e&Kr)===Kr,neg:t=>Br(-t,e),eql:(e,t)=>e===t,sqr:t=>Br(t*t,e),add:(t,r)=>Br(t+r,e),sub:(t,r)=>Br(t-r,e),mul:(t,r)=>Br(t*r,e),pow:(e,t)=>function(e,t,r){if(r<xr)throw new Error("invalid exponent, negatives unsupported");if(r===xr)return e.ONE;if(r===Kr)return t;let s=e.ONE,a=t;for(;r>xr;)r&Kr&&(s=e.mul(s,a)),a=e.sqr(a),r>>=Kr;return s}(i,e,t),div:(t,r)=>Br(t*qr(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>qr(t,e),sqrt:s.sqrt||(t=>(o||(o=Mr(e)),o(i,t))),toBytes:e=>r?_t(e,n):Et(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return r?bt(e):At(e)},invertBatch:e=>Fr(i,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(i)}function Gr(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Hr(e){const t=Gr(e);return t+Math.ceil(t/2)}
|
|
6
6
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
7
|
-
const
|
|
8
|
-
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function rs(e){void 0!==e.lowS&&ot("lowS",e.lowS),void 0!==e.prehash&&ot("prehash",e.prehash)}class ss extends Error{constructor(e=""){super(e)}}const as={Err:ss,_tlv:{encode:(e,t)=>{const{Err:r}=as;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const s=t.length/2,a=ct(s);if(a.length/2&128)throw new r("tlv.encode: long form length too big");const n=s>127?ct(a.length/2|128):"";return ct(e)+n+a+t},decode(e,t){const{Err:r}=as;let s=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new r("tlv.decode: wrong tlv");const a=t[s++];let n=0;if(!!(128&a)){const e=127&a;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const i=t.subarray(s,s+e);if(i.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===i[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of i)n=n<<8|e;if(s+=e,n<128)throw new r("tlv.decode(long): not minimal encoding")}else n=a;const i=t.subarray(s,s+n);if(i.length!==n)throw new r("tlv.decode: wrong value length");return{v:i,l:t.subarray(s+n)}}},_int:{encode(e){const{Err:t}=as;if(e<ns)throw new t("integer: negative integers are not allowed");let r=ct(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=as;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return _t(e)}},toSig(e){const{Err:t,_int:r,_tlv:s}=as,a=It("signature",e),{v:n,l:i}=s.decode(48,a);if(i.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:c}=s.decode(2,n),{v:d,l:l}=s.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(o),s:r.decode(d)}},hexFromSig(e){const{_tlv:t,_int:r}=as,s=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,s)}},ns=BigInt(0),is=BigInt(1);BigInt(2);const os=BigInt(3);function cs(e){const t=function(e){const t=ts(e);Rt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:s,a:a}=t;if(r){if(!s.eql(a,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if("object"!=typeof r||"bigint"!=typeof r.beta||"function"!=typeof r.splitScalar)throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,s=Wr(t.n,t.nBitLength),a=t.toBytes||((e,t,s)=>{const a=t.toAffine();return Pt(Uint8Array.from([4]),r.toBytes(a.x),r.toBytes(a.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function i(e){const{a:s,b:a}=t,n=r.sqr(e),i=r.mul(n,e);return r.add(r.add(i,r.mul(e,s)),a)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(e){const{allowedPrivateKeyLengths:r,nByteLength:s,wrapPrivateKey:a,n:n}=t;if(r&&"bigint"!=typeof e){if(nt(e)&&(e=ut(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*s,"0")}let i;try{i="bigint"==typeof e?e:_t(It("private key",e,s))}catch(t){throw new Error("invalid private key, expected hex or "+s+" bytes, got "+typeof e)}return a&&(i=Rr(i,n)),Ct("private key",i,is,n),i}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const d=Dt(((e,t)=>{const{px:s,py:a,pz:n}=e;if(r.eql(n,r.ONE))return{x:s,y:a};const i=e.is0();null==t&&(t=i?r.ONE:r.inv(n));const o=r.mul(s,t),c=r.mul(a,t),d=r.mul(n,t);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(d,r.ONE))throw new Error("invZ was invalid");return{x:o,y:c}})),l=Dt((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:s,y:a}=e.toAffine();if(!r.isValid(s)||!r.isValid(a))throw new Error("bad point: x or y not FE");const n=r.sqr(a),o=i(s);if(!r.eql(n,o))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class h{constructor(e,t,s){if(null==e||!r.isValid(e))throw new Error("x required");if(null==t||!r.isValid(t)||r.is0(t))throw new Error("y required");if(null==s||!r.isValid(s))throw new Error("z required");this.px=e,this.py=t,this.pz=s,Object.freeze(this)}static fromAffine(e){const{x:t,y:s}=e||{};if(!e||!r.isValid(t)||!r.isValid(s))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const a=e=>r.eql(e,r.ZERO);return a(t)&&a(s)?h.ZERO:new h(t,s,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=qr(r,e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(n(It("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(o(e))}static msm(e,t){return es(h,s,e,t)}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){l(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:s,pz:a}=this,{px:n,py:i,pz:o}=e,d=r.eql(r.mul(t,o),r.mul(n,a)),l=r.eql(r.mul(s,o),r.mul(i,a));return d&&l}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:s}=t,a=r.mul(s,os),{px:n,py:i,pz:o}=this;let c=r.ZERO,d=r.ZERO,l=r.ZERO,u=r.mul(n,n),p=r.mul(i,i),y=r.mul(o,o),f=r.mul(n,i);return f=r.add(f,f),l=r.mul(n,o),l=r.add(l,l),c=r.mul(e,l),d=r.mul(a,y),d=r.add(c,d),c=r.sub(p,d),d=r.add(p,d),d=r.mul(c,d),c=r.mul(f,c),l=r.mul(a,l),y=r.mul(e,y),f=r.sub(u,y),f=r.mul(e,f),f=r.add(f,l),l=r.add(u,u),u=r.add(l,u),u=r.add(u,y),u=r.mul(u,f),d=r.add(d,u),y=r.mul(i,o),y=r.add(y,y),u=r.mul(y,f),c=r.sub(c,u),l=r.mul(y,p),l=r.add(l,l),l=r.add(l,l),new h(c,d,l)}add(e){c(e);const{px:s,py:a,pz:n}=this,{px:i,py:o,pz:d}=e;let l=r.ZERO,u=r.ZERO,p=r.ZERO;const y=t.a,f=r.mul(t.b,os);let g=r.mul(s,i),w=r.mul(a,o),m=r.mul(n,d),v=r.add(s,a),S=r.add(i,o);v=r.mul(v,S),S=r.add(g,w),v=r.sub(v,S),S=r.add(s,n);let _=r.add(i,d);return S=r.mul(S,_),_=r.add(g,m),S=r.sub(S,_),_=r.add(a,n),l=r.add(o,d),_=r.mul(_,l),l=r.add(w,m),_=r.sub(_,l),p=r.mul(y,S),l=r.mul(f,m),p=r.add(l,p),l=r.sub(w,p),p=r.add(w,p),u=r.mul(l,p),w=r.add(g,g),w=r.add(w,g),m=r.mul(y,m),S=r.mul(f,S),w=r.add(w,m),m=r.sub(g,m),m=r.mul(y,m),S=r.add(S,m),g=r.mul(w,S),u=r.add(u,g),g=r.mul(_,S),l=r.mul(v,l),l=r.sub(l,g),g=r.mul(v,w),p=r.mul(_,p),p=r.add(p,g),new h(l,u,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){const{endo:s,n:a}=t;Ct("scalar",e,ns,a);const n=h.ZERO;if(e===ns)return n;if(this.is0()||e===is)return this;if(!s||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,e,h.normalizeZ);let{k1neg:i,k1:o,k2neg:c,k2:d}=s.splitScalar(e),l=n,u=n,y=this;for(;o>ns||d>ns;)o&is&&(l=l.add(y)),d&is&&(u=u.add(y)),y=y.double(),o>>=is,d>>=is;return i&&(l=l.negate()),c&&(u=u.negate()),u=new h(r.mul(u.px,s.beta),u.py,u.pz),l.add(u)}multiply(e){const{endo:s,n:a}=t;let n,i;if(Ct("scalar",e,is,a),s){const{k1neg:t,k1:a,k2neg:o,k2:c}=s.splitScalar(e);let{p:d,f:l}=this.wNAF(a),{p:u,f:y}=this.wNAF(c);d=p.constTimeNegate(t,d),u=p.constTimeNegate(o,u),u=new h(r.mul(u.px,s.beta),u.py,u.pz),n=d.add(u),i=l.add(y)}else{const{p:t,f:r}=this.wNAF(e);n=t,i=r}return h.normalizeZ([n,i])[0]}multiplyAndAddUnsafe(e,t,r){const s=h.BASE,a=(e,t)=>t!==ns&&t!==is&&e.equals(s)?e.multiply(t):e.multiplyUnsafe(t),n=a(this,t).add(a(e,r));return n.is0()?void 0:n}toAffine(e){return d(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===is)return!0;if(r)return r(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===is?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return ot("isCompressed",e),this.assertValidity(),a(h,this,e)}toHex(e=!0){return ot("isCompressed",e),ut(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const u=t.nBitLength,p=(y=h,f=t.endo?Math.ceil(u/2):u,{constTimeNegate:$r,hasPrecomputes:e=>1!==Qr(e),unsafeLadder(e,t,r=y.ZERO){let s=e;for(;t>jr;)t&Hr&&(r=r.add(s)),s=s.double(),t>>=Hr;return r},precomputeWindow(e,t){const{windows:r,windowSize:s}=zr(t,f),a=[];let n=e,i=n;for(let e=0;e<r;e++){i=n,a.push(i);for(let e=1;e<s;e++)i=i.add(n),a.push(i);n=i.double()}return a},wNAF(e,t,r){let s=y.ZERO,a=y.BASE;const n=zr(e,f);for(let e=0;e<n.windows;e++){const{nextN:i,offset:o,isZero:c,isNeg:d,isNegF:l,offsetF:h}=Jr(r,e,n);r=i,c?a=a.add($r(l,t[h])):s=s.add($r(d,t[o]))}return{p:s,f:a}},wNAFUnsafe(e,t,r,s=y.ZERO){const a=zr(e,f);for(let e=0;e<a.windows&&r!==jr;e++){const{nextN:n,offset:i,isZero:o,isNeg:c}=Jr(r,e,a);if(r=n,!o){const e=t[i];s=s.add(c?e.negate():e)}}return s},getPrecomputes(e,t,r){let s=Xr.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&Xr.set(t,r(s))),s},wNAFCached(e,t,r){const s=Qr(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)},wNAFCachedUnsafe(e,t,r,s){const a=Qr(e);return 1===a?this.unsafeLadder(e,t,s):this.wNAFUnsafe(a,this.getPrecomputes(a,e,r),t,s)},setWindowSize(e,t){Yr(t,f),Zr.set(e,t),Xr.delete(e)}});var y,f;return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:o,weierstrassEquation:i,isWithinCurveOrder:function(e){return kt(e,is,t.n)}}}function ds(e){const t=function(e){const t=ts(e);return Rt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n:s}=t,a=r.BYTES+1,n=2*r.BYTES+1;function i(e){return Rr(e,s)}function o(e){return Lr(e,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:h}=cs({...t,toBytes(e,t,s){const a=t.toAffine(),n=r.toBytes(a.x),i=Pt;return ot("isCompressed",s),s?i(Uint8Array.from([t.hasEvenY()?2:3]),n):i(Uint8Array.from([4]),n,r.toBytes(a.y))},fromBytes(e){const t=e.length,s=e[0],i=e.subarray(1);if(t!==a||2!==s&&3!==s){if(t===n&&4===s){return{x:r.fromBytes(i.subarray(0,r.BYTES)),y:r.fromBytes(i.subarray(r.BYTES,2*r.BYTES))}}throw new Error("invalid Point, expected length of "+a+", or uncompressed "+n+", got "+t)}{const e=_t(i);if(!kt(e,is,r.ORDER))throw new Error("Point is not on curve");const t=l(e);let a;try{a=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~s)!==((a&is)===is)&&(a=r.neg(a)),{x:e,y:a}}}}),u=e=>ut(Et(e,t.nByteLength));function p(e){return e>s>>is}const y=(e,t,r)=>_t(e.slice(t,r));class f{constructor(e,t,r){Ct("r",e,is,s),Ct("s",t,is,s),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromCompact(e){const r=t.nByteLength;return e=It("compactSignature",e,2*r),new f(y(e,0,r),y(e,r,2*r))}static fromDER(e){const{r:t,s:r}=as.toSig(It("DER",e));return new f(t,r)}assertValidity(){}addRecoveryBit(e){return new f(this.r,this.s,e)}recoverPublicKey(e){const{r:s,s:a,recovery:n}=this,d=v(It("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const l=2===n||3===n?s+t.n:s;if(l>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&n?"03":"02",p=c.fromHex(h+u(l)),y=o(l),f=i(-d*y),g=i(a*y),w=c.BASE.multiplyAndAddUnsafe(p,f,g);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return St(this.toDERHex())}toDERHex(){return as.hexFromSig(this)}toCompactRawBytes(){return St(this.toCompactHex())}toCompactHex(){return u(this.r)+u(this.s)}}const g={isValidPrivateKey(e){try{return d(e),!0}catch(e){return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const e=Gr(t.n);return function(e,t,r=!1){const s=e.length,a=Fr(t),n=Gr(t);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const i=Rr(r?At(e):_t(e),t-kr)+kr;return r?bt(i,a):Et(i,a)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function w(e){const t=nt(e),r="string"==typeof e,s=(t||r)&&e.length;return t?s===a||s===n:r?s===2*a||s===2*n:e instanceof c}const m=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const r=_t(e),s=8*e.length-t.nBitLength;return s>0?r>>BigInt(s):r},v=t.bits2int_modN||function(e){return i(m(e))},S=xt(t.nBitLength);function _(e){return Ct("num < 2^"+t.nBitLength,e,ns,S),Et(e,t.nByteLength)}function A(e,s,a=E){if(["recovered","canonical"].some((e=>e in a)))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:l}=t;let{lowS:u,prehash:y,extraEntropy:g}=a;null==u&&(u=!0),e=It("msgHash",e),rs(a),y&&(e=It("prehashed msgHash",n(e)));const w=v(e),S=d(s),A=[_(S),_(w)];if(null!=g&&!1!==g){const e=!0===g?l(r.BYTES):g;A.push(It("extraEntropy",e))}const b=Pt(...A),I=w;return{seed:b,k2sig:function(e){const t=m(e);if(!h(t))return;const r=o(t),s=c.BASE.multiply(t).toAffine(),a=i(s.x);if(a===ns)return;const n=i(r*i(I+a*S));if(n===ns)return;let d=(s.x===a?0:2)|Number(s.y&is),l=n;return u&&p(n)&&(l=function(e){return p(e)?i(-e):e}(n),d^=1),new f(a,l,d)}}}const E={lowS:t.lowS,prehash:!1},b={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(w(e))throw new Error("first arg must be private key");if(!w(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(d(e)).toRawBytes(r)},sign:function(e,r,s=E){const{seed:a,k2sig:n}=A(e,r,s),i=t,o=function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let s=Kt(e),a=Kt(e),n=0;const i=()=>{s.fill(1),a.fill(0),n=0},o=(...e)=>r(a,s,...e),c=(e=Kt(0))=>{a=o(Ot([0]),e),s=o(),0!==e.length&&(a=o(Ot([1]),e),s=o())},d=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){s=o();const t=s.slice();r.push(t),e+=s.length}return Pt(...r)};return(e,t)=>{let r;for(i(),c(e);!(r=t(d()));)c();return i(),r}}(i.hash.outputLen,i.nByteLength,i.hmac);return o(a,n)},verify:function(e,r,s,a=b){const n=e;r=It("msgHash",r),s=It("publicKey",s);const{lowS:d,prehash:l,format:h}=a;if(rs(a),"strict"in a)throw new Error("options.strict was renamed to lowS");if(void 0!==h&&"compact"!==h&&"der"!==h)throw new Error("format must be compact or der");const u="string"==typeof n||nt(n),p=!u&&!h&&"object"==typeof n&&null!==n&&"bigint"==typeof n.r&&"bigint"==typeof n.s;if(!u&&!p)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let y,g;try{if(p&&(y=new f(n.r,n.s)),u){try{"compact"!==h&&(y=f.fromDER(n))}catch(e){if(!(e instanceof as.Err))throw e}y||"der"===h||(y=f.fromCompact(n))}g=c.fromHex(s)}catch(e){return!1}if(!y)return!1;if(d&&y.hasHighS())return!1;l&&(r=t.hash(r));const{r:w,s:m}=y,S=v(r),_=o(m),A=i(S*_),E=i(w*_),I=c.BASE.multiplyAndAddUnsafe(g,A,E)?.toAffine();return!!I&&i(I.x)===w},ProjectivePoint:c,Signature:f,utils:g}}
|
|
9
|
-
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function
|
|
10
|
-
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
11
|
-
const hs=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),us=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ps=BigInt(1),ys=BigInt(2),fs=(e,t)=>(e+t/ys)/t;const gs=Wr(hs,void 0,void 0,{sqrt:function(e){const t=hs,r=BigInt(3),s=BigInt(6),a=BigInt(11),n=BigInt(22),i=BigInt(23),o=BigInt(44),c=BigInt(88),d=e*e*e%t,l=d*d*e%t,h=Dr(l,r,t)*l%t,u=Dr(h,r,t)*l%t,p=Dr(u,ys,t)*d%t,y=Dr(p,a,t)*p%t,f=Dr(y,n,t)*y%t,g=Dr(f,o,t)*f%t,w=Dr(g,c,t)*g%t,m=Dr(w,o,t)*f%t,v=Dr(m,r,t)*l%t,S=Dr(v,i,t)*y%t,_=Dr(S,s,t)*d%t,A=Dr(_,ys,t);if(!gs.eql(gs.sqr(A),e))throw new Error("Cannot find square root");return A}}),ws=function(e,t){const r=t=>ds({...e,...ls(t)});return{...r(t),create:r}}({a:BigInt(0),b:BigInt(7),Fp:gs,n:us,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=us,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),s=-ps*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=r,i=BigInt("0x100000000000000000000000000000000"),o=fs(n*e,t),c=fs(-s*e,t);let d=Rr(e-o*r-c*a,t),l=Rr(-o*s-c*n,t);const h=d>i,u=l>i;if(h&&(d=t-d),u&&(l=t-l),d>i||l>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:d,k2neg:u,k2:l}}}},Ar);BigInt(0),ws.ProjectivePoint;const ms=e=>{const t=qt(e),r=ws.getPublicKey(t),s=ws.ProjectivePoint.fromHex(r);return Mt(Me(s.toRawBytes(!1)))},vs=BigInt(0),Ss=BigInt(1),_s=BigInt(2),As=BigInt(7),Es=BigInt(256),bs=BigInt(113),Is=[],Ps=[],Ts=[];for(let e=0,t=Ss,r=1,s=0;e<24;e++){[r,s]=[s,(2*r+3*s)%5],Is.push(2*(5*s+r)),Ps.push((e+1)*(e+2)/2%64);let a=vs;for(let e=0;e<7;e++)t=(t<<Ss^(t>>As)*bs)%Es,t&_s&&(a^=Ss<<(Ss<<BigInt(e))-Ss);Ts.push(a)}const ks=Xt(Ts,!0),Cs=ks[0],xs=ks[1],Ks=(e,t,r)=>r>32?((e,t,r)=>t<<r-32|e>>>64-r)(e,t,r):((e,t,r)=>e<<r|t>>>32-r)(e,t,r),Os=(e,t,r)=>r>32?((e,t,r)=>e<<r-32|t>>>64-r)(e,t,r):((e,t,r)=>t<<r|e>>>32-r)(e,t,r);class Ns extends Ze{constructor(e,t,r,s=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=a,Pe(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ke(this.state)}clone(){return this._cloneInto()}keccak(){Be(this.state32),function(e,t=24){const r=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const s=(t+8)%10,a=(t+2)%10,n=r[a],i=r[a+1],o=Ks(n,i,1)^r[s],c=Os(n,i,1)^r[s+1];for(let r=0;r<50;r+=10)e[t+r]^=o,e[t+r+1]^=c}let t=e[2],a=e[3];for(let r=0;r<24;r++){const s=Ps[r],n=Ks(t,a,s),i=Os(t,a,s),o=Is[r];t=e[o],a=e[o+1],e[o]=n,e[o+1]=i}for(let t=0;t<50;t+=10){for(let s=0;s<10;s++)r[s]=e[t+s];for(let s=0;s<10;s++)e[t+s]^=~r[(s+2)%10]&r[(s+4)%10]}e[0]^=Cs[s],e[1]^=xs[s]}Oe(r)}(this.state32,this.rounds),Be(this.state32),this.posOut=0,this.pos=0}update(e){Ce(this),Te(e=Je(e));const{blockLen:t,state:r}=this,s=e.length;for(let a=0;a<s;){const n=Math.min(t-this.pos,s-a);for(let t=0;t<n;t++)r[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:s}=this;e[r]^=t,128&t&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Ce(this,!1),Te(e),this.finish();const t=this.state,{blockLen:r}=this;for(let s=0,a=e.length;s<a;){this.posOut>=r&&this.keccak();const n=Math.min(r-this.posOut,a-s);e.set(t.subarray(this.posOut,this.posOut+n),s),this.posOut+=n,s+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Pe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(xe(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Oe(this.state)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:s,rounds:a,enableXOF:n}=this;return e||(e=new Ns(t,r,s,n,a)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=r,e.outputLen=s,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Rs=(()=>{return e=1,t=136,r=32,Qe((()=>new Ns(t,e,r)));var e,t,r})(),Ds=(()=>{const e=Bt(Rs);return e.create=Rs.create,e})(),Ls=e=>{const t=(e=>{if(e){if(!(e instanceof Uint8Array)||e.length<32)throw new Error("entropy must be a Uint8Array of at least 32 bytes");const t=new Set(e);if(t.size<Math.min(8,e.length/4))throw new Error(`entropy is too repetitive (only ${t.size} unique byte values)`);const r=Ds(e);return Vt(Me(r))}{const e=Ds(Wt([rt(32),rt(32)])),t=Wt([Wt([rt(32),e]),rt(32)]),r=Ds(t);return Vt(Me(r))}})(e),r=ms(t);return{privateKey:t,publicKey:qt(r)}},Us=(e,t)=>{const r=Vt(t);if(66!==r.length||("string"!=typeof(s=r)||!s.match(/^0x[0-9A-Fa-f]+$/)))throw new Error("Can only sign hashes, given: "+t);var s;const a=ws.sign(Ut(qt(t)),Ut(qt(e))),n=1===a.recovery?"1c":"1b";return"0x"+a.toCompactHex()+n},Bs=(e,t)=>Pr(Ar,e,t),qs=Bt(Er);function Vs(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
|
|
7
|
+
const Yr=BigInt(0),zr=BigInt(1);function Jr(e,t){const r=t.negate();return e?r:t}function Xr(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Zr(e,t){Xr(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:xt(e),maxNumber:r,shiftBy:BigInt(e)}}function Qr(e,t,r){const{windowSize:s,mask:a,maxNumber:n,shiftBy:o}=r;let i=Number(e&a),c=e>>o;i>s&&(i-=n,c+=zr);const d=t*s;return{nextN:c,offset:d+Math.abs(i)-1,isZero:0===i,isNeg:i<0,isNegF:t%2!=0,offsetF:d}}const es=new WeakMap,ts=new WeakMap;function rs(e){return ts.get(e)||1}function ss(e,t,r,s){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)}))}(s,t),r.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const a=e.ZERO,n=function(e){let t;for(t=0;e>st;e>>=at,t+=1);return t}(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,i=xt(o),c=new Array(Number(i)+1).fill(a);let d=a;for(let e=Math.floor((t.BITS-1)/o)*o;e>=0;e-=o){c.fill(a);for(let t=0;t<s.length;t++){const a=s[t],n=Number(a>>BigInt(e)&i);c[n]=c[n].add(r[t])}let t=a;for(let e=c.length-1,r=a;e>0;e--)r=r.add(c[e]),t=t.add(r);if(d=d.add(t),0!==e)for(let e=0;e<o;e++)d=d.double()}return d}function as(e){return Rt(e.Fp,Vr.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),Rt(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Wr(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}
|
|
8
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ns(e){void 0!==e.lowS&&it("lowS",e.lowS),void 0!==e.prehash&&it("prehash",e.prehash)}class os extends Error{constructor(e=""){super(e)}}const is={Err:os,_tlv:{encode:(e,t)=>{const{Err:r}=is;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const s=t.length/2,a=ct(s);if(a.length/2&128)throw new r("tlv.encode: long form length too big");const n=s>127?ct(a.length/2|128):"";return ct(e)+n+a+t},decode(e,t){const{Err:r}=is;let s=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new r("tlv.decode: wrong tlv");const a=t[s++];let n=0;if(!!(128&a)){const e=127&a;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const o=t.subarray(s,s+e);if(o.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of o)n=n<<8|e;if(s+=e,n<128)throw new r("tlv.decode(long): not minimal encoding")}else n=a;const o=t.subarray(s,s+n);if(o.length!==n)throw new r("tlv.decode: wrong value length");return{v:o,l:t.subarray(s+n)}}},_int:{encode(e){const{Err:t}=is;if(e<cs)throw new t("integer: negative integers are not allowed");let r=ct(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=is;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return At(e)}},toSig(e){const{Err:t,_int:r,_tlv:s}=is,a=kt("signature",e),{v:n,l:o}=s.decode(48,a);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:i,l:c}=s.decode(2,n),{v:d,l:l}=s.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(i),s:r.decode(d)}},hexFromSig(e){const{_tlv:t,_int:r}=is,s=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,s)}},cs=BigInt(0),ds=BigInt(1);BigInt(2);const ls=BigInt(3);function us(e){const t=function(e){const t=as(e);Rt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:s,a:a}=t;if(r){if(!s.eql(a,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if("object"!=typeof r||"bigint"!=typeof r.beta||"function"!=typeof r.splitScalar)throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,s=jr(t.n,t.nBitLength),a=t.toBytes||((e,t,s)=>{const a=t.toAffine();return It(Uint8Array.from([4]),r.toBytes(a.x),r.toBytes(a.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function o(e){const{a:s,b:a}=t,n=r.sqr(e),o=r.mul(n,e);return r.add(r.add(o,r.mul(e,s)),a)}if(!r.eql(r.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function i(e){const{allowedPrivateKeyLengths:r,nByteLength:s,wrapPrivateKey:a,n:n}=t;if(r&&"bigint"!=typeof e){if(nt(e)&&(e=ht(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*s,"0")}let o;try{o="bigint"==typeof e?e:At(kt("private key",e,s))}catch(t){throw new Error("invalid private key, expected hex or "+s+" bytes, got "+typeof e)}return a&&(o=Br(o,n)),Ct("private key",o,ds,n),o}function c(e){if(!(e instanceof u))throw new Error("ProjectivePoint expected")}const d=Dt(((e,t)=>{const{px:s,py:a,pz:n}=e;if(r.eql(n,r.ONE))return{x:s,y:a};const o=e.is0();null==t&&(t=o?r.ONE:r.inv(n));const i=r.mul(s,t),c=r.mul(a,t),d=r.mul(n,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(d,r.ONE))throw new Error("invZ was invalid");return{x:i,y:c}})),l=Dt((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:s,y:a}=e.toAffine();if(!r.isValid(s)||!r.isValid(a))throw new Error("bad point: x or y not FE");const n=r.sqr(a),i=o(s);if(!r.eql(n,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class u{constructor(e,t,s){if(null==e||!r.isValid(e))throw new Error("x required");if(null==t||!r.isValid(t)||r.is0(t))throw new Error("y required");if(null==s||!r.isValid(s))throw new Error("z required");this.px=e,this.py=t,this.pz=s,Object.freeze(this)}static fromAffine(e){const{x:t,y:s}=e||{};if(!e||!r.isValid(t)||!r.isValid(s))throw new Error("invalid affine point");if(e instanceof u)throw new Error("projective point not allowed");const a=e=>r.eql(e,r.ZERO);return a(t)&&a(s)?u.ZERO:new u(t,s,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=Fr(r,e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(u.fromAffine)}static fromHex(e){const t=u.fromAffine(n(kt("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return u.BASE.multiply(i(e))}static msm(e,t){return ss(u,s,e,t)}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){l(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:s,pz:a}=this,{px:n,py:o,pz:i}=e,d=r.eql(r.mul(t,i),r.mul(n,a)),l=r.eql(r.mul(s,i),r.mul(o,a));return d&&l}negate(){return new u(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:s}=t,a=r.mul(s,ls),{px:n,py:o,pz:i}=this;let c=r.ZERO,d=r.ZERO,l=r.ZERO,h=r.mul(n,n),p=r.mul(o,o),f=r.mul(i,i),y=r.mul(n,o);return y=r.add(y,y),l=r.mul(n,i),l=r.add(l,l),c=r.mul(e,l),d=r.mul(a,f),d=r.add(c,d),c=r.sub(p,d),d=r.add(p,d),d=r.mul(c,d),c=r.mul(y,c),l=r.mul(a,l),f=r.mul(e,f),y=r.sub(h,f),y=r.mul(e,y),y=r.add(y,l),l=r.add(h,h),h=r.add(l,h),h=r.add(h,f),h=r.mul(h,y),d=r.add(d,h),f=r.mul(o,i),f=r.add(f,f),h=r.mul(f,y),c=r.sub(c,h),l=r.mul(f,p),l=r.add(l,l),l=r.add(l,l),new u(c,d,l)}add(e){c(e);const{px:s,py:a,pz:n}=this,{px:o,py:i,pz:d}=e;let l=r.ZERO,h=r.ZERO,p=r.ZERO;const f=t.a,y=r.mul(t.b,ls);let g=r.mul(s,o),w=r.mul(a,i),m=r.mul(n,d),v=r.add(s,a),S=r.add(o,i);v=r.mul(v,S),S=r.add(g,w),v=r.sub(v,S),S=r.add(s,n);let A=r.add(o,d);return S=r.mul(S,A),A=r.add(g,m),S=r.sub(S,A),A=r.add(a,n),l=r.add(i,d),A=r.mul(A,l),l=r.add(w,m),A=r.sub(A,l),p=r.mul(f,S),l=r.mul(y,m),p=r.add(l,p),l=r.sub(w,p),p=r.add(w,p),h=r.mul(l,p),w=r.add(g,g),w=r.add(w,g),m=r.mul(f,m),S=r.mul(y,S),w=r.add(w,m),m=r.sub(g,m),m=r.mul(f,m),S=r.add(S,m),g=r.mul(w,S),h=r.add(h,g),g=r.mul(A,S),l=r.mul(v,l),l=r.sub(l,g),g=r.mul(v,w),p=r.mul(A,p),p=r.add(p,g),new u(l,h,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(u.ZERO)}wNAF(e){return p.wNAFCached(this,e,u.normalizeZ)}multiplyUnsafe(e){const{endo:s,n:a}=t;Ct("scalar",e,cs,a);const n=u.ZERO;if(e===cs)return n;if(this.is0()||e===ds)return this;if(!s||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,e,u.normalizeZ);let{k1neg:o,k1:i,k2neg:c,k2:d}=s.splitScalar(e),l=n,h=n,f=this;for(;i>cs||d>cs;)i&ds&&(l=l.add(f)),d&ds&&(h=h.add(f)),f=f.double(),i>>=ds,d>>=ds;return o&&(l=l.negate()),c&&(h=h.negate()),h=new u(r.mul(h.px,s.beta),h.py,h.pz),l.add(h)}multiply(e){const{endo:s,n:a}=t;let n,o;if(Ct("scalar",e,ds,a),s){const{k1neg:t,k1:a,k2neg:i,k2:c}=s.splitScalar(e);let{p:d,f:l}=this.wNAF(a),{p:h,f:f}=this.wNAF(c);d=p.constTimeNegate(t,d),h=p.constTimeNegate(i,h),h=new u(r.mul(h.px,s.beta),h.py,h.pz),n=d.add(h),o=l.add(f)}else{const{p:t,f:r}=this.wNAF(e);n=t,o=r}return u.normalizeZ([n,o])[0]}multiplyAndAddUnsafe(e,t,r){const s=u.BASE,a=(e,t)=>t!==cs&&t!==ds&&e.equals(s)?e.multiply(t):e.multiplyUnsafe(t),n=a(this,t).add(a(e,r));return n.is0()?void 0:n}toAffine(e){return d(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===ds)return!0;if(r)return r(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===ds?this:r?r(u,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return it("isCompressed",e),this.assertValidity(),a(u,this,e)}toHex(e=!0){return it("isCompressed",e),ht(this.toRawBytes(e))}}u.BASE=new u(t.Gx,t.Gy,r.ONE),u.ZERO=new u(r.ZERO,r.ONE,r.ZERO);const h=t.nBitLength,p=(f=u,y=t.endo?Math.ceil(h/2):h,{constTimeNegate:Jr,hasPrecomputes:e=>1!==rs(e),unsafeLadder(e,t,r=f.ZERO){let s=e;for(;t>Yr;)t&zr&&(r=r.add(s)),s=s.double(),t>>=zr;return r},precomputeWindow(e,t){const{windows:r,windowSize:s}=Zr(t,y),a=[];let n=e,o=n;for(let e=0;e<r;e++){o=n,a.push(o);for(let e=1;e<s;e++)o=o.add(n),a.push(o);n=o.double()}return a},wNAF(e,t,r){let s=f.ZERO,a=f.BASE;const n=Zr(e,y);for(let e=0;e<n.windows;e++){const{nextN:o,offset:i,isZero:c,isNeg:d,isNegF:l,offsetF:u}=Qr(r,e,n);r=o,c?a=a.add(Jr(l,t[u])):s=s.add(Jr(d,t[i]))}return{p:s,f:a}},wNAFUnsafe(e,t,r,s=f.ZERO){const a=Zr(e,y);for(let e=0;e<a.windows&&r!==Yr;e++){const{nextN:n,offset:o,isZero:i,isNeg:c}=Qr(r,e,a);if(r=n,!i){const e=t[o];s=s.add(c?e.negate():e)}}return s},getPrecomputes(e,t,r){let s=es.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&es.set(t,r(s))),s},wNAFCached(e,t,r){const s=rs(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)},wNAFCachedUnsafe(e,t,r,s){const a=rs(e);return 1===a?this.unsafeLadder(e,t,s):this.wNAFUnsafe(a,this.getPrecomputes(a,e,r),t,s)},setWindowSize(e,t){Xr(t,y),ts.set(e,t),es.delete(e)}});var f,y;return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:i,weierstrassEquation:o,isWithinCurveOrder:function(e){return Pt(e,ds,t.n)}}}function hs(e){const t=function(e){const t=as(e);return Rt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n:s}=t,a=r.BYTES+1,n=2*r.BYTES+1;function o(e){return Br(e,s)}function i(e){return qr(e,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:u}=us({...t,toBytes(e,t,s){const a=t.toAffine(),n=r.toBytes(a.x),o=It;return it("isCompressed",s),s?o(Uint8Array.from([t.hasEvenY()?2:3]),n):o(Uint8Array.from([4]),n,r.toBytes(a.y))},fromBytes(e){const t=e.length,s=e[0],o=e.subarray(1);if(t!==a||2!==s&&3!==s){if(t===n&&4===s){return{x:r.fromBytes(o.subarray(0,r.BYTES)),y:r.fromBytes(o.subarray(r.BYTES,2*r.BYTES))}}throw new Error("invalid Point, expected length of "+a+", or uncompressed "+n+", got "+t)}{const e=At(o);if(!Pt(e,ds,r.ORDER))throw new Error("Point is not on curve");const t=l(e);let a;try{a=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~s)!==((a&ds)===ds)&&(a=r.neg(a)),{x:e,y:a}}}}),h=e=>ht(Et(e,t.nByteLength));function p(e){return e>s>>ds}const f=(e,t,r)=>At(e.slice(t,r));class y{constructor(e,t,r){Ct("r",e,ds,s),Ct("s",t,ds,s),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromCompact(e){const r=t.nByteLength;return e=kt("compactSignature",e,2*r),new y(f(e,0,r),f(e,r,2*r))}static fromDER(e){const{r:t,s:r}=is.toSig(kt("DER",e));return new y(t,r)}assertValidity(){}addRecoveryBit(e){return new y(this.r,this.s,e)}recoverPublicKey(e){const{r:s,s:a,recovery:n}=this,d=v(kt("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const l=2===n||3===n?s+t.n:s;if(l>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const u=1&n?"03":"02",p=c.fromHex(u+h(l)),f=i(l),y=o(-d*f),g=o(a*f),w=c.BASE.multiplyAndAddUnsafe(p,y,g);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return St(this.toDERHex())}toDERHex(){return is.hexFromSig(this)}toCompactRawBytes(){return St(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const g={isValidPrivateKey(e){try{return d(e),!0}catch(e){return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const e=Hr(t.n);return function(e,t,r=!1){const s=e.length,a=Gr(t),n=Hr(t);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=Br(r?bt(e):At(e),t-Kr)+Kr;return r?_t(o,a):Et(o,a)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function w(e){const t=nt(e),r="string"==typeof e,s=(t||r)&&e.length;return t?s===a||s===n:r?s===2*a||s===2*n:e instanceof c}const m=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const r=At(e),s=8*e.length-t.nBitLength;return s>0?r>>BigInt(s):r},v=t.bits2int_modN||function(e){return o(m(e))},S=xt(t.nBitLength);function A(e){return Ct("num < 2^"+t.nBitLength,e,cs,S),Et(e,t.nByteLength)}function b(e,s,a=E){if(["recovered","canonical"].some((e=>e in a)))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:l}=t;let{lowS:h,prehash:f,extraEntropy:g}=a;null==h&&(h=!0),e=kt("msgHash",e),ns(a),f&&(e=kt("prehashed msgHash",n(e)));const w=v(e),S=d(s),b=[A(S),A(w)];if(null!=g&&!1!==g){const e=!0===g?l(r.BYTES):g;b.push(kt("extraEntropy",e))}const _=It(...b),k=w;return{seed:_,k2sig:function(e){const t=m(e);if(!u(t))return;const r=i(t),s=c.BASE.multiply(t).toAffine(),a=o(s.x);if(a===cs)return;const n=o(r*o(k+a*S));if(n===cs)return;let d=(s.x===a?0:2)|Number(s.y&ds),l=n;return h&&p(n)&&(l=function(e){return p(e)?o(-e):e}(n),d^=1),new y(a,l,d)}}}const E={lowS:t.lowS,prehash:!1},_={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(w(e))throw new Error("first arg must be private key");if(!w(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(d(e)).toRawBytes(r)},sign:function(e,r,s=E){const{seed:a,k2sig:n}=b(e,r,s),o=t,i=function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let s=Kt(e),a=Kt(e),n=0;const o=()=>{s.fill(1),a.fill(0),n=0},i=(...e)=>r(a,s,...e),c=(e=Kt(0))=>{a=i(Ot([0]),e),s=i(),0!==e.length&&(a=i(Ot([1]),e),s=i())},d=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){s=i();const t=s.slice();r.push(t),e+=s.length}return It(...r)};return(e,t)=>{let r;for(o(),c(e);!(r=t(d()));)c();return o(),r}}(o.hash.outputLen,o.nByteLength,o.hmac);return i(a,n)},verify:function(e,r,s,a=_){const n=e;r=kt("msgHash",r),s=kt("publicKey",s);const{lowS:d,prehash:l,format:u}=a;if(ns(a),"strict"in a)throw new Error("options.strict was renamed to lowS");if(void 0!==u&&"compact"!==u&&"der"!==u)throw new Error("format must be compact or der");const h="string"==typeof n||nt(n),p=!h&&!u&&"object"==typeof n&&null!==n&&"bigint"==typeof n.r&&"bigint"==typeof n.s;if(!h&&!p)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let f,g;try{if(p&&(f=new y(n.r,n.s)),h){try{"compact"!==u&&(f=y.fromDER(n))}catch(e){if(!(e instanceof is.Err))throw e}f||"der"===u||(f=y.fromCompact(n))}g=c.fromHex(s)}catch(e){return!1}if(!f)return!1;if(d&&f.hasHighS())return!1;l&&(r=t.hash(r));const{r:w,s:m}=f,S=v(r),A=i(m),b=o(S*A),E=o(w*A),k=c.BASE.multiplyAndAddUnsafe(g,b,E)?.toAffine();return!!k&&o(k.x)===w},ProjectivePoint:c,Signature:y,utils:g}}
|
|
9
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ps(e){return{hash:e,hmac:(t,...r)=>Cr(e,t,function(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];Te(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const a=e[t];r.set(a,s),s+=a.length}return r}(...r)),randomBytes:tt}}function fs(e,t){const r=t=>hs({...e,...ps(t)});return{...r(t),create:r}}
|
|
10
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(4);const ys=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),gs=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ws=BigInt(1),ms=BigInt(2),vs=(e,t)=>(e+t/ms)/t;const Ss=jr(ys,void 0,void 0,{sqrt:function(e){const t=ys,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,u=Ur(l,r,t)*l%t,h=Ur(u,r,t)*l%t,p=Ur(h,ms,t)*d%t,f=Ur(p,a,t)*p%t,y=Ur(f,n,t)*f%t,g=Ur(y,i,t)*y%t,w=Ur(g,c,t)*g%t,m=Ur(w,i,t)*y%t,v=Ur(m,r,t)*l%t,S=Ur(v,o,t)*f%t,A=Ur(S,s,t)*d%t,b=Ur(A,ms,t);if(!Ss.eql(Ss.sqr(b),e))throw new Error("Cannot find square root");return b}}),As=fs({a:BigInt(0),b:BigInt(7),Fp:Ss,n:gs,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=gs,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),s=-ws*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=r,o=BigInt("0x100000000000000000000000000000000"),i=vs(n*e,t),c=vs(-s*e,t);let d=Br(e-i*r-c*a,t),l=Br(-i*s-c*n,t);const u=d>o,h=l>o;if(u&&(d=t-d),h&&(l=t-l),d>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:d,k2neg:h,k2:l}}}},_r);BigInt(0),As.ProjectivePoint;const bs=e=>{const t=qt(e),r=As.getPublicKey(t),s=As.ProjectivePoint.fromHex(r);return Vt(Ve(s.toRawBytes(!1)))},Es=BigInt(0),_s=BigInt(1),ks=BigInt(2),Is=BigInt(7),Ts=BigInt(256),Ps=BigInt(113),Cs=[],xs=[],Ks=[];for(let e=0,t=_s,r=1,s=0;e<24;e++){[r,s]=[s,(2*r+3*s)%5],Cs.push(2*(5*s+r)),xs.push((e+1)*(e+2)/2%64);let a=Es;for(let e=0;e<7;e++)t=(t<<_s^(t>>Is)*Ps)%Ts,t&ks&&(a^=_s<<(_s<<BigInt(e))-_s);Ks.push(a)}const Os=Zt(Ks,!0),Ns=Os[0],Rs=Os[1],Ds=(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),Ls=(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 Bs extends Ze{constructor(e,t,r,s=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=a,Ie(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ke(this.state)}clone(){return this._cloneInto()}keccak(){Ue(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=Ds(n,o,1)^r[s],c=Ls(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=xs[r],n=Ds(t,a,s),o=Ls(t,a,s),i=Cs[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]^=Ns[s],e[1]^=Rs[s]}Oe(r)}(this.state32,this.rounds),Ue(this.state32),this.posOut=0,this.pos=0}update(e){Ce(this),Te(e=Je(e));const{blockLen:t,state:r}=this,s=e.length;for(let a=0;a<s;){const n=Math.min(t-this.pos,s-a);for(let t=0;t<n;t++)r[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:s}=this;e[r]^=t,128&t&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Ce(this,!1),Te(e),this.finish();const t=this.state,{blockLen:r}=this;for(let s=0,a=e.length;s<a;){this.posOut>=r&&this.keccak();const n=Math.min(r-this.posOut,a-s);e.set(t.subarray(this.posOut,this.posOut+n),s),this.posOut+=n,s+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ie(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(xe(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Oe(this.state)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:s,rounds:a,enableXOF:n}=this;return e||(e=new Bs(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 Us=(()=>{return e=1,t=136,r=32,Qe((()=>new Bs(t,e,r)));var e,t,r})(),qs=(()=>{const e=Ut(Us);return e.create=Us.create,e})(),Ms=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=qs(e);return Mt(Ve(r))}{const e=qs(Ft([rt(32),rt(32)])),t=Ft([Ft([rt(32),e]),rt(32)]),r=qs(t);return Mt(Ve(r))}})(e),r=bs(t);return{privateKey:t,publicKey:qt(r)}},Vs=(e,t)=>{const r=Mt(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=As.sign(Bt(qt(t)),Bt(qt(e))),n=1===a.recovery?"1c":"1b";return"0x"+a.toCompactHex()+n},Fs=(e,t)=>Cr(_r,e,t),$s=Ut(kr);function Ws(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(r)&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");
|
|
12
11
|
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
13
|
-
var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ms(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ws(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Fs=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Gs(e,t){if(s=t,(r=e).buffer===s.buffer&&r.byteOffset<s.byteOffset+s.byteLength&&s.byteOffset<r.byteOffset+r.byteLength&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported");var r,s}const js=(e,t)=>{function r(r,...s){if(Vs(r),!Fs)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=s[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?Vs(t):Vs(t,e.nonceLength)}const a=e.tagLength;a&&void 0!==s[1]&&Vs(s[1]);const n=t(r,...s),i=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Vs(t)}};let o=!1;const c={encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Vs(e),i(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(Vs(e),a&&e.length<a)throw new Error("invalid ciphertext length: smaller than tagLength="+a);return i(n.decrypt.length,t),n.decrypt(e,t)}};return c}return Object.assign(r,e),r};function Hs(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!$s(t))throw new Error("invalid output, must be aligned");return t}function $s(e){return e.byteOffset%4==0}function Ys(e){return Uint8Array.from(e)}const zs=16;function Js(e){return e<<1^283&-(e>>7)}function Xs(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=Js(e);return r}const Zs=(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=Js(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let s=e[255-r];s|=s<<8,t[e[r]]=255&(s^s>>4^s>>5^s>>6^s>>7^99)}return Ws(e),t})(),Qs=Zs.map(((e,t)=>Zs.indexOf(t))),ea=e=>e<<8|e>>>24;function ta(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map(((r,s)=>t(e[s]))),s=r.map(ea),a=s.map(ea),n=a.map(ea),i=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let d=0;d<256;d++){const l=256*t+d;i[l]=r[t]^s[d],o[l]=a[t]^n[d],c[l]=e[t]<<8|e[d]}return{sbox:e,sbox2:c,T0:r,T1:s,T2:a,T3:n,T01:i,T23:o}}const ra=ta(Zs,(e=>Xs(e,3)<<24|e<<16|e<<8|Xs(e,2))),sa=ta(Qs,(e=>Xs(e,11)<<24|Xs(e,13)<<16|Xs(e,9)<<8|Xs(e,14))),aa=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=Js(r))e[t]=r;return e})();function na(e){Vs(e);const t=e.length;if(![16,24,32].includes(t))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+t);const{sbox2:r}=ra,s=[];$s(e)||s.push(e=Ys(e));const a=Ms(e),n=a.length,i=e=>oa(r,e,e,e,e),o=new Uint32Array(t+28);o.set(a);for(let e=n;e<o.length;e++){let t=o[e-1];e%n==0?t=i((c=t)<<24|c>>>8)^aa[e/n-1]:n>6&&e%n==4&&(t=i(t)),o[e]=o[e-n]^t}var c;return Ws(...s),o}function ia(e,t,r,s,a,n){return e[r<<8&65280|s>>>8&255]^t[a>>>8&65280|n>>>24&255]}function oa(e,t,r,s,a){return e[255&t|65280&r]|e[s>>>16&255|a>>>16&65280]<<16}function ca(e,t,r,s,a){const{sbox2:n,T01:i,T23:o}=ra;let c=0;t^=e[c++],r^=e[c++],s^=e[c++],a^=e[c++];const d=e.length/4-2;for(let n=0;n<d;n++){const n=e[c++]^ia(i,o,t,r,s,a),d=e[c++]^ia(i,o,r,s,a,t),l=e[c++]^ia(i,o,s,a,t,r),h=e[c++]^ia(i,o,a,t,r,s);t=n,r=d,s=l,a=h}return{s0:e[c++]^oa(n,t,r,s,a),s1:e[c++]^oa(n,r,s,a,t),s2:e[c++]^oa(n,s,a,t,r),s3:e[c++]^oa(n,a,t,r,s)}}function da(e,t,r,s,a){const{sbox2:n,T01:i,T23:o}=sa;let c=0;t^=e[c++],r^=e[c++],s^=e[c++],a^=e[c++];const d=e.length/4-2;for(let n=0;n<d;n++){const n=e[c++]^ia(i,o,t,a,s,r),d=e[c++]^ia(i,o,r,t,a,s),l=e[c++]^ia(i,o,s,r,t,a),h=e[c++]^ia(i,o,a,s,r,t);t=n,r=d,s=l,a=h}return{s0:e[c++]^oa(n,t,a,s,r),s1:e[c++]^oa(n,r,t,a,s),s2:e[c++]^oa(n,s,r,t,a),s3:e[c++]^oa(n,a,s,r,t)}}function la(e,t,r,s){Vs(t,zs),Vs(r);const a=r.length;Gs(r,s=Hs(a,s));const n=t,i=Ms(n);let{s0:o,s1:c,s2:d,s3:l}=ca(e,i[0],i[1],i[2],i[3]);const h=Ms(r),u=Ms(s);for(let t=0;t+4<=h.length;t+=4){u[t+0]=h[t+0]^o,u[t+1]=h[t+1]^c,u[t+2]=h[t+2]^d,u[t+3]=h[t+3]^l;let r=1;for(let e=n.length-1;e>=0;e--)r=r+(255&n[e])|0,n[e]=255&r,r>>>=8;({s0:o,s1:c,s2:d,s3:l}=ca(e,i[0],i[1],i[2],i[3]))}const p=zs*Math.floor(h.length/4);if(p<a){const e=new Uint32Array([o,c,d,l]),t=(y=e,new Uint8Array(y.buffer,y.byteOffset,y.byteLength));for(let e=p,n=0;e<a;e++,n++)s[e]=r[e]^t[n];Ws(e)}var y;return s}const ha=js({blockSize:16,nonceLength:16},(function(e,t){function r(r,s){if(Vs(r),void 0!==s&&(Vs(s),!$s(s)))throw new Error("unaligned destination");const a=na(e),n=Ys(t),i=[a,n];$s(r)||i.push(r=Ys(r));const o=la(a,n,r,s);return Ws(...i),o}return{encrypt:(e,t)=>r(e,t),decrypt:(e,t)=>r(e,t)}}));const ua=js({blockSize:16,nonceLength:16},(function(e,t,r={}){const s=!r.disablePadding;return{encrypt(r,a){const n=na(e),{b:i,o:o,out:c}=function(e,t,r){Vs(e);let s=e.length;const a=s%zs;if(!t&&0!==a)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");$s(e)||(e=Ys(e));const n=Ms(e);if(t){let e=zs-a;e||(e=zs),s+=e}return Gs(e,r=Hs(s,r)),{b:n,o:Ms(r),out:r}}(r,s,a);let d=t;const l=[n];$s(d)||l.push(d=Ys(d));const h=Ms(d);let u=h[0],p=h[1],y=h[2],f=h[3],g=0;for(;g+4<=i.length;)u^=i[g+0],p^=i[g+1],y^=i[g+2],f^=i[g+3],({s0:u,s1:p,s2:y,s3:f}=ca(n,u,p,y,f)),o[g++]=u,o[g++]=p,o[g++]=y,o[g++]=f;if(s){const e=function(e){const t=new Uint8Array(16),r=Ms(t);t.set(e);const s=zs-e.length;for(let e=zs-s;e<zs;e++)t[e]=s;return r}(r.subarray(4*g));u^=e[0],p^=e[1],y^=e[2],f^=e[3],({s0:u,s1:p,s2:y,s3:f}=ca(n,u,p,y,f)),o[g++]=u,o[g++]=p,o[g++]=y,o[g++]=f}return Ws(...l),c},decrypt(r,a){!function(e){if(Vs(e),e.length%zs!=0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size 16")}(r);const n=function(e){const t=na(e),r=t.slice(),s=t.length,{sbox2:a}=ra,{T0:n,T1:i,T2:o,T3:c}=sa;for(let e=0;e<s;e+=4)for(let a=0;a<4;a++)r[e+a]=t[s-e-4+a];Ws(t);for(let e=4;e<s-4;e++){const t=r[e],s=oa(a,t,t,t,t);r[e]=n[255&s]^i[s>>>8&255]^o[s>>>16&255]^c[s>>>24]}return r}(e);let i=t;const o=[n];$s(i)||o.push(i=Ys(i));const c=Ms(i);a=Hs(r.length,a),$s(r)||o.push(r=Ys(r)),Gs(r,a);const d=Ms(r),l=Ms(a);let h=c[0],u=c[1],p=c[2],y=c[3];for(let e=0;e+4<=d.length;){const t=h,r=u,s=p,a=y;h=d[e+0],u=d[e+1],p=d[e+2],y=d[e+3];const{s0:i,s1:o,s2:c,s3:f}=da(n,h,u,p,y);l[e++]=i^t,l[e++]=o^r,l[e++]=c^s,l[e++]=f^a}return Ws(...o),function(e,t){if(!t)return e;const r=e.length;if(!r)throw new Error("aes/pcks5: empty ciphertext not allowed");const s=e[r-1];if(s<=0||s>16)throw new Error("aes/pcks5: wrong padding");const a=e.subarray(0,-s);for(let t=0;t<s;t++)if(e[r-t-1]!==s)throw new Error("aes/pcks5: wrong padding");return a}(a,s)}}}));function pa(e,t,r,s=!0){if(!r.startsWith("aes-"))throw new Error("AES: unsupported mode");const a=e.length;if(r.startsWith("aes-128")&&16!==a||r.startsWith("aes-256")&&32!==a)throw new Error("AES: wrong key length");if(16!==t.length)throw new Error("AES: wrong IV length");if(["aes-128-cbc","aes-256-cbc"].includes(r))return ua(e,t,{disablePadding:!s});if(["aes-128-ctr","aes-256-ctr"].includes(r))return ha(e,t);throw new Error("AES: unsupported mode")}const ya=(e,t,r)=>{const s=(null==r?void 0:r.ephemPrivateKey)?Ut(r.ephemPrivateKey):rt(32),a=rt(16),n=ws.getPublicKey(s),i=ws.ProjectivePoint.fromHex(n).toRawBytes(!1),o=ws.getSharedSecret(s,Ut(e),!0).slice(1),c=qs(o),d=c.subarray(0,32),l=c.subarray(32),h=function(e,t,r,s="aes-128-ctr",a=!0){return pa(t,r,s,a).encrypt(e)}(Ft(t),d,a,"aes-256-cbc"),u=Wt([a,i,h]),p=Bs(l,u);return{iv:Me(a),ephemPublicKey:Me(i),ciphertext:Me(h),mac:Me(p)}},fa=(e,t)=>{let r;try{r=ws.getSharedSecret(Ut(e),t.ephemPublicKey,!0).slice(1)}catch(e){throw new Error(`Invalid MAC: data integrity check failed: ${e}`)}const s=qs(r),a=s.subarray(0,32),n=s.subarray(32),i=Ut(t.ciphertext),o=Ut(t.iv),c=Ut(t.ephemPublicKey),d=Ut(t.mac),l=Wt([o,c,i]);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e[s]^t[s];return 0===r}(Bs(n,l),d))throw new Error("Invalid MAC: data integrity check failed");const h=function(e,t,r,s="aes-128-ctr",a=!0){return pa(t,r,s,a).decrypt(e)}(i,a,o,"aes-256-cbc");return function(e){if(!(e instanceof Uint8Array))throw new TypeError("bytesToUtf8 expected Uint8Array, got "+typeof e);return(new TextDecoder).decode(e)}(h)};const ga=(e,t,r)=>{const s=Mt(e);return ya("04"+s,t,r)},wa=(e,t)=>{const r=qt(e);return fa(r,t)},ma=e=>(e=>{const t=Ft(e),r=Vt(Me(t)),s=Ds(Ut(r));return Vt(Me(s))})(e);function va(e,t,r,s=!0,a){Lt(r,32),ot("compressed",s);const n=function(e){return Lt(e,64),ws.Signature.fromCompact(e)}(e);return function(e=e=>new Uint8Array(e),t,r){return"function"==typeof e&&(e=e(t)),Lt(e,t),r&&e.set(r),e}(a,s?33:65,n.addRecoveryBit(t).recoverPublicKey(r).toRawBytes(s))}ws.ProjectivePoint,ws.CURVE.n;const Sa={keccak256:ma};function _a(e){if(!Aa(e))throw new Error("Invalid JSON string");return JSON.parse(e)}function Aa(e){if("string"!=typeof e)return!1;try{return JSON.parse(e),!0}catch(e){return!1}}function Ea(e,t,r,s){ke(e);const a=function(e,t){if(void 0!==t&&"[object Object]"!=={}.toString.call(t))throw new Error("options should be object or undefined");return Object.assign(e,t)}({dkLen:32,asyncTick:10},s),{c:n,dkLen:i,asyncTick:o}=a;if(Pe(n),Pe(i),Pe(o),n<1)throw new Error("iterations (c) should be >= 1");const c=Xe(t),d=Xe(r),l=new Uint8Array(i),h=Pr.create(e,c),u=h._cloneInto().update(d);return{c:n,dkLen:i,asyncTick:o,DK:l,PRF:h,PRFSalt:u}}function ba(e,t,r,s){const{c:a,dkLen:n,DK:i,PRF:o,PRFSalt:c}=Ea(e,t,r,s);let d;const l=new Uint8Array(4),h=Ne(l),u=new Uint8Array(o.outputLen);for(let e=1,t=0;t<n;e++,t+=o.outputLen){const r=i.subarray(t,t+o.outputLen);h.setInt32(0,e,!1),(d=c._cloneInto(d)).update(l).digestInto(u),r.set(u.subarray(0,r.length));for(let e=1;e<a;e++){o._cloneInto(d).update(u).digestInto(u);for(let e=0;e<r.length;e++)r[e]^=u[e]}}return function(e,t,r,s,a){return e.destroy(),t.destroy(),s&&s.destroy(),Oe(a),r}(o,c,i,d,u)}const Ia="wsdkmk:v1:";function Pa(e){if(ze(e).length<16)throw new Error("Salt is too short: must be at least 16 bytes");if(new Set(e).size<=6)throw new Error("Weak salt: too few unique characters")}function Ta({password:e,salt:t}){Pa(t);const r=function(e,t,r,s,a){if(!["sha256","sha512"].includes(a))throw new Error("Only sha256 and sha512 are supported");return Lt(e),Lt(t),ba(Ar,e,t,{c:r,dkLen:s})}(ze(e.normalize("NFKC").trim()),ze(t),131072,32,"sha256");return Ls(r)}function ka(e,t){return Ia+function(e,t){return a.AES.encrypt(e,t).toString()}("string"==typeof e?e:JSON.stringify(e),t)}function Ca(e,t){const r=function(e,t){return a.AES.decrypt(e,t).toString(a.enc.Utf8)}(e.startsWith(Ia)?e.slice(10):e,t);if(r)return Aa(r)?_a(r):r}function xa(e,t){return JSON.stringify({material:e,destinationPubKey:t})}class Ka{constructor(){}validatePrivateKey(e){!function(e){if(!/^0x[0-9a-fA-F]{64}$/.test(e))throw new Error("Invalid private key: must be a 32-byte hex string");if(!ws.utils.isValidPrivateKey(e.slice(2)))throw new Error("Invalid private key: outside secp256k1 scalar range")}(e)}getMasterKey(){return{buffer:ze(me),key:me}}encryptWithMasterKey({data:e}){return ka(e,this.getMasterKey().key)}isWrappedByMasterKey(e){return function(e){return e.startsWith(Ia)||e.startsWith("U2FsdGVkX1")}(e)}decryptWithMasterKey({cipherText:e}){try{const t=Ca(e,this.getMasterKey().key);if(void 0!==t)return t}catch(e){return void pe.error("Decryption failed with master key",e)}pe.error("Decryption failed with master key")}validatePublicKey(e){!function(e){if(!/^[0-9a-fA-F]{128}$/.test(e))throw new Error("Invalid public key: must be a 64-byte raw uncompressed hex string");if(new Set(e).size<=8)throw new Error("Weak public key: too few unique characters")}(e)}validateSalt(e){Pa(e)}sign({message:e,signingKey:t}){try{this.validatePrivateKey(t);const r=ma(e);return{message:e,signature:Us(t,r),hashedMessage:r}}catch(e){throw pe.error("SDK::Cipher::sign",e),new Error(`Error signing message: ${e}`)}}async encrypt({data:e,encryptionKey:t}){try{return this.validatePublicKey(t),await ga(t,e)}catch(e){throw pe.error("Error encrypting data: ",e),new Error("Something happened during data encryption.")}}async decrypt({cipherText:e,decryptionKey:t}){try{this.validatePrivateKey(t);return await wa(t,(r=e,"string"==typeof r?JSON.parse(r):r))}catch(e){throw pe.error("SDK::CipherService::decrypt::error: ",e),new Error("That doesn’t seem right. Check your login details and try again.")}var r}async getCredentialsKeyPair(e){try{let t;switch(e.authType){case exports.AuthType.Password:if(!e.password||!e.salt)throw new Error("Password and salt are required");return t=await this.deriveKeyPairFromPassword({password:e.password,salt:e.salt}),t;case exports.AuthType.Passkey:if(!e.prfValue)throw new Error("PRF value is required");return t=await this.deriveKeyPairFromPasskey({inputKeyMaterial:e.prfValue}),t;default:throw new Error(`Unknown AuthType: ${e.authType}`)}}catch(e){return pe.error("SDK::CipherService::getCredentialsKeyPair::error",e),Promise.reject(e)}}async prepareDataForTransport({data:e,wallabyPublicKey:t,destinationPubKey:r}){try{const s=r?xa(e,r):e;return ga(t,s)}catch(e){throw pe.error("SDK::CipherService::prepareDataForTransport::error",e),new Error("Error preparing data for transport")}}async prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:t,wallabyPublicKey:r,options:s,destinationPubKey:a}){const n=await this.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:t,options:s});return this.prepareDataForTransport({data:n,wallabyPublicKey:r,destinationPubKey:a})}async doubleEncrypt({decryptedData:e,credentialsKeyPair:t,deviceKeyPair:r}){try{const s=await this.encrypt({data:e,encryptionKey:r.publicKey});return await this.encrypt({data:JSON.stringify(s),encryptionKey:t.publicKey})}catch(e){throw pe.error("SDK::doubleEncrypt::error",e),e}}async prepareTransportDataForStorage({transportData:e,credentialsKeyPair:t,deviceKeyPair:r}){try{const s=await this.decrypt({cipherText:e,decryptionKey:r.privateKey}),a=await this.encrypt({data:s,encryptionKey:r.publicKey});return await this.encrypt({data:JSON.stringify(a),encryptionKey:t.publicKey})}catch(e){throw pe.error("SDK::prepareTransportDataForStorage::error",e),e}}async displayDataFromServer({encryptedData:e,encryptedDevicePrivateKey:t,options:r}){try{const s=await this.getCredentialsKeyPair(r),a=await this.decrypt({cipherText:t,decryptionKey:s.privateKey});if(!a)throw new Error("That doesn’t seem right. Check your login details and try again.");return await this.decrypt({cipherText:e,decryptionKey:a})}catch(e){throw pe.error("SDK::CipherService::displayDataFromServer::error",e),e}}async displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:t,options:r}){const s=await this.getCredentialsKeyPair(r),a=await this.decrypt({cipherText:t,decryptionKey:s.privateKey});if(!a)throw new Error("Credentials are not correct, please provide the correct credentials");const n=await this.decrypt({cipherText:e,decryptionKey:s.privateKey});if(!n)throw new Error("That doesn’t seem right. Check your login details and try again.");const i=await this.decrypt({cipherText:JSON.parse(n),decryptionKey:a});if(!i)throw new Error("That doesn’t seem right. Check your login details and try again.");return i}async flipEncryptedData({cipherText:e,decryptionKey:t,encryptionKey:r}){try{const s=await this.decrypt({cipherText:e,decryptionKey:t});return await this.encrypt({data:s,encryptionKey:r})}catch(e){throw pe.error("SDK::CipherService::displayDataFromServer::error",e),e}}async deriveKeyPairFromPasskey({inputKeyMaterial:e}){return function({inputKeyMaterial:e}){return Ls(e)}({inputKeyMaterial:e})}async deriveKeyPairFromPassword({password:e,salt:t}){return Ta({password:e,salt:t})}}class Oa{constructor(){this.activeLocks=new Set}async withLock(e,t){const r="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator?navigator.locks:void 0;if(r)return r.request(e,{ifAvailable:!0},(async r=>{if(!r)throw new Error(`Operation '${e}' is already in progress. Please wait for it to complete.`);return t()}));if(this.activeLocks.has(e))throw new Error(`Operation '${e}' is already in progress. Please wait for it to complete.`);this.activeLocks.add(e);try{return await t()}finally{this.activeLocks.delete(e)}}isLocked(e){return this.activeLocks.has(e)}clearAllLocks(){this.activeLocks.clear()}}const Na=new Oa;class Ra{constructor({deviceStorage:e,userId:t,environment:r}){this._walletSpecificKeys=[exports.V2KeyNames.EncryptedStandardSeedPhrase,exports.V2KeyNames.PrimaryDeviceKeyShare,exports.V2KeyNames.BackupDeviceKeyShare],this._keysProtectedByMasterKey=[exports.V2KeyNames.AccessToken,exports.V2KeyNames.RefreshToken,exports.V2KeyNames.PasskeyCredential,exports.V2KeyNames.ClientAuthToken],this.userId=t,this.environment=null!=r?r:ge,this.shortenedEnv=this.environment.slice(0,1),this.deviceLocalStorage=e,this.cipher=new Ka}async getFromDeviceStorage(e){return this.deviceLocalStorage.getItem?this.deviceLocalStorage.getItem(e):this.deviceLocalStorage.getItemAsync?await this.deviceLocalStorage.getItemAsync(e):null}async setInDeviceStorage(e,t){return this.deviceLocalStorage.setItem?this.deviceLocalStorage.setItem(e,t):this.deviceLocalStorage.setItemAsync?await this.deviceLocalStorage.setItemAsync(e,t):void 0}async fetch(e,t){var r;let s;if(await(null!==(r=this._walRecovery)&&void 0!==r?r:this._walRecovery=this.recoverCommit().catch((e=>{pe.error("SDK::StorageService::fetch::wal recovery failed",e)}))),this._walletSpecificKeys.includes(e)){if(!(null==t?void 0:t.walletId))throw new Error(`A walletId is required to fetch: ${e}`);s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t.walletId}`}else s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;Se.isNative&&(s=be(s));const a=await this.getItem(s);if(a){if(this._keysProtectedByMasterKey.includes(e)){if(!this.cipher.isWrappedByMasterKey(a))return a;const e=this.cipher.decryptWithMasterKey({cipherText:a});return e||void pe.error(`Failed to decrypt item with key ${s}`)}return a}pe.debug(`(404): Item with key ${s} was not found in storage.`)}async save(e,t,r){let s,a;if(this._walletSpecificKeys.includes(e)){if(!(null==r?void 0:r.walletId))throw new Error(`A walletId is required to save: ${e}`);s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${r.walletId}`}else s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;if(Se.isNative&&(s=be(s)),this._keysProtectedByMasterKey.includes(e)){a=this.cipher.encryptWithMasterKey({data:t})}else a="string"==typeof t?t:JSON.stringify(t);return await this.setItem(s,a)}async saveInBulk(e){await Promise.all(e.map((e=>this.save(e.key,e.value,{walletId:e.walletId}))))}_computeRawKey(e,t){let r;if(this._walletSpecificKeys.includes(e)){if(!t)throw new Error(`A walletId is required to compute key: ${e}`);r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t}`}else r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;return ve?r:be(r)}_serializeValue(e,t){return this._keysProtectedByMasterKey.includes(e)?this.cipher.encryptWithMasterKey({data:t}):"string"==typeof t?t:JSON.stringify(t)}async _applyWAL(e){for(const{rawKey:t,value:r}of e.writes)await this.setItem(t,r);for(const t of e.deletes)await this.removeItem(t)}async commitBatch(e,t){const r={writes:e.map((({key:e,value:t,walletId:r})=>({rawKey:this._computeRawKey(e,r),value:this._serializeValue(e,t)}))),deletes:(null!=t?t:[]).map((({key:e,walletId:t})=>this._computeRawKey(e,t)))};await this.recoverCommit();const s=this._computeRawKey(exports.V2KeyNames.PendingCommit);await this.setItem(s,JSON.stringify(r)),await this._applyWAL(r),await this.removeItem(s)}async recoverCommit(){const e=this._computeRawKey(exports.V2KeyNames.PendingCommit),t=await this.getItem(e);if(!t)return;let r;try{r=_a(t)}catch(t){return pe.error("SDK::StorageService::recoverCommit::corrupt WAL, discarding",t),void await this.removeItem(e)}await this._applyWAL(r),await this.removeItem(e)}async delete(e,t){let r;if(this._walletSpecificKeys.includes(e)){if(!(null==t?void 0:t.walletId))throw new Error(`A walletId is required to delete: ${e}`);r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t.walletId}`}else r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;return Se.isNative&&(r=be(r)),await this.removeItem(r)}setItem(e,t){if(this.deviceLocalStorage.setItem)return this.deviceLocalStorage.setItem(e,t);if(this.deviceLocalStorage.setItemAsync)return this.deviceLocalStorage.setItemAsync(e,t);throw new Error("setItem function is is not defined")}getItem(e){if(this.deviceLocalStorage.getItem)return this.deviceLocalStorage.getItem(e);if(this.deviceLocalStorage.getItemAsync)return this.deviceLocalStorage.getItemAsync(e);throw new Error("getItem function is not defined")}removeItem(e){if(this.deviceLocalStorage.removeItem)return this.deviceLocalStorage.removeItem(e);if(this.deviceLocalStorage.deleteItemAsync)return this.deviceLocalStorage.deleteItemAsync(e);throw new Error("removeItem function is not defined")}async checkPrivateKeyExists(){return!!await this.getEncryptedPrivateKey()}async checkPrimaryKeyShareExists(e){return!!await this.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:e})}async checkBackupKeyShareExists(e){return!!await this.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e})}async checkSeedPhraseExists(e){return!!await this.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard,e)}getSeedPhraseV2KeyName(e){if(e===exports.SeedPhraseType.Standard)return exports.V2KeyNames.EncryptedStandardSeedPhrase;throw new Error(`Unsupported seed phrase type: ${e}`)}async setEncryptedPrivateKey(e,t){const r=a.AES.encrypt(e,t).toString();await this.setItem(`${this.environment}-client-auth-private-key-${this.userId}`,r)}async getV1EncryptedPrivateKey(){const e=`encryptedPrivateKey_${this.userId}`,t=`${this.environment}-client-auth-private-key-${this.userId}`,r=await this.getItem(t),s=await this.getItem(e);return r||s}async getEncryptedPrivateKey(){const e=await this.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey);if(e)return e;const t=`encryptedPrivateKey_${this.userId}`,r=await this.getItem(t);if(r)return r;{const e=`${this.environment}-client-auth-private-key-${this.userId}`,t=await this.getItem(e);if(t)return t}pe.error("SDK::StorageService::getEncryptedPrivateKey: private key not found")}async getDecryptedV1PrivateKey(e){try{const t=await this.getV1EncryptedPrivateKey();if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return r||void 0}catch(e){return void pe.error("SDK::StorageService::getDecryptedV1PrivateKey::error",e)}}async getDecryptedPrivateKey(e){try{const t=await this.getEncryptedPrivateKey();if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return r||void 0}catch(e){return void pe.error("SDK::StorageService::getDecryptedPrivateKey::error",e)}}async setEncryptedSeedPhrase({decryptedSeedPhrase:e,seedPhraseType:t,password:r,deviceAuthPublicKey:s,getUserSalt:n,salt:i,walletId:o}){const c=await ga(s,e),d=null!=i?i:await n();if(!d)throw new Error("User salt could not be retrieved, Seed phrase could not be encrypted");const l=`${d}${r}`,h=await a.AES.encrypt(JSON.stringify(c),l),u=this.getSeedPhraseV2KeyName(t);return await this.save(u,h.toString(),{walletId:o}),!0}async getEncryptedSeedPhrase(e,t){const r=this.getSeedPhraseV2KeyName(e),s=await this.fetch(r,{walletId:t});if(s)return s;if(!await this.isLegacySeedFallbackSafeFor(t))return;let a;if(e===exports.SeedPhraseType.Standard&&(a=`encryptedSeed_${this.userId}`),a){const e=await this.getItem(a);if(e){return await this.claimLegacySeedFallbackFor(t)?e:void 0}}if(!s){const r=`${this.environment}-encrypted-${e}-seedPhrase-${this.userId}`,s=await this.getItem(r);if(s){return await this.claimLegacySeedFallbackFor(t)?s:void 0}}}async isLegacySeedFallbackSafeFor(e){const t=await this.fetch(exports.V2KeyNames.LegacySeedClaimedWalletId);return!t||t===e}async claimLegacySeedFallbackFor(e){const t=`legacy-seed-claim:${this.environment}:${this.userId}`;try{return await Na.withLock(t,(async()=>{const t=await this.fetch(exports.V2KeyNames.LegacySeedClaimedWalletId);return t?t===e:(await this.save(exports.V2KeyNames.LegacySeedClaimedWalletId,e),!0)}))}catch(e){return pe.error("SDK::StorageService::claimLegacySeedFallbackFor::lock contention, treating as lost race",e),!1}}async getV1EncryptedSeedPhrase(){const e=`${this.environment}-encrypted-${exports.SeedPhraseType.Standard}-seedPhrase-${this.userId}`,t=await this.getItem(e);if(t)return t}async getV1DecryptedSeedPhrase(e,t){const r=await this.getV1EncryptedSeedPhrase(),s=await this.getDecryptedV1PrivateKey(e);if(!r||!s)return;const n=`${t}${e}`,i=_a(a.AES.decrypt(r,n).toString(a.enc.Utf8));return await wa(s,i)}async getDecryptedSeedPhrase({password:e,seedPhraseType:t,getUserSalt:r,salt:s,walletId:n}){const i=await this.getEncryptedSeedPhrase(t,n),o=await this.getDecryptedPrivateKey(e);if(!i||!o)return;const c=`${null!=s?s:await r()}${e}`,d=_a(a.AES.decrypt(i,c).toString(a.enc.Utf8));return await wa(o,d)}async setAccessToken(e){await this.save(exports.LocalStorageItems.AccessToken,e)}async getAccessToken(){let e=await this.fetch(exports.LocalStorageItems.AccessToken);if(e)return e;const t=`accessToken_${this.userId}`,r=await this.getItem(t);if(r)e=r;else{const t=`${this.environment}-access-token-${this.userId}`,r=await this.getItem(t);r&&(e=r)}return e?(await this.setAccessToken(e),e):void 0}async clearLocalStorage(e){const t=[exports.LocalStorageItems.AccessToken,exports.LocalStorageItems.RefreshToken,exports.V2KeyNames.EncryptedDevicePrivateKey,exports.V2KeyNames.ClientAuthPublicKey,exports.V2KeyNames.WallabyAuthPubKey,exports.V2KeyNames.PasskeyCredential,exports.V2KeyNames.MigrationVersion,exports.V2KeyNames.LastMigratedAt,exports.V2KeyNames.ClientAuthToken,exports.V2KeyNames.PasswordResetAttempts,exports.V2KeyNames.MigrationAttempts,exports.V2KeyNames.CredentialConversionInProgress,exports.V2KeyNames.PendingCommit];await Promise.all(t.map((e=>this.delete(e)))),e&&await Promise.all(this._walletSpecificKeys.map((t=>this.delete(t,{walletId:e}))));const r=[`${this.environment}-access-token-${this.userId}`,`${this.environment}-encrypted-${exports.SeedPhraseType.Standard}-seedPhrase-${this.userId}`,`${this.environment}-client-auth-private-key-${this.userId}`,`${this.environment}-wallaby-auth-public-key-${this.userId}`,`encryptedPrivateKey_${this.userId}`,`wallabyAuthPubKey_${this.userId}`,`encryptedSeed_${this.userId}`,`accessToken_${this.userId}`];await Promise.all(r.map((e=>this.removeItem(e)))),await this.delete(exports.V2KeyNames.LegacySeedClaimedWalletId)}async loadDeviceInformation(e){return{authTokens:{accessToken:await this.fetch(exports.LocalStorageItems.AccessToken),clientAuthToken:await this.fetch(exports.LocalStorageItems.ClientAuthToken)},user:{clientUserId:this.userId,encryptedStandardSeedPhrase:await this.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:e}),wallabyUserId:void 0},credentials:{deviceAuthPrivateKey:void 0,deviceAuthPublicKey:void 0,deviceEncryptedPrivateKey:await this.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),wallabyPublicKey:await this.fetch(exports.V2KeyNames.WallabyAuthPubKey)},hostname:"undefined"==typeof window?"republic.com":window.location.hostname}}}function Da(e,t=Date.now){return!e||Ua(e,t)<=0}function La(e,t,r=Date.now){return!!e&&Ua(e,r)<=1e3*t}function Ua(e,t=Date.now){const r=n.jwtDecode(e).exp;return 1e3*(null!=r?r:0)-t()}const Ba={signatureMessage:{fullPath:"/auth/signature-message",method:exports.RequestMethod.Post,requiresAccessToken:!1},signIn:{fullPath:"/auth/sign-in",method:exports.RequestMethod.Post,requiresAccessToken:!1},signUp:{fullPath:"/auth/sign-up",method:exports.RequestMethod.Post,requiresAccessToken:!1},refreshAccessToken:{fullPath:"/auth/refresh-access-token",method:exports.RequestMethod.Post,requiresAccessToken:!0},clientAuthPubKey:{fullPath:"auth/client-auth-pubkey",method:exports.RequestMethod.Put,requiresAccessToken:!0},wallabyAuthPublicKey:{fullPath:"/auth/wallaby-auth-pubkey",method:exports.RequestMethod.Get,requiresAccessToken:!0},getUserSalt:{fullPath:"/users/salt",method:exports.RequestMethod.Get,requiresAccessToken:!0},getPasskeyCredentials:{fullPath:"/auth/passkey-credentials",method:exports.RequestMethod.Get,requiresAccessToken:!0},issueJwtToken:{fullPath:"/auth/issue-jwt-token",method:exports.RequestMethod.Post,requiresAccessToken:!1}};function qa(e){return/^[a-zA-Z0-9-_]+$/.test(e)}function Va(e){return"string"!=typeof e?"":e.normalize("NFKD").trim().toLowerCase().replace(/\s+/g," ")}function Ma(e){return t.validateMnemonic(Va(e))}function Wa(e,t="The seed phrase is not a valid BIP-39 mnemonic. Expected 12, 15, 18, 21 or 24 words from the BIP-39 English wordlist."){if(!Ma(e))throw new V({message:t,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return Va(e)}function Fa(e){const{apiKey:t,baseUrl:r,userId:s,clientAuthToken:a,options:i}=e;if("string"!=typeof t||!qa(t))throw new Error("Invalid or empty API key provided.");if("string"!=typeof r||!function(e){try{return new URL(e),!0}catch(e){return!1}}(r))throw new Error("Invalid or empty base URL provided.");if("string"!=typeof s||!qa(s))throw new Error("Invalid or empty user ID provided.");if("string"!=typeof a||!function(e){if("string"!=typeof e)return!1;if(3!==e.split(".").length)return!1;try{return n.jwtDecode(e),!0}catch(e){return!1}}(a))throw new Error("Invalid or empty client auth token provided.");if(i&&"object"!=typeof i)throw new Error("Invalid options provided.");return Object.freeze({apiKey:t.trim(),baseUrl:r.trim(),userId:s.trim(),clientAuthToken:a.trim(),options:i?Object.freeze(Object.assign({},i)):void 0})}const Ga={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function ja(e){return Ga}function Ha(e){const t=typeof e;return"string"===t?`"${e}"`:"number"===t||"bigint"===t||"boolean"===t?`${e}`:"object"===t||"function"===t?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function $a(e,t,r,s,a){const n=a&&"input"in a?a.input:r.value,i=a?.expected??e.expects??null,o=a?.received??Ha(n),c={kind:e.kind,type:e.type,input:n,expected:i,received:o,message:`Invalid ${t}: ${i?`Expected ${i} but r`:"R"}eceived ${o}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},d="schema"===e.kind,l=a?.message??e.message??(e.reference,void c.lang)??(d?void c.lang:null)??s.message??void c.lang;void 0!==l&&(c.message="function"==typeof l?l(c):l),d&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}const Ya=new WeakMap;function za(e){let t=Ya.get(e);return t||(t={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},ja())},Ya.set(e,t)),t}function Ja(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}function Xa(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function Za(e,t,r){return"function"==typeof e.fallback?e.fallback(t,r):e.fallback}function Qa(e,t,r){return"function"==typeof e.default?e.default(t,r):e.default}function en(){return{kind:"schema",type:"any",reference:en,expects:"any",async:!1,get"~standard"(){return za(this)},"~run":e=>(e.typed=!0,e)}}function tn(e,t){return{kind:"schema",type:"array",reference:tn,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){const r=e.value;if(Array.isArray(r)){e.typed=!0,e.value=[];for(let s=0;s<r.length;s++){const a=r[s],n=this.item["~run"]({value:a},t);if(n.issues){const i={type:"array",origin:"value",input:r,key:s,value:a};for(const t of n.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||(e.issues=n.issues),t.abortEarly){e.typed=!1;break}}n.typed||(e.typed=!1),e.value.push(n.value)}}else $a(this,"type",e,t);return e}}}function rn(e){return{kind:"schema",type:"boolean",reference:rn,expects:"boolean",async:!1,message:e,get"~standard"(){return za(this)},"~run"(e,t){return"boolean"==typeof e.value?e.typed=!0:$a(this,"type",e,t),e}}}function sn(e,t){if(typeof e==typeof t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{value:e};if(e&&t&&e.constructor===Object&&t.constructor===Object){const r={...e};for(const s in t)if(Object.prototype.hasOwnProperty.call(e,s)){const a=sn(e[s],t[s]);if(a.issue)return a;r[s]=a.value}else r[s]=t[s];return{value:r}}if(Array.isArray(e)&&Array.isArray(t)&&e.length===t.length){const r=[...e];for(let s=0;s<e.length;s++){const a=sn(e[s],t[s]);if(a.issue)return a;r[s]=a.value}return{value:r}}}return{issue:!0}}function an(e,t){return{kind:"schema",type:"intersect",reference:an,expects:Xa(e.map((e=>e.expects)),"&"),async:!1,options:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){if(this.options.length){const r=e.value;let s;e.typed=!0;for(const a of this.options){const n=a["~run"]({value:r},t);if(n.issues){if(e.issues)for(const t of n.issues)e.issues.push(t);else e.issues=n.issues;if(t.abortEarly){e.typed=!1;break}}n.typed||(e.typed=!1),e.typed&&(s?s.push(n.value):s=[n.value])}if(e.typed){e.value=s[0];for(let r=1;r<s.length;r++){const a=sn(e.value,s[r]);if(a.issue){$a(this,"type",e,t,{received:"unknown"});break}e.value=a.value}}}else $a(this,"type",e,t);return e}}}function nn(e){return{kind:"schema",type:"lazy",reference:nn,expects:"unknown",async:!1,getter:e,get"~standard"(){return za(this)},"~run"(e,t){return this.getter(e.value)["~run"](e,t)}}}function on(e,t){return{kind:"schema",type:"nullable",reference:on,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return za(this)},"~run"(e,t){return null===e.value&&(void 0!==this.default&&(e.value=Qa(this,e,t)),null===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function cn(e){return{kind:"schema",type:"number",reference:cn,expects:"number",async:!1,message:e,get"~standard"(){return za(this)},"~run"(e,t){return"number"!=typeof e.value||isNaN(e.value)?$a(this,"type",e,t):e.typed=!0,e}}}function dn(e,t){return{kind:"schema",type:"object",reference:dn,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in this.entries){const a=this.entries[s];if(s in r||("exact_optional"===a.type||"optional"===a.type||"nullish"===a.type)&&void 0!==a.default){const n=s in r?r[s]:Qa(a),i=a["~run"]({value:n},t);if(i.issues){const a={type:"object",origin:"value",input:r,key:s,value:n};for(const t of i.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}i.typed||(e.typed=!1),e.value[s]=i.value}else if(void 0!==a.fallback)e.value[s]=Za(a);else if("exact_optional"!==a.type&&"optional"!==a.type&&"nullish"!==a.type&&($a(this,"key",e,t,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:r,key:s,value:r[s]}]}),t.abortEarly))break}}else $a(this,"type",e,t);return e}}}function ln(e,t){return{kind:"schema",type:"optional",reference:ln,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return za(this)},"~run"(e,t){return void 0===e.value&&(void 0!==this.default&&(e.value=Qa(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function hn(e,t){return{kind:"schema",type:"picklist",reference:hn,expects:Xa(e.map(Ha),"|"),async:!1,options:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:$a(this,"type",e,t),e}}}function un(e,t,r){return{kind:"schema",type:"record",reference:un,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return za(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in r)if(Ja(r,s)){const a=r[s],n=this.key["~run"]({value:s},t);if(n.issues){const i={type:"object",origin:"key",input:r,key:s,value:a};for(const t of n.issues)t.path=[i],e.issues?.push(t);if(e.issues||(e.issues=n.issues),t.abortEarly){e.typed=!1;break}}const i=this.value["~run"]({value:a},t);if(i.issues){const n={type:"object",origin:"value",input:r,key:s,value:a};for(const t of i.issues)t.path?t.path.unshift(n):t.path=[n],e.issues?.push(t);if(e.issues||(e.issues=i.issues),t.abortEarly){e.typed=!1;break}}n.typed&&i.typed||(e.typed=!1),n.typed&&(e.value[n.value]=i.value)}}else $a(this,"type",e,t);return e}}}function pn(e){return{kind:"schema",type:"string",reference:pn,expects:"string",async:!1,message:e,get"~standard"(){return za(this)},"~run"(e,t){return"string"==typeof e.value?e.typed=!0:$a(this,"type",e,t),e}}}function yn(e){let t;if(e)for(const r of e)if(t)for(const e of r.issues)t.push(e);else t=r.issues;return t}function fn(e,t){return{kind:"schema",type:"union",reference:fn,expects:Xa(e.map((e=>e.expects)),"|"),async:!1,options:e,message:t,get"~standard"(){return za(this)},"~run"(e,t){let r,s,a;for(const n of this.options){const i=n["~run"]({value:e.value},t);if(i.typed){if(!i.issues){r=i;break}s?s.push(i):s=[i]}else a?a.push(i):a=[i]}if(r)return r;if(s){if(1===s.length)return s[0];$a(this,"type",e,t,{issues:yn(s)}),e.typed=!0}else{if(1===a?.length)return a[0];$a(this,"type",e,t,{issues:yn(a)})}return e}}}const gn=dn({message:pn(),environment:pn()}),wn=dn({clientAuthPubKey:pn(),passkeyChallengeType:ln(hn(["webauthn.create","webauthn.get"])),walletId:ln(pn())}),mn=dn({message:pn(),wallabyAuthPubKey:ln(pn()),foundDevicePublicKey:rn(),challenge:ln(pn()),registrationOptions:ln(un(pn(),en())),authenticationOptions:ln(un(pn(),en()))}),vn=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),externalUserId:pn(),firstName:ln(pn()),lastName:ln(pn()),merchantId:ln(pn()),passkeyRegistrationResponse:ln(un(pn(),en()))}),Sn=dn({id:pn(),firstName:ln(pn()),externalUserId:pn(),role:ln(hn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),clientSalt:ln(pn()),clientAuthPubKey:ln(pn())}),_n=dn({accessToken:pn(),refreshToken:ln(pn()),user:nn((()=>Sn))}),An=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),externalUserId:ln(pn()),firstName:ln(pn()),lastName:ln(pn()),merchantId:ln(pn()),passkeyRegistrationResponse:ln(un(pn(),en()))}),En=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),passkeyRegistrationResponse:ln(un(pn(),en())),passkeyAuthenticationResponse:ln(un(pn(),en()))}),bn=dn({id:pn(),externalUserId:pn(),clientSalt:pn()}),In=dn({accessToken:pn(),refreshToken:pn(),user:nn((()=>bn))}),Pn=dn({refreshToken:pn()}),Tn=dn({accessToken:pn(),refreshToken:pn()}),kn=dn({message:pn()}),Cn=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),newClientAuthPubKey:pn()}),xn=dn({user:nn((()=>Sn))}),Kn=dn({clientAuthPubKey:pn()}),On=dn({wallabyAuthPubKey:pn()}),Nn=dn({id:pn(),externalUserId:pn(),merchantId:pn(),role:hn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]),firstName:ln(pn()),walletsCount:cn(),latestWallabyAuthPubKey:ln(pn()),latestWallabyAuthPubKeyVersion:ln(pn()),portalInvitationStatus:ln(on(hn(["pending","accepted","rejected"]))),createdAt:pn(),updatedAt:pn(),hasFullPermissions:rn()}),Rn=dn({id:pn(),userId:pn(),publicKey:pn(),status:hn(["active","invalidated"]),createdAt:pn(),updatedAt:pn()}),Dn=dn({id:pn(),authenticatorGlobalId:pn(),credentialID:pn(),publicKey:pn(),authPublicKeyId:pn(),counter:cn(),transports:pn(),credentialDeviceType:pn(),credentialBackedUp:rn(),user:an([nn((()=>Nn))]),authPublicKeys:ln(tn(nn((()=>Rn)))),userId:pn(),externalUserId:pn(),createdAt:pn(),updatedAt:pn(),authenticatorName:ln(pn())}),Ln=dn({credentials:tn(nn((()=>Dn)))}),Un=dn({totalRecords:cn(),currentPage:cn(),totalPages:cn(),nextPage:on(cn()),previousPage:on(cn()),pageSize:cn()}),Bn=dn({address:pn(),publicKey:ln(pn()),type:ln(hn(["SEGWIT","LEGACY","DEFAULT"]))}),qn=dn({id:pn(),name:pn(),nameSlugify:pn(),verified:rn(),status:hn(["active","inactive","invalidated"])}),Vn=dn({id:pn(),userId:pn(),merchantId:pn(),chainId:pn(),userAssetAddress:pn(),walletId:pn(),configId:pn(),assetName:pn(),assetSymbol:pn(),balance:on(pn()),balanceUpdatedAt:on(pn()),claimableBalance:ln(on(pn())),claimableBalanceUpdatedAt:ln(on(pn())),claimablePaymentTokenContractAddress:ln(on(pn())),claimablePaymentTokenAssetConfigId:ln(on(pn())),lockedTokenBalance:on(pn()),lockedTokenBalanceUpdatedAt:on(pn()),mainnetBalance:on(pn()),mainnetBalanceUpdatedAt:on(pn()),testnetBalance:on(pn()),testnetBalanceUpdatedAt:on(pn()),mainnetLockedBalance:on(pn()),mainnetLockedBalanceUpdatedAt:on(pn()),testnetLockedBalance:on(pn()),testnetLockedBalanceUpdatedAt:on(pn()),defaultAddress:pn(),isVisible:rn(),source:hn(["merchant","user","republic"]),addresses:tn(nn((()=>Bn))),ownershipType:pn(),priceConversion:ln(pn()),changePercentageLast24h:ln(pn()),createdAt:pn(),updatedAt:pn(),merchant:an([nn((()=>qn))])}),Mn=dn({id:pn(),name:pn(),nameSlugify:pn()}),Wn=dn({address:pn(),topics:tn(pn()),data:pn(),transactionIndex:cn()}),Fn=dn({event:pn(),args:un(pn(),fn([pn(),cn(),rn()]))}),Gn=dn({message:on(pn()),txLogs:on(tn(nn((()=>Wn)))),txLogsDecoded:on(tn(nn((()=>Fn)))),reqSignature:pn(),reason:on(pn()),requestId:on(pn()),signatureUsed:rn()}),jn=dn({id:pn(),reference:on(pn()),hash:ln(on(pn())),merchantId:pn(),userEmail:pn(),chainId:pn(),chainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:cn(),fromWalletId:pn(),fromAddress:pn(),toWalletId:pn(),toAddress:pn(),assetId:pn(),assetSymbol:pn(),tokenType:hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]),amount:pn(),fee:pn(),note:pn(),nonce:cn(),gasPrice:cn(),submitter:pn(),status:hn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:on(hn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:hn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:pn(),networkEnvironment:on(hn(["mainnet","testnet"])),statusCheckAttempts:cn(),statusCheckedAt:on(pn()),createdAt:pn(),updatedAt:pn(),asset:an([nn((()=>ti))]),merchant:an([nn((()=>ri))]),adminTransactions:tn(nn((()=>Gn))),user:ln(nn((()=>Nn))),chain:nn((()=>li)),splitCoins:pn(),transferObjects:pn()}),Hn=dn({id:cn(),contractTypeName:pn(),assetContracts:tn(nn((()=>$n)))}),$n=dn({configId:pn(),contractTypeId:cn(),contractAddress:pn(),assetConfig:an([nn((()=>ti))]),contractType:an([nn((()=>Hn))])}),Yn=dn({id:pn(),merchantId:pn(),configId:pn(),chainId:pn(),chainName:pn(),assetName:pn(),assetSymbol:pn(),isVisible:rn(),isDefault:rn(),createdAt:pn(),updatedAt:pn(),merchant:an([nn((()=>ri))]),config:an([nn((()=>ti))]),chain:an([nn((()=>li))])}),zn=dn({id:pn(),typeName:pn(),createdAt:pn(),updatedAt:pn()}),Jn=dn({id:pn(),objectId:pn(),packageId:pn(),moduleName:pn(),structName:pn(),coinType:pn(),createdAt:an([nn((()=>zn))]),updatedAt:pn()}),Xn=dn({id:pn(),chainId:pn(),swapProviderId:pn(),providerChainIdentifier:pn(),chain:an([nn((()=>li))]),swapProvider:an([nn((()=>Zn))]),providerAssets:tn(nn((()=>Qn))),createdAt:pn(),updatedAt:pn()}),Zn=dn({id:pn(),name:pn(),explorerBaseUrl:pn(),isActive:rn(),chainMappings:tn(nn((()=>Xn))),providerAssets:tn(nn((()=>Qn))),createdAt:pn(),updatedAt:pn()}),Qn=dn({id:pn(),assetConfigId:pn(),swapProviderId:pn(),chainProviderMappingId:pn(),providerAssetIdentifier:pn(),lastSynced:ln(pn()),isEnabled:rn(),assetConfig:an([nn((()=>ti))]),swapProvider:an([nn((()=>Zn))]),chainProviderMapping:an([nn((()=>Xn))]),createdAt:pn(),updatedAt:pn()}),ei=dn({id:pn(),config:nn((()=>ti)),configId:pn(),timestamp:pn(),createdAt:pn()}),ti=dn({id:pn(),chainId:pn(),merchantId:ln(on(pn())),chainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),name:pn(),symbol:pn(),verified:ln(rn()),isOffChain:ln(rn()),decimals:cn(),iconUrl:ln(pn()),ticker:ln(on(pn())),type:ln(hn(["COIN","TOKEN","OBJECT"])),tokenStandard:ln(on(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]))),assetIndex:ln(on(cn())),contractAddress:ln(on(pn())),description:ln(on(pn())),ownershipType:ln(hn(["SINGLE_OWNER","MULTI_SIG"])),ownerAddresses:ln(on(tn(pn()))),status:ln(hn(["active","inactive","archived"])),createdByUserId:ln(on(pn())),createdByMerchantId:ln(on(pn())),relayerAddress:ln(pn()),contractVersion:ln(pn()),chain:ln(nn((()=>li))),createdByMerchant:ln(an([nn((()=>Mn))])),usersAssets:ln(tn(nn((()=>Vn)))),transactions:ln(tn(nn((()=>jn)))),assetContracts:ln(tn(nn((()=>$n)))),merchantAssets:ln(tn(nn((()=>Yn)))),createdByUser:ln(nn((()=>Nn))),suiConfig:ln(nn((()=>Jn))),isAssetReady:rn(),extendedConfiguration:ln(un(pn(),en())),requiresKyc:rn(),swapProviderAssets:ln(tn(nn((()=>Qn)))),tokenDistributions:ln(tn(nn((()=>ei))))}),ri=dn({id:pn(),name:pn(),nameSlugify:pn(),verified:rn(),contactEmail:pn(),contactPhoneNumber:pn(),usersCount:cn(),assetsCount:cn(),tokensCount:cn(),coinsCount:cn(),walletsCount:cn(),status:hn(["active","inactive","invalidated"]),createdAt:pn(),updatedAt:pn(),createdAssets:tn(nn((()=>ti))),merchantAssets:ln(tn(nn((()=>Yn))))}),si=dn({id:cn(),name:hn(["wallaby_share","owner_main_device_share","owner_backup_device_share"]),keyShares:tn(nn((()=>ai)))}),ai=dn({id:pn(),user:nn((()=>Nn)),wallet:nn((()=>oi)),encryptedKey:pn(),type:nn((()=>si)),createdAt:pn(),updatedAt:pn(),migratedWallabyShareAt:ln(on(pn())),wrappingPublicKey:ln(pn()),migrationStatus:hn(["not_required","pending","migrated","failed"]),migrationErrorMessage:ln(on(pn()))}),ni=dn({id:cn(),roles:tn(hn(["single_sig","shares_single_owner","pooled_custodial","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),wallets:tn(nn((()=>oi)))}),ii=dn({id:pn(),walletId:pn(),userId:pn(),shareCount:cn(),createdAt:pn(),updatedAt:pn()}),oi=dn({id:pn(),userId:pn(),merchantId:pn(),revisionId:pn(),revisionName:pn(),hashedSeedPhraseSalt:pn(),hashedEthAddressSalt:pn(),recoveryCount:cn(),assetsCount:cn(),createdAt:pn(),updatedAt:pn(),lastVerifiedAt:on(pn()),userAssets:ln(tn(nn((()=>Vn)))),merchant:ln(nn((()=>ri))),keyShares:ln(tn(nn((()=>ai)))),type:nn((()=>ni)),creationType:ln(on(hn(["user_imported","user_created"]))),keyMigrationStatus:hn(["not_required","pending","migrated","failed"]),migrationErrorMessage:ln(on(pn())),walletAddresses:ln(tn(nn((()=>di)))),walletKeks:ln(tn(nn((()=>ii))))}),ci=dn({id:cn(),name:hn(["BTC:MAINNET:SEGWIT","BTC:MAINNET:LEGACY","BTC:TESTNET:SEGWIT","BTC:TESTNET:LEGACY","ETH:ALL:DEFAULT","ALGO:ALL:DEFAULT","SUI:ALL:DEFAULT","INJ:ALL:DEFAULT","APT:ALL:DEFAULT","SOL:ALL:DEFAULT","POLYX:ALL:DEFAULT","BSC:ALL:DEFAULT","AVAX:ALL:DEFAULT","POL:ALL:DEFAULT","BASE:ALL:DEFAULT","SEI:ALL:DEFAULT","HBAR:ALL:DEFAULT","CC:ALL:DEFAULT"]),walletAddresses:nn((()=>di))}),di=dn({id:pn(),walletId:pn(),wallet:nn((()=>oi)),chain:nn((()=>li)),typeId:cn(),type:nn((()=>ci)),address:pn(),publicKey:pn(),createdAt:pn(),updatedAt:pn()}),li=dn({id:pn(),name:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),isEvm:rn(),iconUrl:ln(on(pn())),mainnetId:ln(pn()),mainnetIndexUrl:ln(on(pn())),mainnetExplorerUrl:ln(pn()),testnetId:ln(pn()),testnetExplorerUrl:ln(on(pn())),testnetIndexUrl:ln(on(pn())),derivationPath:ln(on(pn())),addressRegex:ln(on(pn())),slip44:hn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767]),signatureScheme:ln(hn(["secp256k1","ed25519","sr25519"])),status:ln(hn(["UP","DOWN"])),search:ln(pn()),createdAt:pn(),updatedAt:pn(),walletAddresses:ln(tn(nn((()=>di)))),isChainReady:rn(),supportsSwaps:rn(),swapChainMappings:ln(tn(nn((()=>Xn)))),indexUrl:ln(on(pn())),chainId:ln(pn())}),hi=dn({pagination:an([nn((()=>Un))]),chains:tn(nn((()=>li)))}),ui=dn({name:pn(),isEvm:rn(),mainnetRpcUrl:pn(),mainnetIndexUrl:ln(pn()),testnetId:ln(pn()),testnetRpcUrl:pn(),testnetIndexUrl:pn(),derivationPath:pn(),addressRegex:pn(),slip44:cn(),signatureScheme:hn(["secp256k1","ed25519","sr25519"])}),pi=dn({chain:nn((()=>li))}),yi=dn({name:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),isEvm:ln(rn()),mainnetId:ln(pn()),mainnetRpcUrl:ln(pn()),mainnetIndexUrl:ln(pn()),testnetId:ln(pn()),testnetRpcUrl:ln(pn()),testnetIndexUrl:ln(pn()),derivationPath:ln(pn()),addressRegex:ln(pn()),slip44:ln(hn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767])),signatureScheme:ln(hn(["secp256k1","ed25519","sr25519"])),supportSwaps:ln(rn())}),fi=dn({chain:nn((()=>li))}),gi=dn({pagination:an([nn((()=>Un))]),assets:tn(nn((()=>ti)))}),wi=dn({asset:nn((()=>ti))}),mi=dn({chainId:pn(),name:pn(),symbol:pn(),verified:ln(rn()),isOffChain:ln(rn()),decimals:cn(),iconUrl:ln(pn()),ticker:pn(),type:hn(["COIN","TOKEN","OBJECT"]),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),assetIndex:ln(cn()),contractAddress:ln(pn()),description:ln(pn()),createdByUserId:ln(pn()),createdByMerchantId:ln(pn()),suiObjectId:ln(pn()),relayerAddress:ln(pn()),isAssetReady:ln(rn()),requiresKyc:ln(rn())}),vi=dn({asset:nn((()=>ti))}),Si=dn({name:ln(pn()),symbol:ln(pn()),isOffChain:ln(rn()),decimals:ln(cn()),iconUrl:ln(pn()),ticker:ln(pn()),type:ln(hn(["COIN","TOKEN","OBJECT"])),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),assetIndex:ln(cn()),contractAddress:ln(pn()),relayerAddress:ln(pn()),description:ln(pn()),suiObjectId:ln(pn())}),_i=dn({asset:nn((()=>ti))}),Ai=dn({message:pn()}),Ei=dn({pagination:an([nn((()=>Un))]),merchants:tn(nn((()=>ri)))}),bi=dn({name:pn(),contactEmail:pn(),contactPhoneNumber:ln(pn()),status:ln(hn(["active","inactive","invalidated"]))}),Ii=dn({name:ln(pn()),contactEmail:ln(pn()),contactPhoneNumber:ln(pn()),status:ln(hn(["active","inactive","invalidated"]))}),Pi=dn({merchant:nn((()=>ri))}),Ti=dn({merchant:nn((()=>ri))}),ki=dn({pagination:an([nn((()=>Un))]),merchant:nn((()=>ri)),assets:ln(tn(nn((()=>Yn)))),merchantAssets:tn(nn((()=>Yn)))}),Ci=dn({id:pn(),name:ln(pn())}),xi=dn({id:pn(),externalUserId:pn(),walletsCount:cn(),createdAt:pn(),updatedAt:pn(),merchantId:ln(pn()),firstName:ln(pn()),email:ln(pn()),role:ln(hn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),polymeshDID:ln(pn()),userMerchants:ln(tn(nn((()=>Ci))))}),Ki=dn({pagination:an([nn((()=>Un))]),merchant:nn((()=>ri)),users:tn(nn((()=>xi)))}),Oi=dn({merchantId:pn(),email:pn(),firstName:pn(),lastName:pn(),role:pn()}),Ni=dn({message:ln(pn()),user:nn((()=>xi))}),Ri=dn({message:ln(pn()),user:nn((()=>xi))}),Di=dn({pagination:an([nn((()=>Un))]),merchant:nn((()=>ri)),wallets:tn(nn((()=>oi)))}),Li=dn({assetConfigId:pn(),userId:pn(),walletId:pn()}),Ui=dn({merchantId:pn(),assets:tn(nn((()=>Li))),updateExistingWallets:ln(rn())}),Bi=dn({message:ln(pn())}),qi=dn({merchantId:pn(),assetConfigId:ln(pn()),isDefault:ln(rn()),addToExistingWallets:ln(rn()),addToWallets:ln(tn(pn())),config:ln(nn((()=>ti)))}),Vi=dn({message:ln(pn()),merchantAsset:nn((()=>Yn))}),Mi=dn({merchantId:pn(),assetConfigId:pn()}),Wi=dn({message:ln(pn())}),Fi=dn({merchantId:pn(),assetConfigId:pn(),isVisible:rn()}),Gi=dn({message:ln(pn()),merchantAsset:nn((()=>Yn))}),ji=dn({merchantId:pn(),assetConfigId:pn(),isDefault:rn()}),Hi=dn({message:ln(pn()),merchantAsset:nn((()=>Yn))}),$i=dn({iv:pn(),ephemPublicKey:pn(),ciphertext:pn(),mac:pn()}),Yi=dn({id:pn(),merchantId:ln(pn()),appName:pn(),ipAddresses:tn(pn()),domainNames:tn(pn()),status:hn(["active","inactive"]),clientJWTPubKey:pn(),usersCount:cn(),requestsCount:cn(),totalRequestSizeInKb:cn(),totalResponseSizeInKb:cn(),totalResponseTimeInKb:cn(),lastRequestAt:on(pn()),onlyDashboardAccess:rn(),allowMobileAccess:rn(),createdAt:pn(),updatedAt:pn(),merchant:ln(nn((()=>ri))),origins:ln(tn(nn((()=>zi))))}),zi=dn({id:pn(),merchantId:ln(pn()),apiKeyId:pn(),origin:pn(),createdAt:pn(),updatedAt:pn(),merchant:ln(nn((()=>ri))),apiKey:ln(nn((()=>Yi)))}),Ji=dn({id:pn(),merchantId:pn(),appName:pn(),apiKey:nn((()=>$i)),status:hn(["active","inactive"]),clientJWTPubKey:pn(),allowMobileAccess:rn(),createdAt:pn(),updatedAt:pn(),origins:ln(tn(nn((()=>zi))))}),Xi=dn({pagination:an([nn((()=>Un))]),apiKeys:tn(nn((()=>Ji)))}),Zi=dn({pagination:an([nn((()=>Un))]),apiKeyOrigins:tn(nn((()=>zi)))}),Qi=dn({clientJWTPubKey:ln(pn()),wrappingPublicKey:ln(pn()),allowMobileAccess:ln(rn()),appName:ln(pn())}),eo=dn({message:ln(pn()),apiKey:nn((()=>Ji)),clientJWTPrivKey:ln(an([nn((()=>$i))]))}),to=dn({merchantId:pn(),apiKeyId:pn(),origins:tn(pn())}),ro=dn({message:ln(pn()),apiKeyOrigins:tn(nn((()=>zi)))}),so=dn({clientJWTPubKey:ln(pn()),wrappingPublicKey:pn(),appName:ln(pn()),status:ln(hn(["active","inactive"])),allowMobileAccess:ln(rn())}),ao=dn({message:ln(pn()),apiKey:nn((()=>Ji))}),no=dn({pagination:an([nn((()=>Un))]),wallets:tn(nn((()=>oi)))}),io=dn({message:pn(),clientAuthPubKey:pn(),signature:pn()}),oo=dn({id:pn(),userId:pn(),merchantId:pn(),chainId:pn(),userAssetAddress:pn(),walletId:pn(),configId:pn(),assetName:pn(),assetSymbol:pn(),balance:on(pn()),balanceUpdatedAt:on(pn()),claimableBalance:ln(on(pn())),claimableBalanceUpdatedAt:ln(on(pn())),claimablePaymentTokenContractAddress:ln(on(pn())),claimablePaymentTokenAssetConfigId:ln(on(pn())),lockedTokenBalance:on(pn()),lockedTokenBalanceUpdatedAt:on(pn()),mainnetBalance:on(pn()),mainnetBalanceUpdatedAt:on(pn()),testnetBalance:on(pn()),testnetBalanceUpdatedAt:on(pn()),mainnetLockedBalance:on(pn()),mainnetLockedBalanceUpdatedAt:on(pn()),testnetLockedBalance:on(pn()),testnetLockedBalanceUpdatedAt:on(pn()),defaultAddress:pn(),isVisible:rn(),source:hn(["merchant","user","republic"]),addresses:tn(nn((()=>Bn))),ownershipType:pn(),priceConversion:ln(pn()),changePercentageLast24h:ln(pn()),createdAt:pn(),updatedAt:pn(),merchant:an([nn((()=>qn))]),config:nn((()=>ti))}),co=dn({id:pn(),userId:pn(),revisionName:pn()}),lo=dn({iv:pn(),ephemPublicKey:pn(),ciphertext:pn(),mac:pn()}),ho=dn({encrypted:an([nn((()=>lo))]),wrappingPublicKey:pn(),type:hn(["wallaby_share","owner_main_device_share","owner_backup_device_share"])}),uo=dn({v:cn(),iv:pn(),ciphertext:pn(),tag:pn()}),po=dn({address:pn(),type:hn(["BTC:MAINNET:SEGWIT","BTC:MAINNET:LEGACY","BTC:TESTNET:SEGWIT","BTC:TESTNET:LEGACY","ETH:ALL:DEFAULT","ALGO:ALL:DEFAULT","SUI:ALL:DEFAULT","INJ:ALL:DEFAULT","APT:ALL:DEFAULT","SOL:ALL:DEFAULT","POLYX:ALL:DEFAULT","BSC:ALL:DEFAULT","AVAX:ALL:DEFAULT","POL:ALL:DEFAULT","BASE:ALL:DEFAULT","SEI:ALL:DEFAULT","HBAR:ALL:DEFAULT","CC:ALL:DEFAULT"]),chainId:pn(),chainName:pn()}),yo=dn({wallabyAuthPubKey:ln(pn()),assets:tn(nn((()=>oo))),encryptedSeed:ln(fn([nn((()=>lo)),nn((()=>uo))])),wallet:an([nn((()=>co))]),shares:ln(tn(nn((()=>ho)))),encryptedBackupShare:ln(an([nn((()=>uo))])),reference:ln(pn()),encryptedSeedForSharesSplit:ln(nn((()=>lo))),walletAddressesInfo:tn(nn((()=>po)))}),fo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedShares:ln(tn(nn((()=>lo)))),encryptedSeed:ln(an([nn((()=>lo))])),walletId:pn()}),go=dn({isAccessVerified:rn()}),wo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),adminWalletTypes:tn(hn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]))}),mo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),returnWalletOption:hn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:pn(),numShares:ln(cn()),threshold:ln(cn()),wallabyKeepsOne:ln(rn()),backupDevicePublicKey:ln(pn()),walletOwnershipType:ln(hn(["SINGLE_OWNER"]))}),vo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedSeed:an([nn((()=>lo))]),walletId:ln(pn()),returnWalletOption:hn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:pn(),numShares:ln(cn()),threshold:ln(cn()),wallabyKeepsOne:ln(rn()),backupDevicePublicKey:ln(pn()),walletOwnershipType:ln(hn(["SINGLE_OWNER"]))}),So=dn({clientAuthPubKey:pn(),walletId:pn(),encryptedBackupShare:fn([nn((()=>uo)),nn((()=>$i))])}),_o=dn({reference:pn(),share:an([nn((()=>ho))])}),Ao=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedSeed:an([nn((()=>lo))]),walletId:ln(pn())}),Eo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo)))),chainName:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]))}),bo=dn({id:pn(),walletId:pn(),typeId:cn(),type:nn((()=>ci)),address:pn(),publicKey:pn()}),Io=dn({walletAddressesInfo:tn(nn((()=>po))),walletAddresses:tn(nn((()=>bo)))}),Po=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),encryptedShares:tn(nn((()=>lo))),chain:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),accountIndexes:tn(cn()),startingAddressIndex:ln(cn())}),To=dn({accountIndex:cn(),addresses:un(pn(),pn())}),ko=dn({walletId:pn(),chain:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),accounts:tn(nn((()=>To)))}),Co=dn({pagination:an([nn((()=>Un))]),assets:tn(nn((()=>oo))),groupedAssets:ln(un(pn(),tn(nn((()=>oo))))),walletAddressesInfo:tn(nn((()=>po)))}),xo=dn({pagination:an([nn((()=>Un))]),addresses:tn(nn((()=>po)))}),Ko=dn({assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])}),Oo=dn({configId:pn(),assetName:ln(pn()),assetSymbol:ln(pn()),isVisible:ln(rn()),walletId:pn()}),No=dn({userAsset:an([nn((()=>oo))]),message:pn()}),Ro=dn({fromAssetConfigId:pn(),toAssetConfigId:pn(),fromAmount:ln(pn()),toAmount:ln(pn()),slippage:ln(cn())}),Do=dn({amount:pn(),amountUSD:ln(on(pn())),symbol:ln(pn()),icon:ln(pn())}),Lo=dn({id:pn(),gasFee:ln(tn(nn((()=>Do)))),providerFee:ln(tn(nn((()=>Do)))),republicFee:ln(tn(nn((()=>Do)))),allowanceFee:ln(tn(nn((()=>Do)))),fromAssetConfigId:pn(),fromAssetSymbol:pn(),fromAssetChain:pn(),toAssetConfigId:pn(),toAssetSymbol:pn(),toAssetChain:pn(),fromAmount:pn(),fromAddress:pn(),toAmount:pn(),toAddress:pn(),slippage:cn(),expiresAt:ln(pn())}),Uo=dn({id:pn(),fromAssetSymbol:pn(),fromAssetChainName:pn(),toAssetSymbol:pn(),toAssetChainName:pn(),fromAddress:pn(),toAddress:pn(),fromAmount:pn(),toAmount:pn(),slippage:cn(),gasFee:ln(on(tn(nn((()=>Do))))),providerFee:ln(on(tn(nn((()=>Do))))),republicFee:ln(on(tn(nn((()=>Do))))),allowanceFee:ln(on(tn(nn((()=>Do))))),status:hn(["quote","executing","in_progress","completed","failed","abandoned","execution_failed","invalid"]),executedAt:on(pn()),completedAt:on(pn()),transactionId:on(pn()),transactionHash:on(pn()),explorerLink:on(pn())}),Bo=dn({pagination:an([nn((()=>Un))]),swaps:tn(nn((()=>Uo)))}),qo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),quoteId:pn(),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo))))}),Vo=dn({swapQuoteId:pn(),status:pn(),explorerLink:pn(),transactionHash:pn()}),Mo=dn({id:pn(),reference:on(pn()),hash:ln(on(pn())),merchantId:pn(),userEmail:pn(),chainId:pn(),chainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:cn(),fromWalletId:pn(),fromAddress:pn(),toWalletId:pn(),toAddress:pn(),assetId:pn(),assetSymbol:pn(),tokenType:hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"]),amount:pn(),fee:pn(),note:pn(),nonce:cn(),gasPrice:cn(),submitter:pn(),status:hn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:on(hn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:hn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:pn(),networkEnvironment:on(hn(["mainnet","testnet"])),statusCheckAttempts:cn(),statusCheckedAt:on(pn()),createdAt:pn(),updatedAt:pn(),asset:an([nn((()=>ti))]),merchant:an([nn((()=>ri))]),adminTransactions:tn(nn((()=>Gn))),user:ln(nn((()=>Nn))),chain:nn((()=>li)),splitCoins:pn(),transferObjects:pn(),type:ln(hn(["INCOMING","OUTGOING","SWAP","UNKNOWN"])),entryType:ln(hn(["INCOMING","OUTGOING","SWAP","UNKNOWN"]))}),Wo=dn({pagination:an([nn((()=>Un))]),transactions:tn(nn((()=>Mo)))}),Fo=dn({id:pn(),amount:pn(),sender:pn(),asset:ln(an([nn((()=>ti))])),expires:ln(pn())}),Go=dn({transactions:tn(nn((()=>Fo)))}),jo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),id:pn(),choice:hn(["approve","deny"]),symbol:pn(),chainName:pn(),walletId:pn(),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo))))}),Ho=dn({id:pn(),status:hn(["confirmed","denied"]),hash:ln(pn()),asset:ln(an([nn((()=>ti))]))}),$o=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),recipientAddress:pn(),assetId:pn(),amount:pn(),reference:pn(),encryptedSeed:an([nn((()=>lo))]),memo:ln(pn()),transactionType:ln(hn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"]))}),Yo=dn({transaction:an([nn((()=>jn))]),message:ln(pn())}),zo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),recipientAddress:pn(),assetId:pn(),amount:pn(),reference:pn(),memo:ln(pn()),transactionType:ln(hn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"])),encryptedShares:tn(nn((()=>lo)))}),Jo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),reference:pn(),note:ln(pn()),encryptedSeed:an([nn((()=>lo))]),assetIndex:cn()}),Xo=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),originAddress:pn(),reference:pn(),note:ln(pn()),encryptedSeed:an([nn((()=>lo))]),appIndex:cn()}),Zo=dn({feePaymentSymbol:pn(),fee:pn(),lowestFee:ln(pn()),highestFee:ln(pn())}),Qo=dn({address:tn(pn()),amount:pn(),txId:pn()}),ec=dn({status:hn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionHash:pn(),reference:pn(),assetSymbol:pn(),transactionValue:pn(),fromAddress:pn(),toAddress:pn(),chain:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),fee:pn(),nonce:ln(cn()),timestamp:ln(cn()),blockNumber:ln(cn()),memo:ln(pn()),origins:ln(tn(nn((()=>Qo)))),recipients:ln(tn(nn((()=>Qo))))}),tc=dn({canTransfer:rn(),restrictionCode:pn(),tokenContractAddress:pn(),fromAddress:pn(),toAddress:pn(),value:pn(),assetId:pn()}),rc=dn({restrictionCode:cn(),restrictionCodeMessage:pn()}),sc=dn({canTransfer:rn(),message:pn(),restrictionCode:pn()}),ac=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),walletId:pn(),ownerAddress:pn(),spenderAddress:pn(),amount:pn(),reference:pn(),memo:ln(pn()),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo)))),chainName:ln(pn()),assetSymbol:ln(pn()),assetId:ln(pn()),contractAddress:ln(pn())}),nc=dn({transaction:an([nn((()=>jn))])}),ic=dn({paymentTokenContractAddress:pn(),assetConfigId:pn(),balance:pn()}),oc=dn({address:pn(),assetSymbol:pn(),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),tokenType:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),chainName:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:ln(pn()),balance:on(pn()),claimable:ln(an([nn((()=>ic))])),lockedTokenBalance:ln(on(pn())),unlockedTokenBalance:ln(pn()),stakedBalance:ln(pn()),claimableBalance:ln(pn()),assetConfigId:ln(pn()),balanceUpdatedAt:ln(pn())}),cc=dn({address:pn(),assetSymbol:pn(),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),tokenType:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),chainName:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:ln(pn())}),dc=dn({assets:tn(nn((()=>cc)))}),lc=dn({balances:tn(nn((()=>oc)))}),hc=dn({walletId:pn()}),uc=dn({assetSymbol:ln(pn()),timestamp:cn(),from:pn(),gas:cn(),gasPrice:ln(pn()),gasUsed:ln(cn()),hash:pn(),input:ln(pn()),nonce:ln(cn()),to:pn(),value:pn(),amount:ln(pn()),memo:ln(pn()),tokenTransfers:ln(tn(un(pn(),en()))),transactionType:ln(pn()),status:hn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),origins:ln(tn(nn((()=>Qo)))),recipients:ln(tn(nn((()=>Qo)))),createdAt:pn()}),pc=dn({address:pn(),transactions:tn(nn((()=>uc)))}),yc=dn({decimals:cn(),symbol:pn(),name:pn(),tokenContractAddress:ln(pn())}),fc=dn({symbol:pn(),price:pn(),changePercentageLast24h:ln(pn())}),gc=dn({data:tn(nn((()=>fc)))}),wc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),encryptedShares:tn(nn((()=>lo))),walletId:pn()}),mc=dn({encryptedSeed:an([nn((()=>lo))])}),vc=dn({pagination:an([nn((()=>Un))]),users:tn(nn((()=>xi)))}),Sc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),email:ln(pn()),firstName:ln(pn()),lastName:ln(pn())}),_c=dn({message:pn(),user:ln(an([nn((()=>Nn))]))}),Ac=dn({user:an([nn((()=>xi))])}),Ec=dn({clientSalt:pn()}),bc=dn({wallets:tn(nn((()=>oi)))}),Ic=dn({pagination:an([nn((()=>Un))]),assets:tn(nn((()=>Vn))),groupedAssets:ln(un(pn(),tn(nn((()=>Vn)))))}),Pc=dn({name:pn(),symbol:pn(),decimals:cn(),contractAddress:pn(),chainId:ln(pn()),chainName:ln(hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),tokenStandard:ln(hn(["ERC_20","ERC_1404","BEP_20","ARC_20","ARC_1404","MRC_20","BRC_20","ALGO_STANDARD","ALGO_APP","SUI_COIN","SUI_MOVE_COIN","SUI_SECURITY_TOKEN","TOKEN_FACTORY","SEI_ERC_20","APT_FUNGIBLE_ASSET","SPL_TOKEN","SPL_TOKEN_2022","POLYMESH_ASSET","HBAR_ERC_20"])),ticker:ln(pn()),iconUrl:ln(pn())}),Tc=dn({assetConfigId:ln(pn()),walletId:pn(),userId:ln(pn()),config:ln(an([nn((()=>Pc))])),message:ln(pn()),clientAuthPubKey:ln(pn()),signature:ln(pn()),encryptedSeed:ln(an([nn((()=>lo))])),encryptedShares:ln(tn(nn((()=>lo))))}),kc=dn({asset:an([nn((()=>Vn))])}),Cc=dn({message:pn()}),xc=dn({user:an([nn((()=>xi))])}),Kc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),releaseCount:cn(),delayUntilFirstReleaseInSeconds:cn(),initialReleasePortionInBips:cn(),periodBetweenReleasesInSeconds:cn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Oc=dn({reference:pn()}),Nc=dn({address:pn(),amount:pn(),commencementTimestamp:ln(cn()),scheduleId:ln(cn()),cancelableBy:ln(tn(pn()))}),Rc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),mints:tn(nn((()=>Nc))),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Dc=dn({references:tn(nn((()=>Oc)))}),Lc=dn({address:pn(),amount:pn(),commencementTimestamp:ln(cn()),scheduleId:ln(cn()),timelockIndex:ln(cn()),reclaimTokenTo:ln(pn())}),Uc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:pn(),burns:tn(nn((()=>Lc))),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Bc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:pn(),payerAddress:pn(),tokenRecipientAddress:pn(),originatorPurchaseAmount:pn(),mintAmount:pn(),adminFeeAmount:pn(),totalAmount:pn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),qc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:pn(),payerAddress:pn(),tokenRecipientAddress:pn(),originatorPurchaseAmount:pn(),mintAmount:pn(),prefundedInterestAmount:pn(),adminFeeExcludingPrefundedInterestAmount:pn(),totalAmount:pn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Vc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),owner:pn(),regions:tn(pn()),accreditationType:cn(),lastAmlKycChangeTimestamp:cn(),lastAccreditationChangeTimestamp:cn(),amlKycPassed:rn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Mc=dn({message:pn(),clientAuthPubKey:pn(),signature:pn(),assetSymbol:pn(),blockchainName:hn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),wallet:pn(),amount:pn(),walletId:pn(),encryptedSeed:an([nn((()=>uo))])}),Wc=dn({assetSymbol:pn(),blockchainName:pn(),releaseCount:cn(),delayUntilFirstReleaseInSeconds:cn(),initialReleasePortionInBips:cn(),periodBetweenReleasesInSeconds:cn(),scheduleId:cn()}),Fc=dn({adminTransaction:an([nn((()=>Gn))])}),Gc=dn({status:hn(["QUEUED","PENDING","SUCCESS","FAILED"]),message:ln(pn()),txHash:ln(pn()),txLogs:ln(tn(nn((()=>Wn)))),txLogsDecoded:ln(tn(nn((()=>Fn)))),reqSignature:ln(pn()),clientRequestSignature:ln(pn()),requestId:ln(pn()),reason:ln(pn()),txId:ln(pn())}),jc=dn({message:pn()}),Hc=dn({chainsCount:cn(),chains:tn(nn((()=>li))),merchantsCount:cn(),merchants:tn(nn((()=>ri))),assetsCount:cn(),usersCount:cn(),users:tn(nn((()=>xi))),adminsCount:cn(),walletsCount:cn()}),$c=dn({id:pn(),userId:pn(),merchantId:pn(),action:ln(on(hn(["logged_in","logged_out","created_wallet","updated_wallet","deleted_wallet","created_merchant","updated_merchant","deleted_merchant"]))),requestUrl:pn(),requestMethod:pn(),createdAt:pn(),updatedAt:pn(),merchant:ln(nn((()=>ri)))}),Yc=dn({pagination:an([nn((()=>Un))]),activities:tn(nn((()=>$c)))}),zc=[{method:"GET",path:"/",response:nn((()=>gn))},{method:"GET",path:"/healthz",response:nn((()=>gn))},{method:"POST",path:"/auth/signature-message/external",request:nn((()=>wn)),response:nn((()=>mn))},{method:"POST",path:"/auth/signature-message",request:nn((()=>wn)),response:nn((()=>mn))},{method:"POST",path:"/auth/sign-up",request:nn((()=>vn)),response:nn((()=>_n))},{method:"POST",path:"/auth/sign-up/external",request:nn((()=>An)),response:nn((()=>_n))},{method:"POST",path:"/auth/sign-in",request:nn((()=>En)),response:nn((()=>_n))},{method:"POST",path:"/auth/issue-jwt-token",response:nn((()=>In))},{method:"POST",path:"/auth/refresh-access-token",request:nn((()=>Pn)),response:nn((()=>Tn))},{method:"POST",path:"/auth/logout",response:nn((()=>kn))},{method:"PUT",path:"/auth/client-auth-pubkey",request:nn((()=>Cn)),response:nn((()=>xn))},{method:"POST",path:"/auth/wallaby-auth-pubkey",request:nn((()=>Kn)),response:nn((()=>On))},{method:"GET",path:"/auth/passkey-credentials",response:nn((()=>Ln))},{method:"GET",path:"/chains",response:nn((()=>hi))},{method:"POST",path:"/chains",request:nn((()=>ui)),response:nn((()=>pi))},{method:"PUT",path:"/chains/{chainId}",request:nn((()=>yi)),response:nn((()=>fi))},{method:"GET",path:"/assets/configurations",response:nn((()=>gi))},{method:"POST",path:"/assets/configurations",request:nn((()=>mi)),response:nn((()=>vi))},{method:"GET",path:"/assets/configurations/{assetConfigId}",response:nn((()=>wi))},{method:"PUT",path:"/assets/configurations/{assetConfigId}",request:nn((()=>Si)),response:nn((()=>_i))},{method:"POST",path:"/assets/configurations/{assetConfigId}/verify",response:nn((()=>Ai))},{method:"DELETE",path:"/assets/configurations/{assetConfigId}/unverify",response:nn((()=>Ai))},{method:"POST",path:"/assets/configurations/{assetConfigId}/archive",response:nn((()=>Ai))},{method:"POST",path:"/assets/configurations/{assetConfigId}/unarchive",response:nn((()=>Ai))},{method:"GET",path:"/merchants",response:nn((()=>Ei))},{method:"POST",path:"/merchants",request:nn((()=>bi)),response:nn((()=>bi))},{method:"PUT",path:"/merchants/{merchantId}",request:nn((()=>Ii)),response:nn((()=>Pi))},{method:"GET",path:"/merchants/{merchantId}",response:nn((()=>Ti))},{method:"GET",path:"/merchants/{merchantId}/assets",response:nn((()=>ki))},{method:"GET",path:"/merchants/{merchantId}/users",response:nn((()=>Ki))},{method:"GET",path:"/merchants/{merchantId}/admins",response:nn((()=>Ki))},{method:"POST",path:"/merchants/admins/invite",request:nn((()=>Oi)),response:nn((()=>Ni))},{method:"DELETE",path:"/merchants/{merchantId}/admins/{userId}",response:nn((()=>Ri))},{method:"GET",path:"/merchants/{merchantId}/wallets",response:nn((()=>Di))},{method:"POST",path:"/merchants/wallets/add-assets",request:nn((()=>Ui)),response:nn((()=>Bi))},{method:"POST",path:"/merchants/assets/add",request:nn((()=>qi)),response:nn((()=>Vi))},{method:"DELETE",path:"/merchants/assets/delete",request:nn((()=>Mi)),response:nn((()=>Wi))},{method:"POST",path:"/merchants/assets/update-visibility",request:nn((()=>Fi)),response:nn((()=>Gi))},{method:"POST",path:"/merchants/assets/update-default-status",request:nn((()=>ji)),response:nn((()=>Hi))},{method:"GET",path:"/merchants/{merchantId}/api-keys",response:nn((()=>Xi))},{method:"POST",path:"/merchants/{merchantId}/api-keys",request:nn((()=>Qi)),response:nn((()=>eo))},{method:"GET",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/origins",response:nn((()=>Zi))},{method:"POST",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/whitelist-origins",request:nn((()=>to)),response:nn((()=>ro))},{method:"PUT",path:"/merchants/{merchantId}/api-keys/{apiKeyId}",request:nn((()=>so)),response:nn((()=>ao))},{method:"GET",path:"/wallets",response:nn((()=>no))},{method:"POST",path:"/wallets/create",request:nn((()=>io)),response:nn((()=>yo))},{method:"POST",path:"/wallets/verify-access",request:nn((()=>fo)),response:nn((()=>go))},{method:"POST",path:"/wallets/create-admin-server-wallet",request:nn((()=>wo)),response:nn((()=>yo))},{method:"POST",path:"/wallets/create-with-shares",request:nn((()=>mo)),response:nn((()=>yo))},{method:"POST",path:"/wallets/create-shares-based-wallet-from-seed",request:nn((()=>vo)),response:nn((()=>yo))},{method:"POST",path:"/wallets/add-new-device",request:nn((()=>So)),response:nn((()=>_o))},{method:"POST",path:"/wallets/import-seed-phrase",request:nn((()=>Ao)),response:nn((()=>yo))},{method:"POST",path:"/wallets/generate-wallet-addresses",request:nn((()=>Eo)),response:nn((()=>Io))},{method:"POST",path:"/wallets/derive-addresses/batch",request:nn((()=>Po)),response:nn((()=>ko))},{method:"GET",path:"/wallets/{walletId}/assets",response:nn((()=>Co))},{method:"GET",path:"/wallets/{walletId}/addresses",response:nn((()=>xo))},{method:"GET",path:"/wallets/asset",request:nn((()=>Ko)),response:nn((()=>oo))},{method:"PUT",path:"/wallets/asset/update",request:nn((()=>Oo)),response:nn((()=>No))},{method:"POST",path:"/wallets/{walletId}/swap/quote",request:nn((()=>Ro)),response:nn((()=>Lo))},{method:"GET",path:"/wallets/{walletId}/swaps",response:nn((()=>Bo))},{method:"GET",path:"/wallets/{walletId}/swaps/{swapId}",response:nn((()=>Uo))},{method:"POST",path:"/wallets/execute-swap",request:nn((()=>qo)),response:nn((()=>Vo))},{method:"GET",path:"/transactions",response:nn((()=>Wo))},{method:"GET",path:"/transactions/pending",response:nn((()=>Go))},{method:"POST",path:"/transactions/resolve",request:nn((()=>jo)),response:nn((()=>Ho))},{method:"POST",path:"/transactions/transfer",request:nn((()=>$o)),response:nn((()=>Yo))},{method:"POST",path:"/transactions/transfer-with-shares",request:nn((()=>zo)),response:nn((()=>Yo))},{method:"POST",path:"/transactions/asset-optin",request:nn((()=>Jo)),response:nn((()=>Yo))},{method:"POST",path:"/transactions/app-optin",request:nn((()=>Xo)),response:nn((()=>Yo))},{method:"GET",path:"/transactions/estimate-fee",response:nn((()=>Zo))},{method:"GET",path:"/transactions/status",response:nn((()=>ec))},{method:"GET",path:"/transactions/raw-status",response:nn((()=>jn))},{method:"GET",path:"/transactions/detect-transfers-restrictions",response:nn((()=>tc))},{method:"GET",path:"/transactions/transfer-restriction-message",response:nn((()=>rc))},{method:"GET",path:"/transactions/restriction",response:nn((()=>sc))},{method:"GET",path:"/transactions/check-asset-optin",response:tn(un(pn(),en()))},{method:"GET",path:"/transactions/check-app-optin",response:tn(un(pn(),en()))},{method:"POST",path:"/transactions/create-allowance",request:nn((()=>ac)),response:nn((()=>nc))},{method:"GET",path:"/query/assets/balance",response:nn((()=>oc))},{method:"GET",path:"/query/address/balance",response:nn((()=>oc))},{method:"POST",path:"/query/assets/bulk-balance",request:nn((()=>dc)),response:nn((()=>lc))},{method:"POST",path:"/query/assets/wallet-bulk-balance",request:nn((()=>hc)),response:nn((()=>lc))},{method:"GET",path:"/query/transactions",response:nn((()=>pc))},{method:"GET",path:"/query/fetch-token-info",response:nn((()=>yc))},{method:"GET",path:"/query/get-asset-price",response:nn((()=>gc))},{method:"POST",path:"/mpc/reconstruct-seed-phrase",request:nn((()=>wc)),response:nn((()=>mc))},{method:"GET",path:"/users",response:nn((()=>vc))},{method:"PUT",path:"/users/profile",request:nn((()=>Sc)),response:nn((()=>_c))},{method:"GET",path:"/users/profile",response:nn((()=>Ac))},{method:"GET",path:"/users/salt",response:nn((()=>Ec))},{method:"GET",path:"/users/{userId}/wallets",response:nn((()=>bc))},{method:"GET",path:"/users/merchants/assets",response:nn((()=>ki))},{method:"GET",path:"/users/merchant/assets",response:nn((()=>ki))},{method:"GET",path:"/users/{userId}/assets",response:nn((()=>Ic))},{method:"POST",path:"/users/assets/add",request:nn((()=>Tc)),response:nn((()=>kc))},{method:"DELETE",path:"/users/{userId}/wallets/{walletId}/assets/{assetConfigId}",response:nn((()=>Cc))},{method:"GET",path:"/users/{userId}",response:nn((()=>Ac))},{method:"GET",path:"/users/{externalUserId}/externalUserId",response:nn((()=>xc))},{method:"POST",path:"/transactions/admin/release-schedule",request:nn((()=>Kc)),response:nn((()=>Oc))},{method:"GET",path:"/transactions/admin/release-schedule",response:nn((()=>Wc))},{method:"POST",path:"/transactions/admin/mint",request:nn((()=>Rc)),response:nn((()=>Dc))},{method:"POST",path:"/transactions/admin/burn",request:nn((()=>Uc)),response:nn((()=>Dc))},{method:"POST",path:"/transactions/admin/execute-purchase",request:nn((()=>Bc)),response:nn((()=>Oc))},{method:"POST",path:"/transactions/admin/execute-purchase-with-interest",request:nn((()=>qc)),response:nn((()=>Oc))},{method:"POST",path:"/transactions/admin/set-identity",request:nn((()=>Vc)),response:nn((()=>Oc))},{method:"POST",path:"/transactions/admin/force-claim",request:nn((()=>Mc)),response:nn((()=>Oc))},{method:"POST",path:"/transactions/admin/force-claim-principal",request:nn((()=>Mc)),response:nn((()=>Oc))},{method:"GET",path:"/transactions/admin/{referenceId}",response:nn((()=>Fc))},{method:"POST",path:"/transactions/admin/callback",request:nn((()=>Gc)),response:nn((()=>jc))},{method:"GET",path:"/dashboard",response:nn((()=>Hc))},{method:"GET",path:"/users-activities",response:nn((()=>Yc))}],Jc=new Map,Xc=[];for(const e of zc)if(e.path.includes("{")){const t=e.path.replace(/\{[^/]+\}/g,"[^/]+");Xc.push({method:e.method,regex:new RegExp(`^${t}$`),entry:e})}else Jc.set(`${e.method} ${e.path}`,e);const Zc={response:{statusCode:200,errorCode:exports.ErrorResponseCodes.sdk_invalid_response,tag:"InvalidResponse"},request:{statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter,tag:"InvalidRequest"}};function Qc(e,t,r,s,a){var n;if("off"===a)return;const i=null===(n=function(e,t){const r=e.toUpperCase(),s=function(e){var t;const r=null!==(t=e.split("?")[0])&&void 0!==t?t:"";return(r.startsWith("/")?r:`/${r}`).replace(/^\/api\/v1/,"")||"/"}(t),a=Jc.get(`${r} ${s}`);if(a)return{request:a.request,response:a.response};const n=Xc.find((({method:e,regex:t})=>e===r&&t.test(s)));return n?{request:n.entry.request,response:n.entry.response}:void 0}(t,r))||void 0===n?void 0:n[e];if(!i)return;const o=function(e,t){const r=e["~run"]({value:t},ja());return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}(i,s);if(o.success)return;const c=`${t} ${r}: ${d=o.issues,d.slice(0,3).map((e=>{var t;return`${null!==(t=function(e){if(e.path){let t="";for(const r of e.path){if("string"!=typeof r.key&&"number"!=typeof r.key)return null;t+=t?`.${r.key}`:r.key}return t}return null}(e))&&void 0!==t?t:"<root>"}: expected ${e.expected}, got ${e.received}`})).join("; ")}`;var d;const{statusCode:l,errorCode:h,tag:u}=Zc[e];if("throw"===a)throw new V({kind:"validation",message:c,statusCode:l,errorCode:h,data:{method:t,path:r,issues:o.issues}});pe.warn(`SDK::ApiValidation::${u} ${c}`)}function ed({method:e,path:t,data:r,mode:s}){Qc("response",e,t,r,s)}function td({method:e,path:t,body:r,mode:s}){Qc("request",e,t,r,s)}const rd=new Set([exports.ErrorResponseCodes.auth_api_jwt_invalid,exports.ErrorResponseCodes.auth_api_jwt_not_active,exports.ErrorResponseCodes.auth_api_jwt_not_provided,exports.ErrorResponseCodes.auth_api_jwt_expired,exports.ErrorResponseCodes.auth_api_unauthorized]),sd=new Set([exports.ErrorResponseCodes.auth_refresh_token_not_found,exports.ErrorResponseCodes.auth_refresh_token_expired,exports.ErrorResponseCodes.auth_refresh_token_reuse_detected]);function ad(e){var t,r,s,a,n;return null!==(a=null!==(r=null!==(t=null==e?void 0:e.status)&&void 0!==t?t:null==e?void 0:e.statusCode)&&void 0!==r?r:null===(s=null==e?void 0:e.error)||void 0===s?void 0:s.statusCode)&&void 0!==a?a:null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.statusCode}function nd(e){var t,r,s,a;return null!==(s=null!==(t=null==e?void 0:e.errorCode)&&void 0!==t?t:null===(r=null==e?void 0:e.error)||void 0===r?void 0:r.errorCode)&&void 0!==s?s:null===(a=null==e?void 0:e.data)||void 0===a?void 0:a.errorCode}function id(e){if(401!==ad(e))return!1;const t=nd(e);return!t||rd.has(t)}const od=new class{constructor(){this.inFlightOperations=new Map}withDedupe(e,t){const r=this.inFlightOperations.get(e);if(r)return r;const s=Promise.resolve().then(t).finally((()=>{this.inFlightOperations.delete(e)}));return this.inFlightOperations.set(e,s),s}isInFlight(e){return this.inFlightOperations.has(e)}clearAll(){this.inFlightOperations.clear()}},cd=new Oa;class dd{constructor(t,r={}){var s,a,n,i,o;const c=Fa(t);this.apiKey=c.apiKey,this.baseUrl=c.baseUrl,this.userId=c.userId,this.options=c.options,(null===(s=this.options)||void 0===s?void 0:s.platform)&&(Se.platform=this.options.platform,Se.isNative="ios"===this.options.platform||"android"===this.options.platform,Se.isWeb=!Se.isNative),this.cipher=null!==(a=r.cipher)&&void 0!==a?a:new Ka,this.transport=null!==(n=r.transport)&&void 0!==n?n:(...e)=>fetch(...e),this.clock=null!==(i=r.clock)&&void 0!==i?i:{now:()=>Date.now()},this.lockManager=cd,this._initializeClientAuthToken(c.clientAuthToken),this.request=this.request.bind(this);const d=new e.H({baseUrl:this.baseUrl.replace(/\/api\/v1\/?$/,""),baseApiParams:{secure:!0},securityWorker:this.securityWorker.bind(this),customFetch:this.transport}),l=d.request.bind(d);d.request=async e=>{const t=async r=>{try{td({method:e.method,path:e.path,body:e.body,mode:this.validationMode});const t=await l(e);return ed({method:e.method,path:e.path,data:t,mode:this.validationMode}),t}catch(e){if(!r&&id(e))return await this._performTokenRefresh(),t(!0);if(null==e?void 0:e.error){const t=e.error;throw this.toWallabyError({message:t.message||"API request failed",statusCode:t.statusCode||e.status||500,errorCode:t.errorCode,data:t})}if(e instanceof V)throw e;throw this.toWallabyError({message:e.message||"Network request failed",statusCode:0,errorCode:"NETWORK_ERROR",data:{code:e.code||e.name,originalError:e},cause:e.cause})}};return t(!1)},this.api=new e.A(d),this.api.http.setSecurityData(Object.assign({"x-api-key":t.apiKey,"x-client-jwt":t.clientAuthToken},null===(o=this.options)||void 0===o?void 0:o.headers))}set setClientAuthToken(e){this._initializeClientAuthToken(e)}get version(){const e=_e;return pe.log(`wsdk is running v${e}`),e}_initializeClientAuthToken(e){if(t=e,r=this.userId,!t||!r||n.jwtDecode(t).externalUserId!==r)throw new V({message:"Client auth token does not match the user id. Blocking API call.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_jwt_invalid});var t,r;this.clientAuthToken=e,!function(e){return n.jwtDecode(e).mfaVerified}(e)?this.deviceAuthType=exports.AuthType.Passkey:this.deviceAuthType=exports.AuthType.Password}get deviceLocalStorage(){var e;if(null===(e=this.options)||void 0===e?void 0:e.storage)return this.options.storage;if("undefined"!=typeof window&&"localStorage"in window)return window.localStorage;throw new V({message:"Your device storage is not supported natively yet, please provide a custom storage in the config options.",statusCode:400,errorCode:"device_storage_unsupported"})}get validationMode(){var e,t;return null!==(t=null===(e=this.options)||void 0===e?void 0:e.runtimeValidation)&&void 0!==t?t:"throw"}get settings(){var e,t,r,s,a,n;return Object.freeze({apiKey:this.apiKey,baseUrl:this.baseUrl,environment:null!==(t=null===(e=this.options)||void 0===e?void 0:e.environment)&&void 0!==t?t:ge,network:null!==(s=null===(r=this.options)||void 0===r?void 0:r.network)&&void 0!==s?s:we,hostname:null!==(n=null===(a=this.options)||void 0===a?void 0:a.hostname)&&void 0!==n?n:"https://www.republic.com"})}get localStorageService(){var e;if(!this.clientAuthToken)throw new V({message:"A client authentication token (JWT) is required",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return null!==(e=this._localStorageService)&&void 0!==e?e:this._localStorageService=new Ra({deviceStorage:this.deviceLocalStorage,userId:this.userId,environment:this.settings.environment})}async _performTokenRefresh(e){const t=`refresh:${this.userId}:${this.settings.environment}:${this.settings.network}`;await od.withDedupe(t,(async()=>{var t;const r=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(r)try{const s=await this.request(Ba.refreshAccessToken,{payload:{refreshToken:r}},!1,null!==(t=null==e?void 0:e.silent)&&void 0!==t&&t);await this.localStorageService.save(exports.LocalStorageItems.AccessToken,s.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,s.refreshToken)}catch(e){throw function(e){const t=ad(e),r=nd(e);return 401===t||!!r&&sd.has(r)}(e)&&(await this.localStorageService.delete(exports.LocalStorageItems.AccessToken),await this.localStorageService.delete(exports.LocalStorageItems.RefreshToken)),e}}))}toWallabyError(e){var t,r;const s=new V(e);try{null===(r=null===(t=this.options)||void 0===t?void 0:t.onError)||void 0===r||r.call(t,s)}catch(e){pe.error("SDK::Base::toWallabyError::onError handler threw",{error:e})}return s}async request(e,t,r=!1,s=!1){var a;const n=e=>s?new V(e):this.toWallabyError(e);if(e!==Ba.refreshAccessToken&&!r){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(e&&La(e,60,this.clock.now))try{await this._performTokenRefresh({silent:!0})}catch(e){}}let i="string"==typeof e.fullPath?e.fullPath:e.fullPath(null==t?void 0:t.payload);(null==t?void 0:t.queryParams)&&(i+=`?${function(e){const t=new URLSearchParams;return Object.keys(e).forEach((r=>{null!==e[r]&&void 0!==e[r]&&""!==e[r]&&t.append(r,e[r])})),t.toString()}(t.queryParams)}`);const o=`${this.baseUrl}${i}`,c=Object.assign(Object.assign({},await this._getRequestHeaders()),null===(a=this.options)||void 0===a?void 0:a.headers);try{td({method:e.method,path:i,body:null==t?void 0:t.payload,mode:this.validationMode});const s={method:e.method,headers:c};e.method!==exports.RequestMethod.Get&&(null==t?void 0:t.payload)&&(s.body=JSON.stringify(t.payload)),pe.debug(`SDK::Base::${e.method}::Request`,{path:o,payload:null==t?void 0:t.payload});const a=await this.transport(o,s),d=a.headers.get("content-type");let l;if(null==d?void 0:d.includes("application/json"))l=await a.json();else{const e=await a.text();try{l=JSON.parse(e)}catch(t){l=e}}if(pe.debug(`SDK::Base::${e.method}::Response`,{status:a.status,statusText:a.statusText,data:l}),!a.ok){if(!r&&e!==Ba.refreshAccessToken&&id({status:a.status,errorCode:null==l?void 0:l.errorCode}))return await this._performTokenRefresh(),this.request(e,t,!0);throw n({message:(null==l?void 0:l.message)||a.statusText||"Request failed",statusCode:a.status,errorCode:null==l?void 0:l.errorCode,data:l})}return ed({method:e.method,path:i,data:l,mode:this.validationMode}),l}catch(t){if(t instanceof V)throw t;if(null==t?void 0:t.error){pe.error("SDK::Base::handleApiCall::API Error",{error:t});const e=t.error;throw n({message:e.message||"API request failed",statusCode:e.statusCode||500,errorCode:e.errorCode,data:e})}throw pe.error(`SDK::Base::${e.method}::NetworkError`,{message:t.message,name:t.name,error:t}),n({message:t.message||"Network request failed",statusCode:0,errorCode:"NETWORK_ERROR",data:{code:t.code||t.name,originalError:t},cause:t.cause})}}async _getRequestHeaders(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(Da(this.clientAuthToken,this.clock.now))throw new V({message:"Auth token has expired",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_jwt_expired});const t={"Content-Type":"application/json","x-api-key":this.settings.apiKey,"x-client-jwt":this.clientAuthToken,[Ae]:Ee};return e&&(t.Authorization="Bearer "+e),t}async securityWorker(e){try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&La(e,60,this.clock.now)&&await this._performTokenRefresh({silent:!0})}catch(e){}const t=Object.assign(Object.assign({"Content-Type":"application/json"},e||{}),{[Ae]:Ee});try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&(t.Authorization=`Bearer ${e}`)}catch(e){}return{headers:t}}}const ld={importSeedPhraseV2:{fullPath:"/wallets/create-shares-based-wallet-from-seed",method:exports.RequestMethod.Post,requiresAccessToken:!0},addNewDevice:{fullPath:"/wallets/add-new-device",method:exports.RequestMethod.Post,requiresAccessToken:!0},initKeyExchange:{fullPath:"/mpc/init-key-exchange",method:exports.RequestMethod.Post,requiresAccessToken:!0},retrieveSeedPhrase:{fullPath:"/mpc/reconstruct-seed-phrase",method:exports.RequestMethod.Post,requiresAccessToken:!0},createWithKeyShares:{fullPath:"/wallets/create-with-shares",method:exports.RequestMethod.Post,requiresAccessToken:!0},create:{fullPath:"/wallets/create",method:exports.RequestMethod.Post,requiresAccessToken:!0},import:{fullPath:"/wallets/import-seed-phrase",method:exports.RequestMethod.Post,requiresAccessToken:!0},getTokenBalance:{fullPath:({address:e,assetSymbol:t,chainName:r,tokenStandard:s})=>`/query/assets/balance?address=${e}&assetSymbol=${t}`+(s?`&tokenType=${s}`:"")+(r?`&chainName=${r}`:""),method:exports.RequestMethod.Get,requiresAccessToken:!1},getMultiTokenBalances:{fullPath:"/query/assets/bulk-balance",method:exports.RequestMethod.Post,requiresAccessToken:!1},getWalletBalances:{fullPath:"/query/assets/wallet-bulk-balance",method:exports.RequestMethod.Post,requiresAccessToken:!1},getWalletAssets:{fullPath:({walletId:e})=>`/wallets/${e}/assets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserAssets:{fullPath:({userId:e})=>`/users/${e}/assets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},addTokenToWallet:{fullPath:"/users/assets/add",method:exports.RequestMethod.Post,requiresAccessToken:!1},generateWalletAddresses:{fullPath:"/wallets/generate-wallet-addresses",method:exports.RequestMethod.Post,requiresAccessToken:!0},updateAsset:{fullPath:"/wallets/asset/update",method:exports.RequestMethod.Put,requiresAccessToken:!1},getUserWallets:{fullPath:({userId:e})=>`/users/${e}/wallets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},convertMnemonicSeedPhrase:{fullPath:"/wallets/convert-mnemonic-seed",method:exports.RequestMethod.Post,requiresAccessToken:!0},createMultisigAsset:{fullPath:"/wallets/create-multisig-asset",method:exports.RequestMethod.Post,requiresAccessToken:!0},verifyAccess:{fullPath:"/wallets/verify-access",method:exports.RequestMethod.Post,requiresAccessToken:!0}},hd={getSupportedBlockchains:{fullPath:"/chains",method:exports.RequestMethod.Get,requiresAccessToken:!1},getSupportedTokens:{fullPath:"/assets/configurations",method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserByExternalUserId:{fullPath:({externalUserId:e})=>`/users/${e}/externalUserId`,method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserData:{fullPath:({userId:e})=>`/users/${e}`,method:exports.RequestMethod.Get,requiresAccessToken:!1},fetchTokenInfo:{fullPath:()=>"/query/fetch-token-info",method:exports.RequestMethod.Get,requiresAccessToken:!1}},ud={transfer:{fullPath:"/transactions/transfer",method:exports.RequestMethod.Post,requiresAccessToken:!0},transferWithShares:{fullPath:"/transactions/transfer-with-shares",method:exports.RequestMethod.Post,requiresAccessToken:!0},createAllowance:{fullPath:"/transactions/create-allowance",method:exports.RequestMethod.Post,requiresAccessToken:!0},estimateFee:{fullPath:"/transactions/estimate-fee",method:exports.RequestMethod.Get,requiresAccessToken:!0},getTransaction:{fullPath:"/transactions/status",method:exports.RequestMethod.Get,requiresAccessToken:!0},getTransactions:{fullPath:"/transactions",method:exports.RequestMethod.Get,requiresAccessToken:!0},detectTransferRestrictions:{fullPath:"/transactions/detect-transfers-restrictions",method:exports.RequestMethod.Get,requiresAccessToken:!0},transferRestrictionMessage:{fullPath:"/transactions/transfer-restriction-message",method:exports.RequestMethod.Get,requiresAccessToken:!0},restriction:{fullPath:"/transactions/restriction",method:exports.RequestMethod.Get,requiresAccessToken:!0},getPendingTransactions:{fullPath:"/transactions/pending",method:exports.RequestMethod.Get,requiresAccessToken:!0},confirmPendingTransaction:{fullPath:"/transactions/resolve",method:exports.RequestMethod.Post,requiresAccessToken:!0}},pd={getQuote:{fullPath:({walletId:e})=>`/wallets/${e}/swap/quote`,method:exports.RequestMethod.Post,requiresAccessToken:!0},executeSwap:{fullPath:"/wallets/execute-swap",method:exports.RequestMethod.Post,requiresAccessToken:!0},getSwaps:{fullPath:({walletId:e})=>`/wallets/${e}/swaps`,method:exports.RequestMethod.Get,requiresAccessToken:!0}};function yd(e,t){if(!e)return{};const r=new Set(t);return Object.fromEntries(Object.entries(e).filter((([e])=>!r.has(e))))}class fd{constructor(){}async register({optionsJSON:e}){if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new V({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await p.startRegistration({optionsJSON:e})}async authenticate({optionsJSON:e,useBrowserAutofill:t=!1,skipUserVerification:r=!1}){try{if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new V({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await p.startAuthentication({optionsJSON:Object.assign(Object.assign({},e),{userVerification:r?"discouraged":e.userVerification}),useBrowserAutofill:t})}catch(e){throw this.handlePasskeyError(e),e}}handlePasskeyError(e){return pe.error("SDK::Authenticator::handlePasskeyError",e),this.throwPasskeyError(this.classifyPasskeyError(e),e)}classifyPasskeyError(e){return e instanceof p.WebAuthnError?(pe.debug("SDK::Authenticator::handlePasskeyError - WebAuthnError",e),{errorCode:e.code}):e instanceof Error?(pe.debug("SDK::Authenticator::handlePasskeyError - Error",e),{errorMessage:e.message}):null!==e&&"object"==typeof e&&e.error&&e.message?(pe.debug("SDK::Authenticator::handlePasskeyError - Object",e),{errorCode:e.error,errorMessage:e.message}):"string"==typeof e?(pe.debug("SDK::Authenticator::handlePasskeyError - String",e),{errorMessage:e}):(pe.debug("SDK::Authenticator::handlePasskeyError - Unknown",e),{})}throwPasskeyError({errorCode:e,errorMessage:t},r){var s,a,n;pe.error("SDK::Authenticator::throwPasskeyError",e);const i=he.find((t=>t.error===e));throw pe.error("SDK::Authenticator::error",i),new V({message:null!==(a=null!==(s=null==i?void 0:i.message)&&void 0!==s?s:t)&&void 0!==a?a:M.message,statusCode:400,errorCode:null!==(n=null==i?void 0:i.error)&&void 0!==n?n:e,cause:r})}}function gd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");return t.padEnd(t.length+(4-t.length%4)%4,"=")}function wd(e){try{return o.toUint8Array(e)}catch(r){return t=e,o.toUint8Array(gd(t))}var t}function md(e){const t=gd(e),r=o.atob(t),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}class vd{constructor(e,t,r,s=new Ka){this.cipher=s,this.localStorageService=t,this.userId=e,this.request=r,this.authenticator=new fd}preparePasskeyRequestOptions(e){var t,r,s,a,n,i,o,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?md(e.extensions.prf.eval.base64):(null===(a=null===(s=e.extensions)||void 0===s?void 0:s.prf.eval)||void 0===a?void 0:a.first)instanceof ArrayBuffer?new Uint8Array(e.extensions.prf.eval.first):"object"==typeof(null===(i=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===i?void 0:i.first)?new Uint8Array(Object.values(e.extensions.prf.eval.first)):void 0,l=Object.assign(Object.assign({},e),{extensions:Object.assign(Object.assign({},e.extensions),{prf:void 0!==d?{eval:{first:d}}:null!==(c=null===(o=e.extensions)||void 0===o?void 0:o.prf)&&void 0!==c?c:{}})});return pe.log("SDK::PasskeyService::preparePasskeyRequestOptions::parsedOptions",!!l),l}preparePasskeyCreationOptions(e){var t,r,s,a,n,i,o,c;const d=(null===(r=null===(t=e.extensions)||void 0===t?void 0:t.prf.eval)||void 0===r?void 0:r.base64)?md(e.extensions.prf.eval.base64):(null===(a=null===(s=e.extensions)||void 0===s?void 0:s.prf.eval)||void 0===a?void 0:a.first)instanceof ArrayBuffer?new Uint8Array(e.extensions.prf.eval.first):"object"==typeof(null===(i=null===(n=e.extensions)||void 0===n?void 0:n.prf.eval)||void 0===i?void 0:i.first)?new Uint8Array(Object.values(e.extensions.prf.eval.first)):void 0,l=Object.assign(Object.assign({},e),{extensions:Object.assign(Object.assign({},e.extensions),{prf:void 0!==d?{eval:{first:d}}:null!==(c=null===(o=e.extensions)||void 0===o?void 0:o.prf)&&void 0!==c?c:{}})});return pe.log("SDK::PasskeyService::preparePasskeyCreationOptions::parsedOptions",!!l),l}async addNewPasskey({deviceKeyPair:e,getSignature:t}){try{let r,s;pe.log("SDK::PasskeyService::addNewPasskey: start adding new passkey");try{const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});if(!a.registrationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const n=this.preparePasskeyCreationOptions(a.registrationOptions);pe.log("SDK::PasskeyService::addNewPasskey: about to register passkey credential"),r=await this.authenticator.register({optionsJSON:n}),pe.log("SDK::PasskeyService::addNewPasskey: finished registering passkey credential");const i=await this.handleCredentialsCreationFromPrfExtension(r);pe.log("SDK::PasskeyService::addNewPasskey:: finished deriving credentials key pair",i.publicKey),s=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyRegistrationResponse:r}}),pe.log("SDK::PasskeyService::addNewPasskey:: signInResponse",s);const o=await this.cipher.encrypt({data:e.privateKey,encryptionKey:i.publicKey});return await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:o},passkeyCredential:r}),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:i.prfValue})}catch(a){if(pe.error("SDK::PasskeyService::addNewPasskey::error",a),a&&a.code===ie.error){const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if(!a.authenticationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const n=this.preparePasskeyRequestOptions(a.authenticationOptions);pe.log("SDK::PasskeyService::addNewPasskey::catch: about to authenticate with passkey"),r=await this.authenticator.authenticate({optionsJSON:n}),pe.log("SDK::PasskeyService::addNewPasskey::catch: finished authenticating with passkey"),s=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyAuthenticationResponse:r}}),pe.log("SDK::PasskeyService::addNewPasskey::catch: finished signing in with passkey",{signInResponse:s});const i=await this.handleCredentialsCreationFromPrfExtension(r);pe.log("SDK::PasskeyService::addNewPasskey::catch: finished deriving credentials key pair",i.publicKey);const o=await this.cipher.encrypt({data:e.privateKey,encryptionKey:i.publicKey});return pe.log("SDK::PasskeyService::addNewPasskey::catch: about to store data"),await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:o},passkeyCredential:r}),pe.log("SDK::PasskeyService::addNewPasskey::catch: finished storing data"),Object.assign(Object.assign({},s),{signatureMessageResponse:a,prfValue:i.prfValue})}throw a}}catch(e){if(e instanceof V)throw e;throw this.authenticator.handlePasskeyError(e)}}async authenticate({deviceKeyPair:e,challengeResponse:t}){var r,s;try{if(!t.authenticationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});const a=this.preparePasskeyRequestOptions(t.authenticationOptions),n=null===(s=null===(r=a.extensions.prf)||void 0===r?void 0:r.eval)||void 0===s?void 0:s.first,i=Object.assign(Object.assign({},t.authenticationOptions),{extensions:Object.assign(Object.assign({},yd(a.extensions,["credProps"])),{prf:{eval:{first:n}}})}),o=await this.authenticator.authenticate({optionsJSON:i}),c=await this.handleCredentialsCreationFromPrfExtension(o),d=t.signature?t.signature:await this.getDeviceSignature({message:t.message,credentialsKeyPair:c,deviceKeyPair:e}),l=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:t.message,clientAuthPubKey:e.publicKey,signature:d,passkeyAuthenticationResponse:o}}),h=e.decryptedPrivateKey?e.decryptedPrivateKey:e.encryptedDevicePrivateKey?await this.cipher.decrypt({cipherText:e.encryptedDevicePrivateKey,decryptionKey:c.privateKey}):void 0;if(!h)throw new V({message:"Device private key is not available for storage.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const u=await this.cipher.encrypt({data:h,encryptionKey:c.publicKey});return await this.handleStoringData({authenticationResponse:l,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:u},passkeyCredential:o}),Object.freeze(Object.assign(Object.assign({},l),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(e instanceof V)throw e;throw this.authenticator.handlePasskeyError(e)}}async getDeviceSignature({message:e,credentialsKeyPair:t,deviceKeyPair:r}){let s;if(r.decryptedPrivateKey)s=r.decryptedPrivateKey;else{if(!r.encryptedDevicePrivateKey)throw new V({message:"Device private key is not available for signing the message.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});s=await this.cipher.decrypt({cipherText:r.encryptedDevicePrivateKey,decryptionKey:t.privateKey})}return(await this.cipher.sign({message:e,signingKey:s})).signature}async register({deviceKeyPair:e,challengeResponse:t}){var r;try{if(!t.registrationOptions)throw new V({message:"Passkey challenge could not be retrieved, please try again later.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_challenge_unavailable});pe.log("SDK::PasskeyService::register:: got challenge",{registrationOptions:t.registrationOptions});const s=this.preparePasskeyCreationOptions(t.registrationOptions);pe.log("SDK::PasskeyService::register:: registering passkey",{parsedOptions:s});const a=await this.authenticator.register({optionsJSON:s});if(pe.log("SDK::PasskeyService::register:: got passkey credential",{id:a.id,type:a.type}),!(null===(r=a.clientExtensionResults.prf)||void 0===r?void 0:r.enabled))throw new V({message:"Device is not compatible with this feature. Try using a different authentication method.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});pe.log("SDK::PasskeyService::register:: getting signature",{message:t.message});const{signature:n,message:i}=await this.cipher.sign({message:t.message,signingKey:e.privateKey}),o=await this.request(Ba.signUp,{payload:{externalUserId:this.userId,message:i,signature:n,clientAuthPubKey:e.publicKey,passkeyRegistrationResponse:a}}),c=await this.handleCredentialsCreationFromPrfExtension(a),d=await this.cipher.encrypt({data:e.privateKey,encryptionKey:c.publicKey});return await this.handleStoringData({authenticationResponse:o,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:d},passkeyCredential:a}),Object.freeze(Object.assign(Object.assign({},o),{prfValue:c.prfValue,signatureMessageResponse:t}))}catch(e){if(pe.log("SDK::PasskeyService::register::error",{error:e,errorCode:e.code,errorMessage:e.message}),e instanceof V)throw pe.log("SDK::PasskeyService::register::API error detected",{error:e}),e;if(e&&e.code===ie.error||e.code===oe.error||"The authenticator was previously registered."===e.message)throw pe.log("SDK::PasskeyService::register::ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",!0),e;throw this.authenticator.handlePasskeyError(e)}}async isDevicePrfCompatible(){var e;try{if("undefined"!=typeof window&&"function"==typeof(null===(e=window.PublicKeyCredential)||void 0===e?void 0:e.getClientCapabilities)){const e=await window.PublicKeyCredential.getClientCapabilities();return pe.log("SDK::PasskeyService::isDevicePrfCompatible::capabilities",e),e["extension:prf"]}return!1}catch(e){return!1}}async publicKeyCredential(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.PasskeyCredential);return null!=e?e:"There are no passkeys stored on this device"}async handleStoringData({authenticationResponse:e,deviceKeyPair:t,passkeyCredential:r}){return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:t.encryptedDevicePrivateKey},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:t.publicKey},{key:exports.LocalStorageItems.PasskeyCredential,value:r},{key:exports.LocalStorageItems.AccessToken,value:e.accessToken},...e.refreshToken?[{key:exports.LocalStorageItems.RefreshToken,value:e.refreshToken}]:[]])}async handleCredentialsCreationFromPrfExtension(e){var t,r,s,a,n;try{const i=e.clientExtensionResults;if(pe.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::extensions",i),!(null===(t=i.prf)||void 0===t?void 0:t.enabled)&&!(null===(s=null===(r=i.prf)||void 0===r?void 0:r.results)||void 0===s?void 0:s.first))throw new V({message:"Device is not compatible with this feature. Try using a different authentication method.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});if(pe.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prf is enabled",i.prf.enabled),!(null===(a=i.prf.results)||void 0===a?void 0:a.first))throw new V({message:"PRF extension did not return any results. Cannot proceed with authentication.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});const o=null===(n=i.prf.results)||void 0===n?void 0:n.first;let c;if("string"==typeof o)c=wd(o);else if(o instanceof Uint8Array)c=o;else if(o instanceof ArrayBuffer)c=new Uint8Array(o);else if(ArrayBuffer.isView(o))c=new Uint8Array(o.buffer);else if(Array.isArray(o))c=new Uint8Array(o);else{if(!o||"object"!=typeof o)throw new V({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});{const e=o.data;if(Array.isArray(e))c=new Uint8Array(e);else{const e=Object.values(o);if(!e.length||!e.every((e=>"number"==typeof e)))throw new V({message:"Unsupported PRF result type.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});c=new Uint8Array(e)}}}pe.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prfValue",c);const d=await this.cipher.getCredentialsKeyPair({prfValue:c,authType:exports.AuthType.Passkey});return pe.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::credentials key pair was created",!!d),Object.assign(Object.assign({},d),{prfValue:c})}catch(e){if(e instanceof V)throw e;if(e instanceof Error)throw new V({message:e.message,statusCode:400,errorCode:"sdk_passkey_prf_handling_failed",data:e,cause:e.cause});throw this.authenticator.handlePasskeyError(e)}}}function Sd(e){return function(t,r,s){if(!s.value)return;const a=s.value;return s.value=async function(...s){var n,i,o,c,d;const l=this.lockManager,h=e||`${t.constructor.name}:${r}`,u=null!==(i=null===(n=this.options)||void 0===n?void 0:n.environment)&&void 0!==i?i:ge,p=null!==(c=null===(o=this.options)||void 0===o?void 0:o.network)&&void 0!==c?c:we,y=`${null!==(d=this.userId)&&void 0!==d?d:"anon"}:${u}:${p}:${h}`;return l.withLock(y,(()=>a.apply(this,s)))},s}}class _d extends dd{constructor(e,t={}){super(e,t),this.getUserSalt=this.getUserSalt.bind(this),this.passkeyService=new vd(e.userId,this.localStorageService,this.request,this.cipher)}async isDevicePrfCompatible(){return await this.passkeyService.isDevicePrfCompatible()}async validateSession(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken),t=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);return!!e&&!Da(e)||!!t}async refreshAuthTokens(){if(!await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken))throw new V({message:"Refresh token is required",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_refresh_token_missing});await this._performTokenRefresh();const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken),t=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(!e||!t)throw new V({message:"Token refresh failed: tokens not present in storage after refresh",statusCode:401,errorCode:exports.ErrorResponseCodes.sdk_refresh_token_missing});return{accessToken:e,refreshToken:t}}async validatePassword({password:e,salt:t}){const r=null!=t?t:await this.getUserSalt();try{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)throw new V({message:"V2 Private key was not found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const s=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:r});return!!await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:s.privateKey})}catch(t){pe.warn("SDK::AuthService::validatePassword::error",t);return!!await this.localStorageService.getDecryptedV1PrivateKey(`${e}`)}}async getUserSalt(){try{return(await this.api.users.getCurrentUserSalt()).clientSalt}catch(e){throw pe.error("SDK::AuthService::getUserSalt::error",e),e}}async getSignature({deviceAuthKeys:e,walletId:t,passkeyChallengeType:r}){try{pe.debug("SDK::AuthService::getSignature::authType",this.deviceAuthType);const s=this.deviceAuthType===exports.AuthType.Passkey?null!=r?r:exports.PasskeyChallengeType.REGISTRATION:void 0;pe.debug("SDK::AuthService::getSignature::challengeType",s);const a=await this.request(Ba.signatureMessage,{payload:{walletId:t,clientAuthPubKey:e.publicKey,passkeyChallengeType:s}}),{signature:n,hashedMessage:i}=await this.cipher.sign({message:a.message,signingKey:e.privateKey});return Object.freeze(Object.assign(Object.assign({},a),{signature:n,hashedMessage:i,authenticationOptions:a.authenticationOptions,registrationOptions:a.registrationOptions}))}catch(e){throw pe.error("SDK::AuthService::getSignatureMessage::error",e),e}}async signUp(e){pe.info("starting signup");const t=Ls();let r;pe.info("key pair generated",!!t);try{const s=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});switch(pe.info("signature has been generated",!!s),this.deviceAuthType){case exports.AuthType.Passkey:pe.info("registering a new passkey"),r=await this.passkeyService.register({deviceKeyPair:t,challengeResponse:s});break;case exports.AuthType.Password:pe.info("signing up with password"),r=await this.handleSignUpWithPassword({signatureMessage:s,deviceKeyPair:t,input:e});break;default:throw new V({message:"Encryption mechanism not supported",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}return Object.freeze(Object.assign(Object.assign(Object.assign({},r),e),{signatureMessageResponse:s}))}catch(e){if(pe.error("SDK::AuthService::signUp::error",e),e&&e.error===oe.error||e.code===ie.error){pe.info("SDK::AuthService::signUp::handling previously registered passkey error");const e=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});return r=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:t.publicKey,decryptedPrivateKey:t.privateKey},challengeResponse:e}),r}throw e}}async signIn(e){let t;try{switch(this.deviceAuthType){case exports.AuthType.Passkey:t=await this.handleSignInWithPasskey({input:e});break;case exports.AuthType.Password:t=await this.handleSignInWithPassword({input:e});break;default:throw new V({message:"Encryption mechanism not supported",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,t.accessToken),t.refreshToken&&await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,t.refreshToken),Object.freeze(Object.assign(Object.assign({},t),e))}catch(e){throw pe.error("SDK::AuthService::signIn::error",e),e}}async hasStoredDevicePublicKey(){return!!await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey)}async handleSignInWithPassword({input:e}){if(!e.password)throw new V({message:"Password is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),r=await this.localStorageService.getEncryptedPrivateKey(),s=await this.getUserSalt(),a=await this.cipher.getCredentialsKeyPair({password:e.password,salt:s,authType:this.deviceAuthType});let n;if(t||r){if(!await this.validatePassword({password:e.password,salt:s}))throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password, please try again."),new V({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(t){const e=_a(t);n=await this.cipher.decrypt({cipherText:e,decryptionKey:a.privateKey})}else n=await this.localStorageService.getDecryptedV1PrivateKey(e.password)}else{if(await this.hasStoredDevicePublicKey())throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Device key missing but wallet data exists"),new V({message:"Device key could not be read but existing wallet data was found on this device. Refusing to create a new identity to avoid orphaning wallet data.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_device_key_missing_with_existing_data});pe.info("No device data found, treating as a fresh device and creating a new key pair");n=Ls().privateKey}if(!n)throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const i=ms(n);await this.storeDeviceKeyPair({deviceAuthKeyPair:{publicKey:i,privateKey:n},credentialsKeyPair:a});const o=await this.getSignature({deviceAuthKeys:{publicKey:i,privateKey:n}}),c=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:o.message,signature:o.signature,clientAuthPubKey:i}});return Object.assign(Object.assign({},c),{signatureMessageResponse:o,password:e.password,clientSalt:c.user.clientSalt})}async handleSignInWithPasskey({input:e}){let t;try{const r=await this.localStorageService.fetch(exports.LocalStorageItems.PasskeyCredential),s=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),a=await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey);let n;if(r){pe.debug("SDK::AuthService::handleSignInWithPasskey:: using existing key pair");const e=await this.request(Ba.signatureMessage,{payload:{clientAuthPubKey:a,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}});t=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:a,encryptedDevicePrivateKey:_a(s)},challengeResponse:e}),pe.debug("SDK::AuthService::handleSignInWithPasskey:: passkey authentication finished",!!t)}else{if(a||s)throw pe.error("SDK::AuthService::handleSignInWithPasskey::error","Passkey credential missing but device data exists"),new V({message:"Passkey credential could not be read but existing wallet data was found on this device. Refusing to create a new identity to avoid orphaning wallet data.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_device_key_missing_with_existing_data});n=Ls(),t=await this.passkeyService.addNewPasskey({deviceKeyPair:n,getSignature:this.getSignature.bind(this)}),pe.debug("SDK::AuthService::handleSignInWithPasskey:: passkey registration finished",t)}return Object.assign(Object.assign(Object.assign({},t),{prfValue:t.prfValue}),e)}catch(e){throw pe.error("SDK::AuthService::handleSignInWithPasskey::error ",e),e}}async storeDeviceKeyPair({deviceAuthKeyPair:e,credentialsKeyPair:t}){const r=await this.cipher.encrypt({data:e.privateKey,encryptionKey:t.publicKey});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:r},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:e.publicKey}])}async handleSignUpWithPassword({signatureMessage:e,input:t,deviceKeyPair:r}){if(!t.password)throw new V({message:"Password is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const s=await this.validatePasswordStrength(t.password);if(!s.valid)throw new V({message:s.message||"Invalid password",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const a=await this.request(Ba.signUp,{payload:{externalUserId:this.userId,message:e.message,signature:e.signature,clientAuthPubKey:r.publicKey}}).then((async e=>{const s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t.password,salt:e.user.clientSalt}),a=await this.cipher.encrypt({data:r.privateKey,encryptionKey:s.publicKey});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:a},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:r.publicKey},{key:exports.LocalStorageItems.AccessToken,value:e.accessToken},...e.refreshToken?[{key:exports.LocalStorageItems.RefreshToken,value:e.refreshToken}]:[]]),e}));return Object.assign(Object.assign({},a),{password:t.password,clientSalt:a.user.clientSalt,signatureMessageResponse:e})}async getPasskeyCredentials(){try{return await this.api.auth.getPasskeyCredentials()}catch(e){if(pe.error("SDK::AuthService::getPasskeyCredentials::error",e),"string"==typeof e)throw new V({message:e,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});if(e&&"object"==typeof e&&"message"in e)throw new V({message:e.message,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_unknown_error,data:e});throw e}}async validatePasswordStrength(e){return e?e.length<8?{valid:!1,message:"Password must be at least 8 characters long"}:e.length>128?{valid:!1,message:"Password must not exceed 128 characters"}:{valid:!0}:{valid:!1,message:"Password is required"}}async exchangeClientToken(){try{const e=await this.request(Ba.issueJwtToken);return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,e.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,e.refreshToken),e}catch(e){throw pe.error("SDK::Auth::exchangeClientToken::error",e),e}}}e._([Sd("signUp"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],_d.prototype,"signUp",null),e._([Sd("signIn"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],_d.prototype,"signIn",null),e._([Sd("storeDeviceKeyPair"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],_d.prototype,"storeDeviceKeyPair",null);class Ad extends dd{constructor(e,t={}){super(e,t),this.authService=new _d(e,t),this.userId=e.userId}async handleImportWallet(e,t){var r,s,a,n,i;try{const{signature:i,message:o,wallabyAuthPubKey:c}=await this.authService.getSignature({walletId:null!==(r=t.walletId)&&void 0!==r?r:t.reference,deviceAuthKeys:{publicKey:e.publicKey,privateKey:e.privateKey},passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0});if(!c)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});if((t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||t.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!t.keyShareOptions)throw new V({message:"Key share options are required when requesting to split the seed phrase",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const{numberOfKeyShares:d,threshold:l}=null!==(s=t.keyShareOptions)&&void 0!==s?s:{};if(l&&d&&d<l)throw new V({message:"Number of shares must be greater than or equal to the threshold",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const h=await this.cipher.encrypt({data:Wa(t.seedPhrase),encryptionKey:c}),u={reference:t.reference,walletId:t.walletId,message:o,signature:i,encryptedSeed:h,clientAuthPubKey:e.publicKey,returnWalletOption:t.returnWalletOption,numShares:d,threshold:l,walletOwnershipType:exports.WalletOwnershipType.SingleOwner,wallabyKeepsOne:null!==(n=null===(a=t.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n},p=await this.request(ld.importSeedPhraseV2,{payload:u}),y=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:t.authenticationOptions.user.clientSalt,password:t.authenticationOptions.password,prfValue:t.authenticationOptions.prfValue});return p.encryptedSeed&&t.returnWalletOption!==exports.ReturnWalletOption.ReturnOnlyEncryptedShares&&await this.handleSeedPhraseFromResponse({walletId:p.wallet.id,encryptedSeed:p.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:t.storeSeedPhrase,credentialsKeyPair:y}),p.shares&&p.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:p.wallet.id,shares:p.shares,credentialsKeyPair:y,encryptedBackupShare:p.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign({},p)}catch(e){throw new V({message:null!==(i=e.message)&&void 0!==i?i:"Failed to handle importing the wallet",statusCode:e.statusCode,errorCode:e.errorCode,data:e.data,cause:e.cause})}}async handleWalletCreation(e,t){var s,a,n,i,o,c;try{const{signature:o,message:c,hashedMessage:d}=await this.authService.getSignature({deviceAuthKeys:{publicKey:e.publicKey,privateKey:e.privateKey},passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if((t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedShares||t.returnWalletOption===exports.ReturnWalletOption.ReturnBothEncryptedSharesAndSeed)&&!t.keyShareOptions)throw new V({message:"Key share options are required when requesting to split the seed phrase",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const{numberOfKeyShares:l,threshold:h}=null!==(s=t.keyShareOptions)&&void 0!==s?s:{};if(h&&l&&l<h)throw new V({message:"Number of shares must be greater than or equal to the threshold",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const u={reference:r.v4(),message:c,signature:o,hashedMessage:d,clientAuthPubKey:e.publicKey,returnWalletOption:t.returnWalletOption,numShares:l,threshold:h,wallabyKeepsOne:null!==(n=null===(a=t.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n,walletOwnershipType:null!==(i=t.walletOwnershipType)&&void 0!==i?i:exports.WalletOwnershipType.SingleOwner},p=await this.request(ld.createWithKeyShares,{payload:u});let y;const f=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:t.authenticationOptions.user.clientSalt,password:t.authenticationOptions.password,prfValue:t.authenticationOptions.prfValue});return p.encryptedSeed&&(y=await this.handleSeedPhraseFromResponse({walletId:p.wallet.id,encryptedSeed:p.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:t.storeSeedPhrase,credentialsKeyPair:f})),p.shares&&p.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:p.wallet.id,shares:p.shares,credentialsKeyPair:f,encryptedBackupShare:p.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign(Object.assign({},p),{standardSeedPhrase:y})}catch(e){throw pe.error("SDK::handleWalletCreation::error",e),new V({message:null!==(o=e.message)&&void 0!==o?o:"Failed to handle creating the wallet",statusCode:e.statusCode,errorCode:null!==(c=e.errorCode)&&void 0!==c?c:"unspecified_error",data:e.data,cause:e.cause})}}async handleKeySharesFromResponse({walletId:e,shares:t,credentialsKeyPair:r,encryptedBackupShare:s,devicePrivateKey:a}){try{!function(e){if(!e.length)throw new V({message:"No key shares were returned from the API.",statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter})}(t);try{await this.cipher.decrypt({cipherText:t[0].encrypted,decryptionKey:a})}catch(e){throw new V({message:"Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.",statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_key_share_decryption_failed,cause:e})}const n=await this.cipher.encrypt({data:JSON.stringify(t[0].encrypted),encryptionKey:r.publicKey}),i=await this.cipher.encrypt({data:JSON.stringify(s),encryptionKey:r.publicKey});return await this.localStorageService.saveInBulk([{key:exports.V2KeyNames.PrimaryDeviceKeyShare,value:n,walletId:e},{key:exports.V2KeyNames.BackupDeviceKeyShare,value:i,walletId:e}]),[n,i]}catch(e){throw pe.error("SDK::handleKeySharesFromResponse::error",e),e}}async handleSeedPhraseFromResponse({walletId:e,encryptedSeed:t,devicePrivateKey:r,credentialsKeyPair:s,storeSeedPhrase:a}){try{const n=await this.cipher.decrypt({cipherText:t,decryptionKey:r});if(a){const t=ms(r),a=await this.cipher.encrypt({data:n,encryptionKey:t}),i=await this.cipher.encrypt({data:JSON.stringify(a),encryptionKey:s.publicKey});await this.localStorageService.save(exports.V2KeyNames.EncryptedStandardSeedPhrase,i,{walletId:e})}return n}catch(e){throw pe.error("SDK::handleSeedPhraseFromResponse::error",e),e}}}function Ed(e){const t=[];let r=0,s=0;for(const a of e)r|=a<<s,s+=8,s>=11&&(t.push(2047&r),r>>>=11,s-=11);return s>0&&t.push(2047&r),t}class bd extends dd{constructor(e,t={}){super(e,t),this.authService=new _d(e,t),this.handlers=new Ad(e,t),this.userId=e.userId,this.passkeyService=new vd(e.userId,this.localStorageService,this.request,this.cipher)}async getRateState(e){const t=Date.now(),r=await this.localStorageService.fetch(e),s=r?_a(r):void 0;return!s||t-s.windowStart>bd.RATE_LIMIT_WINDOW_MS?{count:0,windowStart:t}:s}async recordRateAttempt(e){const t=await this.getRateState(e);return t.count+=1,await this.localStorageService.save(e,JSON.stringify(t)),t.count}async assertUnderRateLimit(e,t){const{count:r}=await this.getRateState(e);if(r>bd.RATE_LIMIT_MAX)throw new V({message:t,statusCode:429,errorCode:exports.ErrorResponseCodes.sdk_too_many_requests})}async hasSeedPhraseOnDevice({walletId:e}){return await this.localStorageService.checkSeedPhraseExists(e)}async hasPrimaryKeyShareOnDevice({walletId:e}){return await this.localStorageService.checkPrimaryKeyShareExists(e)}async hasBackupKeyShareOnDevice({walletId:e}){return await this.localStorageService.checkBackupKeyShareExists(e)}async hasWalletOnDevice({walletId:e}){return await this.hasSeedPhraseOnDevice({walletId:e})||await this.hasPrimaryKeyShareOnDevice({walletId:e})}async create(e){try{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)throw new V({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const r=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,prfValue:e.authenticationOptions.prfValue,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt}),s=await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:r.privateKey});if(!s)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const a=ms(s);return await this.handlers.handleWalletCreation({publicKey:a,privateKey:s},e)}catch(e){throw pe.error("SDK::Wallet::create::error",e),e}}async export({walletId:e,authenticationOptions:t,exportOptions:r}){try{if(!r.algorandSeedPhrase&&!r.standardSeedPhrase&&!r.keyShares)throw new V({message:"exportOptions must be provided with at least one of the following options: algorandSeedPhrase, standardSeedPhrase, keyShares",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&t.password&&await this.migrateToV2Safe({password:t.password,walletId:e});const s=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:e}),a=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:e}),n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);let i,o,c;if(!n)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const d=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}),l=_a(n),h=await this.cipher.decrypt({cipherText:l,decryptionKey:d.privateKey});if(!h)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});if(r.keyShares){if(!a)throw new V({message:"You do not have any key shares stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const e=_a(a);i=await this.cipher.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:l,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}})}if(r.standardSeedPhrase||r.algorandSeedPhrase)if(s){const e=_a(s);if(o=await this.cipher.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:l,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),r.algorandSeedPhrase&&(c=this.getAlgorandSeedPhrase(o),!c))throw new V({message:"Something went wrong decrypting algorand seed phrase.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed})}else{if(!a)throw new V({message:"You do not have a wallet stored on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const s=_a(a),n={publicKey:ms(h),privateKey:h},{signature:i,message:d,wallabyAuthPubKey:u}=await this.authService.getSignature({deviceAuthKeys:n,walletId:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),p=u;if(!p)throw new V({message:"Wallaby public key is required for wallet export.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:s,encryptedDevicePrivateKey:l,wallabyPublicKey:p,destinationPubKey:n.publicKey,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),f=await this.request(ld.retrieveSeedPhrase,{payload:{walletId:e,signature:i,message:d,clientAuthPubKey:n.publicKey,encryptedShares:[y]}});o=await this.cipher.decrypt({cipherText:f.encryptedSeed,decryptionKey:h}),r.algorandSeedPhrase&&(c=this.getAlgorandSeedPhrase(o))}return{keyShares:r.keyShares&&i?i:void 0,standardSeedPhrase:r.standardSeedPhrase&&o?o:void 0,algorandSeedPhrase:r.algorandSeedPhrase&&c?c:void 0}}catch(e){throw pe.error("SDK::WalletService::export::error",e),e}}async import(e){var t;try{const s=null!==(t=e.reference)&&void 0!==t?t:r.v4(),a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new V({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=_a(a),i=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue}),o=await this.cipher.decrypt({cipherText:n,decryptionKey:i.privateKey});if(!o)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ms(o);return await this.handlers.handleImportWallet({publicKey:c,privateKey:o},Object.assign(Object.assign({},e),{reference:s}))}catch(e){throw pe.error("SDK::WalletService::import::error",e),e}}async changePassword({walletId:e,oldPassword:t,newPassword:r}){try{if(await this.recordRateAttempt(exports.V2KeyNames.PasswordResetAttempts)>bd.RATE_LIMIT_MAX)throw new V({message:"Too many password change attempts. Please try again later.",statusCode:429,errorCode:exports.ErrorResponseCodes.sdk_too_many_requests});this.deviceAuthType===exports.AuthType.Password&&t&&await this.migrateToV2Safe({password:t,walletId:e});const s=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),a=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:e}),n=await this.localStorageService.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:e}),i=await this.localStorageService.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e});if(!s||"undefined"===s)throw new V({message:"Could not locate client keys on this device.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=await this.authService.getUserSalt(),c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t,salt:o});if(!c.privateKey)throw new V({message:"Could not derive keys from old password. Please make sure the password is correct.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const d=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,salt:o});if(!d.publicKey||!d.privateKey)throw new V({message:"Could not derive keys for new password.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});const l=await this.cipher.flipEncryptedData({cipherText:JSON.parse(s),decryptionKey:c.privateKey,encryptionKey:d.publicKey});if(!l)throw new V({message:"Failed to re-wrap device private key during password change.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});await this.assertRoundTrip(l,d.privateKey,"device key");const h=a?await this.cipher.flipEncryptedData({cipherText:_a(a),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,u=n?await this.cipher.flipEncryptedData({cipherText:_a(n),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,p=i?await this.cipher.flipEncryptedData({cipherText:_a(i),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null;return h&&await this.assertRoundTrip(h,d.privateKey,"seed phrase"),u&&await this.assertRoundTrip(u,d.privateKey,"primary share"),p&&await this.assertRoundTrip(p,d.privateKey,"backup share"),await this.localStorageService.commitBatch([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:l},...h?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,value:h,walletId:e}]:[],...u?[{key:exports.LocalStorageItems.PrimaryDeviceKeyShare,value:u,walletId:e}]:[],...p?[{key:exports.LocalStorageItems.BackupDeviceKeyShare,value:p,walletId:e}]:[]]),await this.localStorageService.delete(exports.V2KeyNames.PasswordResetAttempts),!0}catch(e){throw pe.error("SDK::Wallet::changePassword::error",e),e}}getAlgorandSeedPhrase(e){try{const r=h.mnemonicToSeedSync(e),s=function(e){if(32!==e.length)throw new Error(`Algorand seed must be 32 bytes, got ${e.length}`);const r=t.wordlists.english,s=Ed(e).map((e=>r[e])),a=Ed(br(e).subarray(0,2))[0];return[...s,r[a]].join(" ")}(r.slice(0,32));return s}catch(e){throw pe.error("SDK::Wallet::getAlgorandSeedPhrase::error",e),new V({message:e instanceof Error?e.message:"Failed to convert seed phrase to Algorand mnemonic.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}async initAddNewDevice(e){const{walletId:t,backupUrl:r,authenticationOptions:s}=e,a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=_a(a);this.deviceAuthType===exports.AuthType.Password&&e.authenticationOptions.password&&await this.migrateToV2Safe({password:e.authenticationOptions.password,walletId:e.walletId});const i=await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare,{walletId:t});if(!i)throw new V({message:"You do not have any additional key shares stored on this device, you cannot add a new device from here.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_key_shares_not_found});const o=_a(i),c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:s.password,salt:s.user.clientSalt,prfValue:s.prfValue});if(!await this.cipher.decrypt({cipherText:n,decryptionKey:c.privateKey}))throw new V({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});return{walletId:t,backupUrl:r,encryptedBackupShare:_a(await this.cipher.decrypt({cipherText:o,decryptionKey:c.privateKey}))}}async addNewDevice(e){var t;try{const r=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!r)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:e.authenticationOptions.password,salt:e.authenticationOptions.user.clientSalt,prfValue:e.authenticationOptions.prfValue}),a=await this.cipher.decrypt({cipherText:JSON.parse(r),decryptionKey:s.privateKey});if(!a)throw new V({message:"Failed to decrypt device private key",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const n=null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey))&&void 0!==t?t:ms(a),i=await this.authService.getSignature({deviceAuthKeys:{privateKey:a,publicKey:n},walletId:e.walletId,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),o=await this.request(ld.addNewDevice,{payload:{walletId:e.walletId,clientAuthPubKey:n,signature:i.signature,message:i.message,wallabyAuthPubKey:i.wallabyAuthPubKey,encryptedBackupShare:e.encryptedBackupShare}});return await this.handlers.handleKeySharesFromResponse({walletId:e.walletId,shares:[o.share],credentialsKeyPair:s,encryptedBackupShare:e.encryptedBackupShare,devicePrivateKey:a}),{success:!0,reference:o.reference}}catch(e){throw pe.error("SDK::Wallet::backupKeyShare::error",e),e}}async generateWalletAddresses(e){const{walletId:t}=e;if(!t)throw new V({message:"Wallet ID is missing in the request",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&e.authenticationOptions.password&&await this.migrateToV2Safe({password:e.authenticationOptions.password,walletId:e.walletId});try{const r=await this.prepareWalletOperationAuth({walletId:t,authenticationOptions:e.authenticationOptions});return await this.request(ld.generateWalletAddresses,{payload:{walletId:t,message:r.signatureMessage.message,clientAuthPubKey:r.deviceAuthPublicKey,signature:r.signatureMessage.signature,encryptedSeed:r.readyForTransportSeedPhrase,encryptedShares:r.sharesEncryptedWithWallabyPubKey,chainName:e.blockchainName}})}catch(e){throw pe.error("SDK::Wallet::generateWalletAddresses::error",e),e}}async migrateToV2Safe({password:e,walletId:t}){try{await this.handleUpdateToV2({password:e,walletId:t})}catch(e){if(e instanceof V&&e.errorCode===exports.ErrorResponseCodes.sdk_ambiguous_legacy_migration_data)throw e;throw pe.error("SDK::WalletService::migrateToV2Safe::error",e),new V({message:"Error accessing user wallet on this device. Please ensure the password is correct and try again.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}assertValidDeviceKey(e){try{this.cipher.validatePrivateKey(e)}catch(e){throw pe.error("SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material",e),new V({message:"Could not access your device key — your stored wallet credentials appear to be corrupted.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed})}}async handleUpdateToV2({password:e,walletId:t}){const r=Date.now();await this.assertUnderRateLimit(exports.V2KeyNames.MigrationAttempts,"Too many migration attempts. Please try again later.");try{if(!e)throw new V({message:"Password is required for migration to v2",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const s=this.version,n=await this.localStorageService.fetch(exports.V2KeyNames.MigrationVersion),i=await this.localStorageService.fetch(exports.V2KeyNames.LastMigratedAt);if(pe.info("SDK::WalletService::handleUpdateToV2::starting migration check",{timestamp:new Date(r).toISOString(),walletId:t.substring(0,8)+"...",lastMigratedAt:i,currentSdkVersion:s,sdkMigrationVersion:n}),i&&"never"!==i&&n)return void pe.info("SDK::WalletService::handleUpdateToV2::Migration already completed successfully, skipping",{migratedVersion:n,migratedAt:i});const o=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),c=await this.localStorageService.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:t}),d=await this.localStorageService.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:t}),l=await this.authService.getUserSalt(),h=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:l});if(o&&(c||d))try{await this.cipher.decrypt({cipherText:_a(o),decryptionKey:h.privateKey});const t=c||d;return await this.cipher.displayStoredData({storedEncryptedData:_a(t),encryptedDevicePrivateKey:_a(o),options:{authType:exports.AuthType.Password,password:e,salt:l}}),pe.info("SDK::WalletService::handleUpdateToV2::V2 items already exist and are valid, no migration needed"),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,(new Date).toISOString()),void await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,s)}catch(e){pe.info("SDK::WalletService::handleUpdateToV2::V2 items exist but decryption failed, proceeding with migration",{error:JSON.stringify(e)})}let u,p;await this.recordRateAttempt(exports.V2KeyNames.MigrationAttempts);const y=await this.localStorageService.isLegacySeedFallbackSafeFor(t),f=y?await this.localStorageService.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`):void 0,g=await this.localStorageService.getDecryptedV1PrivateKey(e);if(f&&g){this.assertValidDeviceKey(g),pe.info("SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration",{storageFormat:"legacy"});try{const r=_a(a.AES.decrypt(f,`${l}${e}`).toString(a.enc.Utf8));if(u=wa(g,r),p=g,!u)throw new V({message:"Failed to decrypt legacy seed phrase items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});pe.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted legacy items"),await this.localStorageService.claimLegacySeedFallbackFor(t)}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt legacy items",e),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}else{const r=await this.localStorageService.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard,t),s=await this.localStorageService.getEncryptedPrivateKey();if(!r||!s){if(!y){const e=await this.localStorageService.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`),t=await this.localStorageService.getV1EncryptedSeedPhrase();if(e||t)throw pe.error("SDK::WalletService::handleUpdateToV2::Legacy seed data on this device is already claimed by a different wallet; refusing to migrate ambiguously"),new V({message:"Legacy wallet data on this device is associated with a different wallet and cannot be safely migrated for this wallet.",statusCode:409,errorCode:exports.ErrorResponseCodes.sdk_ambiguous_legacy_migration_data})}return pe.info("SDK::WalletService::handleUpdateToV2::No legacy or V1 items found to migrate"),void pe.info("SDK::WalletService::handleUpdateToV2:: You do not have a wallet stored on this device. Nothing to migrate.")}p=await this.localStorageService.getDecryptedV1PrivateKey(e),p&&this.assertValidDeviceKey(p),pe.info("SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration",{storageFormat:"v1",validPrivateKey:!!p});try{if(pe.log("Attempting to decrypt V1 items during migration..."),pe.log("getV1DecryptedSeedPhrase should be called with password and clientSalt:",{hasPassword:!!e,hasClientSalt:!!l}),u=await this.localStorageService.getV1DecryptedSeedPhrase(e,l),p=await this.localStorageService.getDecryptedV1PrivateKey(e),!u||!p)throw new V({message:"Failed to decrypt V1 items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});pe.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted V1 items"),await this.localStorageService.claimLegacySeedFallbackFor(t)}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt V1 items",e),new V({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}if(u&&p){pe.info("SDK::WalletService::handleUpdateToV2::Initiating wallet recovery for V2 migration"),pe.info("SDK::WalletService::handleUpdateToV2::Migration data prepared"),pe.info("SDK::WalletService::handleUpdateToV2::Seed phrase available:",!!u);const e=ms(p),s=await this.authService.getSignature({deviceAuthKeys:{publicKey:e,privateKey:p},walletId:t}),a=await this.request(Ba.signIn,{payload:{externalUserId:this.userId,message:s.message,signature:s.signature,clientAuthPubKey:e}}),n=await this.cipher.encrypt({data:p,encryptionKey:h.publicKey}),i=await this.cipher.doubleEncrypt({decryptedData:u,credentialsKeyPair:h,deviceKeyPair:{publicKey:e,privateKey:p}});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.AccessToken,value:a.accessToken},{key:exports.V2KeyNames.EncryptedStandardSeedPhrase,value:i,walletId:t},{key:exports.V2KeyNames.EncryptedDevicePrivateKey,value:n}]),pe.info("SDK::WalletService::handleUpdateToV2::Migration completed successfully",{timestamp:(new Date).toISOString(),duration:Date.now()-r,devicePublicKey:e.substring(0,16)+"...",migratedKeys:["EncryptedDevicePrivateKey","EncryptedStandardSeedPhrase"]}),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,(new Date).toISOString()),void await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,this.version)}throw new V({message:"Decrypted data required for migration is missing, operation cannot be completed.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Migration failed",{timestamp:(new Date).toISOString(),duration:Date.now()-r,error:e instanceof Error?e.message:"Unknown error"}),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,"never"),await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,this.version),e}}async verifyAccess(e){try{const{readyForTransportSeedPhrase:t,sharesEncryptedWithWallabyPubKey:r,hasShares:s,signatureMessage:a,deviceAuthPublicKey:n}=await this.prepareWalletOperationAuth({authenticationOptions:e.authenticationOptions,walletId:e.walletId}),i=t&&!s;return await this.api.wallets.verifyAccess({message:a.message,signature:a.signature,clientAuthPubKey:n,encryptedSeed:i?t:void 0,encryptedShares:i?void 0:r,walletId:e.walletId})}catch(e){throw pe.error("SDK::WalletService::verifyAccess::Error occurred",e),e}}async clearDevice({walletId:e}){await this.localStorageService.clearLocalStorage(e)}async prepareWalletOperationAuth({authenticationOptions:e,walletId:t}){const{password:r,prfValue:s,user:a}=e,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!n)throw new V({message:"Device private key could not be found",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const i=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}),o=await this.cipher.decrypt({cipherText:JSON.parse(n),decryptionKey:i.privateKey});if(!o)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const c=ms(o),d=await this.authService.getSignature({deviceAuthKeys:{publicKey:c,privateKey:o},walletId:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),l=d.wallabyAuthPubKey;if(!l)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const h=[];let u;const p=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(p){const e=_a(p),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(n),wallabyPublicKey:l,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}});h.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to complete this request.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const i=_a(e);u=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:i,encryptedDevicePrivateKey:JSON.parse(n),wallabyPublicKey:l,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}})}return{deviceAuthPublicKey:c,signatureMessage:d,readyForTransportSeedPhrase:u,sharesEncryptedWithWallabyPubKey:h.length?h:void 0,hasShares:h.length>0}}async convertToPasskey(e){let t=!1;try{const s=await this.localStorageService.fetch(exports.V2KeyNames.CredentialConversionInProgress),a=s?_a(s):void 0;(null==a?void 0:a.encryptedDevicePrivateKey)&&await this.localStorageService.save(exports.LocalStorageItems.EncryptedDevicePrivateKey,a.encryptedDevicePrivateKey),(null==a?void 0:a.walletId)===e.walletId&&pe.info("SDK::WalletService::convertToPasskey::resuming interrupted conversion");const n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:e.walletId}),o=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:e.walletId}),c=await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare,{walletId:e.walletId}),d=await this.authService.getUserSalt(),l=await this.cipher.getCredentialsKeyPair({password:e.password,salt:d,authType:exports.AuthType.Password});let h;if(!await this.authService.validatePassword({password:e.password,salt:d}))throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Incorrect password"),new V({message:"Incorrect password, please try again.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password});if(n){pe.log("SDK::WalletService::convertToPasskey::Decrypting v2 device private key with password-derived key");const e=_a(n);h=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}else pe.log("SDK::WalletService::convertToPasskey::No encrypted device private key found, checking for v1 format"),h=await this.localStorageService.getDecryptedV1PrivateKey(e.password);if(!h)throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Device private key could not be decrypted"),new V({message:"Device private key could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const u=ms(h);await this.localStorageService.save(exports.V2KeyNames.CredentialConversionInProgress,Object.assign({walletId:e.walletId},n?{encryptedDevicePrivateKey:n}:{}));const p=await this.passkeyService.addNewPasskey({deviceKeyPair:{publicKey:u,privateKey:h},getSignature:this.authService.getSignature.bind(this)});t=!0;const y=p.prfValue;if(!(y&&y instanceof Uint8Array&&0!==y.length))throw pe.error("SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array"),new V({message:"PRF value from passkey is required to derive credentials and could not be obtained",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_passkey_prf_not_available});let f,g,w;if(pe.log("SDK::WalletService::convertToPasskey::Received authentication response",!!p),i&&n)try{f=await this.cipher.displayStoredData({storedEncryptedData:_a(i),encryptedDevicePrivateKey:_a(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){pe.error("SDK::WalletService::convertToPasskey::seed_decryption_error",e)}if(!f)try{f=await this.localStorageService.getV1DecryptedSeedPhrase(e.password,d)}catch(e){pe.error("SDK::WalletService::convertToPasskey::v1_seed_decryption_error",e)}if(o&&n)try{const t=_a(o);g=await this.cipher.displayStoredData({storedEncryptedData:t,encryptedDevicePrivateKey:_a(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){pe.error("SDK::WalletService::convertToPasskey::primary_share_decryption_error",e)}if(c)try{const e=_a(c);w=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}catch(e){pe.error("SDK::WalletService::convertToPasskey::backup_share_decryption_error",e)}if(!f&&!(!!g||!!w))throw new V({message:"Seed phrase or key shares on this device could not be decrypted",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});if(f&&!g)return pe.info("SDK::WalletService::convertToPasskey::No primary share found, importing wallet"),await this.handlers.handleImportWallet({publicKey:u,privateKey:h},{authenticationOptions:p,seedPhrase:f,storeSeedPhrase:!1,returnWalletOption:exports.ReturnWalletOption.ReturnOnlyEncryptedShares,walletId:e.walletId,reference:r.v4(),keyShareOptions:{threshold:2,numberOfKeyShares:3,numberOfSharesReturned:2,storeOneKeyShareWithWallaby:!0}}),await this.localStorageService.commitBatch([],[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId},{key:exports.V2KeyNames.CredentialConversionInProgress}]),pe.info("SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed"),{authentication:p,seedPhrase:f};const m=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Passkey,prfValue:y}),v=[];if(g){const t=await this.cipher.doubleEncrypt({decryptedData:g,credentialsKeyPair:m,deviceKeyPair:{publicKey:u,privateKey:h}}),r=await this.cipher.decrypt({cipherText:t,decryptionKey:m.privateKey});if((r?await this.cipher.decrypt({cipherText:_a(r),decryptionKey:h}):null)!==g)throw new V({message:"Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error});v.push({key:exports.V2KeyNames.PrimaryDeviceKeyShare,value:t,walletId:e.walletId})}if(w){const t=await this.cipher.encrypt({data:w,encryptionKey:m.publicKey});v.push({key:exports.V2KeyNames.BackupDeviceKeyShare,value:t,walletId:e.walletId})}for(const e of v)await this.assertRoundTrip(e.value,m.privateKey,e.key);if(await this.localStorageService.commitBatch(v,[...i?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId}]:[],{key:exports.V2KeyNames.CredentialConversionInProgress}]),i&&pe.info("SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey"),!f&&g){const t={publicKey:u,privateKey:h},{signature:r,message:s,wallabyAuthPubKey:a}=await this.authService.getSignature({deviceAuthKeys:t,walletId:e.walletId,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if(!a)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const n=await this.cipher.encrypt({data:xa(g,t.publicKey),encryptionKey:a}),i=await this.request(ld.retrieveSeedPhrase,{payload:{walletId:e.walletId,signature:r,message:s,clientAuthPubKey:t.publicKey,encryptedShares:[n]}});f=await this.cipher.decrypt({cipherText:i.encryptedSeed,decryptionKey:h})}if(!f)throw new V({message:"Seed phrase could not be reconstructed from the provided shares",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});return{authentication:p,seedPhrase:f}}catch(e){throw pe.error("SDK::WalletService::convertToPasskey::error",e),t||await this.localStorageService.delete(exports.V2KeyNames.CredentialConversionInProgress),e}}async assertRoundTrip(e,t,r){try{await this.cipher.decrypt({cipherText:e,decryptionKey:t})}catch(e){throw new V({message:`Re-wrap validation failed for ${r}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}}}bd.RATE_LIMIT_MAX=5,bd.RATE_LIMIT_WINDOW_MS=18e5,e._([Sd("create"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"create",null),e._([Sd("import"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"import",null),e._([Sd("credential-rewrap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"changePassword",null),e._([Sd("migrateToV2"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"handleUpdateToV2",null),e._([Sd("credential-rewrap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],bd.prototype,"convertToPasskey",null);class Id extends dd{constructor(e,t={}){super(e,t),this.userId=e.userId,this.walletService=new bd(e,t)}validateWalletAddressInfo(e,t){return e.some((e=>e.chainName===t))}async getTokenBalance({address:e,assetSymbol:t,tokenStandard:r,chainName:s}){try{if(!e||!t||!s&&!r)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.getTokenBalance,{payload:{address:e,assetSymbol:t,chainName:s,tokenStandard:r}})}catch(e){throw pe.error("SDK::WalletDataService::getTokenBalance::error",e),e}}async getMultiTokenBalances({walletId:e,tokensAndAddressesList:t}){try{if(!t.length)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.getMultiTokenBalances,{payload:{assets:t,walletId:e}})}catch(e){throw pe.error("SDK::WalletDataService::getMultiTokenBalances::error",e),e}}async getWalletBalances({walletId:e}){try{if(!e)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.getWalletBalances,{payload:{walletId:e}})}catch(e){throw pe.error("SDK::WalletDataService::getWalletBalances::error",e),e}}async getUserAssets({userId:e,queryOptions:t}){try{if(!e)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.getUserAssets,{payload:{userId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getUserAssets::error",e),e}}async getUserWallets({userId:e,queryOptions:t}){try{return await this.request(ld.getUserWallets,{payload:{userId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getUserWallets::error",e),e}}async getWalletAssets({walletId:e,queryOptions:t}){try{if(void 0!==(null==t?void 0:t.search)&&t.search.length<3)throw new V({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(ld.getWalletAssets,{payload:{walletId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getWalletAssets::error",e),e}}async addTokenToWallet({assetConfigId:e,walletId:t,userId:r,config:s,authenticationOptions:a}){try{if(!t)throw new V({message:"Wallet ID is required.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!e&&!s)throw new V({message:"Either assetConfigId or config must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});let n={};if(a){const e=await this.walletService.prepareWalletOperationAuth({walletId:t,authenticationOptions:a});n={message:e.signatureMessage.message,clientAuthPubKey:e.deviceAuthPublicKey,signature:e.signatureMessage.signature,encryptedSeed:e.readyForTransportSeedPhrase,encryptedShares:e.sharesEncryptedWithWallabyPubKey}}return await this.request(ld.addTokenToWallet,{payload:Object.assign({assetConfigId:e,walletId:t,userId:r||void 0,config:s},n)})}catch(e){throw pe.error("SDK::WalletDataService::addTokenToWallet::error",e),e}}async addNewChainAndTokenToWallet(e){const{authenticationOptions:t,walletId:r,userId:s,assetConfigId:a,blockchainName:n}=e;if(!(t&&r&&s&&a&&n))throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&t.password&&await this.walletService.migrateToV2Safe({password:t.password,walletId:r});try{const t=await this.walletService.generateWalletAddresses({walletId:e.walletId,authenticationOptions:e.authenticationOptions});if(this.validateWalletAddressInfo(t.walletAddressesInfo,n)){const t=(await this.getWalletAssets({walletId:r})).assets.find((e=>e.configId===a));if(t)return{asset:t};return await this.addTokenToWallet({assetConfigId:a,walletId:r,userId:s,authenticationOptions:e.authenticationOptions})}throw new V({message:`Wallet address is not present for blockchain: ${n}`,statusCode:400,errorCode:"sdk_wallet_address_not_found"})}catch(e){throw pe.error("SDK::WalletDataService::addNewChainAndTokenToWallet::error",e),e}}async updateAsset(t){var{configId:r,walletId:s}=t,a=e.b(t,["configId","walletId"]);try{if(!r||!s)throw new V({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ld.updateAsset,{payload:Object.assign({configId:r,walletId:s},a)})}catch(e){throw pe.error("SDK::WalletDataService::updateAsset::error",e),e}}}class Pd extends dd{constructor(e,t={}){super(e,t),this.getDecryptedPrivateKey=async e=>{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return""!==r?r:void 0},this.decryptDevicePrivateKey=({encryptedPrivateKey:e,password:t})=>{const r=a.AES.decrypt(e,t).toString(a.enc.Utf8);return""!==r?r:void 0},this.auth=new _d(e,t)}async decryptSeedPhrase({password:e}){var t;const r=await this.auth.getUserSalt();if(!r)throw new Error("Salt could not be found");const s=`${r}${e}`,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase);if(!n)throw new Error("Seed phrase could not be found");const i=_a(a.AES.decrypt(n,s).toString(a.enc.Utf8)),o=this.decryptDevicePrivateKey({encryptedPrivateKey:null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey))&&void 0!==t?t:"",password:e});if(!o)throw pe.error("SDK::Utils::decryptSeedPhrase::devicePrivateKey: Device private key could not be decrypted"),new Error("Device private key could not be decrypted");return await wa(o,i)}async fetchFromEndpoint({endpoint:e,method:t,requiresAccessToken:r,payload:s}){try{const a=new RegExp("https?://[^/]*.?wallaby.cash/api/v1","i"),n={fullPath:e.replace(a,""),method:t,requiresAccessToken:null!=r&&r};return await this.request(n,{payload:s})}catch(e){return pe.error("SDK::Utils::fetchFromEndpoint::error",e),Promise.reject(e)}}async validatePassword({password:e}){const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return{valid:!1,message:"Could not locate client keys or seed phrase on this device."};try{const r=await this.auth.getUserSalt(),s=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:r});return await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:s.privateKey})?{valid:!0}:{valid:!1,message:"Password is incorrect"}}catch(e){return pe.error("SDK::Utils::validatePassword::error",e),{valid:!1,message:"Password is incorrect."}}}}class Td extends dd{constructor(e,t={}){super(e,t)}}class kd extends dd{constructor(e,t={}){super(e,t),this.authService=new _d(e,t),this.walletService=new bd(e,t)}async getQuote(e){try{const{walletId:t,fromAssetConfigId:r,toAssetConfigId:s,fromAmount:a,toAmount:n,slippage:i}=e;if(!t||!r||!s)throw new V({message:"Missing required parameters: walletId, fromAssetConfigId, and toAssetConfigId",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(!a&&!n)throw new V({message:"Either fromAmount or toAmount must be provided",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(a&&n)throw new V({message:"Only one of fromAmount or toAmount may be provided, not both",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});const o={walletId:t},c=Object.assign(Object.assign(Object.assign({fromAssetConfigId:r,toAssetConfigId:s},a&&{fromAmount:a}),n&&{toAmount:n}),null!=i&&{slippage:i});return await this.request(Object.assign(Object.assign({},pd.getQuote),{fullPath:pd.getQuote.fullPath(o)}),{payload:c})}catch(e){throw pe.error("SDK::Swap::getQuote::error",e),e}}async executeSwap({walletId:e,quoteId:t,authenticationOptions:r}){try{this.deviceAuthType===exports.AuthType.Password&&r.password&&await this.walletService.migrateToV2Safe({password:r.password,walletId:e});const{deviceAuthPublicKey:s,signatureMessage:a,readyForTransportSeedPhrase:n,sharesEncryptedWithWallabyPubKey:i,hasShares:o}=await this.prepareSwapAuth(r,e);let c;if(n)c=await this.request(Object.assign(Object.assign({},pd.executeSwap),{fullPath:pd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedSeed:n}});else{if(!o)throw new V({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});c=await this.request(Object.assign(Object.assign({},pd.executeSwap),{fullPath:pd.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedShares:i}})}return c}catch(e){throw pe.error("SDK::Swap::executeSwap::error",e),e}}async getSwaps({walletId:e,queryParams:t}){try{if(!e)throw new V({message:"Missing required parameter: walletId",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const r={walletId:e};return await this.request(Object.assign(Object.assign({},pd.getSwaps),{fullPath:pd.getSwaps.fullPath(r)}),{queryParams:t})}catch(e){throw pe.error("SDK::Swap::getSwaps::error",e),e}}async prepareSwapAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!i)throw new V({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:o}),d=await this.cipher.decrypt({cipherText:JSON.parse(i),decryptionKey:c.privateKey});if(!d)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ms(d),h=await this.authService.getSignature({deviceAuthKeys:{publicKey:l,privateKey:d},passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0,walletId:t}),u=h.wallabyAuthPubKey;if(!u)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const p=[];let y;const f=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(f){const e=_a(f),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}});p.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to sign the transaction.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const a=_a(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:p,hasShares:p.length>0})}}e._([Sd("executeSwap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],kd.prototype,"executeSwap",null);class Cd extends dd{constructor(e,t={}){super(e,t)}async getSupportedBlockchains(e){try{return(await this.request(hd.getSupportedBlockchains,{queryParams:void 0!==(null==e?void 0:e.supportSwaps)?{supportSwaps:e.supportSwaps}:void 0})).chains}catch(e){throw pe.error("SDK::System::getSupportedBlockchains::error",e),e}}validateContractAddress({blockchain:e,contractAddress:t,suiObjectId:r}){switch(e){case exports.BlockchainName.Algorand:case exports.BlockchainName.Bitcoin:throw new V({message:`${e} does not support contract addresses.`,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});case exports.BlockchainName.Sui:if(r&&t)throw new V({message:"You can only provide either suiObjectId or contractAddress",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(t)throw new V({message:"You can only provide suiObjectId for SUI blockchain",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});if(!r)throw new V({message:"You must provide suiObjectId for SUI blockchain",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return(e=>{if(!e)throw new Error("Sui object ID is required");if(!e.startsWith("0x"))throw new Error("Invalid Sui object ID");return e.includes("::")?e.split("::")[0]:e})(r);default:if(!t)throw new V({message:"You must provide contractAddress for non-SUI blockchains",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return t}}async fetchTokenInfo({blockchain:e,contractAddress:t,suiObjectId:r,assetSymbol:s}){try{const a=this.validateContractAddress({blockchain:e,contractAddress:t,suiObjectId:r}),n=null!=s?s:e===exports.BlockchainName.Sui?(e=>{var t;if(!e||!e.includes("::"))return;const r=e.split("::");return(null===(t=r[r.length-1])||void 0===t?void 0:t.trim())||void 0})(r):void 0;return await this.request(hd.fetchTokenInfo,{queryParams:Object.assign({chainName:e,tokenContractAddress:a},n?{assetSymbol:n}:{})})}catch(e){throw pe.error("SDK::Wallet::fetchTokenInfo::error",e),e}}async getSupportedTokens(e){try{if(void 0!==(null==e?void 0:e.search)&&e.search.length<3)throw new V({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(hd.getSupportedTokens,{queryParams:e})}catch(e){throw pe.error("SDK::System::getSupportedTokens::error",e),e}}async getUserData(e){try{return(await this.request(hd.getUserData,{payload:{userId:e}})).user}catch(e){throw pe.error("SDK::System::getUserData::error",e),e}}async getUserByExternalUserId(e){try{return(await this.request(hd.getUserByExternalUserId,{payload:{externalUserId:e}})).user}catch(e){throw pe.error("SDK::System::getUserByExternalUserId::error",e),e}}}class xd extends dd{constructor(e,t={}){super(e,t),this.authService=new _d(e,t),this.walletService=new bd(e,t),this.userId=e.userId}async estimateFee({originAddress:e,recipientAddress:t,amount:r,transactionType:s,token:a}){try{return await this.request(ud.estimateFee,{queryParams:Object.assign({chainName:a.chainName,originAddress:e,recipientAddress:t,amount:r,assetSymbol:a.symbol,transactionType:s},a.tokenStandard&&{tokenStandard:a.tokenStandard})})}catch(e){throw pe.error("SDK::Transactions::estimateFee::error",e),e}}async getTransactionStatus({transactionHash:e,reference:t,blockchain:r}){try{return await this.request(ud.getTransaction,{payload:{transactionHash:e,transactionReference:t,chain:r.toString().toUpperCase()}})}catch(e){throw pe.error("SDK::Transactions::getTransactionStatus::error",e),e}}async getTransactions(e){try{return await this.request(ud.getTransactions,{queryParams:e})}catch(e){throw pe.error("SDK::Transactions::getTransactions::error",e),e}}async getRestriction(e){try{const t=Boolean(e.assetId),r=Boolean(e.contractAddress&&e.blockchainName);if(!t&&!r)throw new V({message:"Either assetId or both contractAddress and blockchainName must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(ud.restriction,{queryParams:Object.assign(Object.assign(Object.assign({fromAddress:e.fromAddress,toAddress:e.toAddress,amount:e.amount},e.assetId&&{assetId:e.assetId}),e.contractAddress&&{contractAddress:e.contractAddress}),e.blockchainName&&{blockchainName:e.blockchainName})})}catch(e){throw pe.error("SDK::Transactions::getRestriction::error",e),e}}async transfer({originAddress:e,recipientAddress:t,amount:s,assetId:a,walletId:n,reference:i,authenticationOptions:o,memo:c,transactionType:d}){try{this.deviceAuthType===exports.AuthType.Password&&o.password&&await this.walletService.migrateToV2Safe({password:o.password,walletId:n});const{deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:u,sharesEncryptedWithWallabyPubKey:p,hasShares:y}=await this.prepareTransactionAuth(o,n);let f;if(u)f=await this.request(ud.transfer,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedSeed:u,originAddress:e,recipientAddress:t,assetId:a,amount:s,reference:i||r.v4(),memo:c,transactionType:d}});else{if(!y)throw new V({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});f=await this.request(ud.transferWithShares,{payload:{walletId:n,message:h.message,signature:h.signature,clientAuthPubKey:l,encryptedShares:p,originAddress:e,recipientAddress:t,assetId:a,amount:s,reference:i||r.v4(),memo:c,transactionType:d}})}return f}catch(e){throw pe.error("SDK::Transactions::transfer::error",e),e}}async createAllowance({authenticationOptions:e,walletId:t,ownerAddress:r,spenderAddress:s,amount:a,assetId:n,suiObjectId:i,contractAddress:o,chainName:c,assetSymbol:d,reference:l,memo:h,transactionType:u}){try{if(!(i||o||n||d||c))throw new V({message:"AssetId, asset symbol, chain name or contract address must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});if(d&&!c||!d&&c)throw new V({message:"Asset symbol and chain name must be provided when asset is not in user wallet.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});this.deviceAuthType===exports.AuthType.Password&&e.password&&await this.walletService.migrateToV2Safe({password:e.password,walletId:t});const{deviceAuthPublicKey:p,signatureMessage:y,readyForTransportSeedPhrase:f,sharesEncryptedWithWallabyPubKey:g,hasShares:w}=await this.prepareTransactionAuth(e,t),{message:m,signature:v}=y;if(!f&&!w)throw new Error("No valid seed option found on this device.");const S=Object.assign({message:m,signature:v,walletId:t,clientAuthPubKey:p,ownerAddress:r,spenderAddress:s,chainName:c,assetSymbol:d,amount:a,assetId:n,contractAddress:null!=o?o:i,reference:l,memo:h,transactionType:u},w?{encryptedShares:g}:{encryptedSeed:f});return await this.request(ud.createAllowance,{payload:S})}catch(e){throw pe.error("SDK::Transactions::createAllowance::error",e),e}}async getPendingTransactions({walletId:e,chainName:t}){try{return await this.request(ud.getPendingTransactions,{queryParams:{walletId:e,chainName:t}})}catch(e){throw pe.error("SDK::Transactions::getPendingTransactions::error",e),e}}async resolvePendingTransaction({id:e,choice:t,symbol:r,chainName:s,walletId:a,authenticationOptions:n}){try{this.deviceAuthType===exports.AuthType.Password&&n.password&&await this.walletService.migrateToV2Safe({password:n.password,walletId:a});const{deviceAuthPublicKey:i,signatureMessage:o,readyForTransportSeedPhrase:c,sharesEncryptedWithWallabyPubKey:d,hasShares:l}=await this.prepareTransactionAuth(n,a);if(!c&&!l)throw new Error("No valid seed option found on this device.");return await this.request(ud.confirmPendingTransaction,{payload:{message:o.message,signature:o.signature,clientAuthPubKey:i,encryptedShares:d,encryptedSeed:c,id:e,choice:t,symbol:r,chainName:s,walletId:a}})}catch(e){throw pe.error("SDK::Transactions::transfer::error",e),e}}async prepareTransactionAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,i=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey,{walletId:t});if(!i)throw new V({message:"No private key was found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const o=n||a.clientSalt,c=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:r,prfValue:s,salt:o}),d=await this.cipher.decrypt({cipherText:JSON.parse(i),decryptionKey:c.privateKey});if(!d)throw new V({message:"Credentials are wrong, please pass the correct credentials.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_decryption_failed});const l=ms(d),h=await this.authService.getSignature({deviceAuthKeys:{publicKey:l,privateKey:d},walletId:t,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),u=h.wallabyAuthPubKey;if(!u)throw new V({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const p=[];let y;const f=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(f){const e=_a(f),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}});p.push(t)}else{const e=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase,{walletId:t});if(!e)throw new V({message:"Your device does not have a seed phrase or an operating share to sign the transaction.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const a=_a(e);y=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(i),wallabyPublicKey:u,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:o}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:h,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:p,hasShares:p.length>0})}}e._([Sd("transaction-restriction-message"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],xd.prototype,"getRestriction",null),e._([Sd("transfer"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],xd.prototype,"transfer",null),e._([Sd("createAllowance"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],xd.prototype,"createAllowance",null),e._([Sd("confirmPendingTransaction"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],xd.prototype,"resolvePendingTransaction",null);const Kd={mainnet:{genesisHash:"0x6fbd74e5e1d0a61d52ccfe9d4adaed16dd3a7caa37c6bc4d0c2fa12e8b2f4063",specVersion:7003003,transactionVersion:7,ss58Format:12,balanceDecimals:6},testnet:{genesisHash:"0x2ace05e703aa50b48c0ccccfc8b424f7aab9a1e2c424ed12e45d20b1e8ffd0d6",specVersion:7003003,transactionVersion:7,ss58Format:42,balanceDecimals:6}};function Od(e){return"mainnet"===e||"testnet"===e}class Nd extends Error{constructor(e,t,r){super(r),this.name=e,this.reason=t}}class Rd extends Nd{constructor(e,t){super("PolymeshDecodeError",e,t),this.reason=e}}class Dd extends Nd{constructor(e,t){super("PolymeshVerifyError",e,t),this.reason=e}}const Ld=/^[0-9a-fA-F]*$/;function Ud(e){return"0x"+Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Bd(...e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}const qd=c.Bytes(32),Vd=c.Bytes(32),Md=c.Bytes(16),Wd=c.Bytes(32),Fd=c.u64,Gd=c.Enum({Id:qd},[0]),jd=c.Enum({Default:c._void,User:c.u64},[0,1]),Hd=c.Struct({did:Vd,kind:jd}),$d=c.Enum({SettleOnAffirmation:c._void},[0]),Yd=c.Enum({Fungible:c.Struct({sender:Hd,receiver:Hd,assetId:Md,amount:c.u128})},[0]),zd=c.Struct({fungible:c.u32,nonFungible:c.u32,offChain:c.u32}),Jd=c.Struct({senderAssetCount:zd,receiverAssetCount:zd,offchainCount:c.u32});function Xd(e){return e.replace(/^0x/i,"").toLowerCase()}const Zd={"5:1":{variant:"balances.transferWithMemo",codec:c.Struct({dest:Gd,value:c.compact,memo:c.Option(Wd)})},"37:20":{variant:"settlement.addAndAffirmWithMediators",codec:c.Struct({venueId:c.Option(c.u64),settlementType:$d,tradeDate:c.Option(c.u64),valueDate:c.Option(c.u64),legs:c.Vector(Yd),portfolios:c.Vector(Hd),instructionMemo:c.Option(Wd),mediators:c.Vector(Vd)})},"37:16":{variant:"settlement.affirmInstruction",codec:c.Struct({id:Fd,portfolios:c.Vector(Hd),numberOfAssets:c.Option(Jd)})},"37:11":{variant:"settlement.affirmInstruction",codec:c.Struct({id:Fd,portfolios:c.Vector(Hd)})},"37:17":{variant:"settlement.rejectInstruction",codec:c.Struct({id:Fd,portfolio:Hd,numberOfAssets:c.Option(zd)})},"37:13":{variant:"settlement.rejectInstruction",codec:c.Struct({id:Fd,portfolio:Hd})}};function Qd(e,t,r){if(!t.genesisHash)throw new Rd("context-not-pinned","Polymesh chain context has no pinned genesisHash — see context.ts before using this in production");if(!r.genesisHash)throw new Rd("genesis-hash-mismatch","No genesisHash was observed on the transaction under verification — cannot confirm which chain this call targets");if(Xd(r.genesisHash)!==Xd(t.genesisHash))throw new Rd("genesis-hash-mismatch",`Observed genesisHash ${r.genesisHash} does not match the pinned genesisHash ${t.genesisHash} for this network`);if(r.specVersion!==t.specVersion)throw new Rd("spec-version-mismatch",`Observed specVersion ${r.specVersion} does not match the pinned specVersion ${t.specVersion} this decoder was validated against`);if(void 0!==r.transactionVersion&&r.transactionVersion!==t.transactionVersion)throw new Rd("transaction-version-mismatch",`Observed transactionVersion ${r.transactionVersion} does not match the pinned transactionVersion ${t.transactionVersion} this decoder was validated against`);let s;try{s=function(e){const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0)throw new Error("hexToU8a: hex string must have an even number of digits");if(!Ld.test(t))throw new Error("hexToU8a: invalid hex string");const r=new Uint8Array(t.length/2);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}(e)}catch(e){throw new Rd("malformed",`Call bytes are not valid hex: ${e.message}`)}if(s.length<2)throw new Rd("malformed","Call bytes are too short to contain a pallet/call index");const[a,n]=s,i=Zd[`${a}:${n}`];if(!i)throw new Rd("unrecognized-call",`Unrecognized or unsupported Polymesh call (pallet=${a}, call=${n})`);const o=s.slice(2);let c,d;try{c=i.codec.dec(o)}catch(e){throw new Rd("malformed",`Failed to decode ${i.variant} args: ${e.message}`)}try{d=i.codec.enc(c)}catch(e){throw new Rd("malformed",`Failed to re-encode decoded ${i.variant} args: ${e.message}`)}if(!function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(d,o))throw new Rd("trailing-bytes",`Decoded ${i.variant} args do not round-trip to the original bytes — unrecognized trailing data`);return{variant:i.variant,args:c}}const el=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),tl=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),rl=new Uint32Array(32);function sl(e,t,r,s,a,n){const i=a[n],o=a[n+1];let c=rl[2*e],d=rl[2*e+1],l=rl[2*t],h=rl[2*t+1],u=rl[2*r],p=rl[2*r+1],y=rl[2*s],f=rl[2*s+1],g=nr(c,l,i);var w,m;d=ir(g,d,h,o),c=0|g,({Dh:f,Dl:y}={Dh:f^d,Dl:y^c}),({Dh:f,Dl:y}={Dh:(m=y,m),Dl:(w=f,w)}),({h:p,l:u}=ar(p,u,f,y)),({Bh:h,Bl:l}={Bh:h^p,Bl:l^u}),({Bh:h,Bl:l}={Bh:er(h,l,24),Bl:tr(h,l,24)}),rl[2*e]=c,rl[2*e+1]=d,rl[2*t]=l,rl[2*t+1]=h,rl[2*r]=u,rl[2*r+1]=p,rl[2*s]=y,rl[2*s+1]=f}function al(e,t,r,s,a,n){const i=a[n],o=a[n+1];let c=rl[2*e],d=rl[2*e+1],l=rl[2*t],h=rl[2*t+1],u=rl[2*r],p=rl[2*r+1],y=rl[2*s],f=rl[2*s+1],g=nr(c,l,i);d=ir(g,d,h,o),c=0|g,({Dh:f,Dl:y}={Dh:f^d,Dl:y^c}),({Dh:f,Dl:y}={Dh:er(f,y,16),Dl:tr(f,y,16)}),({h:p,l:u}=ar(p,u,f,y)),({Bh:h,Bl:l}={Bh:h^p,Bl:l^u}),({Bh:h,Bl:l}={Bh:rr(h,l,63),Bl:sr(h,l,63)}),rl[2*e]=c,rl[2*e+1]=d,rl[2*t]=l,rl[2*t+1]=h,rl[2*r]=u,rl[2*r+1]=p,rl[2*s]=y,rl[2*s+1]=f}class nl extends Ze{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Pe(e),Pe(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=Ke(this.buffer)}update(e){Ce(this),Te(e=Je(e));const{blockLen:t,buffer:r,buffer32:s}=this,a=e.length,n=e.byteOffset,i=e.buffer;for(let o=0;o<a;){this.pos===t&&(Be(s),this.compress(s,0,!1),Be(s),this.pos=0);const c=Math.min(t-this.pos,a-o),d=n+o;if(c!==t||d%4||!(o+c<a))r.set(e.subarray(o,o+c),this.pos),this.pos+=c,this.length+=c,o+=c;else{const e=new Uint32Array(i,d,Math.floor((a-o)/4));Be(e);for(let r=0;o+t<a;r+=s.length,o+=t)this.length+=t,this.compress(e,r,!1);Be(e)}}return this}digestInto(e){Ce(this),xe(e,this);const{pos:t,buffer32:r}=this;this.finished=!0,Oe(this.buffer.subarray(t)),Be(r),this.compress(r,0,!0),Be(r);const s=Ke(e);this.get().forEach(((e,t)=>s[t]=Ue(e)))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){const{buffer:t,length:r,finished:s,destroyed:a,outputLen:n,pos:i}=this;return e||(e=new this.constructor({dkLen:n})),e.set(...this.get()),e.buffer.set(t),e.destroyed=a,e.finished=s,e.length=r,e.pos=i,e.outputLen=n,e}clone(){return this._cloneInto()}}class il extends nl{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|tl[0],this.v0h=0|tl[1],this.v1l=0|tl[2],this.v1h=0|tl[3],this.v2l=0|tl[4],this.v2h=0|tl[5],this.v3l=0|tl[6],this.v3h=0|tl[7],this.v4l=0|tl[8],this.v4h=0|tl[9],this.v5l=0|tl[10],this.v5h=0|tl[11],this.v6l=0|tl[12],this.v6h=0|tl[13],this.v7l=0|tl[14],this.v7h=0|tl[15],function(e,t={},r,s,a){if(Pe(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");const{key:n,salt:i,personalization:o}=t;if(void 0!==n&&(n.length<1||n.length>r))throw new Error("key length must be undefined or 1.."+r);if(void 0!==i&&i.length!==s)throw new Error("salt must be undefined or "+s);if(void 0!==o&&o.length!==a)throw new Error("personalization must be undefined or "+a)}(t,e,64,16,16);let{key:r,personalization:s,salt:a}=e,n=0;if(void 0!==r&&(r=Je(r),n=r.length),this.v0l^=this.outputLen|n<<8|65536|1<<24,void 0!==a){a=Je(a);const e=Ke(a);this.v4l^=Ue(e[0]),this.v4h^=Ue(e[1]),this.v5l^=Ue(e[2]),this.v5h^=Ue(e[3])}if(void 0!==s){s=Je(s);const e=Ke(s);this.v6l^=Ue(e[0]),this.v6h^=Ue(e[1]),this.v7l^=Ue(e[2]),this.v7h^=Ue(e[3])}if(void 0!==r){const e=new Uint8Array(this.blockLen);e.set(r),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:r,v1h:s,v2l:a,v2h:n,v3l:i,v3h:o,v4l:c,v4h:d,v5l:l,v5h:h,v6l:u,v6h:p,v7l:y,v7h:f}=this;return[e,t,r,s,a,n,i,o,c,d,l,h,u,p,y,f]}set(e,t,r,s,a,n,i,o,c,d,l,h,u,p,y,f){this.v0l=0|e,this.v0h=0|t,this.v1l=0|r,this.v1h=0|s,this.v2l=0|a,this.v2h=0|n,this.v3l=0|i,this.v3h=0|o,this.v4l=0|c,this.v4h=0|d,this.v5l=0|l,this.v5h=0|h,this.v6l=0|u,this.v6h=0|p,this.v7l=0|y,this.v7h=0|f}compress(e,t,r){this.get().forEach(((e,t)=>rl[t]=e)),rl.set(tl,16);let{h:s,l:a}=Jt(BigInt(this.length));rl[24]=tl[8]^a,rl[25]=tl[9]^s,r&&(rl[28]=~rl[28],rl[29]=~rl[29]);let n=0;const i=el;for(let r=0;r<12;r++)sl(0,4,8,12,e,t+2*i[n++]),al(0,4,8,12,e,t+2*i[n++]),sl(1,5,9,13,e,t+2*i[n++]),al(1,5,9,13,e,t+2*i[n++]),sl(2,6,10,14,e,t+2*i[n++]),al(2,6,10,14,e,t+2*i[n++]),sl(3,7,11,15,e,t+2*i[n++]),al(3,7,11,15,e,t+2*i[n++]),sl(0,5,10,15,e,t+2*i[n++]),al(0,5,10,15,e,t+2*i[n++]),sl(1,6,11,12,e,t+2*i[n++]),al(1,6,11,12,e,t+2*i[n++]),sl(2,7,8,13,e,t+2*i[n++]),al(2,7,8,13,e,t+2*i[n++]),sl(3,4,9,14,e,t+2*i[n++]),al(3,4,9,14,e,t+2*i[n++]);this.v0l^=rl[0]^rl[16],this.v0h^=rl[1]^rl[17],this.v1l^=rl[2]^rl[18],this.v1h^=rl[3]^rl[19],this.v2l^=rl[4]^rl[20],this.v2h^=rl[5]^rl[21],this.v3l^=rl[6]^rl[22],this.v3h^=rl[7]^rl[23],this.v4l^=rl[8]^rl[24],this.v4h^=rl[9]^rl[25],this.v5l^=rl[10]^rl[26],this.v5h^=rl[11]^rl[27],this.v6l^=rl[12]^rl[28],this.v6h^=rl[13]^rl[29],this.v7l^=rl[14]^rl[30],this.v7h^=rl[15]^rl[31],Oe(rl)}destroy(){this.destroyed=!0,Oe(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const ol=et((e=>new il(e))),cl="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const dl=(new TextEncoder).encode("SS58PRE");function ll(e,t){if(32!==e.length)throw new Error("encodeAccountId32: expected a 32-byte public key");if(t<0||t>=64)throw new Error("encodeAccountId32: only single-byte ss58Format prefixes (0-63) are supported");const r=Bd(new Uint8Array([t]),e),s=function(e){return ol(Bd(dl,e),{dkLen:64}).slice(0,2)}(r);return function(e){let t=0;for(;t<e.length&&0===e[t];)t++;const r=[];for(let s=t;s<e.length;s++){let t=e[s];for(let e=0;e<r.length;e++)t+=r[e]<<8,r[e]=t%58,t=Math.floor(t/58);for(;t>0;)r.push(t%58),t=Math.floor(t/58)}let s=cl[0].repeat(t);for(let e=r.length-1;e>=0;e--)s+=cl[r[e]];return s}(Bd(r,s))}const hl=/^\d+$/,ul=/^\d+(?:\.\d+)?$/;function pl(e){return e.replace(/^0x/i,"").replace(/-/g,"").toLowerCase()}function yl(e,t,r="amount"){if("string"!=typeof e||!ul.test(e))throw new Dd("intent-field-malformed",`intent.${r} must be a non-negative decimal string in human-readable units (e.g. "1.5"), got ${JSON.stringify(e)}`);const[s,a=""]=e.split(".");if(a.length>t)throw new Dd("intent-field-malformed",`intent.${r} "${e}" has ${a.length} decimal places, more than this chain's ${t} — refusing to round a verification input`);return BigInt(s+a.padEnd(t,"0"))}function fl(e,t,r){const s=e[t];if(!s)throw new Dd("intent-field-missing",`${r}: intent.${String(t)} is required to verify this call — refusing to report a call as verified with this field unchecked`);return s}function gl(e,t,r){const s=[],{ss58Format:a,balanceDecimals:n}=r;switch(e.variant){case"balances.transferWithMemo":{const{args:r}=e,i=fl(t,"recipientAddress",e.variant),o=ll(r.dest.value,a);s.push({field:"destination",enforced:!0,matched:o===i,expected:t.recipientAddress,actual:o});const c=yl(fl(t,"amount",e.variant),n);s.push({field:"amount",enforced:!0,matched:BigInt(r.value)===c,expected:c.toString(),actual:String(r.value)});const d=fl(t,"assetSymbol",e.variant),l="POLYX";s.push({field:"asset",enforced:!0,matched:d.toUpperCase()===l,expected:d,actual:l});break}case"settlement.addAndAffirmWithMediators":{const{args:r}=e;if(1!==r.legs.length)throw new Dd("unsupported-call-shape",`settlement.addAndAffirmWithMediators carries ${r.legs.length} legs; an Intent describes a single transfer, so this call shape cannot be verified`);const a=r.legs[0].value;s.push({field:"destination",enforced:!1,actual:`did:${Ud(a.receiver.did)}`});const i=yl(fl(t,"amount",e.variant),n);s.push({field:"amount",enforced:!0,matched:BigInt(a.amount)===i,expected:i.toString(),actual:String(a.amount)});const o=fl(t,"assetId",e.variant),c=Ud(a.assetId);s.push({field:"asset",enforced:!0,matched:pl(c)===pl(o),expected:o,actual:c});break}case"settlement.affirmInstruction":case"settlement.rejectInstruction":{const{args:r}=e,a=function(e,t){if("string"!=typeof e||!hl.test(e))throw new Dd("intent-field-malformed",`intent.${t} must be a plain base-10 integer string, got ${JSON.stringify(e)}`);return BigInt(e)}(fl(t,"instructionId",e.variant),"instructionId");s.push({field:"instructionId",enforced:!0,matched:BigInt(r.id)===a,expected:a.toString(),actual:String(r.id)});const n=fl(t,"instructionDecision",e.variant),i="settlement.affirmInstruction"===e.variant?"approve":"deny";s.push({field:"instructionDecision",enforced:!0,matched:i===n,expected:n,actual:i});break}default:throw new Dd("unsupported-call-shape",`No verification rules are defined for Polymesh call variant "${e.variant}"`)}const i=s.filter((e=>e.enforced));if(0===i.length)throw new Dd("no-enforced-fields",`${e.variant} produced no enforced fields — refusing to report a call as verified with nothing checked`);return{chainName:exports.BlockchainName.Polymesh,callVariant:e.variant,fields:s,verified:i.every((e=>!0===e.matched))}}function wl(e,t,r,s){if(!Od(r))throw new Dd("intent-field-malformed",`Unknown Polymesh network ${JSON.stringify(r)} — expected "mainnet" or "testnet"`);const a=Kd[r];return gl(Qd(e,a,s),t,a)}const ml=Object.freeze(Object.defineProperty({__proto__:null,POLYMESH_CONTEXT:Kd,PolymeshDecodeError:Rd,PolymeshVerificationError:Nd,PolymeshVerifyError:Dd,decimalAmountToBaseUnits:yl,decodePolymeshCall:Qd,isPolymeshNetwork:Od,verifyPolymeshCallAgainstIntent:wl,verifyPolymeshIntent:gl},Symbol.toStringTag,{value:"Module"}));exports.WallabyApiClient=e.A,exports.WallabyHttpClient=e.H,exports.AndroidVersionNotSupportedError=F,exports.AuthenticatorGeneralError=se,exports.AuthenticatorMissingDiscoverableCredentialSupportError=ae,exports.AuthenticatorMissingUserVerificationSupportError=ne,exports.AuthenticatorNoSupportedPubKeyCredParamsAlgError=ce,exports.AuthenticatorNotRegisteredError={error:"ERROR_AUTHENTICATOR_NOT_REGISTERED",message:"Authenticator is not registered."},exports.AuthenticatorPreviouslyRegisteredError=ie,exports.AutoRegisterUserVerificationFailureError=de,exports.BadConfiguration=Y,exports.CeremonyAbortedError=Z,exports.IOSVersionNotSupportedError=W,exports.InterruptedError=J,exports.InvalidChallengeError=H,exports.InvalidDomainError=Q,exports.InvalidRpIdError=ee,exports.InvalidStateError=oe,exports.InvalidUserIdError=$,exports.InvalidUserIdLengthError=te,exports.MalformedPubKeyCredParamsError=re,exports.NativeError=(e="An unknown error occurred")=>({error:"Unknown",message:e}),exports.NoCredentialsError=z,exports.NotAllowedError={error:"NotAllowedError",message:"CredentialContainer request is not allowed."},exports.PasskeyErrorCodes=he,exports.PassthroughSeeCausePropertyError=le,exports.RequestFailedError=G,exports.TimeoutError=X,exports.UnknownError=M,exports.UserCancelledError=j,exports.Wallaby=class{constructor(e,t={}){this.wallet=new bd(e,t),this.walletData=new Id(e,t),this.utils=new Pd(e,t),this.auth=new _d(e,t),this.system=new Cd(e,t),this.transactions=new xd(e,t),this.swap=new kd(e,t),this.httpApi=new Td(e,t)}get version(){return _e}},exports.WallabyError=V,exports.createIdentity=Ls,exports.decryptWithPrivateKey=wa,exports.encryptWithPublicKey=ga,exports.hash=Sa,exports.isValidSeedPhrase=Ma,exports.keccak256=ma,exports.normalizeSeedPhrase=Va,exports.publicKeyByPrivateKey=ms,exports.recoverPublicKey=(e,t)=>{const r=qt(e),s=r.substring(0,r.length-2),a="1c"===r.slice(-2)?1:0;let n=Me(va(Ut(s),a,Ut(qt(t)),!1));return n=n.slice(2),n},exports.sign=Us,exports.verification=ml,exports.verifyCallAgainstIntent=function(e,t,r,s,a){if(r.chainName!==e)throw new Error(`verifyCallAgainstIntent: intent is for chain "${r.chainName}" but the call is for "${e}" — refusing to verify across chains`);if(e===exports.BlockchainName.Polymesh)return wl(t,r,s,a);throw new Error(`verifyCallAgainstIntent: no verifier registered for chain "${e}"`)};//# sourceMappingURL=index.cjs.map
|
|
12
|
+
var r;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function js(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Gs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Hs=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Ys(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 zs=(e,t)=>{function r(r,...s){if(Ws(r),!Hs)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?Ws(t):Ws(t,e.nonceLength)}const a=e.tagLength;a&&void 0!==s[1]&&Ws(s[1]);const n=t(r,...s),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Ws(t)}};let i=!1;const c={encrypt(e,t){if(i)throw new Error("cannot encrypt() twice with same key + nonce");return i=!0,Ws(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(Ws(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 Js(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&&!Xs(t))throw new Error("invalid output, must be aligned");return t}function Xs(e){return e.byteOffset%4==0}function Zs(e){return Uint8Array.from(e)}const Qs=16;function ea(e){return e<<1^283&-(e>>7)}function ta(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=ea(e);return r}const ra=(()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=ea(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 Gs(e),t})(),sa=ra.map(((e,t)=>ra.indexOf(t))),aa=e=>e<<8|e>>>24;function na(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(aa),a=s.map(aa),n=a.map(aa),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 oa=na(ra,(e=>ta(e,3)<<24|e<<16|e<<8|ta(e,2))),ia=na(sa,(e=>ta(e,11)<<24|ta(e,13)<<16|ta(e,9)<<8|ta(e,14))),ca=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=ea(r))e[t]=r;return e})();function da(e){Ws(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}=oa,s=[];Xs(e)||s.push(e=Zs(e));const a=js(e),n=a.length,o=e=>ua(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)^ca[e/n-1]:n>6&&e%n==4&&(t=o(t)),i[e]=i[e-n]^t}var c;return Gs(...s),i}function la(e,t,r,s,a,n){return e[r<<8&65280|s>>>8&255]^t[a>>>8&65280|n>>>24&255]}function ua(e,t,r,s,a){return e[255&t|65280&r]|e[s>>>16&255|a>>>16&65280]<<16}function ha(e,t,r,s,a){const{sbox2:n,T01:o,T23:i}=oa;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++]^la(o,i,t,r,s,a),d=e[c++]^la(o,i,r,s,a,t),l=e[c++]^la(o,i,s,a,t,r),u=e[c++]^la(o,i,a,t,r,s);t=n,r=d,s=l,a=u}return{s0:e[c++]^ua(n,t,r,s,a),s1:e[c++]^ua(n,r,s,a,t),s2:e[c++]^ua(n,s,a,t,r),s3:e[c++]^ua(n,a,t,r,s)}}function pa(e,t,r,s,a){const{sbox2:n,T01:o,T23:i}=ia;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++]^la(o,i,t,a,s,r),d=e[c++]^la(o,i,r,t,a,s),l=e[c++]^la(o,i,s,r,t,a),u=e[c++]^la(o,i,a,s,r,t);t=n,r=d,s=l,a=u}return{s0:e[c++]^ua(n,t,a,s,r),s1:e[c++]^ua(n,r,t,a,s),s2:e[c++]^ua(n,s,r,t,a),s3:e[c++]^ua(n,a,s,r,t)}}function fa(e,t,r,s){Ws(t,Qs),Ws(r);const a=r.length;Ys(r,s=Js(a,s));const n=t,o=js(n);let{s0:i,s1:c,s2:d,s3:l}=ha(e,o[0],o[1],o[2],o[3]);const u=js(r),h=js(s);for(let t=0;t+4<=u.length;t+=4){h[t+0]=u[t+0]^i,h[t+1]=u[t+1]^c,h[t+2]=u[t+2]^d,h[t+3]=u[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}=ha(e,o[0],o[1],o[2],o[3]))}const p=Qs*Math.floor(u.length/4);if(p<a){const e=new Uint32Array([i,c,d,l]),t=(f=e,new Uint8Array(f.buffer,f.byteOffset,f.byteLength));for(let e=p,n=0;e<a;e++,n++)s[e]=r[e]^t[n];Gs(e)}var f;return s}const ya=zs({blockSize:16,nonceLength:16},(function(e,t){function r(r,s){if(Ws(r),void 0!==s&&(Ws(s),!Xs(s)))throw new Error("unaligned destination");const a=da(e),n=Zs(t),o=[a,n];Xs(r)||o.push(r=Zs(r));const i=fa(a,n,r,s);return Gs(...o),i}return{encrypt:(e,t)=>r(e,t),decrypt:(e,t)=>r(e,t)}}));const ga=zs({blockSize:16,nonceLength:16},(function(e,t,r={}){const s=!r.disablePadding;return{encrypt(r,a){const n=da(e),{b:o,o:i,out:c}=function(e,t,r){Ws(e);let s=e.length;const a=s%Qs;if(!t&&0!==a)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Xs(e)||(e=Zs(e));const n=js(e);if(t){let e=Qs-a;e||(e=Qs),s+=e}return Ys(e,r=Js(s,r)),{b:n,o:js(r),out:r}}(r,s,a);let d=t;const l=[n];Xs(d)||l.push(d=Zs(d));const u=js(d);let h=u[0],p=u[1],f=u[2],y=u[3],g=0;for(;g+4<=o.length;)h^=o[g+0],p^=o[g+1],f^=o[g+2],y^=o[g+3],({s0:h,s1:p,s2:f,s3:y}=ha(n,h,p,f,y)),i[g++]=h,i[g++]=p,i[g++]=f,i[g++]=y;if(s){const e=function(e){const t=new Uint8Array(16),r=js(t);t.set(e);const s=Qs-e.length;for(let e=Qs-s;e<Qs;e++)t[e]=s;return r}(r.subarray(4*g));h^=e[0],p^=e[1],f^=e[2],y^=e[3],({s0:h,s1:p,s2:f,s3:y}=ha(n,h,p,f,y)),i[g++]=h,i[g++]=p,i[g++]=f,i[g++]=y}return Gs(...l),c},decrypt(r,a){!function(e){if(Ws(e),e.length%Qs!=0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size 16")}(r);const n=function(e){const t=da(e),r=t.slice(),s=t.length,{sbox2:a}=oa,{T0:n,T1:o,T2:i,T3:c}=ia;for(let e=0;e<s;e+=4)for(let a=0;a<4;a++)r[e+a]=t[s-e-4+a];Gs(t);for(let e=4;e<s-4;e++){const t=r[e],s=ua(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];Xs(o)||i.push(o=Zs(o));const c=js(o);a=Js(r.length,a),Xs(r)||i.push(r=Zs(r)),Ys(r,a);const d=js(r),l=js(a);let u=c[0],h=c[1],p=c[2],f=c[3];for(let e=0;e+4<=d.length;){const t=u,r=h,s=p,a=f;u=d[e+0],h=d[e+1],p=d[e+2],f=d[e+3];const{s0:o,s1:i,s2:c,s3:y}=pa(n,u,h,p,f);l[e++]=o^t,l[e++]=i^r,l[e++]=c^s,l[e++]=y^a}return Gs(...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 wa(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 ga(e,t,{disablePadding:!s});if(["aes-128-ctr","aes-256-ctr"].includes(r))return ya(e,t);throw new Error("AES: unsupported mode")}const ma=(e,t,r)=>{const s=(null==r?void 0:r.ephemPrivateKey)?Bt(r.ephemPrivateKey):rt(32),a=rt(16),n=As.getPublicKey(s),o=As.ProjectivePoint.fromHex(n).toRawBytes(!1),i=As.getSharedSecret(s,Bt(e),!0).slice(1),c=$s(i),d=c.subarray(0,32),l=c.subarray(32),u=function(e,t,r,s="aes-128-ctr",a=!0){return wa(t,r,s,a).encrypt(e)}($t(t),d,a,"aes-256-cbc"),h=Ft([a,o,u]),p=Fs(l,h);return{iv:Ve(a),ephemPublicKey:Ve(o),ciphertext:Ve(u),mac:Ve(p)}},va=(e,t)=>{let r;try{r=As.getSharedSecret(Bt(e),t.ephemPublicKey,!0).slice(1)}catch(e){throw new Error(`Invalid MAC: data integrity check failed: ${e}`)}const s=$s(r),a=s.subarray(0,32),n=s.subarray(32),o=Bt(t.ciphertext),i=Bt(t.iv),c=Bt(t.ephemPublicKey),d=Bt(t.mac),l=Ft([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}(Fs(n,l),d))throw new Error("Invalid MAC: data integrity check failed");const u=function(e,t,r,s="aes-128-ctr",a=!0){return wa(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)}(u)};const Sa=(e,t,r)=>{const s=Vt(e);return ma("04"+s,t,r)},Aa=(e,t)=>{const r=qt(e);return va(r,t)},ba=e=>(e=>{const t=$t(e),r=Mt(Ve(t)),s=qs(Bt(r));return Mt(Ve(s))})(e);function Ea(e,t,r,s=!0,a){Lt(r,32),it("compressed",s);const n=function(e){return Lt(e,64),As.Signature.fromCompact(e)}(e);return function(e=e=>new Uint8Array(e),t,r){return"function"==typeof e&&(e=e(t)),Lt(e,t),r&&e.set(r),e}(a,s?33:65,n.addRecoveryBit(t).recoverPublicKey(r).toRawBytes(s))}As.ProjectivePoint,As.CURVE.n;const _a={keccak256:ba};function ka(e){if(!Ia(e))throw new Error("Invalid JSON string");return JSON.parse(e)}function Ia(e){if("string"!=typeof e)return!1;try{return JSON.parse(e),!0}catch(e){return!1}}function Ta(e,t,r,s){Pe(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(Ie(n),Ie(o),Ie(i),n<1)throw new Error("iterations (c) should be >= 1");const c=Xe(t),d=Xe(r),l=new Uint8Array(o),u=Cr.create(e,c),h=u._cloneInto().update(d);return{c:n,dkLen:o,asyncTick:i,DK:l,PRF:u,PRFSalt:h}}function Pa(e,t,r,s){const{c:a,dkLen:n,DK:o,PRF:i,PRFSalt:c}=Ta(e,t,r,s);let d;const l=new Uint8Array(4),u=Ne(l),h=new Uint8Array(i.outputLen);for(let e=1,t=0;t<n;e++,t+=i.outputLen){const r=o.subarray(t,t+i.outputLen);u.setInt32(0,e,!1),(d=c._cloneInto(d)).update(l).digestInto(h),r.set(h.subarray(0,r.length));for(let e=1;e<a;e++){i._cloneInto(d).update(h).digestInto(h);for(let e=0;e<r.length;e++)r[e]^=h[e]}}return function(e,t,r,s,a){return e.destroy(),t.destroy(),s&&s.destroy(),Oe(a),r}(i,c,o,d,h)}const Ca="wsdkmk:v1:";function xa(e){if(ze(e).length<16)throw new Error("Salt is too short: must be at least 16 bytes");if(new Set(e).size<=6)throw new Error("Weak salt: too few unique characters")}function Ka({password:e,salt:t}){xa(t);const r=function(e,t,r,s,a){if(!["sha256","sha512"].includes(a))throw new Error("Only sha256 and sha512 are supported");return Lt(e),Lt(t),Pa(_r,e,t,{c:r,dkLen:s})}(ze(e.normalize("NFKC").trim()),ze(t),131072,32,"sha256");return Ms(r)}function Oa(e,t){return Ca+function(e,t){return a.AES.encrypt(e,t).toString()}("string"==typeof e?e:JSON.stringify(e),t)}function Na(e,t){const r=function(e,t){return a.AES.decrypt(e,t).toString(a.enc.Utf8)}(e.startsWith(Ca)?e.slice(10):e,t);if(r)return Ia(r)?ka(r):r}function Ra(e,t){return JSON.stringify({material:e,destinationPubKey:t})}class Da{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(!As.utils.isValidPrivateKey(e.slice(2)))throw new Error("Invalid private key: outside secp256k1 scalar range")}(e)}getMasterKey(){return{buffer:ze(me),key:me}}encryptWithMasterKey({data:e}){return Oa(e,this.getMasterKey().key)}isWrappedByMasterKey(e){return function(e){return e.startsWith(Ca)||e.startsWith("U2FsdGVkX1")}(e)}decryptWithMasterKey({cipherText:e}){try{const t=Na(e,this.getMasterKey().key);if(void 0!==t)return t}catch(e){return void pe.error("Decryption failed with master key",e)}pe.error("Decryption failed with master key")}validatePublicKey(e){!function(e){if(!/^[0-9a-fA-F]{128}$/.test(e))throw new Error("Invalid public key: must be a 64-byte raw uncompressed hex string");if(new Set(e).size<=8)throw new Error("Weak public key: too few unique characters")}(e)}validateSalt(e){xa(e)}sign({message:e,signingKey:t}){try{this.validatePrivateKey(t);const r=ba(e);return{message:e,signature:Vs(t,r),hashedMessage:r}}catch(e){throw pe.error("SDK::Cipher::sign",e),new Error(`Error signing message: ${e}`)}}async encrypt({data:e,encryptionKey:t}){try{return this.validatePublicKey(t),await Sa(t,e)}catch(e){throw pe.error("Error encrypting data: ",e),new Error("Something happened during data encryption.")}}async decrypt({cipherText:e,decryptionKey:t}){try{this.validatePrivateKey(t);return await Aa(t,(r=e,"string"==typeof r?JSON.parse(r):r))}catch(e){throw pe.error("SDK::CipherService::decrypt::error: ",e),new Error("That doesn’t seem right. Check your login details and try again.")}var r}async getCredentialsKeyPair(e){try{let t;switch(e.authType){case exports.AuthType.Password:if(!e.password||!e.salt)throw new Error("Password and salt are required");return t=await this.deriveKeyPairFromPassword({password:e.password,salt:e.salt}),t;case exports.AuthType.Passkey:if(!e.prfValue)throw new Error("PRF value is required");return t=await this.deriveKeyPairFromPasskey({inputKeyMaterial:e.prfValue}),t;default:throw new Error(`Unknown AuthType: ${e.authType}`)}}catch(e){return pe.error("SDK::CipherService::getCredentialsKeyPair::error",e),Promise.reject(e)}}async prepareDataForTransport({data:e,wallabyPublicKey:t,destinationPubKey:r}){try{const s=r?Ra(e,r):e;return Sa(t,s)}catch(e){throw pe.error("SDK::CipherService::prepareDataForTransport::error",e),new Error("Error preparing data for transport")}}async prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:t,wallabyPublicKey:r,options:s,destinationPubKey:a}){const n=await this.displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:t,options:s});return this.prepareDataForTransport({data:n,wallabyPublicKey:r,destinationPubKey:a})}async doubleEncrypt({decryptedData:e,credentialsKeyPair:t,deviceKeyPair:r}){try{const s=await this.encrypt({data:e,encryptionKey:r.publicKey});return await this.encrypt({data:JSON.stringify(s),encryptionKey:t.publicKey})}catch(e){throw pe.error("SDK::doubleEncrypt::error",e),e}}async prepareTransportDataForStorage({transportData:e,credentialsKeyPair:t,deviceKeyPair:r}){try{const s=await this.decrypt({cipherText:e,decryptionKey:r.privateKey}),a=await this.encrypt({data:s,encryptionKey:r.publicKey});return await this.encrypt({data:JSON.stringify(a),encryptionKey:t.publicKey})}catch(e){throw pe.error("SDK::prepareTransportDataForStorage::error",e),e}}async displayDataFromServer({encryptedData:e,encryptedDevicePrivateKey:t,options:r}){try{const s=await this.getCredentialsKeyPair(r),a=await this.decrypt({cipherText:t,decryptionKey:s.privateKey});if(!a)throw new Error("That doesn’t seem right. Check your login details and try again.");return await this.decrypt({cipherText:e,decryptionKey:a})}catch(e){throw pe.error("SDK::CipherService::displayDataFromServer::error",e),e}}async displayStoredData({storedEncryptedData:e,encryptedDevicePrivateKey:t,options:r}){const s=await this.getCredentialsKeyPair(r),a=await this.decrypt({cipherText:t,decryptionKey:s.privateKey});if(!a)throw new Error("Credentials are not correct, please provide the correct credentials");const n=await this.decrypt({cipherText:e,decryptionKey:s.privateKey});if(!n)throw new Error("That doesn’t seem right. Check your login details and try again.");const 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 pe.error("SDK::CipherService::displayDataFromServer::error",e),e}}async deriveKeyPairFromPasskey({inputKeyMaterial:e}){return function({inputKeyMaterial:e}){return Ms(e)}({inputKeyMaterial:e})}async deriveKeyPairFromPassword({password:e,salt:t}){return Ka({password:e,salt:t})}}class La{constructor(){this.activeLocks=new Set}async withLock(e,t){const r="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator?navigator.locks:void 0;if(r)return r.request(e,{ifAvailable:!0},(async r=>{if(!r)throw new Error(`Operation '${e}' is already in progress. Please wait for it to complete.`);return t()}));if(this.activeLocks.has(e))throw new Error(`Operation '${e}' is already in progress. Please wait for it to complete.`);this.activeLocks.add(e);try{return await t()}finally{this.activeLocks.delete(e)}}isLocked(e){return this.activeLocks.has(e)}clearAllLocks(){this.activeLocks.clear()}}const Ba=new La;class Ua{constructor({deviceStorage:e,userId:t,environment:r}){this._walletSpecificKeys=[exports.V2KeyNames.EncryptedStandardSeedPhrase,exports.V2KeyNames.PrimaryDeviceKeyShare,exports.V2KeyNames.BackupDeviceKeyShare],this._keysProtectedByMasterKey=[exports.V2KeyNames.AccessToken,exports.V2KeyNames.RefreshToken,exports.V2KeyNames.PasskeyCredential,exports.V2KeyNames.ClientAuthToken],this.userId=t,this.environment=null!=r?r:ge,this.shortenedEnv=this.environment.slice(0,1),this.deviceLocalStorage=e,this.cipher=new Da}async getFromDeviceStorage(e){return this.deviceLocalStorage.getItem?this.deviceLocalStorage.getItem(e):this.deviceLocalStorage.getItemAsync?await this.deviceLocalStorage.getItemAsync(e):null}async setInDeviceStorage(e,t){return this.deviceLocalStorage.setItem?this.deviceLocalStorage.setItem(e,t):this.deviceLocalStorage.setItemAsync?await this.deviceLocalStorage.setItemAsync(e,t):void 0}async fetch(e,t){var r;let s;if(await(null!==(r=this._walRecovery)&&void 0!==r?r:this._walRecovery=this.recoverCommit().catch((e=>{pe.error("SDK::StorageService::fetch::wal recovery failed",e)}))),this._walletSpecificKeys.includes(e)){if(!(null==t?void 0:t.walletId))throw new Error(`A walletId is required to fetch: ${e}`);s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t.walletId}`}else s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;Se.isNative&&(s=_e(s));const a=await this.getItem(s);if(a){if(this._keysProtectedByMasterKey.includes(e)){if(!this.cipher.isWrappedByMasterKey(a))return a;const e=this.cipher.decryptWithMasterKey({cipherText:a});return e||void pe.error(`Failed to decrypt item with key ${s}`)}return a}pe.debug(`(404): Item with key ${s} was not found in storage.`)}async save(e,t,r){let s,a;if(this._walletSpecificKeys.includes(e)){if(!(null==r?void 0:r.walletId))throw new Error(`A walletId is required to save: ${e}`);s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${r.walletId}`}else s=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;if(Se.isNative&&(s=_e(s)),this._keysProtectedByMasterKey.includes(e)){a=this.cipher.encryptWithMasterKey({data:t})}else a="string"==typeof t?t:JSON.stringify(t);return await this.setItem(s,a)}async saveInBulk(e){await Promise.all(e.map((e=>this.save(e.key,e.value,{walletId:e.walletId}))))}_computeRawKey(e,t){let r;if(this._walletSpecificKeys.includes(e)){if(!t)throw new Error(`A walletId is required to compute key: ${e}`);r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t}`}else r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;return ve?r:_e(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=ka(t)}catch(t){return pe.error("SDK::StorageService::recoverCommit::corrupt WAL, discarding",t),void await this.removeItem(e)}await this._applyWAL(r),await this.removeItem(e)}async delete(e,t){let r;if(this._walletSpecificKeys.includes(e)){if(!(null==t?void 0:t.walletId))throw new Error(`A walletId is required to delete: ${e}`);r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}:${t.walletId}`}else r=`wsdk:v2:${this.shortenedEnv}:${e}:${this.userId}`;return Se.isNative&&(r=_e(r)),await this.removeItem(r)}setItem(e,t){if(this.deviceLocalStorage.setItem)return this.deviceLocalStorage.setItem(e,t);if(this.deviceLocalStorage.setItemAsync)return this.deviceLocalStorage.setItemAsync(e,t);throw new Error("setItem function is is not defined")}getItem(e){if(this.deviceLocalStorage.getItem)return this.deviceLocalStorage.getItem(e);if(this.deviceLocalStorage.getItemAsync)return this.deviceLocalStorage.getItemAsync(e);throw new Error("getItem function is not defined")}removeItem(e){if(this.deviceLocalStorage.removeItem)return this.deviceLocalStorage.removeItem(e);if(this.deviceLocalStorage.deleteItemAsync)return this.deviceLocalStorage.deleteItemAsync(e);throw new Error("removeItem function is not defined")}async checkPrivateKeyExists(){return!!await this.getEncryptedPrivateKey()}async checkPrimaryKeyShareExists(e){return!!await this.fetch(exports.V2KeyNames.PrimaryDeviceKeyShare,{walletId:e})}async checkBackupKeyShareExists(e){return!!await this.fetch(exports.V2KeyNames.BackupDeviceKeyShare,{walletId:e})}async checkSeedPhraseExists(e){return!!await this.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard,e)}getSeedPhraseV2KeyName(e){if(e===exports.SeedPhraseType.Standard)return exports.V2KeyNames.EncryptedStandardSeedPhrase;throw new Error(`Unsupported seed phrase type: ${e}`)}async setEncryptedPrivateKey(e,t){const r=a.AES.encrypt(e,t).toString();await this.setItem(`${this.environment}-client-auth-private-key-${this.userId}`,r)}async getV1EncryptedPrivateKey(){const e=`encryptedPrivateKey_${this.userId}`,t=`${this.environment}-client-auth-private-key-${this.userId}`,r=await this.getItem(t),s=await this.getItem(e);return r||s}async getEncryptedPrivateKey(){const e=await this.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey);if(e)return e;const t=`encryptedPrivateKey_${this.userId}`,r=await this.getItem(t);if(r)return r;{const e=`${this.environment}-client-auth-private-key-${this.userId}`,t=await this.getItem(e);if(t)return t}pe.error("SDK::StorageService::getEncryptedPrivateKey: private key not found")}async getDecryptedV1PrivateKey(e){try{const t=await this.getV1EncryptedPrivateKey();if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return r||void 0}catch(e){return void pe.error("SDK::StorageService::getDecryptedV1PrivateKey::error",e)}}async getDecryptedPrivateKey(e){try{const t=await this.getEncryptedPrivateKey();if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return r||void 0}catch(e){return void pe.error("SDK::StorageService::getDecryptedPrivateKey::error",e)}}async setEncryptedSeedPhrase({decryptedSeedPhrase:e,seedPhraseType:t,password:r,deviceAuthPublicKey:s,getUserSalt:n,salt:o,walletId:i}){const c=await Sa(s,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}`,u=await a.AES.encrypt(JSON.stringify(c),l),h=this.getSeedPhraseV2KeyName(t);return await this.save(h,u.toString(),{walletId:i}),!0}async getEncryptedSeedPhrase(e,t){const r=this.getSeedPhraseV2KeyName(e),s=await this.fetch(r,{walletId:t});if(s)return s;if(!await this.isLegacySeedFallbackSafeFor(t))return;let a;if(e===exports.SeedPhraseType.Standard&&(a=`encryptedSeed_${this.userId}`),a){const e=await this.getItem(a);if(e){return await this.claimLegacySeedFallbackFor(t)?e:void 0}}if(!s){const r=`${this.environment}-encrypted-${e}-seedPhrase-${this.userId}`,s=await this.getItem(r);if(s){return await this.claimLegacySeedFallbackFor(t)?s:void 0}}}async isLegacySeedFallbackSafeFor(e){const t=await this.fetch(exports.V2KeyNames.LegacySeedClaimedWalletId);return!t||t===e}async claimLegacySeedFallbackFor(e){const t=`legacy-seed-claim:${this.environment}:${this.userId}`;try{return await Ba.withLock(t,(async()=>{const t=await this.fetch(exports.V2KeyNames.LegacySeedClaimedWalletId);return t?t===e:(await this.save(exports.V2KeyNames.LegacySeedClaimedWalletId,e),!0)}))}catch(e){return pe.error("SDK::StorageService::claimLegacySeedFallbackFor::lock contention, treating as lost race",e),!1}}async getV1EncryptedSeedPhrase(){const e=`${this.environment}-encrypted-${exports.SeedPhraseType.Standard}-seedPhrase-${this.userId}`,t=await this.getItem(e);if(t)return t}async getV1DecryptedSeedPhrase(e,t){const r=await this.getV1EncryptedSeedPhrase(),s=await this.getDecryptedV1PrivateKey(e);if(!r||!s)return;const n=`${t}${e}`,o=ka(a.AES.decrypt(r,n).toString(a.enc.Utf8));return await Aa(s,o)}async getDecryptedSeedPhrase({password:e,seedPhraseType:t,getUserSalt:r,salt:s,walletId:n}){const o=await this.getEncryptedSeedPhrase(t,n),i=await this.getDecryptedPrivateKey(e);if(!o||!i)return;const c=`${null!=s?s:await r()}${e}`,d=ka(a.AES.decrypt(o,c).toString(a.enc.Utf8));return await Aa(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)))),await this.delete(exports.V2KeyNames.LegacySeedClaimedWalletId)}async loadDeviceInformation(e){return{authTokens:{accessToken:await this.fetch(exports.LocalStorageItems.AccessToken),clientAuthToken:await this.fetch(exports.LocalStorageItems.ClientAuthToken)},user:{clientUserId:this.userId,encryptedStandardSeedPhrase:await this.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase,{walletId:e}),wallabyUserId:void 0},credentials:{deviceAuthPrivateKey:void 0,deviceAuthPublicKey:void 0,deviceEncryptedPrivateKey:await this.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey),wallabyPublicKey:await this.fetch(exports.V2KeyNames.WallabyAuthPubKey)},hostname:"undefined"==typeof window?"republic.com":window.location.hostname}}}function qa(e,t=Date.now){return!e||Va(e,t)<=0}function Ma(e,t,r=Date.now){return!!e&&Va(e,r)<=1e3*t}function Va(e,t=Date.now){const r=n.jwtDecode(e).exp;return 1e3*(null!=r?r:0)-t()}const Fa={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},attestation:{fullPath:"/auth/attestation",method:exports.RequestMethod.Get,requiresAccessToken:!1},attestationPublicKey:{fullPath:"/auth/attestation/pub",method:exports.RequestMethod.Get,requiresAccessToken:!1}};function $a(e){return/^[a-zA-Z0-9-_]+$/.test(e)}function Wa(e){return"string"!=typeof e?"":e.normalize("NFKD").trim().toLowerCase().replace(/\s+/g," ")}function ja(e){return t.validateMnemonic(Wa(e))}function Ga(e){const{apiKey:t,baseUrl:r,userId:s,clientAuthToken:a,options:o}=e;if("string"!=typeof t||!$a(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||!$a(s))throw new Error("Invalid or empty user ID provided.");if("string"!=typeof a||!function(e){if("string"!=typeof e)return!1;if(3!==e.split(".").length)return!1;try{return n.jwtDecode(e),!0}catch(e){return!1}}(a))throw new Error("Invalid or empty client auth token provided.");if(o&&"object"!=typeof o)throw new Error("Invalid options provided.");return Object.freeze({apiKey:t.trim(),baseUrl:r.trim(),userId:s.trim(),clientAuthToken:a.trim(),options:o?Object.freeze(Object.assign({},o)):void 0})}const Ha={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Ya(e){return Ha}function za(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 Ja(e,t,r,s,a){const n=a&&"input"in a?a.input:r.value,o=a?.expected??e.expects??null,i=a?.received??za(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 Xa=new WeakMap;function Za(e){let t=Xa.get(e);return t||(t={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},Ya())},Xa.set(e,t)),t}function Qa(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&"__proto__"!==t&&"prototype"!==t&&"constructor"!==t}function en(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function tn(e,t,r){return"function"==typeof e.fallback?e.fallback(t,r):e.fallback}function rn(e,t,r){return"function"==typeof e.default?e.default(t,r):e.default}function sn(){return{kind:"schema",type:"any",reference:sn,expects:"any",async:!1,get"~standard"(){return Za(this)},"~run":e=>(e.typed=!0,e)}}function an(e,t){return{kind:"schema",type:"array",reference:an,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return Za(this)},"~run"(e,t){const r=e.value;if(Array.isArray(r)){e.typed=!0,e.value=[];for(let s=0;s<r.length;s++){const a=r[s],n=this.item["~run"]({value:a},t);if(n.issues){const 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 Ja(this,"type",e,t);return e}}}function nn(e){return{kind:"schema",type:"boolean",reference:nn,expects:"boolean",async:!1,message:e,get"~standard"(){return Za(this)},"~run"(e,t){return"boolean"==typeof e.value?e.typed=!0:Ja(this,"type",e,t),e}}}function on(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=on(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=on(e[s],t[s]);if(a.issue)return a;r[s]=a.value}return{value:r}}}return{issue:!0}}function cn(e,t){return{kind:"schema",type:"intersect",reference:cn,expects:en(e.map((e=>e.expects)),"&"),async:!1,options:e,message:t,get"~standard"(){return Za(this)},"~run"(e,t){if(this.options.length){const r=e.value;let s;e.typed=!0;for(const a of this.options){const n=a["~run"]({value:r},t);if(n.issues){if(e.issues)for(const t of n.issues)e.issues.push(t);else e.issues=n.issues;if(t.abortEarly){e.typed=!1;break}}n.typed||(e.typed=!1),e.typed&&(s?s.push(n.value):s=[n.value])}if(e.typed){e.value=s[0];for(let r=1;r<s.length;r++){const a=on(e.value,s[r]);if(a.issue){Ja(this,"type",e,t,{received:"unknown"});break}e.value=a.value}}}else Ja(this,"type",e,t);return e}}}function dn(e){return{kind:"schema",type:"lazy",reference:dn,expects:"unknown",async:!1,getter:e,get"~standard"(){return Za(this)},"~run"(e,t){return this.getter(e.value)["~run"](e,t)}}}function ln(e,t){return{kind:"schema",type:"nullable",reference:ln,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return Za(this)},"~run"(e,t){return null===e.value&&(void 0!==this.default&&(e.value=rn(this,e,t)),null===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function un(e){return{kind:"schema",type:"number",reference:un,expects:"number",async:!1,message:e,get"~standard"(){return Za(this)},"~run"(e,t){return"number"!=typeof e.value||isNaN(e.value)?Ja(this,"type",e,t):e.typed=!0,e}}}function hn(e,t){return{kind:"schema",type:"object",reference:hn,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return Za(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in this.entries){const a=this.entries[s];if(s in r||("exact_optional"===a.type||"optional"===a.type||"nullish"===a.type)&&void 0!==a.default){const n=s in r?r[s]:rn(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]=tn(a);else if("exact_optional"!==a.type&&"optional"!==a.type&&"nullish"!==a.type&&(Ja(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 Ja(this,"type",e,t);return e}}}function pn(e,t){return{kind:"schema",type:"optional",reference:pn,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return Za(this)},"~run"(e,t){return void 0===e.value&&(void 0!==this.default&&(e.value=rn(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function fn(e,t){return{kind:"schema",type:"picklist",reference:fn,expects:en(e.map(za),"|"),async:!1,options:e,message:t,get"~standard"(){return Za(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:Ja(this,"type",e,t),e}}}function yn(e,t,r){return{kind:"schema",type:"record",reference:yn,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return Za(this)},"~run"(e,t){const r=e.value;if(r&&"object"==typeof r){e.typed=!0,e.value={};for(const s in r)if(Qa(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 Ja(this,"type",e,t);return e}}}function gn(e){return{kind:"schema",type:"string",reference:gn,expects:"string",async:!1,message:e,get"~standard"(){return Za(this)},"~run"(e,t){return"string"==typeof e.value?e.typed=!0:Ja(this,"type",e,t),e}}}function wn(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 mn(e,t){return{kind:"schema",type:"union",reference:mn,expects:en(e.map((e=>e.expects)),"|"),async:!1,options:e,message:t,get"~standard"(){return Za(this)},"~run"(e,t){let r,s,a;for(const n of this.options){const 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];Ja(this,"type",e,t,{issues:wn(s)}),e.typed=!0}else{if(1===a?.length)return a[0];Ja(this,"type",e,t,{issues:wn(a)})}return e}}}const vn=hn({message:gn(),environment:gn()}),Sn=hn({clientAuthPubKey:gn(),passkeyChallengeType:pn(fn(["webauthn.create","webauthn.get"])),walletId:pn(gn())}),An=hn({message:gn(),wallabyAuthPubKey:pn(gn()),foundDevicePublicKey:nn(),challenge:pn(gn()),registrationOptions:pn(yn(gn(),sn())),authenticationOptions:pn(yn(gn(),sn()))}),bn=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),externalUserId:gn(),firstName:pn(gn()),lastName:pn(gn()),merchantId:pn(gn()),passkeyRegistrationResponse:pn(yn(gn(),sn()))}),En=hn({id:gn(),firstName:pn(gn()),externalUserId:gn(),role:pn(fn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),clientSalt:pn(gn()),clientAuthPubKey:pn(gn())}),_n=hn({accessToken:gn(),refreshToken:pn(gn()),user:dn((()=>En))}),kn=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),externalUserId:pn(gn()),firstName:pn(gn()),lastName:pn(gn()),merchantId:pn(gn()),passkeyRegistrationResponse:pn(yn(gn(),sn()))}),In=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),passkeyRegistrationResponse:pn(yn(gn(),sn())),passkeyAuthenticationResponse:pn(yn(gn(),sn()))}),Tn=hn({id:gn(),externalUserId:gn(),clientSalt:gn()}),Pn=hn({accessToken:gn(),refreshToken:gn(),user:dn((()=>Tn))}),Cn=hn({refreshToken:gn()}),xn=hn({accessToken:gn(),refreshToken:gn()}),Kn=hn({message:gn()}),On=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),newClientAuthPubKey:gn()}),Nn=hn({user:dn((()=>En))}),Rn=hn({clientAuthPubKey:gn()}),Dn=hn({wallabyAuthPubKey:gn()}),Ln=hn({id:gn(),externalUserId:gn(),merchantId:gn(),role:ln(fn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),firstName:pn(ln(gn())),walletsCount:un(),latestWallabyAuthPubKey:pn(gn()),latestWallabyAuthPubKeyVersion:pn(gn()),portalInvitationStatus:pn(ln(fn(["pending","accepted","rejected"]))),createdAt:gn(),updatedAt:gn(),hasFullPermissions:pn(nn())}),Bn=hn({id:gn(),userId:gn(),publicKey:gn(),status:fn(["active","invalidated"]),createdAt:gn(),updatedAt:gn()}),Un=hn({id:gn(),authenticatorGlobalId:gn(),credentialID:gn(),publicKey:gn(),authPublicKeyId:gn(),counter:un(),transports:gn(),credentialDeviceType:gn(),credentialBackedUp:nn(),user:cn([dn((()=>Ln))]),authPublicKeys:pn(an(dn((()=>Bn)))),userId:gn(),externalUserId:gn(),createdAt:gn(),updatedAt:gn(),authenticatorName:pn(gn())}),qn=hn({credentials:an(dn((()=>Un)))}),Mn=hn({attestationDoc:gn(),pub:gn(),mocked:nn()}),Vn=hn({pub:gn()}),Fn=hn({totalRecords:un(),currentPage:un(),totalPages:un(),nextPage:ln(un()),previousPage:ln(un()),pageSize:un()}),$n=hn({address:gn(),publicKey:pn(gn()),type:pn(fn(["SEGWIT","LEGACY","DEFAULT"]))}),Wn=hn({id:gn(),name:gn(),nameSlugify:gn(),verified:nn(),status:fn(["active","inactive","invalidated"])}),jn=hn({id:gn(),userId:gn(),merchantId:gn(),chainId:gn(),userAssetAddress:gn(),walletId:gn(),configId:gn(),assetName:gn(),assetSymbol:gn(),balance:ln(gn()),balanceUpdatedAt:ln(gn()),claimableBalance:pn(ln(gn())),claimableBalanceUpdatedAt:pn(ln(gn())),claimablePaymentTokenContractAddress:pn(ln(gn())),claimablePaymentTokenAssetConfigId:pn(ln(gn())),lockedTokenBalance:ln(gn()),lockedTokenBalanceUpdatedAt:ln(gn()),mainnetBalance:ln(gn()),mainnetBalanceUpdatedAt:ln(gn()),testnetBalance:ln(gn()),testnetBalanceUpdatedAt:ln(gn()),mainnetLockedBalance:ln(gn()),mainnetLockedBalanceUpdatedAt:ln(gn()),testnetLockedBalance:ln(gn()),testnetLockedBalanceUpdatedAt:ln(gn()),defaultAddress:gn(),isVisible:nn(),source:fn(["merchant","user","republic"]),addresses:an(dn((()=>$n))),ownershipType:gn(),priceConversion:pn(gn()),changePercentageLast24h:pn(gn()),createdAt:gn(),updatedAt:gn(),merchant:cn([dn((()=>Wn))])}),Gn=hn({id:gn(),name:gn(),nameSlugify:gn()}),Hn=hn({address:gn(),topics:an(gn()),data:gn(),transactionIndex:un()}),Yn=hn({event:gn(),args:yn(gn(),mn([gn(),un(),nn()]))}),zn=hn({message:ln(gn()),txLogs:ln(an(dn((()=>Hn)))),txLogsDecoded:ln(an(dn((()=>Yn)))),reqSignature:gn(),reason:ln(gn()),requestId:ln(gn()),signatureUsed:nn()}),Jn=hn({id:gn(),reference:ln(gn()),hash:pn(ln(gn())),merchantId:gn(),userEmail:gn(),chainId:gn(),chainName:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:un(),fromWalletId:gn(),fromAddress:gn(),toWalletId:gn(),toAddress:gn(),assetId:gn(),assetSymbol:gn(),tokenType:fn(["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:gn(),fee:gn(),note:gn(),nonce:un(),gasPrice:un(),submitter:gn(),status:fn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:ln(fn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:fn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:gn(),networkEnvironment:ln(fn(["mainnet","testnet"])),statusCheckAttempts:un(),statusCheckedAt:ln(gn()),createdAt:gn(),updatedAt:gn(),asset:cn([dn((()=>oo))]),merchant:cn([dn((()=>io))]),adminTransactions:an(dn((()=>zn))),user:pn(dn((()=>Ln))),chain:dn((()=>go)),splitCoins:gn(),transferObjects:gn()}),Xn=hn({id:un(),contractTypeName:gn(),assetContracts:an(dn((()=>Zn)))}),Zn=hn({configId:gn(),contractTypeId:un(),contractAddress:gn(),assetConfig:cn([dn((()=>oo))]),contractType:cn([dn((()=>Xn))])}),Qn=hn({id:gn(),merchantId:gn(),configId:gn(),chainId:gn(),chainName:gn(),assetName:gn(),assetSymbol:gn(),isVisible:nn(),isDefault:nn(),createdAt:gn(),updatedAt:gn(),merchant:cn([dn((()=>io))]),config:cn([dn((()=>oo))]),chain:cn([dn((()=>go))])}),eo=hn({id:gn(),typeName:gn(),createdAt:gn(),updatedAt:gn()}),to=hn({id:gn(),objectId:gn(),packageId:gn(),moduleName:gn(),structName:gn(),coinType:gn(),createdAt:cn([dn((()=>eo))]),updatedAt:gn()}),ro=hn({id:gn(),chainId:gn(),swapProviderId:gn(),providerChainIdentifier:gn(),chain:cn([dn((()=>go))]),swapProvider:cn([dn((()=>so))]),providerAssets:an(dn((()=>ao))),createdAt:gn(),updatedAt:gn()}),so=hn({id:gn(),name:gn(),explorerBaseUrl:gn(),isActive:nn(),chainMappings:an(dn((()=>ro))),providerAssets:an(dn((()=>ao))),createdAt:gn(),updatedAt:gn()}),ao=hn({id:gn(),assetConfigId:gn(),swapProviderId:gn(),chainProviderMappingId:gn(),providerAssetIdentifier:gn(),lastSynced:pn(gn()),isEnabled:nn(),assetConfig:cn([dn((()=>oo))]),swapProvider:cn([dn((()=>so))]),chainProviderMapping:cn([dn((()=>ro))]),createdAt:gn(),updatedAt:gn()}),no=hn({id:gn(),config:dn((()=>oo)),configId:gn(),timestamp:gn(),createdAt:gn()}),oo=hn({id:gn(),chainId:gn(),merchantId:pn(ln(gn())),chainName:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),name:gn(),symbol:gn(),verified:pn(nn()),isOffChain:pn(nn()),decimals:un(),iconUrl:pn(ln(gn())),ticker:pn(ln(gn())),type:pn(fn(["COIN","TOKEN","OBJECT"])),tokenStandard:pn(ln(fn(["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:pn(ln(un())),contractAddress:pn(ln(gn())),description:pn(ln(gn())),ownershipType:pn(fn(["SINGLE_OWNER","MULTI_SIG"])),ownerAddresses:pn(ln(an(gn()))),status:pn(fn(["active","inactive","archived"])),createdByUserId:pn(ln(gn())),createdByMerchantId:pn(ln(gn())),relayerAddress:pn(ln(gn())),contractVersion:pn(ln(gn())),chain:pn(dn((()=>go))),createdByMerchant:pn(ln(cn([dn((()=>Gn))]))),usersAssets:pn(an(dn((()=>jn)))),transactions:pn(an(dn((()=>Jn)))),assetContracts:pn(an(dn((()=>Zn)))),merchantAssets:pn(an(dn((()=>Qn)))),createdByUser:pn(ln(dn((()=>Ln)))),suiConfig:pn(dn((()=>to))),isAssetReady:nn(),extendedConfiguration:pn(ln(yn(gn(),sn()))),requiresKyc:nn(),swapProviderAssets:pn(an(dn((()=>ao)))),tokenDistributions:pn(an(dn((()=>no))))}),io=hn({id:gn(),name:gn(),nameSlugify:gn(),verified:nn(),contactEmail:gn(),contactPhoneNumber:gn(),usersCount:un(),assetsCount:un(),tokensCount:un(),coinsCount:un(),walletsCount:un(),status:fn(["active","inactive","invalidated"]),createdAt:gn(),updatedAt:gn(),createdAssets:an(dn((()=>oo))),merchantAssets:pn(an(dn((()=>Qn))))}),co=hn({id:un(),name:fn(["wallaby_share","owner_main_device_share","owner_backup_device_share"]),keyShares:an(dn((()=>lo)))}),lo=hn({id:gn(),user:dn((()=>Ln)),wallet:dn((()=>po)),encryptedKey:gn(),type:dn((()=>co)),createdAt:gn(),updatedAt:gn(),migratedWallabyShareAt:pn(ln(gn())),wrappingPublicKey:pn(gn()),migrationStatus:fn(["not_required","pending","migrated","failed"]),migrationErrorMessage:pn(ln(gn()))}),uo=hn({id:un(),roles:an(fn(["single_sig","shares_single_owner","pooled_custodial","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"])),wallets:an(dn((()=>po)))}),ho=hn({id:gn(),walletId:gn(),userId:gn(),shareCount:un(),createdAt:gn(),updatedAt:gn()}),po=hn({id:gn(),userId:gn(),merchantId:gn(),revisionId:gn(),revisionName:gn(),hashedSeedPhraseSalt:gn(),hashedEthAddressSalt:gn(),recoveryCount:un(),assetsCount:un(),createdAt:gn(),updatedAt:gn(),lastVerifiedAt:ln(gn()),userAssets:pn(an(dn((()=>jn)))),merchant:pn(dn((()=>io))),keyShares:pn(an(dn((()=>lo)))),type:dn((()=>uo)),creationType:pn(ln(fn(["user_imported","user_created"]))),keyMigrationStatus:fn(["not_required","pending","migrated","failed"]),migrationErrorMessage:pn(ln(gn())),walletAddresses:pn(an(dn((()=>yo)))),walletKeks:pn(an(dn((()=>ho))))}),fo=hn({id:un(),name:fn(["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:dn((()=>yo))}),yo=hn({id:gn(),walletId:gn(),wallet:dn((()=>po)),chain:dn((()=>go)),typeId:un(),type:dn((()=>fo)),address:gn(),publicKey:gn(),createdAt:gn(),updatedAt:gn()}),go=hn({id:gn(),name:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),isEvm:nn(),iconUrl:pn(ln(gn())),mainnetId:pn(gn()),mainnetIndexUrl:pn(ln(gn())),mainnetExplorerUrl:pn(gn()),testnetId:pn(gn()),testnetExplorerUrl:pn(ln(gn())),testnetIndexUrl:pn(ln(gn())),derivationPath:pn(ln(gn())),addressRegex:pn(ln(gn())),slip44:fn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767]),signatureScheme:pn(fn(["secp256k1","ed25519","sr25519"])),status:pn(fn(["UP","DOWN"])),search:pn(gn()),createdAt:gn(),updatedAt:gn(),walletAddresses:pn(an(dn((()=>yo)))),isChainReady:nn(),supportsSwaps:nn(),swapChainMappings:pn(an(dn((()=>ro)))),indexUrl:pn(ln(gn())),chainId:pn(gn())}),wo=hn({pagination:cn([dn((()=>Fn))]),chains:an(dn((()=>go)))}),mo=hn({name:gn(),isEvm:nn(),mainnetRpcUrl:gn(),mainnetIndexUrl:pn(gn()),testnetId:pn(gn()),testnetRpcUrl:gn(),testnetIndexUrl:gn(),derivationPath:gn(),addressRegex:gn(),slip44:un(),signatureScheme:fn(["secp256k1","ed25519","sr25519"])}),vo=hn({chain:dn((()=>go))}),So=hn({name:pn(fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),isEvm:pn(nn()),mainnetId:pn(gn()),mainnetRpcUrl:pn(gn()),mainnetIndexUrl:pn(gn()),testnetId:pn(gn()),testnetRpcUrl:pn(gn()),testnetIndexUrl:pn(gn()),derivationPath:pn(gn()),addressRegex:pn(gn()),slip44:pn(fn([0,60,283,9e3,966,519,8453,784,2525,19000118,637,501,595,3030,6767])),signatureScheme:pn(fn(["secp256k1","ed25519","sr25519"])),supportSwaps:pn(nn())}),Ao=hn({chain:dn((()=>go))}),bo=hn({pagination:cn([dn((()=>Fn))]),assets:an(dn((()=>oo)))}),Eo=hn({asset:dn((()=>oo))}),_o=hn({chainId:gn(),name:gn(),symbol:gn(),verified:pn(nn()),isOffChain:pn(nn()),decimals:un(),iconUrl:pn(gn()),ticker:gn(),type:fn(["COIN","TOKEN","OBJECT"]),tokenStandard:pn(fn(["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:pn(un()),contractAddress:pn(gn()),description:pn(gn()),createdByUserId:pn(gn()),createdByMerchantId:pn(gn()),suiObjectId:pn(gn()),relayerAddress:pn(gn()),isAssetReady:pn(nn()),requiresKyc:pn(nn())}),ko=hn({asset:dn((()=>oo))}),Io=hn({name:pn(gn()),symbol:pn(gn()),isOffChain:pn(nn()),decimals:pn(un()),iconUrl:pn(gn()),ticker:pn(gn()),type:pn(fn(["COIN","TOKEN","OBJECT"])),tokenStandard:pn(fn(["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:pn(un()),contractAddress:pn(gn()),relayerAddress:pn(gn()),description:pn(gn()),suiObjectId:pn(gn())}),To=hn({asset:dn((()=>oo))}),Po=hn({message:gn()}),Co=hn({pagination:cn([dn((()=>Fn))]),merchants:an(dn((()=>io)))}),xo=hn({name:gn(),contactEmail:gn(),contactPhoneNumber:pn(gn()),status:pn(fn(["active","inactive","invalidated"]))}),Ko=hn({name:pn(gn()),contactEmail:pn(gn()),contactPhoneNumber:pn(gn()),status:pn(fn(["active","inactive","invalidated"]))}),Oo=hn({merchant:dn((()=>io))}),No=hn({merchant:dn((()=>io))}),Ro=hn({pagination:cn([dn((()=>Fn))]),merchant:dn((()=>io)),assets:pn(an(dn((()=>Qn)))),merchantAssets:an(dn((()=>Qn)))}),Do=hn({id:gn(),name:pn(gn())}),Lo=hn({id:gn(),externalUserId:gn(),walletsCount:un(),createdAt:gn(),updatedAt:gn(),merchantId:pn(gn()),firstName:pn(ln(gn())),email:pn(gn()),role:pn(ln(fn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]))),polymeshDID:pn(ln(gn())),userMerchants:pn(an(dn((()=>Do))))}),Bo=hn({pagination:cn([dn((()=>Fn))]),merchant:dn((()=>io)),users:an(dn((()=>Lo)))}),Uo=hn({merchantId:gn(),email:gn(),firstName:gn(),lastName:gn(),role:gn()}),qo=hn({message:pn(gn()),user:dn((()=>Lo))}),Mo=hn({message:pn(gn()),user:dn((()=>Lo))}),Vo=hn({pagination:cn([dn((()=>Fn))]),merchant:dn((()=>io)),wallets:an(dn((()=>po)))}),Fo=hn({assetConfigId:gn(),userId:gn(),walletId:gn()}),$o=hn({merchantId:gn(),assets:an(dn((()=>Fo))),updateExistingWallets:pn(nn())}),Wo=hn({message:pn(gn())}),jo=hn({merchantId:gn(),assetConfigId:pn(gn()),isDefault:pn(nn()),addToExistingWallets:pn(nn()),addToWallets:pn(an(gn())),config:pn(dn((()=>oo)))}),Go=hn({message:pn(gn()),merchantAsset:dn((()=>Qn))}),Ho=hn({merchantId:gn(),assetConfigId:gn()}),Yo=hn({message:pn(gn())}),zo=hn({merchantId:gn(),assetConfigId:gn(),isVisible:nn()}),Jo=hn({message:pn(gn()),merchantAsset:dn((()=>Qn))}),Xo=hn({merchantId:gn(),assetConfigId:gn(),isDefault:nn()}),Zo=hn({message:pn(gn()),merchantAsset:dn((()=>Qn))}),Qo=hn({iv:gn(),ephemPublicKey:gn(),ciphertext:gn(),mac:gn()}),ei=hn({id:gn(),merchantId:pn(gn()),appName:gn(),ipAddresses:an(gn()),domainNames:an(gn()),status:fn(["active","inactive"]),clientJWTPubKey:gn(),usersCount:un(),requestsCount:un(),totalRequestSizeInKb:un(),totalResponseSizeInKb:un(),totalResponseTimeInKb:un(),lastRequestAt:ln(gn()),onlyDashboardAccess:nn(),allowMobileAccess:nn(),createdAt:gn(),updatedAt:gn(),merchant:pn(dn((()=>io))),origins:pn(an(dn((()=>ti))))}),ti=hn({id:gn(),merchantId:pn(gn()),apiKeyId:gn(),origin:gn(),createdAt:gn(),updatedAt:gn(),merchant:pn(dn((()=>io))),apiKey:pn(dn((()=>ei)))}),ri=hn({id:gn(),merchantId:gn(),appName:gn(),apiKey:dn((()=>Qo)),status:fn(["active","inactive"]),clientJWTPubKey:gn(),allowMobileAccess:nn(),createdAt:gn(),updatedAt:gn(),origins:pn(an(dn((()=>ti))))}),si=hn({pagination:cn([dn((()=>Fn))]),apiKeys:an(dn((()=>ri)))}),ai=hn({pagination:cn([dn((()=>Fn))]),apiKeyOrigins:an(dn((()=>ti)))}),ni=hn({clientJWTPubKey:pn(gn()),wrappingPublicKey:pn(gn()),allowMobileAccess:pn(nn()),appName:pn(gn())}),oi=hn({message:pn(gn()),apiKey:dn((()=>ri)),clientJWTPrivKey:pn(cn([dn((()=>Qo))]))}),ii=hn({merchantId:gn(),apiKeyId:gn(),origins:an(gn())}),ci=hn({message:pn(gn()),apiKeyOrigins:an(dn((()=>ti)))}),di=hn({clientJWTPubKey:pn(gn()),wrappingPublicKey:gn(),appName:pn(gn()),status:pn(fn(["active","inactive"])),allowMobileAccess:pn(nn())}),li=hn({message:pn(gn()),apiKey:dn((()=>ri))}),ui=hn({pagination:cn([dn((()=>Fn))]),wallets:an(dn((()=>po)))}),hi=hn({message:gn(),clientAuthPubKey:gn(),signature:gn()}),pi=hn({id:gn(),userId:gn(),merchantId:gn(),chainId:gn(),userAssetAddress:gn(),walletId:gn(),configId:gn(),assetName:gn(),assetSymbol:gn(),balance:ln(gn()),balanceUpdatedAt:ln(gn()),claimableBalance:pn(ln(gn())),claimableBalanceUpdatedAt:pn(ln(gn())),claimablePaymentTokenContractAddress:pn(ln(gn())),claimablePaymentTokenAssetConfigId:pn(ln(gn())),lockedTokenBalance:ln(gn()),lockedTokenBalanceUpdatedAt:ln(gn()),mainnetBalance:ln(gn()),mainnetBalanceUpdatedAt:ln(gn()),testnetBalance:ln(gn()),testnetBalanceUpdatedAt:ln(gn()),mainnetLockedBalance:ln(gn()),mainnetLockedBalanceUpdatedAt:ln(gn()),testnetLockedBalance:ln(gn()),testnetLockedBalanceUpdatedAt:ln(gn()),defaultAddress:gn(),isVisible:nn(),source:fn(["merchant","user","republic"]),addresses:an(dn((()=>$n))),ownershipType:gn(),priceConversion:pn(gn()),changePercentageLast24h:pn(gn()),createdAt:gn(),updatedAt:gn(),merchant:cn([dn((()=>Wn))]),config:dn((()=>oo))}),fi=hn({id:gn(),userId:gn(),revisionName:gn()}),yi=hn({iv:gn(),ephemPublicKey:gn(),ciphertext:gn(),mac:gn()}),gi=hn({encrypted:cn([dn((()=>yi))]),wrappingPublicKey:gn(),type:fn(["wallaby_share","owner_main_device_share","owner_backup_device_share"])}),wi=hn({v:un(),iv:gn(),ciphertext:gn(),tag:gn()}),mi=hn({address:gn(),type:fn(["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:gn(),chainName:gn()}),vi=hn({wallabyAuthPubKey:pn(gn()),assets:an(dn((()=>pi))),encryptedSeed:pn(mn([dn((()=>yi)),dn((()=>wi))])),wallet:cn([dn((()=>fi))]),shares:pn(an(dn((()=>gi)))),encryptedBackupShare:pn(cn([dn((()=>wi))])),reference:pn(gn()),encryptedSeedForSharesSplit:pn(dn((()=>yi))),walletAddressesInfo:an(dn((()=>mi)))}),Si=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),encryptedShares:pn(an(dn((()=>yi)))),encryptedSeed:pn(cn([dn((()=>yi))])),walletId:gn()}),Ai=hn({isAccessVerified:nn()}),bi=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),adminWalletTypes:an(fn(["super_admin","merchant_admin","merchant_user","wallet_user","contract_admin","reserve_admin","wallets_admin","transfer_admin","soft_burn_admin","mint_admin","automation_admin"]))}),Ei=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),returnWalletOption:fn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:gn(),numShares:pn(un()),threshold:pn(un()),wallabyKeepsOne:pn(nn()),backupDevicePublicKey:pn(gn()),walletOwnershipType:pn(fn(["SINGLE_OWNER"]))}),_i=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),encryptedSeed:cn([dn((()=>yi))]),walletId:pn(gn()),returnWalletOption:fn(["RETURN_ONLY_ENCRYPTED_SEED_PHRASE","RETURN_ONLY_ENCRYPTED_SHARES","RETURN_BOTH_ENCRYPTED_SHARES_AND_SEED"]),reference:gn(),numShares:pn(un()),threshold:pn(un()),wallabyKeepsOne:pn(nn()),backupDevicePublicKey:pn(gn()),walletOwnershipType:pn(fn(["SINGLE_OWNER"]))}),ki=hn({clientAuthPubKey:gn(),walletId:gn(),encryptedBackupShare:mn([dn((()=>wi)),dn((()=>Qo))])}),Ii=hn({reference:gn(),share:cn([dn((()=>gi))])}),Ti=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),encryptedSeed:cn([dn((()=>yi))]),walletId:pn(gn())}),Pi=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),walletId:gn(),encryptedSeed:pn(cn([dn((()=>yi))])),encryptedShares:pn(an(dn((()=>yi)))),chainName:pn(fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]))}),Ci=hn({id:gn(),walletId:gn(),typeId:un(),type:dn((()=>fo)),address:gn(),publicKey:gn()}),xi=hn({walletAddressesInfo:an(dn((()=>mi))),walletAddresses:an(dn((()=>Ci)))}),Ki=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),walletId:gn(),encryptedShares:an(dn((()=>yi))),chain:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),accountIndexes:an(un()),startingAddressIndex:pn(un())}),Oi=hn({accountIndex:un(),addresses:yn(gn(),gn())}),Ni=hn({walletId:gn(),chain:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),accounts:an(dn((()=>Oi)))}),Ri=hn({pagination:cn([dn((()=>Fn))]),assets:an(dn((()=>pi))),groupedAssets:pn(yn(gn(),an(dn((()=>pi))))),walletAddressesInfo:an(dn((()=>mi)))}),Di=hn({pagination:cn([dn((()=>Fn))]),addresses:an(dn((()=>mi)))}),Li=hn({assetSymbol:gn(),blockchainName:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])}),Bi=hn({configId:gn(),assetName:pn(gn()),assetSymbol:pn(gn()),isVisible:pn(nn()),walletId:gn()}),Ui=hn({userAsset:cn([dn((()=>pi))]),message:gn()}),qi=hn({fromAssetConfigId:gn(),toAssetConfigId:gn(),fromAmount:pn(gn()),toAmount:pn(gn()),slippage:pn(un())}),Mi=hn({amount:gn(),amountUSD:pn(ln(gn())),symbol:pn(gn()),icon:pn(gn())}),Vi=hn({id:gn(),gasFee:pn(an(dn((()=>Mi)))),providerFee:pn(an(dn((()=>Mi)))),republicFee:pn(an(dn((()=>Mi)))),allowanceFee:pn(an(dn((()=>Mi)))),fromAssetConfigId:gn(),fromAssetSymbol:gn(),fromAssetChain:gn(),toAssetConfigId:gn(),toAssetSymbol:gn(),toAssetChain:gn(),fromAmount:gn(),fromAddress:gn(),toAmount:gn(),toAddress:gn(),slippage:un(),expiresAt:pn(gn())}),Fi=hn({id:gn(),fromAssetSymbol:gn(),fromAssetChainName:gn(),toAssetSymbol:gn(),toAssetChainName:gn(),fromAddress:gn(),toAddress:gn(),fromAmount:gn(),toAmount:gn(),slippage:un(),gasFee:pn(ln(an(dn((()=>Mi))))),providerFee:pn(ln(an(dn((()=>Mi))))),republicFee:pn(ln(an(dn((()=>Mi))))),allowanceFee:pn(ln(an(dn((()=>Mi))))),status:fn(["quote","executing","in_progress","completed","failed","abandoned","execution_failed","invalid"]),executedAt:ln(gn()),completedAt:ln(gn()),transactionId:ln(gn()),transactionHash:ln(gn()),explorerLink:ln(gn())}),$i=hn({pagination:cn([dn((()=>Fn))]),swaps:an(dn((()=>Fi)))}),Wi=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),walletId:gn(),quoteId:gn(),encryptedSeed:pn(cn([dn((()=>yi))])),encryptedShares:pn(an(dn((()=>yi))))}),ji=hn({swapQuoteId:gn(),status:gn(),explorerLink:gn(),transactionHash:gn()}),Gi=hn({id:gn(),reference:ln(gn()),hash:pn(ln(gn())),merchantId:gn(),userEmail:gn(),chainId:gn(),chainName:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),chainSlip44:un(),fromWalletId:gn(),fromAddress:gn(),toWalletId:gn(),toAddress:gn(),assetId:gn(),assetSymbol:gn(),tokenType:fn(["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:gn(),fee:gn(),note:gn(),nonce:un(),gasPrice:un(),submitter:gn(),status:fn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionFailedReason:ln(fn(["INSUFFICIENT_FUNDS","GAS_PRICE_TOO_LOW","NONCE_TOO_LOW","REPLACEMENT_UNDERPRICED","UNKNOWN"])),ownershipType:fn(["SINGLE_OWNER","MULTI_SIG"]),txBlob:gn(),networkEnvironment:ln(fn(["mainnet","testnet"])),statusCheckAttempts:un(),statusCheckedAt:ln(gn()),createdAt:gn(),updatedAt:gn(),asset:cn([dn((()=>oo))]),merchant:cn([dn((()=>io))]),adminTransactions:an(dn((()=>zn))),user:pn(dn((()=>Ln))),chain:dn((()=>go)),splitCoins:gn(),transferObjects:gn(),type:pn(fn(["INCOMING","OUTGOING","SWAP","UNKNOWN"])),entryType:pn(fn(["INCOMING","OUTGOING","SWAP","UNKNOWN"]))}),Hi=hn({pagination:cn([dn((()=>Fn))]),transactions:an(dn((()=>Gi)))}),Yi=hn({id:gn(),amount:gn(),sender:gn(),asset:pn(cn([dn((()=>oo))])),expires:pn(gn())}),zi=hn({transactions:an(dn((()=>Yi)))}),Ji=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),id:gn(),choice:fn(["approve","deny"]),symbol:gn(),chainName:gn(),walletId:gn(),encryptedSeed:pn(cn([dn((()=>yi))])),encryptedShares:pn(an(dn((()=>yi))))}),Xi=hn({id:gn(),status:fn(["confirmed","denied"]),hash:pn(gn()),asset:pn(cn([dn((()=>oo))]))}),Zi=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),walletId:gn(),originAddress:gn(),recipientAddress:gn(),assetId:gn(),amount:gn(),reference:gn(),encryptedSeed:cn([dn((()=>yi))]),memo:pn(gn()),transactionType:pn(fn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"]))}),Qi=hn({transaction:cn([dn((()=>Jn))]),message:pn(gn())}),ec=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),walletId:gn(),originAddress:gn(),recipientAddress:gn(),assetId:gn(),amount:gn(),reference:gn(),memo:pn(gn()),transactionType:pn(fn(["TRANSFER_TX","OPTIN_TX","ALLOWANCE_TX","SWAP_ALLOWANCE_TX","SWAP_TX","CLAIM_DIVIDEND_TX"])),encryptedShares:an(dn((()=>yi)))}),tc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),walletId:gn(),originAddress:gn(),reference:gn(),note:pn(gn()),encryptedSeed:cn([dn((()=>yi))]),assetIndex:un()}),rc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),walletId:gn(),originAddress:gn(),reference:gn(),note:pn(gn()),encryptedSeed:cn([dn((()=>yi))]),appIndex:un()}),sc=hn({feePaymentSymbol:gn(),fee:gn(),lowestFee:pn(gn()),highestFee:pn(gn())}),ac=hn({address:an(gn()),amount:gn(),txId:gn()}),nc=hn({status:fn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),transactionHash:gn(),reference:gn(),assetSymbol:gn(),transactionValue:gn(),fromAddress:gn(),toAddress:gn(),chain:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),fee:gn(),nonce:pn(un()),timestamp:pn(un()),blockNumber:pn(un()),memo:pn(gn()),origins:pn(an(dn((()=>ac)))),recipients:pn(an(dn((()=>ac))))}),oc=hn({canTransfer:nn(),restrictionCode:gn(),tokenContractAddress:gn(),fromAddress:gn(),toAddress:gn(),value:gn(),assetId:gn()}),ic=hn({restrictionCode:un(),restrictionCodeMessage:gn()}),cc=hn({canTransfer:nn(),message:gn(),restrictionCode:gn()}),dc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),walletId:gn(),ownerAddress:gn(),spenderAddress:gn(),amount:gn(),reference:gn(),memo:pn(gn()),encryptedSeed:pn(cn([dn((()=>yi))])),encryptedShares:pn(an(dn((()=>yi)))),chainName:pn(gn()),assetSymbol:pn(gn()),assetId:pn(gn()),contractAddress:pn(gn())}),lc=hn({transaction:cn([dn((()=>Jn))])}),uc=hn({paymentTokenContractAddress:gn(),assetConfigId:gn(),balance:gn()}),hc=hn({address:gn(),assetSymbol:gn(),tokenStandard:pn(fn(["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:pn(fn(["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:pn(fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:pn(gn()),balance:ln(gn()),claimable:pn(cn([dn((()=>uc))])),lockedTokenBalance:pn(ln(gn())),unlockedTokenBalance:pn(gn()),stakedBalance:pn(gn()),claimableBalance:pn(gn()),assetConfigId:pn(gn()),balanceUpdatedAt:pn(ln(gn()))}),pc=hn({address:gn(),assetSymbol:gn(),tokenStandard:pn(fn(["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:pn(fn(["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:pn(fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),walletId:pn(gn())}),fc=hn({assets:an(dn((()=>pc)))}),yc=hn({balances:an(dn((()=>hc)))}),gc=hn({walletId:gn()}),wc=hn({assetSymbol:pn(gn()),timestamp:un(),from:gn(),gas:un(),gasPrice:pn(gn()),gasUsed:pn(un()),hash:gn(),input:pn(gn()),nonce:pn(un()),to:gn(),value:gn(),amount:pn(gn()),memo:pn(gn()),tokenTransfers:pn(an(yn(gn(),sn()))),transactionType:pn(gn()),status:fn(["PENDING-APPROVAL","PENDING","FAILED","SUCCESSFUL","ABANDONED"]),origins:pn(an(dn((()=>ac)))),recipients:pn(an(dn((()=>ac)))),createdAt:gn()}),mc=hn({address:gn(),transactions:an(dn((()=>wc)))}),vc=hn({decimals:un(),symbol:gn(),name:gn(),tokenContractAddress:pn(gn())}),Sc=hn({symbol:gn(),price:gn(),changePercentageLast24h:pn(gn())}),Ac=hn({data:an(dn((()=>Sc)))}),bc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),encryptedShares:an(dn((()=>yi))),walletId:gn()}),Ec=hn({encryptedSeed:cn([dn((()=>yi))])}),_c=hn({pagination:cn([dn((()=>Fn))]),users:an(dn((()=>Lo)))}),kc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),email:pn(gn()),firstName:pn(gn()),lastName:pn(gn())}),Ic=hn({message:gn(),user:pn(cn([dn((()=>Ln))]))}),Tc=hn({user:cn([dn((()=>Lo))])}),Pc=hn({clientSalt:gn()}),Cc=hn({wallets:an(dn((()=>po)))}),xc=hn({pagination:cn([dn((()=>Fn))]),assets:an(dn((()=>jn))),groupedAssets:pn(yn(gn(),an(dn((()=>jn)))))}),Kc=hn({name:gn(),symbol:gn(),decimals:un(),contractAddress:gn(),chainId:pn(gn()),chainName:pn(fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"])),tokenStandard:pn(fn(["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:pn(gn()),iconUrl:pn(gn())}),Oc=hn({assetConfigId:pn(gn()),walletId:gn(),userId:pn(gn()),config:pn(cn([dn((()=>Kc))])),message:pn(gn()),clientAuthPubKey:pn(gn()),signature:pn(gn()),encryptedSeed:pn(cn([dn((()=>yi))])),encryptedShares:pn(an(dn((()=>yi))))}),Nc=hn({asset:cn([dn((()=>jn))])}),Rc=hn({message:gn()}),Dc=hn({user:cn([dn((()=>Lo))])}),Lc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),assetSymbol:gn(),blockchainName:gn(),releaseCount:un(),delayUntilFirstReleaseInSeconds:un(),initialReleasePortionInBips:un(),periodBetweenReleasesInSeconds:un(),walletId:gn(),encryptedSeed:cn([dn((()=>wi))])}),Bc=hn({reference:gn()}),Uc=hn({address:gn(),amount:gn(),commencementTimestamp:pn(un()),scheduleId:pn(un()),cancelableBy:pn(an(gn()))}),qc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),assetSymbol:gn(),blockchainName:gn(),mints:an(dn((()=>Uc))),walletId:gn(),encryptedSeed:cn([dn((()=>wi))])}),Mc=hn({references:an(dn((()=>Bc)))}),Vc=hn({address:gn(),amount:gn(),commencementTimestamp:pn(un()),scheduleId:pn(un()),timelockIndex:pn(un()),reclaimTokenTo:pn(gn())}),Fc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),assetSymbol:gn(),blockchainName:gn(),burns:an(dn((()=>Vc))),walletId:gn(),encryptedSeed:cn([dn((()=>wi))])}),$c=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),assetSymbol:gn(),blockchainName:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:gn(),payerAddress:gn(),tokenRecipientAddress:gn(),originatorPurchaseAmount:gn(),mintAmount:gn(),adminFeeAmount:gn(),totalAmount:gn(),walletId:gn(),encryptedSeed:cn([dn((()=>wi))])}),Wc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),assetSymbol:gn(),blockchainName:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),purchaseId:gn(),payerAddress:gn(),tokenRecipientAddress:gn(),originatorPurchaseAmount:gn(),mintAmount:gn(),prefundedInterestAmount:gn(),adminFeeExcludingPrefundedInterestAmount:gn(),totalAmount:gn(),walletId:gn(),encryptedSeed:cn([dn((()=>wi))])}),jc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),assetSymbol:gn(),blockchainName:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),owner:gn(),regions:an(gn()),accreditationType:un(),lastAmlKycChangeTimestamp:un(),lastAccreditationChangeTimestamp:un(),amlKycPassed:nn(),walletId:gn(),encryptedSeed:cn([dn((()=>wi))])}),Gc=hn({message:gn(),clientAuthPubKey:gn(),signature:gn(),assetSymbol:gn(),blockchainName:fn(["BITCOIN","ETHEREUM","ALGORAND","AVALANCHE","POLYGON","BASE","BSC","SUI","INJECTIVE","SEI","APTOS","SOLANA","POLYMESH","HEDERA","CANTON"]),wallet:gn(),amount:gn(),walletId:gn(),encryptedSeed:cn([dn((()=>wi))])}),Hc=hn({assetSymbol:gn(),blockchainName:gn(),releaseCount:un(),delayUntilFirstReleaseInSeconds:un(),initialReleasePortionInBips:un(),periodBetweenReleasesInSeconds:un(),scheduleId:un()}),Yc=hn({adminTransaction:cn([dn((()=>zn))])}),zc=hn({status:fn(["QUEUED","PENDING","SUCCESS","FAILED"]),message:pn(gn()),txHash:pn(gn()),txLogs:pn(an(dn((()=>Hn)))),txLogsDecoded:pn(an(dn((()=>Yn)))),reqSignature:pn(gn()),clientRequestSignature:pn(gn()),requestId:pn(gn()),reason:pn(gn()),txId:pn(gn())}),Jc=hn({message:gn()}),Xc=hn({chainsCount:un(),chains:an(dn((()=>go))),merchantsCount:un(),merchants:an(dn((()=>io))),assetsCount:un(),usersCount:un(),users:an(dn((()=>Lo))),adminsCount:un(),walletsCount:un()}),Zc=hn({id:gn(),userId:gn(),merchantId:gn(),action:pn(ln(fn(["logged_in","logged_out","created_wallet","updated_wallet","deleted_wallet","created_merchant","updated_merchant","deleted_merchant"]))),requestUrl:gn(),requestMethod:gn(),createdAt:gn(),updatedAt:gn(),merchant:pn(dn((()=>io)))}),Qc=hn({pagination:cn([dn((()=>Fn))]),activities:an(dn((()=>Zc)))}),ed=[{method:"GET",path:"/",response:dn((()=>vn))},{method:"GET",path:"/healthz",response:dn((()=>vn))},{method:"POST",path:"/auth/signature-message/external",request:dn((()=>Sn)),response:dn((()=>An))},{method:"POST",path:"/auth/signature-message",request:dn((()=>Sn)),response:dn((()=>An))},{method:"POST",path:"/auth/sign-up",request:dn((()=>bn)),response:dn((()=>_n))},{method:"POST",path:"/auth/sign-up/external",request:dn((()=>kn)),response:dn((()=>_n))},{method:"POST",path:"/auth/sign-in",request:dn((()=>In)),response:dn((()=>_n))},{method:"POST",path:"/auth/issue-jwt-token",response:dn((()=>Pn))},{method:"POST",path:"/auth/refresh-access-token",request:dn((()=>Cn)),response:dn((()=>xn))},{method:"POST",path:"/auth/logout",response:dn((()=>Kn))},{method:"PUT",path:"/auth/client-auth-pubkey",request:dn((()=>On)),response:dn((()=>Nn))},{method:"POST",path:"/auth/wallaby-auth-pubkey",request:dn((()=>Rn)),response:dn((()=>Dn))},{method:"GET",path:"/auth/passkey-credentials",response:dn((()=>qn))},{method:"GET",path:"/auth/attestation",response:dn((()=>Mn))},{method:"GET",path:"/auth/attestation/pub",response:dn((()=>Vn))},{method:"GET",path:"/chains",response:dn((()=>wo))},{method:"POST",path:"/chains",request:dn((()=>mo)),response:dn((()=>vo))},{method:"PUT",path:"/chains/{chainId}",request:dn((()=>So)),response:dn((()=>Ao))},{method:"GET",path:"/assets/configurations",response:dn((()=>bo))},{method:"POST",path:"/assets/configurations",request:dn((()=>_o)),response:dn((()=>ko))},{method:"GET",path:"/assets/configurations/{assetConfigId}",response:dn((()=>Eo))},{method:"PUT",path:"/assets/configurations/{assetConfigId}",request:dn((()=>Io)),response:dn((()=>To))},{method:"POST",path:"/assets/configurations/{assetConfigId}/verify",response:dn((()=>Po))},{method:"DELETE",path:"/assets/configurations/{assetConfigId}/unverify",response:dn((()=>Po))},{method:"POST",path:"/assets/configurations/{assetConfigId}/archive",response:dn((()=>Po))},{method:"POST",path:"/assets/configurations/{assetConfigId}/unarchive",response:dn((()=>Po))},{method:"GET",path:"/merchants",response:dn((()=>Co))},{method:"POST",path:"/merchants",request:dn((()=>xo)),response:dn((()=>xo))},{method:"PUT",path:"/merchants/{merchantId}",request:dn((()=>Ko)),response:dn((()=>Oo))},{method:"GET",path:"/merchants/{merchantId}",response:dn((()=>No))},{method:"GET",path:"/merchants/{merchantId}/assets",response:dn((()=>Ro))},{method:"GET",path:"/merchants/{merchantId}/users",response:dn((()=>Bo))},{method:"GET",path:"/merchants/{merchantId}/admins",response:dn((()=>Bo))},{method:"POST",path:"/merchants/admins/invite",request:dn((()=>Uo)),response:dn((()=>qo))},{method:"DELETE",path:"/merchants/{merchantId}/admins/{userId}",response:dn((()=>Mo))},{method:"GET",path:"/merchants/{merchantId}/wallets",response:dn((()=>Vo))},{method:"POST",path:"/merchants/wallets/add-assets",request:dn((()=>$o)),response:dn((()=>Wo))},{method:"POST",path:"/merchants/assets/add",request:dn((()=>jo)),response:dn((()=>Go))},{method:"DELETE",path:"/merchants/assets/delete",request:dn((()=>Ho)),response:dn((()=>Yo))},{method:"POST",path:"/merchants/assets/update-visibility",request:dn((()=>zo)),response:dn((()=>Jo))},{method:"POST",path:"/merchants/assets/update-default-status",request:dn((()=>Xo)),response:dn((()=>Zo))},{method:"GET",path:"/merchants/{merchantId}/api-keys",response:dn((()=>si))},{method:"POST",path:"/merchants/{merchantId}/api-keys",request:dn((()=>ni)),response:dn((()=>oi))},{method:"GET",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/origins",response:dn((()=>ai))},{method:"POST",path:"/merchants/{merchantId}/api-keys/{apiKeyId}/whitelist-origins",request:dn((()=>ii)),response:dn((()=>ci))},{method:"PUT",path:"/merchants/{merchantId}/api-keys/{apiKeyId}",request:dn((()=>di)),response:dn((()=>li))},{method:"GET",path:"/wallets",response:dn((()=>ui))},{method:"POST",path:"/wallets/create",request:dn((()=>hi)),response:dn((()=>vi))},{method:"POST",path:"/wallets/verify-access",request:dn((()=>Si)),response:dn((()=>Ai))},{method:"POST",path:"/wallets/create-admin-server-wallet",request:dn((()=>bi)),response:dn((()=>vi))},{method:"POST",path:"/wallets/create-with-shares",request:dn((()=>Ei)),response:dn((()=>vi))},{method:"POST",path:"/wallets/create-shares-based-wallet-from-seed",request:dn((()=>_i)),response:dn((()=>vi))},{method:"POST",path:"/wallets/add-new-device",request:dn((()=>ki)),response:dn((()=>Ii))},{method:"POST",path:"/wallets/import-seed-phrase",request:dn((()=>Ti)),response:dn((()=>vi))},{method:"POST",path:"/wallets/generate-wallet-addresses",request:dn((()=>Pi)),response:dn((()=>xi))},{method:"POST",path:"/wallets/derive-addresses/batch",request:dn((()=>Ki)),response:dn((()=>Ni))},{method:"GET",path:"/wallets/{walletId}/assets",response:dn((()=>Ri))},{method:"GET",path:"/wallets/{walletId}/addresses",response:dn((()=>Di))},{method:"GET",path:"/wallets/asset",request:dn((()=>Li)),response:dn((()=>pi))},{method:"PUT",path:"/wallets/asset/update",request:dn((()=>Bi)),response:dn((()=>Ui))},{method:"POST",path:"/wallets/{walletId}/swap/quote",request:dn((()=>qi)),response:dn((()=>Vi))},{method:"GET",path:"/wallets/{walletId}/swaps",response:dn((()=>$i))},{method:"GET",path:"/wallets/{walletId}/swaps/{swapId}",response:dn((()=>Fi))},{method:"POST",path:"/wallets/execute-swap",request:dn((()=>Wi)),response:dn((()=>ji))},{method:"GET",path:"/transactions",response:dn((()=>Hi))},{method:"GET",path:"/transactions/pending",response:dn((()=>zi))},{method:"POST",path:"/transactions/resolve",request:dn((()=>Ji)),response:dn((()=>Xi))},{method:"POST",path:"/transactions/transfer",request:dn((()=>Zi)),response:dn((()=>Qi))},{method:"POST",path:"/transactions/transfer-with-shares",request:dn((()=>ec)),response:dn((()=>Qi))},{method:"POST",path:"/transactions/asset-optin",request:dn((()=>tc)),response:dn((()=>Qi))},{method:"POST",path:"/transactions/app-optin",request:dn((()=>rc)),response:dn((()=>Qi))},{method:"GET",path:"/transactions/estimate-fee",response:dn((()=>sc))},{method:"GET",path:"/transactions/status",response:dn((()=>nc))},{method:"GET",path:"/transactions/raw-status",response:dn((()=>Jn))},{method:"GET",path:"/transactions/detect-transfers-restrictions",response:dn((()=>oc))},{method:"GET",path:"/transactions/transfer-restriction-message",response:dn((()=>ic))},{method:"GET",path:"/transactions/restriction",response:dn((()=>cc))},{method:"GET",path:"/transactions/check-asset-optin",response:an(yn(gn(),sn()))},{method:"GET",path:"/transactions/check-app-optin",response:an(yn(gn(),sn()))},{method:"POST",path:"/transactions/create-allowance",request:dn((()=>dc)),response:dn((()=>lc))},{method:"GET",path:"/query/assets/balance",response:dn((()=>hc))},{method:"GET",path:"/query/address/balance",response:dn((()=>hc))},{method:"POST",path:"/query/assets/bulk-balance",request:dn((()=>fc)),response:dn((()=>yc))},{method:"POST",path:"/query/assets/wallet-bulk-balance",request:dn((()=>gc)),response:dn((()=>yc))},{method:"GET",path:"/query/transactions",response:dn((()=>mc))},{method:"GET",path:"/query/fetch-token-info",response:dn((()=>vc))},{method:"GET",path:"/query/get-asset-price",response:dn((()=>Ac))},{method:"POST",path:"/mpc/reconstruct-seed-phrase",request:dn((()=>bc)),response:dn((()=>Ec))},{method:"GET",path:"/users",response:dn((()=>_c))},{method:"PUT",path:"/users/profile",request:dn((()=>kc)),response:dn((()=>Ic))},{method:"GET",path:"/users/profile",response:dn((()=>Tc))},{method:"GET",path:"/users/salt",response:dn((()=>Pc))},{method:"GET",path:"/users/{userId}/wallets",response:dn((()=>Cc))},{method:"GET",path:"/users/merchants/assets",response:dn((()=>Ro))},{method:"GET",path:"/users/merchant/assets",response:dn((()=>Ro))},{method:"GET",path:"/users/{userId}/assets",response:dn((()=>xc))},{method:"POST",path:"/users/assets/add",request:dn((()=>Oc)),response:dn((()=>Nc))},{method:"DELETE",path:"/users/{userId}/wallets/{walletId}/assets/{assetConfigId}",response:dn((()=>Rc))},{method:"GET",path:"/users/{userId}",response:dn((()=>Tc))},{method:"GET",path:"/users/{externalUserId}/externalUserId",response:dn((()=>Dc))},{method:"POST",path:"/transactions/admin/release-schedule",request:dn((()=>Lc)),response:dn((()=>Bc))},{method:"GET",path:"/transactions/admin/release-schedule",response:dn((()=>Hc))},{method:"POST",path:"/transactions/admin/mint",request:dn((()=>qc)),response:dn((()=>Mc))},{method:"POST",path:"/transactions/admin/burn",request:dn((()=>Fc)),response:dn((()=>Mc))},{method:"POST",path:"/transactions/admin/execute-purchase",request:dn((()=>$c)),response:dn((()=>Bc))},{method:"POST",path:"/transactions/admin/execute-purchase-with-interest",request:dn((()=>Wc)),response:dn((()=>Bc))},{method:"POST",path:"/transactions/admin/set-identity",request:dn((()=>jc)),response:dn((()=>Bc))},{method:"POST",path:"/transactions/admin/force-claim",request:dn((()=>Gc)),response:dn((()=>Bc))},{method:"POST",path:"/transactions/admin/force-claim-principal",request:dn((()=>Gc)),response:dn((()=>Bc))},{method:"GET",path:"/transactions/admin/{referenceId}",response:dn((()=>Yc))},{method:"POST",path:"/transactions/admin/callback",request:dn((()=>zc)),response:dn((()=>Jc))},{method:"GET",path:"/dashboard",response:dn((()=>Xc))},{method:"GET",path:"/users-activities",response:dn((()=>Qc))}],td=new Map,rd=[];for(const e of ed)if(e.path.includes("{")){const t=e.path.replace(/\{[^/]+\}/g,"[^/]+");rd.push({method:e.method,regex:new RegExp(`^${t}$`),entry:e})}else td.set(`${e.method} ${e.path}`,e);const sd={response:{statusCode:200,errorCode:exports.ErrorResponseCodes.sdk_invalid_response,tag:"InvalidResponse"},request:{statusCode:422,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter,tag:"InvalidRequest"}};function ad(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=td.get(`${r} ${s}`);if(a)return{request:a.request,response:a.response};const n=rd.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},Ya());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:u,tag:h}=sd[e];if("throw"===a)throw new M({kind:"validation",message:c,statusCode:l,errorCode:u,data:{method:t,path:r,issues:i.issues}});pe.warn(`SDK::ApiValidation::${h} ${c}`)}function nd({method:e,path:t,data:r,mode:s}){ad("response",e,t,r,s)}function od({method:e,path:t,body:r,mode:s}){ad("request",e,t,r,s)}const id=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]),cd=new Set([exports.ErrorResponseCodes.auth_refresh_token_not_found,exports.ErrorResponseCodes.auth_refresh_token_expired,exports.ErrorResponseCodes.auth_refresh_token_reuse_detected]);function dd(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 ld(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 ud(e){if(401!==dd(e))return!1;const t=ld(e);return!t||id.has(t)}const hd=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()}},pd=new La;class fd{constructor(t,r={}){var s,a,n,o,i;const c=Ga(t);this.apiKey=c.apiKey,this.baseUrl=c.baseUrl,this.userId=c.userId,this.options=c.options,(null===(s=this.options)||void 0===s?void 0:s.platform)&&(Se.platform=this.options.platform,Se.isNative="ios"===this.options.platform||"android"===this.options.platform,Se.isWeb=!Se.isNative),this.cipher=null!==(a=r.cipher)&&void 0!==a?a:new Da,this.transport=null!==(n=r.transport)&&void 0!==n?n:(...e)=>fetch(...e),this.clock=null!==(o=r.clock)&&void 0!==o?o:{now:()=>Date.now()},this.lockManager=pd,this._initializeClientAuthToken(c.clientAuthToken),this.request=this.request.bind(this);const d=new e.H({baseUrl:this.baseUrl.replace(/\/api\/v1\/?$/,""),baseApiParams:{secure:!0},securityWorker:this.securityWorker.bind(this),customFetch:this.transport}),l=d.request.bind(d);d.request=async e=>{const t=async r=>{try{od({method:e.method,path:e.path,body:e.body,mode:this.validationMode});const t=await l(e);return nd({method:e.method,path:e.path,data:t,mode:this.validationMode}),t}catch(e){if(!r&&ud(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 e.A(d),this.api.http.setSecurityData(Object.assign({"x-api-key":t.apiKey,"x-client-jwt":t.clientAuthToken},null===(i=this.options)||void 0===i?void 0:i.headers))}set setClientAuthToken(e){this._initializeClientAuthToken(e)}get version(){const e=Ae;return pe.log(`wsdk is running v${e}`),e}_initializeClientAuthToken(e){if(t=e,r=this.userId,!t||!r||n.jwtDecode(t).externalUserId!==r)throw new 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 n.jwtDecode(e).mfaVerified}(e)?this.deviceAuthType=exports.AuthType.Passkey:this.deviceAuthType=exports.AuthType.Password}get deviceLocalStorage(){var e;if(null===(e=this.options)||void 0===e?void 0:e.storage)return this.options.storage;if("undefined"!=typeof window&&"localStorage"in window)return window.localStorage;throw new 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:ge,network:null!==(s=null===(r=this.options)||void 0===r?void 0:r.network)&&void 0!==s?s:we,hostname:null!==(n=null===(a=this.options)||void 0===a?void 0:a.hostname)&&void 0!==n?n:"https://www.republic.com"})}get localStorageService(){var e;if(!this.clientAuthToken)throw new 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 Ua({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 hd.withDedupe(t,(async()=>{var t;const r=await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);if(r)try{const s=await this.request(Fa.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=dd(e),r=ld(e);return 401===t||!!r&&cd.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){pe.error("SDK::Base::toWallabyError::onError handler threw",{error:e})}return s}async request(e,t,r=!1,s=!1){var a;const n=e=>s?new M(e):this.toWallabyError(e);if(e!==Fa.refreshAccessToken&&!r){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(e&&Ma(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{od({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)),pe.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(pe.debug(`SDK::Base::${e.method}::Response`,{status:a.status,statusText:a.statusText,data:l}),!a.ok){if(!r&&e!==Fa.refreshAccessToken&&ud({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 nd({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){pe.error("SDK::Base::handleApiCall::API Error",{error:t});const e=t.error;throw n({message:e.message||"API request failed",statusCode:e.statusCode||500,errorCode:e.errorCode,data:e})}throw pe.error(`SDK::Base::${e.method}::NetworkError`,{message:t.message,name:t.name,error:t}),n({message:t.message||"Network request failed",statusCode:0,errorCode:"NETWORK_ERROR",data:{code:t.code||t.name,originalError:t},cause:t.cause})}}async _getRequestHeaders(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);if(qa(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,[be]:Ee};return e&&(t.Authorization="Bearer "+e),t}async securityWorker(e){try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&Ma(e,60,this.clock.now)&&await this._performTokenRefresh({silent:!0})}catch(e){}const t=Object.assign(Object.assign({"Content-Type":"application/json"},e||{}),{[be]:Ee});try{const e=await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);e&&(t.Authorization=`Bearer ${e}`)}catch(e){}return{headers:t}}}const yd={importSeedPhraseV2:{fullPath:"/wallets/create-shares-based-wallet-from-seed",method:exports.RequestMethod.Post,requiresAccessToken:!0},addNewDevice:{fullPath:"/wallets/add-new-device",method:exports.RequestMethod.Post,requiresAccessToken:!0},initKeyExchange:{fullPath:"/mpc/init-key-exchange",method:exports.RequestMethod.Post,requiresAccessToken:!0},retrieveSeedPhrase:{fullPath:"/mpc/reconstruct-seed-phrase",method:exports.RequestMethod.Post,requiresAccessToken:!0},createWithKeyShares:{fullPath:"/wallets/create-with-shares",method:exports.RequestMethod.Post,requiresAccessToken:!0},create:{fullPath:"/wallets/create",method:exports.RequestMethod.Post,requiresAccessToken:!0},import:{fullPath:"/wallets/import-seed-phrase",method:exports.RequestMethod.Post,requiresAccessToken:!0},getTokenBalance:{fullPath:({address:e,assetSymbol:t,chainName:r,tokenStandard:s})=>`/query/assets/balance?address=${e}&assetSymbol=${t}`+(s?`&tokenType=${s}`:"")+(r?`&chainName=${r}`:""),method:exports.RequestMethod.Get,requiresAccessToken:!1},getMultiTokenBalances:{fullPath:"/query/assets/bulk-balance",method:exports.RequestMethod.Post,requiresAccessToken:!1},getWalletBalances:{fullPath:"/query/assets/wallet-bulk-balance",method:exports.RequestMethod.Post,requiresAccessToken:!1},getWalletAssets:{fullPath:({walletId:e})=>`/wallets/${e}/assets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},getUserAssets:{fullPath:({userId:e})=>`/users/${e}/assets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},addTokenToWallet:{fullPath:"/users/assets/add",method:exports.RequestMethod.Post,requiresAccessToken:!1},generateWalletAddresses:{fullPath:"/wallets/generate-wallet-addresses",method:exports.RequestMethod.Post,requiresAccessToken:!0},updateAsset:{fullPath:"/wallets/asset/update",method:exports.RequestMethod.Put,requiresAccessToken:!1},getUserWallets:{fullPath:({userId:e})=>`/users/${e}/wallets`,method:exports.RequestMethod.Get,requiresAccessToken:!1},convertMnemonicSeedPhrase:{fullPath:"/wallets/convert-mnemonic-seed",method:exports.RequestMethod.Post,requiresAccessToken:!0},createMultisigAsset:{fullPath:"/wallets/create-multisig-asset",method:exports.RequestMethod.Post,requiresAccessToken:!0},verifyAccess:{fullPath:"/wallets/verify-access",method:exports.RequestMethod.Post,requiresAccessToken:!0}},gd={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}},wd={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}},md={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 vd(e,t){if(!e)return{};const r=new Set(t);return Object.fromEntries(Object.entries(e).filter((([e])=>!r.has(e))))}class Sd{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 p.startRegistration({optionsJSON:e})}async authenticate({optionsJSON:e,useBrowserAutofill:t=!1,skipUserVerification:r=!1}){try{if("undefined"==typeof window||!("navigator"in window)||!("credentials"in window.navigator))throw new M({message:"WebAuthn is not supported in this browser.",statusCode:501,errorCode:"sdk_auth_webauthn_unsupported"});return await p.startAuthentication({optionsJSON:Object.assign(Object.assign({},e),{userVerification:r?"discouraged":e.userVerification}),useBrowserAutofill:t})}catch(e){throw this.handlePasskeyError(e),e}}handlePasskeyError(e){return pe.error("SDK::Authenticator::handlePasskeyError",e),this.throwPasskeyError(this.classifyPasskeyError(e),e)}classifyPasskeyError(e){return e instanceof p.WebAuthnError?(pe.debug("SDK::Authenticator::handlePasskeyError - WebAuthnError",e),{errorCode:e.code}):e instanceof Error?(pe.debug("SDK::Authenticator::handlePasskeyError - Error",e),{errorMessage:e.message}):null!==e&&"object"==typeof e&&e.error&&e.message?(pe.debug("SDK::Authenticator::handlePasskeyError - Object",e),{errorCode:e.error,errorMessage:e.message}):"string"==typeof e?(pe.debug("SDK::Authenticator::handlePasskeyError - String",e),{errorMessage:e}):(pe.debug("SDK::Authenticator::handlePasskeyError - Unknown",e),{})}throwPasskeyError({errorCode:e,errorMessage:t},r){var s,a,n;pe.error("SDK::Authenticator::throwPasskeyError",e);const o=ue.find((t=>t.error===e));throw pe.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:V.message,statusCode:400,errorCode:null!==(n=null==o?void 0:o.error)&&void 0!==n?n:e,cause:r})}}function Ad(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");return t.padEnd(t.length+(4-t.length%4)%4,"=")}function bd(e){try{return i.toUint8Array(e)}catch(r){return t=e,i.toUint8Array(Ad(t))}var t}function Ed(e){const t=Ad(e),r=i.atob(t),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}class _d{constructor(e,t,r,s=new Da){this.cipher=s,this.localStorageService=t,this.userId=e,this.request=r,this.authenticator=new Sd}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)?Ed(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 pe.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)?Ed(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 pe.log("SDK::PasskeyService::preparePasskeyCreationOptions::parsedOptions",!!l),l}async addNewPasskey({deviceKeyPair:e,getSignature:t}){try{let r,s;pe.log("SDK::PasskeyService::addNewPasskey: start adding new passkey");try{const a=await t({deviceAuthKeys:e,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});if(!a.registrationOptions)throw new 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);pe.log("SDK::PasskeyService::addNewPasskey: about to register passkey credential"),r=await this.authenticator.register({optionsJSON:n}),pe.log("SDK::PasskeyService::addNewPasskey: finished registering passkey credential");const o=await this.handleCredentialsCreationFromPrfExtension(r);pe.log("SDK::PasskeyService::addNewPasskey:: finished deriving credentials key pair",o.publicKey),s=await this.request(Fa.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyRegistrationResponse:r}}),pe.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(pe.error("SDK::PasskeyService::addNewPasskey::error",a),a&&a.code===oe.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);pe.log("SDK::PasskeyService::addNewPasskey::catch: about to authenticate with passkey"),r=await this.authenticator.authenticate({optionsJSON:n}),pe.log("SDK::PasskeyService::addNewPasskey::catch: finished authenticating with passkey"),s=await this.request(Fa.signIn,{payload:{externalUserId:this.userId,message:a.message,clientAuthPubKey:e.publicKey,signature:a.signature,passkeyAuthenticationResponse:r}}),pe.log("SDK::PasskeyService::addNewPasskey::catch: finished signing in with passkey",{signInResponse:s});const o=await this.handleCredentialsCreationFromPrfExtension(r);pe.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 pe.log("SDK::PasskeyService::addNewPasskey::catch: about to store data"),await this.handleStoringData({authenticationResponse:s,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:i},passkeyCredential:r}),pe.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({},vd(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(Fa.signIn,{payload:{externalUserId:this.userId,message:t.message,clientAuthPubKey:e.publicKey,signature:d,passkeyAuthenticationResponse:i}}),u=e.decryptedPrivateKey?e.decryptedPrivateKey:e.encryptedDevicePrivateKey?await this.cipher.decrypt({cipherText:e.encryptedDevicePrivateKey,decryptionKey:c.privateKey}):void 0;if(!u)throw new M({message:"Device private key is not available for storage.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const h=await this.cipher.encrypt({data:u,encryptionKey:c.publicKey});return await this.handleStoringData({authenticationResponse:l,deviceKeyPair:{publicKey:e.publicKey,encryptedDevicePrivateKey:h},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});pe.log("SDK::PasskeyService::register:: got challenge",{registrationOptions:t.registrationOptions});const s=this.preparePasskeyCreationOptions(t.registrationOptions);pe.log("SDK::PasskeyService::register:: registering passkey",{parsedOptions:s});const a=await this.authenticator.register({optionsJSON:s});if(pe.log("SDK::PasskeyService::register:: got passkey credential",{id:a.id,type:a.type}),!(null===(r=a.clientExtensionResults.prf)||void 0===r?void 0:r.enabled))throw new 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});pe.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(Fa.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(pe.log("SDK::PasskeyService::register::error",{error:e,errorCode:e.code,errorMessage:e.message}),e instanceof M)throw pe.log("SDK::PasskeyService::register::API error detected",{error:e}),e;if(e&&e.code===oe.error||e.code===ie.error||"The authenticator was previously registered."===e.message)throw pe.log("SDK::PasskeyService::register::ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",!0),e;throw this.authenticator.handlePasskeyError(e)}}async isDevicePrfCompatible(){var e;try{if("undefined"!=typeof window&&"function"==typeof(null===(e=window.PublicKeyCredential)||void 0===e?void 0:e.getClientCapabilities)){const e=await window.PublicKeyCredential.getClientCapabilities();return pe.log("SDK::PasskeyService::isDevicePrfCompatible::capabilities",e),e["extension:prf"]}return!1}catch(e){return!1}}async publicKeyCredential(){const e=await this.localStorageService.fetch(exports.LocalStorageItems.PasskeyCredential);return null!=e?e:"There are no passkeys stored on this device"}async handleStoringData({authenticationResponse:e,deviceKeyPair:t,passkeyCredential:r}){return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:t.encryptedDevicePrivateKey},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:t.publicKey},{key:exports.LocalStorageItems.PasskeyCredential,value:r},{key:exports.LocalStorageItems.AccessToken,value:e.accessToken},...e.refreshToken?[{key:exports.LocalStorageItems.RefreshToken,value:e.refreshToken}]:[]])}async handleCredentialsCreationFromPrfExtension(e){var t,r,s,a,n;try{const o=e.clientExtensionResults;if(pe.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(pe.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=bd(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)}}}pe.debug("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::prfValue",c);const d=await this.cipher.getCredentialsKeyPair({prfValue:c,authType:exports.AuthType.Passkey});return pe.log("SDK::PasskeyService::handleCredentialsCreationFromPrfExtension::credentials key pair was created",!!d),Object.assign(Object.assign({},d),{prfValue:c})}catch(e){if(e instanceof 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 kd(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,u=e||`${t.constructor.name}:${r}`,h=null!==(o=null===(n=this.options)||void 0===n?void 0:n.environment)&&void 0!==o?o:ge,p=null!==(c=null===(i=this.options)||void 0===i?void 0:i.network)&&void 0!==c?c:we,f=`${null!==(d=this.userId)&&void 0!==d?d:"anon"}:${h}:${p}:${u}`;return l.withLock(f,(()=>a.apply(this,s)))},s}}class Id extends fd{constructor(e,t={}){super(e,t),this.getUserSalt=this.getUserSalt.bind(this),this.passkeyService=new _d(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&&!qa(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){pe.warn("SDK::AuthService::validatePassword::error",t);return!!await this.localStorageService.getDecryptedV1PrivateKey(`${e}`)}}async getUserSalt(){try{return(await this.api.users.getCurrentUserSalt()).clientSalt}catch(e){throw pe.error("SDK::AuthService::getUserSalt::error",e),e}}async getSignature({deviceAuthKeys:e,walletId:t,passkeyChallengeType:r}){try{pe.debug("SDK::AuthService::getSignature::authType",this.deviceAuthType);const s=this.deviceAuthType===exports.AuthType.Passkey?null!=r?r:exports.PasskeyChallengeType.REGISTRATION:void 0;pe.debug("SDK::AuthService::getSignature::challengeType",s);const a=await this.request(Fa.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 pe.error("SDK::AuthService::getSignatureMessage::error",e),e}}async signUp(e){pe.info("starting signup");const t=Ms();let r;pe.info("key pair generated",!!t);try{const s=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.REGISTRATION});switch(pe.info("signature has been generated",!!s),this.deviceAuthType){case exports.AuthType.Passkey:pe.info("registering a new passkey"),r=await this.passkeyService.register({deviceKeyPair:t,challengeResponse:s});break;case exports.AuthType.Password:pe.info("signing up with password"),r=await this.handleSignUpWithPassword({signatureMessage:s,deviceKeyPair:t,input:e});break;default:throw new 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(pe.error("SDK::AuthService::signUp::error",e),e&&e.error===ie.error||e.code===oe.error){pe.info("SDK::AuthService::signUp::handling previously registered passkey error");const e=await this.getSignature({deviceAuthKeys:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});return r=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:t.publicKey,decryptedPrivateKey:t.privateKey},challengeResponse:e}),r}throw e}}async signIn(e){let t;try{switch(this.deviceAuthType){case exports.AuthType.Passkey:t=await this.handleSignInWithPasskey({input:e});break;case exports.AuthType.Password:t=await this.handleSignInWithPassword({input:e});break;default:throw new 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 pe.error("SDK::AuthService::signIn::error",e),e}}async hasStoredDevicePublicKey(){return!!await this.localStorageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey)}async handleSignInWithPassword({input:e}){if(!e.password)throw new 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 pe.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=ka(t);n=await this.cipher.decrypt({cipherText:e,decryptionKey:a.privateKey})}else n=await this.localStorageService.getDecryptedV1PrivateKey(e.password)}else{if(await this.hasStoredDevicePublicKey())throw pe.error("SDK::AuthService::handleSignInWithPassword::error","Device key missing but wallet data exists"),new 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});pe.info("No device data found, treating as a fresh device and creating a new key pair");n=Ms().privateKey}if(!n)throw pe.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=bs(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(Fa.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){pe.debug("SDK::AuthService::handleSignInWithPasskey:: using existing key pair");const e=await this.request(Fa.signatureMessage,{payload:{clientAuthPubKey:a,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}});t=await this.passkeyService.authenticate({deviceKeyPair:{publicKey:a,encryptedDevicePrivateKey:ka(s)},challengeResponse:e}),pe.debug("SDK::AuthService::handleSignInWithPasskey:: passkey authentication finished",!!t)}else{if(a||s)throw pe.error("SDK::AuthService::handleSignInWithPasskey::error","Passkey credential missing but device data exists"),new 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=Ms(),t=await this.passkeyService.addNewPasskey({deviceKeyPair:n,getSignature:this.getSignature.bind(this)}),pe.debug("SDK::AuthService::handleSignInWithPasskey:: passkey registration finished",t)}return Object.assign(Object.assign(Object.assign({},t),{prfValue:t.prfValue}),e)}catch(e){throw pe.error("SDK::AuthService::handleSignInWithPasskey::error ",e),e}}async storeDeviceKeyPair({deviceAuthKeyPair:e,credentialsKeyPair:t}){const r=await this.cipher.encrypt({data:e.privateKey,encryptionKey:t.publicKey});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:r},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:e.publicKey}])}async handleSignUpWithPassword({signatureMessage:e,input:t,deviceKeyPair:r}){if(!t.password)throw new 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(Fa.signUp,{payload:{externalUserId:this.userId,message:e.message,signature:e.signature,clientAuthPubKey:r.publicKey}}).then((async e=>{const s=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,password:t.password,salt:e.user.clientSalt}),a=await this.cipher.encrypt({data:r.privateKey,encryptionKey:s.publicKey});return await this.localStorageService.saveInBulk([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:a},{key:exports.LocalStorageItems.ClientAuthPublicKey,value:r.publicKey},{key:exports.LocalStorageItems.AccessToken,value:e.accessToken},...e.refreshToken?[{key:exports.LocalStorageItems.RefreshToken,value:e.refreshToken}]:[]]),e}));return Object.assign(Object.assign({},a),{password:t.password,clientSalt:a.user.clientSalt,signatureMessageResponse:e})}async getPasskeyCredentials(){try{return await this.api.auth.getPasskeyCredentials()}catch(e){if(pe.error("SDK::AuthService::getPasskeyCredentials::error",e),"string"==typeof e)throw new 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(Fa.issueJwtToken);return await this.localStorageService.save(exports.LocalStorageItems.AccessToken,e.accessToken),await this.localStorageService.save(exports.LocalStorageItems.RefreshToken,e.refreshToken),e}catch(e){throw pe.error("SDK::Auth::exchangeClientToken::error",e),e}}}e._([kd("signUp"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Id.prototype,"signUp",null),e._([kd("signIn"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Id.prototype,"signIn",null),e._([kd("storeDeviceKeyPair"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Id.prototype,"storeDeviceKeyPair",null);class Td extends fd{constructor(e,t={}){super(e,t),this.authService=new Id(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_response});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 u=function(e,t="The seed phrase is not a valid BIP-39 mnemonic. Expected 12, 15, 18, 21 or 24 words from the BIP-39 English wordlist."){if(!ja(e))throw new M({message:t,statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return Wa(e)}(t.seedPhrase),h=await this.cipher.encrypt({data:t.returnWalletOption===exports.ReturnWalletOption.ReturnOnlyEncryptedSeedPhrase?Ra(u,e.publicKey):u,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},f=await this.request(yd.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 f.encryptedSeed&&t.returnWalletOption!==exports.ReturnWalletOption.ReturnOnlyEncryptedShares&&await this.handleSeedPhraseFromResponse({walletId:f.wallet.id,encryptedSeed:f.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:t.storeSeedPhrase,credentialsKeyPair:y}),f.shares&&f.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:f.wallet.id,shares:f.shares,credentialsKeyPair:y,encryptedBackupShare:f.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign({},f)}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,t){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((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_invalid_parameter});const{numberOfKeyShares:l,threshold:u}=null!==(s=t.keyShareOptions)&&void 0!==s?s:{};if(u&&l&&l<u)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 h={reference:r.v4(),message:c,signature:i,hashedMessage:d,clientAuthPubKey:e.publicKey,returnWalletOption:t.returnWalletOption,numShares:l,threshold:u,wallabyKeepsOne:null!==(n=null===(a=t.keyShareOptions)||void 0===a?void 0:a.storeOneKeyShareWithWallaby)&&void 0!==n&&n,walletOwnershipType:null!==(o=t.walletOwnershipType)&&void 0!==o?o:exports.WalletOwnershipType.SingleOwner},p=await this.request(yd.createWithKeyShares,{payload:h});let f;const y=await this.cipher.getCredentialsKeyPair({authType:this.deviceAuthType,salt:t.authenticationOptions.user.clientSalt,password:t.authenticationOptions.password,prfValue:t.authenticationOptions.prfValue});return p.encryptedSeed&&(f=await this.handleSeedPhraseFromResponse({walletId:p.wallet.id,encryptedSeed:p.encryptedSeed,devicePrivateKey:e.privateKey,storeSeedPhrase:t.storeSeedPhrase,credentialsKeyPair:y})),p.shares&&p.encryptedBackupShare&&await this.handleKeySharesFromResponse({walletId:p.wallet.id,shares:p.shares,credentialsKeyPair:y,encryptedBackupShare:p.encryptedBackupShare,devicePrivateKey:e.privateKey}),Object.assign(Object.assign({},p),{standardSeedPhrase:f})}catch(e){throw pe.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 pe.error("SDK::handleKeySharesFromResponse::error",e),e}}async handleSeedPhraseFromResponse({walletId:e,encryptedSeed:t,devicePrivateKey:r,credentialsKeyPair:s,storeSeedPhrase:a}){try{const n=await this.cipher.decrypt({cipherText:t,decryptionKey:r});if(a){const t=bs(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 pe.error("SDK::handleSeedPhraseFromResponse::error",e),e}}}function Pd(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 Cd extends fd{constructor(e,t={}){super(e,t),this.authService=new Id(e,t),this.handlers=new Td(e,t),this.userId=e.userId,this.passkeyService=new _d(e.userId,this.localStorageService,this.request,this.cipher)}async getRateState(e){const t=Date.now(),r=await this.localStorageService.fetch(e),s=r?ka(r):void 0;return!s||t-s.windowStart>Cd.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>Cd.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=bs(s);return await this.handlers.handleWalletCreation({publicKey:a,privateKey:s},e)}catch(e){throw pe.error("SDK::Wallet::create::error",e),e}}async export({walletId:e,authenticationOptions:t,exportOptions:r}){try{if(!r.algorandSeedPhrase&&!r.standardSeedPhrase&&!r.keyShares)throw new 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=ka(n),u=await this.cipher.decrypt({cipherText:l,decryptionKey:d.privateKey});if(!u)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=ka(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=ka(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=ka(a),n={publicKey:bs(u),privateKey:u},{signature:o,message:d,wallabyAuthPubKey:h}=await this.authService.getSignature({deviceAuthKeys:n,walletId:e,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),p=h;if(!p)throw new M({message:"Wallaby public key is required for wallet export.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});const f=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:s,encryptedDevicePrivateKey:l,wallabyPublicKey:p,destinationPubKey:n.publicKey,options:{authType:this.deviceAuthType,password:t.password,salt:t.user.clientSalt,prfValue:t.prfValue}}),y=await this.request(yd.retrieveSeedPhrase,{payload:{walletId:e,signature:o,message:d,clientAuthPubKey:n.publicKey,encryptedShares:[f]}});i=await this.cipher.decrypt({cipherText:y.encryptedSeed,decryptionKey:u}),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 pe.error("SDK::WalletService::export::error",e),e}}async import(e){var t;try{const s=null!==(t=e.reference)&&void 0!==t?t:r.v4(),a=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!a)throw new M({message:"Device private key is required",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_private_key_not_found});const n=ka(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=bs(i);return await this.handlers.handleImportWallet({publicKey:c,privateKey:i},Object.assign(Object.assign({},e),{reference:s}))}catch(e){throw pe.error("SDK::WalletService::import::error",e),e}}async changePassword({walletId:e,oldPassword:t,newPassword:r}){try{if(await this.recordRateAttempt(exports.V2KeyNames.PasswordResetAttempts)>Cd.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 u=a?await this.cipher.flipEncryptedData({cipherText:ka(a),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,h=n?await this.cipher.flipEncryptedData({cipherText:ka(n),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null,p=o?await this.cipher.flipEncryptedData({cipherText:ka(o),decryptionKey:c.privateKey,encryptionKey:d.publicKey}):null;return u&&await this.assertRoundTrip(u,d.privateKey,"seed phrase"),h&&await this.assertRoundTrip(h,d.privateKey,"primary share"),p&&await this.assertRoundTrip(p,d.privateKey,"backup share"),await this.localStorageService.commitBatch([{key:exports.LocalStorageItems.EncryptedDevicePrivateKey,value:l},...u?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,value:u,walletId:e}]:[],...h?[{key:exports.LocalStorageItems.PrimaryDeviceKeyShare,value:h,walletId:e}]:[],...p?[{key:exports.LocalStorageItems.BackupDeviceKeyShare,value:p,walletId:e}]:[]]),await this.localStorageService.delete(exports.V2KeyNames.PasswordResetAttempts),!0}catch(e){throw pe.error("SDK::Wallet::changePassword::error",e),e}}getAlgorandSeedPhrase(e){try{const r=u.mnemonicToSeedSync(e),s=function(e){if(32!==e.length)throw new Error(`Algorand seed must be 32 bytes, got ${e.length}`);const r=t.wordlists.english,s=Pd(e).map((e=>r[e])),a=Pd(Tr(e).subarray(0,2))[0];return[...s,r[a]].join(" ")}(r.slice(0,32));return s}catch(e){throw pe.error("SDK::Wallet::getAlgorandSeedPhrase::error",e),new 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=ka(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=ka(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:ka(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:bs(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(yd.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 pe.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(yd.generateWalletAddresses,{payload:{walletId:t,message:r.signatureMessage.message,clientAuthPubKey:r.deviceAuthPublicKey,signature:r.signatureMessage.signature,encryptedSeed:r.readyForTransportSeedPhrase,encryptedShares:r.sharesEncryptedWithWallabyPubKey,chainName:e.blockchainName}})}catch(e){throw pe.error("SDK::Wallet::generateWalletAddresses::error",e),e}}async migrateToV2Safe({password:e,walletId:t}){try{await this.handleUpdateToV2({password:e,walletId:t})}catch(e){if(e instanceof M&&e.errorCode===exports.ErrorResponseCodes.sdk_ambiguous_legacy_migration_data)throw e;throw pe.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 pe.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 s=this.version,n=await this.localStorageService.fetch(exports.V2KeyNames.MigrationVersion),o=await this.localStorageService.fetch(exports.V2KeyNames.LastMigratedAt);if(pe.info("SDK::WalletService::handleUpdateToV2::starting migration check",{timestamp:new Date(r).toISOString(),walletId:t.substring(0,8)+"...",lastMigratedAt:o,currentSdkVersion:s,sdkMigrationVersion:n}),o&&"never"!==o&&n)return void pe.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(),u=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:l});if(i&&(c||d))try{await this.cipher.decrypt({cipherText:ka(i),decryptionKey:u.privateKey});const t=c||d;return await this.cipher.displayStoredData({storedEncryptedData:ka(t),encryptedDevicePrivateKey:ka(i),options:{authType:exports.AuthType.Password,password:e,salt:l}}),pe.info("SDK::WalletService::handleUpdateToV2::V2 items already exist and are valid, no migration needed"),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,(new Date).toISOString()),void await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,s)}catch(e){pe.info("SDK::WalletService::handleUpdateToV2::V2 items exist but decryption failed, proceeding with migration",{error:JSON.stringify(e)})}let h,p;await this.recordRateAttempt(exports.V2KeyNames.MigrationAttempts);const f=await this.localStorageService.isLegacySeedFallbackSafeFor(t),y=f?await this.localStorageService.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`):void 0,g=await this.localStorageService.getDecryptedV1PrivateKey(e);if(y&&g){this.assertValidDeviceKey(g),pe.info("SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration",{storageFormat:"legacy"});try{const r=ka(a.AES.decrypt(y,`${l}${e}`).toString(a.enc.Utf8));if(h=Aa(g,r),p=g,!h)throw new M({message:"Failed to decrypt legacy seed phrase items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});pe.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted legacy items"),await this.localStorageService.claimLegacySeedFallbackFor(t)}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt legacy items",e),new 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){if(!f){const e=await this.localStorageService.getFromDeviceStorage(`${exports.LegacyKeyNames.EncryptedSeed}_${this.userId}`),t=await this.localStorageService.getV1EncryptedSeedPhrase();if(e||t)throw pe.error("SDK::WalletService::handleUpdateToV2::Legacy seed data on this device is already claimed by a different wallet; refusing to migrate ambiguously"),new M({message:"Legacy wallet data on this device is associated with a different wallet and cannot be safely migrated for this wallet.",statusCode:409,errorCode:exports.ErrorResponseCodes.sdk_ambiguous_legacy_migration_data})}return pe.info("SDK::WalletService::handleUpdateToV2::No legacy or V1 items found to migrate"),void pe.info("SDK::WalletService::handleUpdateToV2:: You do not have a wallet stored on this device. Nothing to migrate.")}p=await this.localStorageService.getDecryptedV1PrivateKey(e),p&&this.assertValidDeviceKey(p),pe.info("SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration",{storageFormat:"v1",validPrivateKey:!!p});try{if(pe.log("Attempting to decrypt V1 items during migration..."),pe.log("getV1DecryptedSeedPhrase should be called with password and clientSalt:",{hasPassword:!!e,hasClientSalt:!!l}),h=await this.localStorageService.getV1DecryptedSeedPhrase(e,l),p=await this.localStorageService.getDecryptedV1PrivateKey(e),!h||!p)throw new M({message:"Failed to decrypt V1 items with provided password",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_decryption_failed});pe.info("SDK::WalletService::handleUpdateToV2::Successfully decrypted V1 items"),await this.localStorageService.claimLegacySeedFallbackFor(t)}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Failed to decrypt V1 items",e),new M({message:"Please enter the correct password.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_wrong_password})}}if(h&&p){pe.info("SDK::WalletService::handleUpdateToV2::Initiating wallet recovery for V2 migration"),pe.info("SDK::WalletService::handleUpdateToV2::Migration data prepared"),pe.info("SDK::WalletService::handleUpdateToV2::Seed phrase available:",!!h);const e=bs(p),s=await this.authService.getSignature({deviceAuthKeys:{publicKey:e,privateKey:p},walletId:t}),a=await this.request(Fa.signIn,{payload:{externalUserId:this.userId,message:s.message,signature:s.signature,clientAuthPubKey:e}}),n=await this.cipher.encrypt({data:p,encryptionKey:u.publicKey}),o=await this.cipher.doubleEncrypt({decryptedData:h,credentialsKeyPair:u,deviceKeyPair:{publicKey:e,privateKey:p}});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}]),pe.info("SDK::WalletService::handleUpdateToV2::Migration completed successfully",{timestamp:(new Date).toISOString(),duration:Date.now()-r,devicePublicKey:e.substring(0,16)+"...",migratedKeys:["EncryptedDevicePrivateKey","EncryptedStandardSeedPhrase"]}),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,(new Date).toISOString()),void await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,this.version)}throw new M({message:"Decrypted data required for migration is missing, operation cannot be completed.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_unknown_error})}catch(e){throw pe.error("SDK::WalletService::handleUpdateToV2::Migration failed",{timestamp:(new Date).toISOString(),duration:Date.now()-r,error:e instanceof Error?e.message:"Unknown error"}),await this.localStorageService.save(exports.V2KeyNames.LastMigratedAt,"never"),await this.localStorageService.save(exports.V2KeyNames.MigrationVersion,this.version),e}}async verifyAccess(e){try{const{readyForTransportSeedPhrase:t,sharesEncryptedWithWallabyPubKey:r,hasShares:s,signatureMessage:a,deviceAuthPublicKey:n}=await this.prepareWalletOperationAuth({authenticationOptions:e.authenticationOptions,walletId:e.walletId}),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 pe.error("SDK::WalletService::verifyAccess::Error occurred",e),e}}async clearDevice({walletId:e}){await this.localStorageService.clearLocalStorage(e)}async prepareWalletOperationAuth({authenticationOptions:e,walletId:t}){const{password:r,prfValue:s,user:a}=e,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!n)throw new 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=bs(i),d=await this.authService.getSignature({deviceAuthKeys:{publicKey:c,privateKey:i},walletId:t,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION}),l=d.wallabyAuthPubKey;if(!l)throw new M({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const u=[];let h;const p=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(p){const e=ka(p),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(n),wallabyPublicKey:l,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:a.clientSalt}});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 complete this request.",statusCode:404,errorCode:exports.ErrorResponseCodes.sdk_seed_phrase_not_found});const o=ka(e);h=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:h,sharesEncryptedWithWallabyPubKey:u.length?u:void 0,hasShares:u.length>0}}async convertToPasskey(e){let t=!1;try{const s=await this.localStorageService.fetch(exports.V2KeyNames.CredentialConversionInProgress),a=s?ka(s):void 0;(null==a?void 0:a.encryptedDevicePrivateKey)&&await this.localStorageService.save(exports.LocalStorageItems.EncryptedDevicePrivateKey,a.encryptedDevicePrivateKey),(null==a?void 0:a.walletId)===e.walletId&&pe.info("SDK::WalletService::convertToPasskey::resuming interrupted conversion");const n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey),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 u;if(!await this.authService.validatePassword({password:e.password,salt:d}))throw pe.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){pe.log("SDK::WalletService::convertToPasskey::Decrypting v2 device private key with password-derived key");const e=ka(n);u=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}else pe.log("SDK::WalletService::convertToPasskey::No encrypted device private key found, checking for v1 format"),u=await this.localStorageService.getDecryptedV1PrivateKey(e.password);if(!u)throw pe.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 h=bs(u);await this.localStorageService.save(exports.V2KeyNames.CredentialConversionInProgress,Object.assign({walletId:e.walletId},n?{encryptedDevicePrivateKey:n}:{}));const p=await this.passkeyService.addNewPasskey({deviceKeyPair:{publicKey:h,privateKey:u},getSignature:this.authService.getSignature.bind(this)});t=!0;const f=p.prfValue;if(!(f&&f instanceof Uint8Array&&0!==f.length))throw pe.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 y,g,w;if(pe.log("SDK::WalletService::convertToPasskey::Received authentication response",!!p),o&&n)try{y=await this.cipher.displayStoredData({storedEncryptedData:ka(o),encryptedDevicePrivateKey:ka(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){pe.error("SDK::WalletService::convertToPasskey::seed_decryption_error",e)}if(!y)try{y=await this.localStorageService.getV1DecryptedSeedPhrase(e.password,d)}catch(e){pe.error("SDK::WalletService::convertToPasskey::v1_seed_decryption_error",e)}if(i&&n)try{const t=ka(i);g=await this.cipher.displayStoredData({storedEncryptedData:t,encryptedDevicePrivateKey:ka(n),options:{authType:exports.AuthType.Password,password:e.password,salt:d}})}catch(e){pe.error("SDK::WalletService::convertToPasskey::primary_share_decryption_error",e)}if(c)try{const e=ka(c);w=await this.cipher.decrypt({cipherText:e,decryptionKey:l.privateKey})}catch(e){pe.error("SDK::WalletService::convertToPasskey::backup_share_decryption_error",e)}if(!y&&!(!!g||!!w))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(y&&!g)return pe.info("SDK::WalletService::convertToPasskey::No primary share found, importing wallet"),await this.handlers.handleImportWallet({publicKey:h,privateKey:u},{authenticationOptions:p,seedPhrase:y,storeSeedPhrase:!1,returnWalletOption:exports.ReturnWalletOption.ReturnOnlyEncryptedShares,walletId:e.walletId,reference:r.v4(),keyShareOptions:{threshold:2,numberOfKeyShares:3,numberOfSharesReturned:2,storeOneKeyShareWithWallaby:!0}}),await this.localStorageService.commitBatch([],[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId},{key:exports.V2KeyNames.CredentialConversionInProgress}]),pe.info("SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed"),{authentication:p,seedPhrase:y};const m=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Passkey,prfValue:f}),v=[];if(g){const t=await this.cipher.doubleEncrypt({decryptedData:g,credentialsKeyPair:m,deviceKeyPair:{publicKey:h,privateKey:u}}),r=await this.cipher.decrypt({cipherText:t,decryptionKey:m.privateKey});if((r?await this.cipher.decrypt({cipherText:ka(r),decryptionKey:u}):null)!==g)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(w){const t=await this.cipher.encrypt({data:w,encryptionKey:m.publicKey});v.push({key:exports.V2KeyNames.BackupDeviceKeyShare,value:t,walletId:e.walletId})}for(const e of v)await this.assertRoundTrip(e.value,m.privateKey,e.key);if(!y&&g){const t={publicKey:h,privateKey:u},{signature:r,message:s,wallabyAuthPubKey:a}=await this.authService.getSignature({deviceAuthKeys:t,walletId:e.walletId,passkeyChallengeType:exports.PasskeyChallengeType.AUTHENTICATION});if(!a)throw new M({message:"Failed to obtain wallaby auth public key.",statusCode:500,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const n=await this.cipher.encrypt({data:Ra(g,t.publicKey),encryptionKey:a}),o=await this.request(yd.retrieveSeedPhrase,{payload:{walletId:e.walletId,signature:r,message:s,clientAuthPubKey:t.publicKey,encryptedShares:[n]}});y=await this.cipher.decrypt({cipherText:o.encryptedSeed,decryptionKey:u})}if(!y)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 await this.localStorageService.commitBatch(v,[...o?[{key:exports.LocalStorageItems.EncryptedStandardSeedPhrase,walletId:e.walletId}]:[],{key:exports.V2KeyNames.CredentialConversionInProgress}]),o&&pe.info("SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey"),{authentication:p,seedPhrase:y}}catch(e){throw pe.error("SDK::WalletService::convertToPasskey::error",e),t||await this.localStorageService.delete(exports.V2KeyNames.CredentialConversionInProgress),e}}async assertRoundTrip(e,t,r){try{await this.cipher.decrypt({cipherText:e,decryptionKey:t})}catch(e){throw new 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})}}}Cd.RATE_LIMIT_MAX=5,Cd.RATE_LIMIT_WINDOW_MS=18e5,e._([kd("create"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"create",null),e._([kd("import"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"import",null),e._([kd("credential-rewrap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"changePassword",null),e._([kd("migrateToV2"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"handleUpdateToV2",null),e._([kd("credential-rewrap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Cd.prototype,"convertToPasskey",null);class xd extends fd{constructor(e,t={}){super(e,t),this.userId=e.userId,this.walletService=new Cd(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(yd.getTokenBalance,{payload:{address:e,assetSymbol:t,chainName:s,tokenStandard:r}})}catch(e){throw pe.error("SDK::WalletDataService::getTokenBalance::error",e),e}}async getMultiTokenBalances({walletId:e,tokensAndAddressesList:t}){try{if(!t.length)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(yd.getMultiTokenBalances,{payload:{assets:t,walletId:e}})}catch(e){throw pe.error("SDK::WalletDataService::getMultiTokenBalances::error",e),e}}async getWalletBalances({walletId:e}){try{if(!e)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(yd.getWalletBalances,{payload:{walletId:e}})}catch(e){throw pe.error("SDK::WalletDataService::getWalletBalances::error",e),e}}async getUserAssets({userId:e,queryOptions:t}){try{if(!e)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(yd.getUserAssets,{payload:{userId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getUserAssets::error",e),e}}async getUserWallets({userId:e,queryOptions:t}){try{return await this.request(yd.getUserWallets,{payload:{userId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getUserWallets::error",e),e}}async getWalletAssets({walletId:e,queryOptions:t}){try{if(void 0!==(null==t?void 0:t.search)&&t.search.length<3)throw new M({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(yd.getWalletAssets,{payload:{walletId:e},queryParams:t})}catch(e){throw pe.error("SDK::WalletDataService::getWalletAssets::error",e),e}}async addTokenToWallet({assetConfigId:e,walletId:t,userId:r,config:s,authenticationOptions:a}){try{if(!t)throw new 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(yd.addTokenToWallet,{payload:Object.assign({assetConfigId:e,walletId:t,userId:r||void 0,config:s},n)})}catch(e){throw pe.error("SDK::WalletDataService::addTokenToWallet::error",e),e}}async addNewChainAndTokenToWallet(e){const{authenticationOptions:t,walletId:r,userId:s,assetConfigId:a,blockchainName:n}=e;if(!(t&&r&&s&&a&&n))throw new 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 pe.error("SDK::WalletDataService::addNewChainAndTokenToWallet::error",e),e}}async updateAsset(t){var{configId:r,walletId:s}=t,a=e.b(t,["configId","walletId"]);try{if(!r||!s)throw new M({message:"Missing required parameters",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(yd.updateAsset,{payload:Object.assign({configId:r,walletId:s},a)})}catch(e){throw pe.error("SDK::WalletDataService::updateAsset::error",e),e}}}class Kd extends fd{constructor(e,t={}){super(e,t),this.getDecryptedPrivateKey=async e=>{const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return;const r=a.AES.decrypt(t,e).toString(a.enc.Utf8);return""!==r?r:void 0},this.decryptDevicePrivateKey=({encryptedPrivateKey:e,password:t})=>{const r=a.AES.decrypt(e,t).toString(a.enc.Utf8);return""!==r?r:void 0},this.auth=new Id(e,t)}async decryptSeedPhrase({password:e}){var t;const r=await this.auth.getUserSalt();if(!r)throw new Error("Salt could not be found");const s=`${r}${e}`,n=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase);if(!n)throw new Error("Seed phrase could not be found");const o=ka(a.AES.decrypt(n,s).toString(a.enc.Utf8)),i=this.decryptDevicePrivateKey({encryptedPrivateKey:null!==(t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey))&&void 0!==t?t:"",password:e});if(!i)throw pe.error("SDK::Utils::decryptSeedPhrase::devicePrivateKey: Device private key could not be decrypted"),new Error("Device private key could not be decrypted");return await Aa(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 pe.error("SDK::Utils::fetchFromEndpoint::error",e),Promise.reject(e)}}async validatePassword({password:e}){const t=await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);if(!t)return{valid:!1,message:"Could not locate client keys or seed phrase on this device."};try{const r=await this.auth.getUserSalt(),s=await this.cipher.getCredentialsKeyPair({authType:exports.AuthType.Password,password:e,salt:r});return await this.cipher.decrypt({cipherText:JSON.parse(t),decryptionKey:s.privateKey})?{valid:!0}:{valid:!1,message:"Password is incorrect"}}catch(e){return pe.error("SDK::Utils::validatePassword::error",e),{valid:!1,message:"Password is incorrect."}}}}class Od extends fd{constructor(e,t={}){super(e,t)}}class Nd extends fd{constructor(e,t={}){super(e,t),this.authService=new Id(e,t),this.walletService=new Cd(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({},md.getQuote),{fullPath:md.getQuote.fullPath(i)}),{payload:c})}catch(e){throw pe.error("SDK::Swap::getQuote::error",e),e}}async executeSwap({walletId:e,quoteId:t,authenticationOptions:r}){try{this.deviceAuthType===exports.AuthType.Password&&r.password&&await this.walletService.migrateToV2Safe({password:r.password,walletId:e});const{deviceAuthPublicKey:s,signatureMessage:a,readyForTransportSeedPhrase:n,sharesEncryptedWithWallabyPubKey:o,hasShares:i}=await this.prepareSwapAuth(r,e);let c;if(n)c=await this.request(Object.assign(Object.assign({},md.executeSwap),{fullPath:md.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({},md.executeSwap),{fullPath:md.executeSwap.fullPath}),{payload:{walletId:e,quoteId:t,message:a.message,signature:a.signature,clientAuthPubKey:s,encryptedShares:o}})}return c}catch(e){throw pe.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({},md.getSwaps),{fullPath:md.getSwaps.fullPath(r)}),{queryParams:t})}catch(e){throw pe.error("SDK::Swap::getSwaps::error",e),e}}async prepareSwapAuth(e,t){const{password:r,prfValue:s,user:a,clientSalt:n}=e,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=bs(d),u=await this.authService.getSignature({deviceAuthKeys:{publicKey:l,privateKey:d},passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0,walletId:t}),h=u.wallabyAuthPubKey;if(!h)throw new M({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const p=[];let f;const y=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(y){const e=ka(y),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:h,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}});p.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=ka(e);f=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:h,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:u,readyForTransportSeedPhrase:f,sharesEncryptedWithWallabyPubKey:p,hasShares:p.length>0})}}e._([kd("executeSwap"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Nd.prototype,"executeSwap",null);class Rd extends fd{constructor(e,t={}){super(e,t)}async getSupportedBlockchains(e){try{return(await this.request(gd.getSupportedBlockchains,{queryParams:void 0!==(null==e?void 0:e.supportSwaps)?{supportSwaps:e.supportSwaps}:void 0})).chains}catch(e){throw pe.error("SDK::System::getSupportedBlockchains::error",e),e}}validateContractAddress({blockchain:e,contractAddress:t,suiObjectId:r}){switch(e){case exports.BlockchainName.Algorand:case exports.BlockchainName.Bitcoin:throw new 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(gd.fetchTokenInfo,{queryParams:Object.assign({chainName:e,tokenContractAddress:a},n?{assetSymbol:n}:{})})}catch(e){throw pe.error("SDK::Wallet::fetchTokenInfo::error",e),e}}async getSupportedTokens(e){try{if(void 0!==(null==e?void 0:e.search)&&e.search.length<3)throw new M({message:"Search parameter must be at least 3 characters long",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_parameter});return await this.request(gd.getSupportedTokens,{queryParams:e})}catch(e){throw pe.error("SDK::System::getSupportedTokens::error",e),e}}async getUserData(e){try{return(await this.request(gd.getUserData,{payload:{userId:e}})).user}catch(e){throw pe.error("SDK::System::getUserData::error",e),e}}async getUserByExternalUserId(e){try{return(await this.request(gd.getUserByExternalUserId,{payload:{externalUserId:e}})).user}catch(e){throw pe.error("SDK::System::getUserByExternalUserId::error",e),e}}}class Dd extends fd{constructor(e,t={}){super(e,t),this.authService=new Id(e,t),this.walletService=new Cd(e,t),this.userId=e.userId}async estimateFee({originAddress:e,recipientAddress:t,amount:r,transactionType:s,token:a}){try{return await this.request(wd.estimateFee,{queryParams:Object.assign({chainName:a.chainName,originAddress:e,recipientAddress:t,amount:r,assetSymbol:a.symbol,transactionType:s},a.tokenStandard&&{tokenStandard:a.tokenStandard})})}catch(e){throw pe.error("SDK::Transactions::estimateFee::error",e),e}}async getTransactionStatus({transactionHash:e,reference:t,blockchain:r}){try{return await this.request(wd.getTransaction,{payload:{transactionHash:e,transactionReference:t,chain:r.toString().toUpperCase()}})}catch(e){throw pe.error("SDK::Transactions::getTransactionStatus::error",e),e}}async getTransactions(e){try{return await this.request(wd.getTransactions,{queryParams:e})}catch(e){throw pe.error("SDK::Transactions::getTransactions::error",e),e}}async getRestriction(e){try{const t=Boolean(e.assetId),r=Boolean(e.contractAddress&&e.blockchainName);if(!t&&!r)throw new M({message:"Either assetId or both contractAddress and blockchainName must be provided.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_missing_parameter});return await this.request(wd.restriction,{queryParams:Object.assign(Object.assign(Object.assign({fromAddress:e.fromAddress,toAddress:e.toAddress,amount:e.amount},e.assetId&&{assetId:e.assetId}),e.contractAddress&&{contractAddress:e.contractAddress}),e.blockchainName&&{blockchainName:e.blockchainName})})}catch(e){throw pe.error("SDK::Transactions::getRestriction::error",e),e}}async transfer({originAddress:e,recipientAddress:t,amount:s,assetId:a,walletId:n,reference: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:u,readyForTransportSeedPhrase:h,sharesEncryptedWithWallabyPubKey:p,hasShares:f}=await this.prepareTransactionAuth(i,n);let y;if(h)y=await this.request(wd.transfer,{payload:{walletId:n,message:u.message,signature:u.signature,clientAuthPubKey:l,encryptedSeed:h,originAddress:e,recipientAddress:t,assetId:a,amount:s,reference:o||r.v4(),memo:c,transactionType:d}});else{if(!f)throw new M({message:"No valid seed option found on this device.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_no_valid_seed_option});y=await this.request(wd.transferWithShares,{payload:{walletId:n,message:u.message,signature:u.signature,clientAuthPubKey:l,encryptedShares:p,originAddress:e,recipientAddress:t,assetId:a,amount:s,reference:o||r.v4(),memo:c,transactionType:d}})}return y}catch(e){throw pe.error("SDK::Transactions::transfer::error",e),e}}async createAllowance({authenticationOptions:e,walletId:t,ownerAddress:r,spenderAddress:s,amount:a,assetId:n,suiObjectId:o,contractAddress:i,chainName:c,assetSymbol:d,reference:l,memo:u,transactionType:h}){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:p,signatureMessage:f,readyForTransportSeedPhrase:y,sharesEncryptedWithWallabyPubKey:g,hasShares:w}=await this.prepareTransactionAuth(e,t),{message:m,signature:v}=f;if(!y&&!w)throw new Error("No valid seed option found on this device.");const S=Object.assign({message:m,signature:v,walletId:t,clientAuthPubKey:p,ownerAddress:r,spenderAddress:s,chainName:c,assetSymbol:d,amount:a,assetId:n,contractAddress:null!=i?i:o,reference:l,memo:u,transactionType:h},w?{encryptedShares:g}:{encryptedSeed:y});return await this.request(wd.createAllowance,{payload:S})}catch(e){throw pe.error("SDK::Transactions::createAllowance::error",e),e}}async getPendingTransactions({walletId:e,chainName:t}){try{return await this.request(wd.getPendingTransactions,{queryParams:{walletId:e,chainName:t}})}catch(e){throw pe.error("SDK::Transactions::getPendingTransactions::error",e),e}}async resolvePendingTransaction({id:e,choice:t,symbol:r,chainName:s,walletId:a,authenticationOptions:n}){try{this.deviceAuthType===exports.AuthType.Password&&n.password&&await this.walletService.migrateToV2Safe({password:n.password,walletId:a});const{deviceAuthPublicKey: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(wd.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 pe.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=bs(d),u=await this.authService.getSignature({deviceAuthKeys:{publicKey:l,privateKey:d},walletId:t,passkeyChallengeType:this.deviceAuthType===exports.AuthType.Passkey?exports.PasskeyChallengeType.AUTHENTICATION:void 0}),h=u.wallabyAuthPubKey;if(!h)throw new M({message:"Failed to obtain wallaby auth public key.",statusCode:400,errorCode:exports.ErrorResponseCodes.sdk_invalid_response});const p=[];let f;const y=await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare,{walletId:t});if(y){const e=ka(y),t=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:e,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:h,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}});p.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=ka(e);f=await this.cipher.prepareStoredDataForTransport({storedEncryptedData:a,encryptedDevicePrivateKey:JSON.parse(o),wallabyPublicKey:h,options:{authType:this.deviceAuthType,password:r,prfValue:s,salt:i}})}return Object.freeze({deviceAuthPublicKey:l,signatureMessage:u,readyForTransportSeedPhrase:f,sharesEncryptedWithWallabyPubKey:p,hasShares:p.length>0})}}e._([kd("transaction-restriction-message"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Dd.prototype,"getRestriction",null),e._([kd("transfer"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Dd.prototype,"transfer",null),e._([kd("createAllowance"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Dd.prototype,"createAllowance",null),e._([kd("confirmPendingTransaction"),e.a("design:type",Function),e.a("design:paramtypes",[Object]),e.a("design:returntype",Promise)],Dd.prototype,"resolvePendingTransaction",null);const Ld={mainnet:{genesisHash:"0x6fbd74e5e1d0a61d52ccfe9d4adaed16dd3a7caa37c6bc4d0c2fa12e8b2f4063",specVersion:7003003,transactionVersion:7,ss58Format:12,balanceDecimals:6},testnet:{genesisHash:"0x2ace05e703aa50b48c0ccccfc8b424f7aab9a1e2c424ed12e45d20b1e8ffd0d6",specVersion:7003003,transactionVersion:7,ss58Format:42,balanceDecimals:6}};function Bd(e){return"mainnet"===e||"testnet"===e}class Ud extends Error{constructor(e,t,r){super(r),this.name=e,this.reason=t}}class qd extends Ud{constructor(e,t){super("PolymeshDecodeError",e,t),this.reason=e}}class Md extends Ud{constructor(e,t){super("PolymeshVerifyError",e,t),this.reason=e}}const Vd=/^[0-9a-fA-F]*$/;function Fd(e){const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0)throw new Error("hexToU8a: hex string must have an even number of digits");if(!Vd.test(t))throw new Error("hexToU8a: invalid hex string");const r=new Uint8Array(t.length/2);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}function $d(e){return"0x"+Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}function Wd(...e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}function jd(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}const Gd=c.Bytes(32),Hd=c.Bytes(32),Yd=c.Bytes(16),zd=c.Bytes(32),Jd=c.u64,Xd=c.Enum({Id:Gd},[0]),Zd=c.Enum({Default:c._void,User:c.u64},[0,1]),Qd=c.Struct({did:Hd,kind:Zd}),el=c.Enum({SettleOnAffirmation:c._void},[0]),tl=c.Enum({Fungible:c.Struct({sender:Qd,receiver:Qd,assetId:Yd,amount:c.u128})},[0]),rl=c.Struct({fungible:c.u32,nonFungible:c.u32,offChain:c.u32}),sl=c.Struct({senderAssetCount:rl,receiverAssetCount:rl,offchainCount:c.u32});function al(e){return e.replace(/^0x/i,"").toLowerCase()}const nl={"5:1":{variant:"balances.transferWithMemo",codec:c.Struct({dest:Xd,value:c.compact,memo:c.Option(zd)})},"37:20":{variant:"settlement.addAndAffirmWithMediators",codec:c.Struct({venueId:c.Option(c.u64),settlementType:el,tradeDate:c.Option(c.u64),valueDate:c.Option(c.u64),legs:c.Vector(tl),portfolios:c.Vector(Qd),instructionMemo:c.Option(zd),mediators:c.Vector(Hd)})},"37:16":{variant:"settlement.affirmInstruction",codec:c.Struct({id:Jd,portfolios:c.Vector(Qd),numberOfAssets:c.Option(sl)})},"37:11":{variant:"settlement.affirmInstruction",codec:c.Struct({id:Jd,portfolios:c.Vector(Qd)})},"37:17":{variant:"settlement.rejectInstruction",codec:c.Struct({id:Jd,portfolio:Qd,numberOfAssets:c.Option(rl)})},"37:13":{variant:"settlement.rejectInstruction",codec:c.Struct({id:Jd,portfolio:Qd})}};function ol(e,t,r){if(!t.genesisHash)throw new qd("context-not-pinned","Polymesh chain context has no pinned genesisHash — see context.ts before using this in production");if(!r.genesisHash)throw new qd("genesis-hash-mismatch","No genesisHash was observed on the transaction under verification — cannot confirm which chain this call targets");if(al(r.genesisHash)!==al(t.genesisHash))throw new qd("genesis-hash-mismatch",`Observed genesisHash ${r.genesisHash} does not match the pinned genesisHash ${t.genesisHash} for this network`);if(r.specVersion!==t.specVersion)throw new qd("spec-version-mismatch",`Observed specVersion ${r.specVersion} does not match the pinned specVersion ${t.specVersion} this decoder was validated against`);if(void 0!==r.transactionVersion&&r.transactionVersion!==t.transactionVersion)throw new qd("transaction-version-mismatch",`Observed transactionVersion ${r.transactionVersion} does not match the pinned transactionVersion ${t.transactionVersion} this decoder was validated against`);let s;try{s=Fd(e)}catch(e){throw new qd("malformed",`Call bytes are not valid hex: ${e.message}`)}if(s.length<2)throw new qd("malformed","Call bytes are too short to contain a pallet/call index");const[a,n]=s,o=nl[`${a}:${n}`];if(!o)throw new qd("unrecognized-call",`Unrecognized or unsupported Polymesh call (pallet=${a}, call=${n})`);const i=s.slice(2);let c,d;try{c=o.codec.dec(i)}catch(e){throw new qd("malformed",`Failed to decode ${o.variant} args: ${e.message}`)}try{d=o.codec.enc(c)}catch(e){throw new qd("malformed",`Failed to re-encode decoded ${o.variant} args: ${e.message}`)}if(!jd(d,i))throw new qd("trailing-bytes",`Decoded ${o.variant} args do not round-trip to the original bytes — unrecognized trailing data`);return{variant:o.variant,args:c}}const il=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),cl=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),dl=new Uint32Array(32);function ll(e,t,r,s,a,n){const o=a[n],i=a[n+1];let c=dl[2*e],d=dl[2*e+1],l=dl[2*t],u=dl[2*t+1],h=dl[2*r],p=dl[2*r+1],f=dl[2*s],y=dl[2*s+1],g=or(c,l,o);var w,m;d=ir(g,d,u,i),c=0|g,({Dh:y,Dl:f}={Dh:y^d,Dl:f^c}),({Dh:y,Dl:f}={Dh:(m=f,m),Dl:(w=y,w)}),({h:p,l:h}=nr(p,h,y,f)),({Bh:u,Bl:l}={Bh:u^p,Bl:l^h}),({Bh:u,Bl:l}={Bh:tr(u,l,24),Bl:rr(u,l,24)}),dl[2*e]=c,dl[2*e+1]=d,dl[2*t]=l,dl[2*t+1]=u,dl[2*r]=h,dl[2*r+1]=p,dl[2*s]=f,dl[2*s+1]=y}function ul(e,t,r,s,a,n){const o=a[n],i=a[n+1];let c=dl[2*e],d=dl[2*e+1],l=dl[2*t],u=dl[2*t+1],h=dl[2*r],p=dl[2*r+1],f=dl[2*s],y=dl[2*s+1],g=or(c,l,o);d=ir(g,d,u,i),c=0|g,({Dh:y,Dl:f}={Dh:y^d,Dl:f^c}),({Dh:y,Dl:f}={Dh:tr(y,f,16),Dl:rr(y,f,16)}),({h:p,l:h}=nr(p,h,y,f)),({Bh:u,Bl:l}={Bh:u^p,Bl:l^h}),({Bh:u,Bl:l}={Bh:sr(u,l,63),Bl:ar(u,l,63)}),dl[2*e]=c,dl[2*e+1]=d,dl[2*t]=l,dl[2*t+1]=u,dl[2*r]=h,dl[2*r+1]=p,dl[2*s]=f,dl[2*s+1]=y}class hl extends Ze{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Ie(e),Ie(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=Ke(this.buffer)}update(e){Ce(this),Te(e=Je(e));const{blockLen:t,buffer:r,buffer32:s}=this,a=e.length,n=e.byteOffset,o=e.buffer;for(let i=0;i<a;){this.pos===t&&(Ue(s),this.compress(s,0,!1),Ue(s),this.pos=0);const c=Math.min(t-this.pos,a-i),d=n+i;if(c!==t||d%4||!(i+c<a))r.set(e.subarray(i,i+c),this.pos),this.pos+=c,this.length+=c,i+=c;else{const e=new Uint32Array(o,d,Math.floor((a-i)/4));Ue(e);for(let r=0;i+t<a;r+=s.length,i+=t)this.length+=t,this.compress(e,r,!1);Ue(e)}}return this}digestInto(e){Ce(this),xe(e,this);const{pos:t,buffer32:r}=this;this.finished=!0,Oe(this.buffer.subarray(t)),Ue(r),this.compress(r,0,!0),Ue(r);const s=Ke(e);this.get().forEach(((e,t)=>s[t]=Be(e)))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){const{buffer:t,length:r,finished:s,destroyed:a,outputLen:n,pos:o}=this;return e||(e=new this.constructor({dkLen:n})),e.set(...this.get()),e.buffer.set(t),e.destroyed=a,e.finished=s,e.length=r,e.pos=o,e.outputLen=n,e}clone(){return this._cloneInto()}}class pl extends hl{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|cl[0],this.v0h=0|cl[1],this.v1l=0|cl[2],this.v1h=0|cl[3],this.v2l=0|cl[4],this.v2h=0|cl[5],this.v3l=0|cl[6],this.v3h=0|cl[7],this.v4l=0|cl[8],this.v4h=0|cl[9],this.v5l=0|cl[10],this.v5h=0|cl[11],this.v6l=0|cl[12],this.v6h=0|cl[13],this.v7l=0|cl[14],this.v7h=0|cl[15],function(e,t={},r,s,a){if(Ie(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");const{key:n,salt:o,personalization:i}=t;if(void 0!==n&&(n.length<1||n.length>r))throw new Error("key length must be undefined or 1.."+r);if(void 0!==o&&o.length!==s)throw new Error("salt must be undefined or "+s);if(void 0!==i&&i.length!==a)throw new Error("personalization must be undefined or "+a)}(t,e,64,16,16);let{key:r,personalization:s,salt:a}=e,n=0;if(void 0!==r&&(r=Je(r),n=r.length),this.v0l^=this.outputLen|n<<8|65536|1<<24,void 0!==a){a=Je(a);const e=Ke(a);this.v4l^=Be(e[0]),this.v4h^=Be(e[1]),this.v5l^=Be(e[2]),this.v5h^=Be(e[3])}if(void 0!==s){s=Je(s);const e=Ke(s);this.v6l^=Be(e[0]),this.v6h^=Be(e[1]),this.v7l^=Be(e[2]),this.v7h^=Be(e[3])}if(void 0!==r){const e=new Uint8Array(this.blockLen);e.set(r),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:r,v1h:s,v2l:a,v2h:n,v3l:o,v3h:i,v4l:c,v4h:d,v5l:l,v5h:u,v6l:h,v6h:p,v7l:f,v7h:y}=this;return[e,t,r,s,a,n,o,i,c,d,l,u,h,p,f,y]}set(e,t,r,s,a,n,o,i,c,d,l,u,h,p,f,y){this.v0l=0|e,this.v0h=0|t,this.v1l=0|r,this.v1h=0|s,this.v2l=0|a,this.v2h=0|n,this.v3l=0|o,this.v3h=0|i,this.v4l=0|c,this.v4h=0|d,this.v5l=0|l,this.v5h=0|u,this.v6l=0|h,this.v6h=0|p,this.v7l=0|f,this.v7h=0|y}compress(e,t,r){this.get().forEach(((e,t)=>dl[t]=e)),dl.set(cl,16);let{h:s,l:a}=Xt(BigInt(this.length));dl[24]=cl[8]^a,dl[25]=cl[9]^s,r&&(dl[28]=~dl[28],dl[29]=~dl[29]);let n=0;const o=il;for(let r=0;r<12;r++)ll(0,4,8,12,e,t+2*o[n++]),ul(0,4,8,12,e,t+2*o[n++]),ll(1,5,9,13,e,t+2*o[n++]),ul(1,5,9,13,e,t+2*o[n++]),ll(2,6,10,14,e,t+2*o[n++]),ul(2,6,10,14,e,t+2*o[n++]),ll(3,7,11,15,e,t+2*o[n++]),ul(3,7,11,15,e,t+2*o[n++]),ll(0,5,10,15,e,t+2*o[n++]),ul(0,5,10,15,e,t+2*o[n++]),ll(1,6,11,12,e,t+2*o[n++]),ul(1,6,11,12,e,t+2*o[n++]),ll(2,7,8,13,e,t+2*o[n++]),ul(2,7,8,13,e,t+2*o[n++]),ll(3,4,9,14,e,t+2*o[n++]),ul(3,4,9,14,e,t+2*o[n++]);this.v0l^=dl[0]^dl[16],this.v0h^=dl[1]^dl[17],this.v1l^=dl[2]^dl[18],this.v1h^=dl[3]^dl[19],this.v2l^=dl[4]^dl[20],this.v2h^=dl[5]^dl[21],this.v3l^=dl[6]^dl[22],this.v3h^=dl[7]^dl[23],this.v4l^=dl[8]^dl[24],this.v4h^=dl[9]^dl[25],this.v5l^=dl[10]^dl[26],this.v5h^=dl[11]^dl[27],this.v6l^=dl[12]^dl[28],this.v6h^=dl[13]^dl[29],this.v7l^=dl[14]^dl[30],this.v7h^=dl[15]^dl[31],Oe(dl)}destroy(){this.destroyed=!0,Oe(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const fl=et((e=>new pl(e))),yl="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const gl=(new TextEncoder).encode("SS58PRE");function wl(e,t){if(32!==e.length)throw new Error("encodeAccountId32: expected a 32-byte public key");if(t<0||t>=64)throw new Error("encodeAccountId32: only single-byte ss58Format prefixes (0-63) are supported");const r=Wd(new Uint8Array([t]),e),s=function(e){return fl(Wd(gl,e),{dkLen:64}).slice(0,2)}(r);return function(e){let t=0;for(;t<e.length&&0===e[t];)t++;const r=[];for(let s=t;s<e.length;s++){let t=e[s];for(let e=0;e<r.length;e++)t+=r[e]<<8,r[e]=t%58,t=Math.floor(t/58);for(;t>0;)r.push(t%58),t=Math.floor(t/58)}let s=yl[0].repeat(t);for(let e=r.length-1;e>=0;e--)s+=yl[r[e]];return s}(Wd(r,s))}const ml=/^\d+$/,vl=/^\d+(?:\.\d+)?$/;function Sl(e){return e.replace(/^0x/i,"").replace(/-/g,"").toLowerCase()}function Al(e,t,r="amount"){if("string"!=typeof e||!vl.test(e))throw new Md("intent-field-malformed",`intent.${r} must be a non-negative decimal string in human-readable units (e.g. "1.5"), got ${JSON.stringify(e)}`);const[s,a=""]=e.split(".");if(a.length>t)throw new Md("intent-field-malformed",`intent.${r} "${e}" has ${a.length} decimal places, more than this chain's ${t} — refusing to round a verification input`);return BigInt(s+a.padEnd(t,"0"))}function bl(e,t,r){const s=e[t];if(!s)throw new Md("intent-field-missing",`${r}: intent.${String(t)} is required to verify this call — refusing to report a call as verified with this field unchecked`);return s}function El(e,t,r){const s=[],{ss58Format:a,balanceDecimals:n}=r;switch(e.variant){case"balances.transferWithMemo":{const{args:r}=e,o=bl(t,"recipientAddress",e.variant),i=wl(r.dest.value,a);s.push({field:"destination",enforced:!0,matched:i===o,expected:t.recipientAddress,actual:i});const c=Al(bl(t,"amount",e.variant),n);s.push({field:"amount",enforced:!0,matched:BigInt(r.value)===c,expected:c.toString(),actual:String(r.value)});const d=bl(t,"assetSymbol",e.variant),l="POLYX";s.push({field:"asset",enforced:!0,matched:d.toUpperCase()===l,expected:d,actual:l});break}case"settlement.addAndAffirmWithMediators":{const{args:r}=e;if(1!==r.legs.length)throw new Md("unsupported-call-shape",`settlement.addAndAffirmWithMediators carries ${r.legs.length} legs; an Intent describes a single transfer, so this call shape cannot be verified`);const a=r.legs[0].value;s.push({field:"destination",enforced:!1,actual:`did:${$d(a.receiver.did)}`});const o=Al(bl(t,"amount",e.variant),n);s.push({field:"amount",enforced:!0,matched:BigInt(a.amount)===o,expected:o.toString(),actual:String(a.amount)});const i=bl(t,"assetId",e.variant),c=$d(a.assetId);s.push({field:"asset",enforced:!0,matched:Sl(c)===Sl(i),expected:i,actual:c});break}case"settlement.affirmInstruction":case"settlement.rejectInstruction":{const{args:r}=e,a=function(e,t){if("string"!=typeof e||!ml.test(e))throw new Md("intent-field-malformed",`intent.${t} must be a plain base-10 integer string, got ${JSON.stringify(e)}`);return BigInt(e)}(bl(t,"instructionId",e.variant),"instructionId");s.push({field:"instructionId",enforced:!0,matched:BigInt(r.id)===a,expected:a.toString(),actual:String(r.id)});const n=bl(t,"instructionDecision",e.variant),o="settlement.affirmInstruction"===e.variant?"approve":"deny";s.push({field:"instructionDecision",enforced:!0,matched:o===n,expected:n,actual:o});break}default:throw new Md("unsupported-call-shape",`No verification rules are defined for Polymesh call variant "${e.variant}"`)}const o=s.filter((e=>e.enforced));if(0===o.length)throw new Md("no-enforced-fields",`${e.variant} produced no enforced fields — refusing to report a call as verified with nothing checked`);return{chainName:exports.BlockchainName.Polymesh,callVariant:e.variant,fields:s,verified:o.every((e=>!0===e.matched))}}function _l(e,t,r,s){if(!Bd(r))throw new Md("intent-field-malformed",`Unknown Polymesh network ${JSON.stringify(r)} — expected "mainnet" or "testnet"`);const a=Ld[r];return El(ol(e,a,s),t,a)}const kl=Object.freeze(Object.defineProperty({__proto__:null,POLYMESH_CONTEXT:Ld,PolymeshDecodeError:qd,PolymeshVerificationError:Ud,PolymeshVerifyError:Md,decimalAmountToBaseUnits:Al,decodePolymeshCall:ol,isPolymeshNetwork:Bd,verifyPolymeshCallAgainstIntent:_l,verifyPolymeshIntent:El},Symbol.toStringTag,{value:"Module"}));const Il=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function Tl(e){if(null===e)return"null";if(void 0===e)return"undefined";if(!0===e||!1===e)return"boolean";const t=typeof e;if("string"===t||"number"===t||"bigint"===t||"symbol"===t)return t;if("function"===t)return"Function";if(Array.isArray(e))return"Array";if(e instanceof Uint8Array)return"Uint8Array";if(e.constructor===Object)return"Object";const r=function(e){const t=Object.prototype.toString.call(e).slice(8,-1);if(Il.includes(t))return t;return}(e);return r||"Object"}class Pl{constructor(e,t,r){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}}Pl.uint=new Pl(0,"uint",!0),Pl.negint=new Pl(1,"negint",!0),Pl.bytes=new Pl(2,"bytes",!0),Pl.string=new Pl(3,"string",!0),Pl.array=new Pl(4,"array",!1),Pl.map=new Pl(5,"map",!1),Pl.tag=new Pl(6,"tag",!1),Pl.float=new Pl(7,"float",!0),Pl.false=new Pl(7,"false",!0),Pl.true=new Pl(7,"true",!0),Pl.null=new Pl(7,"null",!0),Pl.undefined=new Pl(7,"undefined",!0),Pl.break=new Pl(7,"break",!0);class Cl{constructor(e,t,r){this.type=e,this.value=t,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}}const xl=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&"function"==typeof globalThis.Buffer.isBuffer,Kl=new TextEncoder;function Ol(e){return xl&&globalThis.Buffer.isBuffer(e)}function Nl(e){return e instanceof Uint8Array?Ol(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}const Rl=xl?e=>e.length>=24?globalThis.Buffer.from(e):Ml(e):e=>e.length>=200?Kl.encode(e):Ml(e),Dl=e=>Uint8Array.from(e),Ll=xl?(e,t,r)=>Ol(e)?new Uint8Array(e.subarray(t,r)):e.slice(t,r):(e,t,r)=>e.slice(t,r),Bl=xl?(e,t)=>(e=e.map((e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e))),Nl(globalThis.Buffer.concat(e,t))):(e,t)=>{const r=new Uint8Array(t);let s=0;for(let t of e)s+t.length>r.length&&(t=t.subarray(0,r.length-s)),r.set(t,s),s+=t.length;return r},Ul=xl?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function ql(e,t){if(Ol(e)&&Ol(t))return e.compare(t);for(let r=0;r<e.length;r++)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return 0}function Ml(e){const t=[];let r=0;for(let s=0;s<e.length;s++){let a=e.charCodeAt(s);a<128?t[r++]=a:a<2048?(t[r++]=a>>6|192,t[r++]=63&a|128):55296==(64512&a)&&s+1<e.length&&56320==(64512&e.charCodeAt(s+1))?(a=65536+((1023&a)<<10)+(1023&e.charCodeAt(++s)),t[r++]=a>>18|240,t[r++]=a>>12&63|128,t[r++]=a>>6&63|128,t[r++]=63&a|128):(a>=55296&&a<=57343&&(a=65533),t[r++]=a>>12|224,t[r++]=a>>6&63|128,t[r++]=63&a|128)}return t}class Vl{constructor(e=256){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),null!==this._initReuseChunk&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}pushByte(e){let t=this.chunks[this.chunks.length-1];this.cursor>this.maxCursor&&(t=Ul(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,null===this._initReuseChunk&&(this._initReuseChunk=t));t[t.length-(this.maxCursor-this.cursor)-1]=e,this.cursor++}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){const r=t.length-(this.maxCursor-this.cursor)-1;t.set(e,r)}else{if(t){const e=t.length-(this.maxCursor-this.cursor)-1;e<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,e),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Ul(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,null===this._initReuseChunk&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(1===this.chunks.length){const r=this.chunks[0];e&&this.cursor>r.length/2?(t=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Ll(r,0,this.cursor)}else t=Bl(this.chunks,this.cursor);return e&&this.reset(),t}}class Fl{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}pushByte(e){if(this.cursor>=this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest[this.cursor++]=e}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){const t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}}const $l="CBOR decode error:",Wl="CBOR encode error:";function jl(e,t,r){if(e.length-t<r)throw new Error(`${$l} not enough data for type`)}const Gl=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Hl(e,t,r){jl(e,t,1);const s=e[t];if(!0===r.strict&&s<Gl[0])throw new Error(`${$l} integer encoded in more bytes than necessary (strict decode)`);return s}function Yl(e,t,r){jl(e,t,2);const s=e[t]<<8|e[t+1];if(!0===r.strict&&s<Gl[1])throw new Error(`${$l} integer encoded in more bytes than necessary (strict decode)`);return s}function zl(e,t,r){jl(e,t,4);const s=16777216*e[t]+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(!0===r.strict&&s<Gl[2])throw new Error(`${$l} integer encoded in more bytes than necessary (strict decode)`);return s}function Jl(e,t,r){jl(e,t,8);const s=16777216*e[t]+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],a=16777216*e[t+4]+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],n=(BigInt(s)<<BigInt(32))+BigInt(a);if(!0===r.strict&&n<Gl[3])throw new Error(`${$l} integer encoded in more bytes than necessary (strict decode)`);if(n<=Number.MAX_SAFE_INTEGER)return Number(n);if(!0===r.allowBigInt)return n;throw new Error(`${$l} integers outside of the safe integer range are not supported`)}function Xl(e,t){return Zl(e,0,t.value)}function Zl(e,t,r){if(r<Gl[0]){const s=Number(r);e.pushByte(t|s)}else if(r<Gl[1]){const s=Number(r);e.push([24|t,s])}else if(r<Gl[2]){const s=Number(r);e.push([25|t,s>>>8,255&s])}else if(r<Gl[3]){const s=Number(r);e.push([26|t,s>>>24&255,s>>>16&255,s>>>8&255,255&s])}else{const s=BigInt(r);if(!(s<Gl[4]))throw new Error(`${$l} encountered BigInt larger than allowable range`);{const r=[27|t,0,0,0,0,0,0,0];let a=Number(s&BigInt(4294967295)),n=Number(s>>BigInt(32)&BigInt(4294967295));r[8]=255&a,a>>=8,r[7]=255&a,a>>=8,r[6]=255&a,a>>=8,r[5]=255&a,r[4]=255&n,n>>=8,r[3]=255&n,n>>=8,r[2]=255&n,n>>=8,r[1]=255&n,e.push(r)}}}Xl.encodedSize=function(e){return Zl.encodedSize(e.value)},Zl.encodedSize=function(e){return e<Gl[0]?1:e<Gl[1]?2:e<Gl[2]?3:e<Gl[3]?5:9},Xl.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};const Ql=BigInt(-1),eu=BigInt(1);function tu(e,t){const r=t.value,s="bigint"==typeof r?r*Ql-eu:-1*r-1;Zl(e,t.type.majorEncoded,s)}function ru(e,t,r,s){jl(e,t,r+s);const a=e.slice(t+r,t+r+s);return new Cl(Pl.bytes,a,r+s)}function su(e,t,r,s){return ru(e,t,1,r)}function au(e){return void 0===e.encodedBytes&&(e.encodedBytes=Pl.equals(e.type,Pl.string)?Rl(e.value):e.value),e.encodedBytes}function nu(e,t){const r=au(t);Zl(e,t.type.majorEncoded,r.length),e.push(r)}tu.encodedSize=function(e){const t=e.value,r="bigint"==typeof t?t*Ql-eu:-1*t-1;return r<Gl[0]?1:r<Gl[1]?2:r<Gl[2]?3:r<Gl[3]?5:9},tu.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0},nu.encodedSize=function(e){const t=au(e);return Zl.encodedSize(t.length)+t.length},nu.compareTokens=function(e,t){return r=au(e),s=au(t),r.length<s.length?-1:r.length>s.length?1:ql(r,s);var r,s};const ou=new TextDecoder;function iu(e,t,r,s,a){const n=r+s;jl(e,t,n);const o=new Cl(Pl.string,function(e,t,r){if(r-t<32){let s="";for(let a=t;a<r;a++){const n=e[a];if(128&n)return ou.decode(e.subarray(t,r));s+=String.fromCharCode(n)}return s}return ou.decode(e.subarray(t,r))}(e,t+r,t+n),n);return!0===a.retainStringBytes&&(o.byteValue=e.slice(t+r,t+n)),o}function cu(e,t,r,s){return iu(e,t,1,r,s)}const du=nu;function lu(e,t,r,s){return new Cl(Pl.array,s,r)}function uu(e,t,r,s){return lu(0,0,1,r)}function hu(e,t){Zl(e,Pl.array.majorEncoded,t.value)}function pu(e,t,r,s){return new Cl(Pl.map,s,r)}function fu(e,t,r,s){return pu(0,0,1,r)}function yu(e,t){Zl(e,Pl.map.majorEncoded,t.value)}function gu(e,t,r,s){return new Cl(Pl.tag,r,1)}function wu(e,t){Zl(e,Pl.tag.majorEncoded,t.value)}hu.compareTokens=Xl.compareTokens,hu.encodedSize=function(e){return Zl.encodedSize(e.value)},yu.compareTokens=Xl.compareTokens,yu.encodedSize=function(e){return Zl.encodedSize(e.value)},wu.compareTokens=Xl.compareTokens,wu.encodedSize=function(e){return Zl.encodedSize(e.value)};function mu(e,t,r){if(r){if(!1===r.allowNaN&&Number.isNaN(e))throw new Error(`${$l} NaN values are not supported`);if(!1===r.allowInfinity&&(e===1/0||e===-1/0))throw new Error(`${$l} Infinity values are not supported`)}return new Cl(Pl.float,e,t)}function vu(e,t,r){const s=t.value;if(!1===s)e.pushByte(20|Pl.float.majorEncoded);else if(!0===s)e.pushByte(21|Pl.float.majorEncoded);else if(null===s)e.pushByte(22|Pl.float.majorEncoded);else if(void 0===s)e.pushByte(23|Pl.float.majorEncoded);else{let t,a=!1;r&&!0===r.float64||(Eu(s),t=_u(bu,1),s===t||Number.isNaN(s)?(bu[0]=249,e.push(bu.slice(0,3)),a=!0):(ku(s),t=Iu(bu,1),s===t&&(bu[0]=250,e.push(bu.slice(0,5)),a=!0))),a||(Tu(s),t=Pu(bu,1),bu[0]=251,e.push(bu.slice(0,9)))}}vu.encodedSize=function(e,t){const r=e.value;if(!1===r||!0===r||null==r)return 1;if(!t||!0!==t.float64){Eu(r);let e=_u(bu,1);if(r===e||Number.isNaN(r))return 3;if(ku(r),e=Iu(bu,1),r===e)return 5}return 9};const Su=new ArrayBuffer(9),Au=new DataView(Su,1),bu=new Uint8Array(Su,0);function Eu(e){if(e===1/0)Au.setUint16(0,31744,!1);else if(e===-1/0)Au.setUint16(0,64512,!1);else if(Number.isNaN(e))Au.setUint16(0,32256,!1);else{Au.setFloat32(0,e);const t=Au.getUint32(0),r=(2139095040&t)>>23,s=8388607&t;if(255===r)Au.setUint16(0,31744,!1);else if(0===r)Au.setUint16(0,(2147483648&t)>>16|s>>13,!1);else{const e=r-127;e<-24?Au.setUint16(0,0):e<-14?Au.setUint16(0,(2147483648&t)>>16|1<<24+e,!1):Au.setUint16(0,(2147483648&t)>>16|e+15<<10|s>>13,!1)}}}function _u(e,t){if(e.length-t<2)throw new Error(`${$l} not enough data for float16`);const r=(e[t]<<8)+e[t+1];if(31744===r)return 1/0;if(64512===r)return-1/0;if(32256===r)return NaN;const s=r>>10&31,a=1023&r;let n;return n=0===s?a*2**-24:31!==s?(a+1024)*2**(s-25):0===a?1/0:NaN,32768&r?-n:n}function ku(e){Au.setFloat32(0,e,!1)}function Iu(e,t){if(e.length-t<4)throw new Error(`${$l} not enough data for float32`);const r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,4).getFloat32(0,!1)}function Tu(e){Au.setFloat64(0,e,!1)}function Pu(e,t){if(e.length-t<8)throw new Error(`${$l} not enough data for float64`);const r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,8).getFloat64(0,!1)}function Cu(e,t){const r=e,s=!0===t?.float64,a=s?r._keyBytesFloat64:r._keyBytes;if(void 0!==a)return a;const n=function(e,t){const r=e.value;if(!1===r)return Uint8Array.of(20|Pl.float.majorEncoded);if(!0===r)return Uint8Array.of(21|Pl.float.majorEncoded);if(null===r)return Uint8Array.of(22|Pl.float.majorEncoded);if(void 0===r)return Uint8Array.of(23|Pl.float.majorEncoded);if(!t){if(Eu(r),r===_u(bu,1)||Number.isNaN(r))return bu[0]=249,bu.slice(0,3);if(ku(r),r===Iu(bu,1))return bu[0]=250,bu.slice(0,5)}return Tu(r),bu[0]=251,bu.slice(0,9)}(e,s);return s?r._keyBytesFloat64=n:r._keyBytes=n,n}function xu(e,t,r){throw new Error(`${$l} encountered invalid minor (${r}) for major ${e[t]>>>5}`)}function Ku(e){return()=>{throw new Error(`${$l} ${e}`)}}vu.compareTokens=function(e,t,r){const s=Cu(e,r),a=Cu(t,r);return s.length!==a.length?s.length<a.length?-1:1:ql(s,a)};const Ou=[];for(let e=0;e<=23;e++)Ou[e]=xu;Ou[24]=function(e,t,r,s){return new Cl(Pl.uint,Hl(e,t+1,s),2)},Ou[25]=function(e,t,r,s){return new Cl(Pl.uint,Yl(e,t+1,s),3)},Ou[26]=function(e,t,r,s){return new Cl(Pl.uint,zl(e,t+1,s),5)},Ou[27]=function(e,t,r,s){return new Cl(Pl.uint,Jl(e,t+1,s),9)},Ou[28]=xu,Ou[29]=xu,Ou[30]=xu,Ou[31]=xu;for(let e=32;e<=55;e++)Ou[e]=xu;Ou[56]=function(e,t,r,s){return new Cl(Pl.negint,-1-Hl(e,t+1,s),2)},Ou[57]=function(e,t,r,s){return new Cl(Pl.negint,-1-Yl(e,t+1,s),3)},Ou[58]=function(e,t,r,s){return new Cl(Pl.negint,-1-zl(e,t+1,s),5)},Ou[59]=function(e,t,r,s){const a=Jl(e,t+1,s);if("bigint"!=typeof a){const e=-1-a;if(e>=Number.MIN_SAFE_INTEGER)return new Cl(Pl.negint,e,9)}if(!0!==s.allowBigInt)throw new Error(`${$l} integers outside of the safe integer range are not supported`);return new Cl(Pl.negint,Ql-BigInt(a),9)},Ou[60]=xu,Ou[61]=xu,Ou[62]=xu,Ou[63]=xu;for(let e=64;e<=87;e++)Ou[e]=su;Ou[88]=function(e,t,r,s){return ru(e,t,2,Hl(e,t+1,s))},Ou[89]=function(e,t,r,s){return ru(e,t,3,Yl(e,t+1,s))},Ou[90]=function(e,t,r,s){return ru(e,t,5,zl(e,t+1,s))},Ou[91]=function(e,t,r,s){const a=Jl(e,t+1,s);if("bigint"==typeof a)throw new Error(`${$l} 64-bit integer bytes lengths not supported`);return ru(e,t,9,a)},Ou[92]=xu,Ou[93]=xu,Ou[94]=xu,Ou[95]=Ku("indefinite length bytes/strings are not supported");for(let e=96;e<=119;e++)Ou[e]=cu;Ou[120]=function(e,t,r,s){return iu(e,t,2,Hl(e,t+1,s),s)},Ou[121]=function(e,t,r,s){return iu(e,t,3,Yl(e,t+1,s),s)},Ou[122]=function(e,t,r,s){return iu(e,t,5,zl(e,t+1,s),s)},Ou[123]=function(e,t,r,s){const a=Jl(e,t+1,s);if("bigint"==typeof a)throw new Error(`${$l} 64-bit integer string lengths not supported`);return iu(e,t,9,a,s)},Ou[124]=xu,Ou[125]=xu,Ou[126]=xu,Ou[127]=Ku("indefinite length bytes/strings are not supported");for(let e=128;e<=151;e++)Ou[e]=uu;Ou[152]=function(e,t,r,s){return lu(0,0,2,Hl(e,t+1,s))},Ou[153]=function(e,t,r,s){return lu(0,0,3,Yl(e,t+1,s))},Ou[154]=function(e,t,r,s){return lu(0,0,5,zl(e,t+1,s))},Ou[155]=function(e,t,r,s){const a=Jl(e,t+1,s);if("bigint"==typeof a)throw new Error(`${$l} 64-bit integer array lengths not supported`);return lu(0,0,9,a)},Ou[156]=xu,Ou[157]=xu,Ou[158]=xu,Ou[159]=function(e,t,r,s){if(!1===s.allowIndefinite)throw new Error(`${$l} indefinite length items not allowed`);return lu(0,0,1,1/0)};for(let e=160;e<=183;e++)Ou[e]=fu;Ou[184]=function(e,t,r,s){return pu(0,0,2,Hl(e,t+1,s))},Ou[185]=function(e,t,r,s){return pu(0,0,3,Yl(e,t+1,s))},Ou[186]=function(e,t,r,s){return pu(0,0,5,zl(e,t+1,s))},Ou[187]=function(e,t,r,s){const a=Jl(e,t+1,s);if("bigint"==typeof a)throw new Error(`${$l} 64-bit integer map lengths not supported`);return pu(0,0,9,a)},Ou[188]=xu,Ou[189]=xu,Ou[190]=xu,Ou[191]=function(e,t,r,s){if(!1===s.allowIndefinite)throw new Error(`${$l} indefinite length items not allowed`);return pu(0,0,1,1/0)};for(let e=192;e<=215;e++)Ou[e]=gu;Ou[216]=function(e,t,r,s){return new Cl(Pl.tag,Hl(e,t+1,s),2)},Ou[217]=function(e,t,r,s){return new Cl(Pl.tag,Yl(e,t+1,s),3)},Ou[218]=function(e,t,r,s){return new Cl(Pl.tag,zl(e,t+1,s),5)},Ou[219]=function(e,t,r,s){return new Cl(Pl.tag,Jl(e,t+1,s),9)},Ou[220]=xu,Ou[221]=xu,Ou[222]=xu,Ou[223]=xu;for(let e=224;e<=243;e++)Ou[e]=Ku("simple values are not supported");Ou[244]=xu,Ou[245]=xu,Ou[246]=xu,Ou[247]=function(e,t,r,s){if(!1===s.allowUndefined)throw new Error(`${$l} undefined values are not supported`);return!0===s.coerceUndefinedToNull?new Cl(Pl.null,null,1):new Cl(Pl.undefined,void 0,1)},Ou[248]=Ku("simple values are not supported"),Ou[249]=function(e,t,r,s){return mu(_u(e,t+1),3,s)},Ou[250]=function(e,t,r,s){return mu(Iu(e,t+1),5,s)},Ou[251]=function(e,t,r,s){return mu(Pu(e,t+1),9,s)},Ou[252]=xu,Ou[253]=xu,Ou[254]=xu,Ou[255]=function(e,t,r,s){if(!1===s.allowIndefinite)throw new Error(`${$l} indefinite length items not allowed`);return new Cl(Pl.break,void 0,1)};const Nu=[];for(let e=0;e<24;e++)Nu[e]=new Cl(Pl.uint,e,1);for(let e=-1;e>=-24;e--)Nu[31-e]=new Cl(Pl.negint,e,1);Nu[64]=new Cl(Pl.bytes,new Uint8Array(0),1),Nu[96]=new Cl(Pl.string,"",1),Nu[128]=new Cl(Pl.array,0,1),Nu[160]=new Cl(Pl.map,0,1),Nu[244]=new Cl(Pl.false,!1,1),Nu[245]=new Cl(Pl.true,!0,1),Nu[246]=new Cl(Pl.null,null,1);const Ru={float64:!1,mapSorter:Vu,quickEncodeToken:function(e){switch(e.type){case Pl.false:return Dl([244]);case Pl.true:return Dl([245]);case Pl.null:return Dl([246]);case Pl.bytes:return e.value.length?void 0:Dl([64]);case Pl.string:return""===e.value?Dl([96]):void 0;case Pl.array:return 0===e.value?Dl([128]):void 0;case Pl.map:return 0===e.value?Dl([160]):void 0;case Pl.uint:return e.value<24?Dl([Number(e.value)]):void 0;case Pl.negint:if(e.value>=-24)return Dl([31-Number(e.value)])}}};const Du=function(){const e=[];return e[Pl.uint.major]=Xl,e[Pl.negint.major]=tu,e[Pl.bytes.major]=nu,e[Pl.string.major]=du,e[Pl.array.major]=hu,e[Pl.map.major]=yu,e[Pl.tag.major]=wu,e[Pl.float.major]=vu,e}(),Lu=new Vl;class Bu{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do{if(t.obj===e)return!0}while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Wl} object contains circular references`);return new Bu(t,e)}}const Uu={null:new Cl(Pl.null,null),undefined:new Cl(Pl.undefined,void 0),true:new Cl(Pl.true,!0),false:new Cl(Pl.false,!1),emptyArray:new Cl(Pl.array,0),emptyMap:new Cl(Pl.map,0)},qu={number:(e,t,r,s)=>Number.isInteger(e)&&Number.isSafeInteger(e)?new Cl(e>=0?Pl.uint:Pl.negint,e):new Cl(Pl.float,e),bigint:(e,t,r,s)=>e>=BigInt(0)?new Cl(Pl.uint,e):new Cl(Pl.negint,e),Uint8Array:(e,t,r,s)=>new Cl(Pl.bytes,e),string:(e,t,r,s)=>new Cl(Pl.string,e),boolean:(e,t,r,s)=>e?Uu.true:Uu.false,null:(e,t,r,s)=>Uu.null,undefined:(e,t,r,s)=>Uu.undefined,ArrayBuffer:(e,t,r,s)=>new Cl(Pl.bytes,new Uint8Array(e)),DataView:(e,t,r,s)=>new Cl(Pl.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),Array(e,t,r,s){if(!e.length)return!0===r.addBreakTokens?[Uu.emptyArray,new Cl(Pl.break)]:Uu.emptyArray;s=Bu.createCheck(s,e);const a=[];let n=0;for(const t of e)a[n++]=Mu(t,r,s);return r.addBreakTokens?[new Cl(Pl.array,e.length),a,new Cl(Pl.break)]:[new Cl(Pl.array,e.length),a]},Object(e,t,r,s){const a="Object"!==t,n=a?e.keys():Object.keys(e),o=a?e.size:n.length;let i;if(o){i=new Array(o),s=Bu.createCheck(s,e);const t=!a&&r.ignoreUndefinedProperties;let c=0;for(const o of n){const n=a?e.get(o):e[o];t&&void 0===n||(i[c++]=[Mu(o,r,s),Mu(n,r,s)])}c<o&&(i.length=c)}return i?.length?(function(e,t){const r=t.mapSorter;r&&e.sort(((e,s)=>r(e,s,t)))}(i,r),r.addBreakTokens?[new Cl(Pl.map,i.length),i,new Cl(Pl.break)]:[new Cl(Pl.map,i.length),i]):!0===r.addBreakTokens?[Uu.emptyMap,new Cl(Pl.break)]:Uu.emptyMap},Tagged:(e,t,r,s)=>[new Cl(Pl.tag,e.tag),Mu(e.value,r,s)]};qu.Map=qu.Object,qu.Buffer=qu.Uint8Array;for(const e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))qu[`${e}Array`]=qu.DataView;function Mu(e,t={},r){const s=Tl(e),a=t&&t.typeEncoders&&t.typeEncoders[s]||qu[s];if("function"==typeof a){const n=a(e,s,t,r);if(null!=n)return n}const n=qu[s];if(!n)throw new Error(`${Wl} unsupported type: ${s}`);return n(e,s,t,r)}function Vu(e,t,r){const s=Array.isArray(e[0])?e[0][0]:e[0],a=Array.isArray(t[0])?t[0][0]:t[0];if(s.type.major!==a.type.major)return s.type.compare(a.type);const n=s.type.major,o=Du[n].compareTokens(s,a,r);return 0===o&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Fu(e,t,r,s){if(Array.isArray(t))for(const a of t)Fu(e,a,r,s);else r[t.type.major](e,t,s)}const $u=Pl.uint.majorEncoded,Wu=Pl.negint.majorEncoded,ju=Pl.bytes.majorEncoded,Gu=Pl.string.majorEncoded,Hu=Pl.array.majorEncoded,Yu=Pl.map.majorEncoded,zu=20|Pl.float.majorEncoded,Ju=21|Pl.float.majorEncoded,Xu=22|Pl.float.majorEncoded,Zu=23|Pl.float.majorEncoded,Qu=BigInt(-1),eh=BigInt(1);function th(e,t,r){r<24?e.pushByte(t|Number(r)):Zl(e,t,r)}function rh(e,t,r,s){const a=Tl(t),n=r.typeEncoders&&r.typeEncoders[a];if(n){const o=n(t,a,r,s);if(null!=o)return void Fu(e,o,Du,r)}switch(a){case"null":return void e.pushByte(Xu);case"undefined":return void e.pushByte(Zu);case"boolean":return void e.pushByte(t?Ju:zu);case"number":return void(Number.isInteger(t)&&Number.isSafeInteger(t)?t>=0?th(e,$u,t):th(e,Wu,-1*t-1):vu(e,new Cl(Pl.float,t),r));case"bigint":return void(t>=BigInt(0)?th(e,$u,t):th(e,Wu,t*Qu-eh));case"string":{const r=Rl(t);return th(e,Gu,r.length),void e.push(r)}case"Uint8Array":return th(e,ju,t.length),void e.push(t);case"Array":if(!t.length)return void e.pushByte(Hu);s=Bu.createCheck(s,t),th(e,Hu,t.length);for(const a of t)rh(e,a,r,s);return;case"Object":case"Map":if(r.mapSorter===Vu)!function(e,t,r,s,a){const n="Map"===r,o=n?t.keys():Object.keys(t),i=n?t.size:o.length;if(!i)return void e.pushByte(Yu);a=Bu.createCheck(a,t);const c=!n&&s.ignoreUndefinedProperties,d=new Array(i);let l=0;for(const e of o){const r=n?t.get(e):t[e];c&&void 0===r||(d[l++]=[Mu(e,s,a),r])}if(0!==l){l<i&&(d.length=l),d.sort(((e,t)=>Vu(e,t,s))),th(e,Yu,l);for(const[t,r]of d)Fu(e,t,Du,s),rh(e,r,s,a)}else e.pushByte(Yu)}(e,t,a,r,s);else{Fu(e,qu.Object(t,a,r,s),Du,r)}return;default:{const n=qu[a];if(!n)throw new Error(`${Wl} unsupported type: ${a}`);Fu(e,n(t,a,r,s),Du,r)}}}function sh(e,t){return function(e){return!0!==e.addBreakTokens}(t=Object.assign({},Ru,t))?(Lu.reset(),rh(Lu,e,t,void 0),Lu.toBytes(!0)):function(e,t,r,s){const a=s instanceof Uint8Array;let n=a?new Fl(s):Lu;const o=Mu(e,r);if(!Array.isArray(o)&&r.quickEncodeToken){const e=r.quickEncodeToken(o);if(e)return a?(n.push(e),n.toBytes()):e;const s=t[o.type.major];if(s.encodedSize){const e=s.encodedSize(o,r);if(a||(n=new Vl(e)),s(n,o,r),1!==n.chunks.length)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return a?n.toBytes():Nl(n.chunks[0])}}return n.reset(),Fu(n,o,t,r),n.toBytes(!0)}(e,Du,t)}const ah={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};class nh{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){const e=this.data[this._pos];let t=Nu[e];if(void 0===t){const r=Ou[e];if(!r)throw new Error(`${$l} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);const s=31&e;t=r(this.data,this._pos,s,this.options)}return this._pos+=t.encodedLength,t}}const oh=Symbol.for("DONE"),ih=Symbol.for("BREAK");function ch(e,t){const r=function(){if(r._called)throw new Error(`${$l} tag decode() may only be called once`);r._called=!0;const s=dh(e,t);if(s===oh)throw new Error(`${$l} tag content missing`);if(s===ih)throw new Error(`${$l} got unexpected break in tag content`);return s};return r.entries=function(){if(r._called)throw new Error(`${$l} tag decode() may only be called once`);r._called=!0;const s=e.next();if(!Pl.equals(s.type,Pl.map))throw new Error(`${$l} entries() requires map content, got ${s.type.name}`);const a=[];for(const r of function*(e,t,r){for(let s=0;s<e.value;s++){const a=dh(t,r);if(a===ih){if(e.value===1/0)break;throw new Error(`${$l} got unexpected break to lengthed map`)}if(a===oh)throw new Error(`${$l} found map but not enough entries (got ${s} [no key], expected ${e.value})`);const n=dh(t,r);if(n===oh)throw new Error(`${$l} found map but not enough entries (got ${s} [no value], expected ${e.value})`);yield[a,n]}}(s,e,t))a.push(r);return a},r._called=!1,r}function dh(e,t){if(e.done())return oh;const r=e.next();if(Pl.equals(r.type,Pl.break))return ih;if(r.type.terminal)return r.value;if(Pl.equals(r.type,Pl.array))return function(e,t,r){const s=[];for(let a=0;a<e.value;a++){const n=dh(t,r);if(n===ih){if(e.value===1/0)break;throw new Error(`${$l} got unexpected break to lengthed array`)}if(n===oh)throw new Error(`${$l} found array but not enough entries (got ${a}, expected ${e.value})`);s[a]=n}return s}(r,e,t);if(Pl.equals(r.type,Pl.map))return function(e,t,r){const s=!0===r.useMaps,a=!0===r.rejectDuplicateMapKeys,n=s?void 0:{},o=s?new Map:void 0;for(let i=0;i<e.value;i++){const c=dh(t,r);if(c===ih){if(e.value===1/0)break;throw new Error(`${$l} got unexpected break to lengthed map`)}if(c===oh)throw new Error(`${$l} found map but not enough entries (got ${i} [no key], expected ${e.value})`);if(!s&&"string"!=typeof c)throw new Error(`${$l} non-string keys not supported (got ${typeof c})`);if(a&&(s&&o.has(c)||!s&&Object.hasOwn(n,c)))throw new Error(`${$l} found repeat map key "${c}"`);const d=dh(t,r);if(d===oh)throw new Error(`${$l} found map but not enough entries (got ${i} [no value], expected ${e.value})`);s?o.set(c,d):"__proto__"===c?Object.defineProperty(n,c,{value:d,configurable:!0,enumerable:!0,writable:!0}):n[c]=d}return s?o:n}(r,e,t);if(Pl.equals(r.type,Pl.tag)){if(t.tags&&"function"==typeof t.tags[r.value]){const s=ch(e,t),a=t.tags[r.value](s);if(!s._called)throw new Error(`${$l} tag decoder must call decode() or entries()`);return a}throw new Error(`${$l} tag not supported (${r.value})`)}throw new Error("unsupported")}function lh(e,t){const[r,s]=function(e,t){if(!(e instanceof Uint8Array))throw new Error(`${$l} data to decode must be a Uint8Array`);t=Object.assign({},ah,t);const r=Nl(e),s=t.tokenizer||new nh(r,t),a=dh(s,t);if(a===oh)throw new Error(`${$l} did not find any content to decode`);if(a===ih)throw new Error(`${$l} got unexpected break`);return[a,e.subarray(s.pos())]}(e,t);if(s.length>0)throw new Error(`${$l} too many terminals, data makes no sense`);return r}const uh={useMaps:!0,rejectDuplicateMapKeys:!0,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};function hh(e){throw new Error(`CBOR decode error: ${e}`)}function ph(e){return void 0===e?"undefined":null===e?"null":e instanceof Uint8Array?"bytes":e instanceof Map?"map":Array.isArray(e)?"array":typeof e}function fh(e,t){if(t>16&&hh("maximum depth exceeded"),void 0===e&&hh("undefined values are not supported"),"number"!=typeof e||Number.isInteger(e)||hh("floating-point values are not supported"),Array.isArray(e))for(const r of e)fh(r,t+1);else if(e instanceof Map)for(const[r,s]of e.entries())fh(r,t+1),fh(s,t+1)}function yh(e){const t=lh(e,uh);return fh(t,0),t}function gh(e,t){return e instanceof Uint8Array||hh(`expected ${t} to be a CBOR byte string, got ${ph(e)}`),e}function wh(e,t){return"string"!=typeof e&&hh(`expected ${t} to be a CBOR text string, got ${ph(e)}`),e.includes("�")&&hh(`expected ${t} to be valid UTF-8`),e}function mh(e,t){return Array.isArray(e)||hh(`expected ${t} to be a CBOR array, got ${ph(e)}`),e}function vh(e,t){return e instanceof Map||hh(`expected ${t} to be a CBOR map, got ${ph(e)}`),e}function Sh(e,t){return"bigint"==typeof e?e:"number"==typeof e&&Number.isInteger(e)?BigInt(e):hh(`expected ${t} to be a CBOR integer, got ${ph(e)}`)}function Ah(e,t){return null===e?null:gh(e,t)}function bh(e,t,r){return e.has(t)||hh(`${r} is missing required field "${t}"`),e.get(t)}class Eh extends Error{constructor(e,t,r,s){super(s),this.name=e,this.step=t,this.reason=r}}class _h extends Eh{constructor(e,t){super("AttestationDecodeError","decode",e,t),this.reason=e}}class kh extends Eh{constructor(e,t){super("AttestationChainError","chain",e,t),this.reason=e}}class Ih extends Eh{constructor(e,t){super("AttestationSignatureError","signature",e,t),this.reason=e}}class Th extends Eh{constructor(e,t){super("AttestationPcrError","pcr",e,t),this.reason=e}}class Ph extends Eh{constructor(e,t){super("AttestationNonceError","nonce",e,t),this.reason=e}}const Ch=BigInt(-35);function xh(e,t){try{return t()}catch(t){if(t instanceof Eh)throw t;throw new _h("unexpected-shape",`${e}: ${t.message}`)}}function Kh(e){return xh("attestation document does not match the expected COSE_Sign1 shape",(()=>{const t=mh(yh(e),"COSE_Sign1 envelope");if(4!==t.length)throw new _h("unexpected-shape",`COSE_Sign1 envelope must have exactly 4 elements, got ${t.length}`);const[r,s,a,n]=t,o=gh(r,"COSE_Sign1[0] (protected header)");vh(s,"COSE_Sign1[1] (unprotected header)");const i=gh(a,"COSE_Sign1[2] (payload)"),c=gh(n,"COSE_Sign1[3] (signature)"),d=function(e){if(0===e.length)return;const t=vh(xh("COSE protected header is not valid CBOR",(()=>yh(e))),"COSE protected header").get(1);return void 0!==t?Sh(t,'protected header "alg" (label 1)'):void 0}(o);if(void 0!==d&&d!==Ch)throw new _h("unsupported-algorithm",`COSE protected header declares alg ${d}, this module only verifies ES384 (-35)`);if(96!==c.length)throw new _h("unexpected-shape",`ES384 signature must be 96 raw bytes (r||s), got ${c.length}`);return{protectedHeaderBytes:o,payloadBytes:i,signatureBytes:c}}))}function Oh(e,t){return sh(["Signature1",e,new Uint8Array(0),t])}const Nh=BigInt(864e13),Rh=["module_id","digest","timestamp","pcrs","certificate","cabundle","public_key","user_data","nonce"];function Dh(e){return xh("attestation payload does not match the expected shape",(()=>{const t=vh(yh(e),"attestation payload"),r=Array.from(t.keys());for(const e of r)if("string"!=typeof e||!Rh.includes(e))throw new _h("unexpected-shape",`attestation payload has an unrecognized field ${"string"!=typeof e?"(non-text key)":JSON.stringify(e)}`);for(const e of Rh)if(!t.has(e))throw new _h("unexpected-shape",`attestation payload is missing required field "${e}"`);const s=wh(bh(t,"module_id","attestation payload"),"module_id"),a=wh(bh(t,"digest","attestation payload"),"digest");if("SHA384"!==a)throw new _h("unsupported-digest",`attestation payload declares digest ${JSON.stringify(a)}, only "SHA384" is supported`);const n=function(e,t){const r=Sh(e,t);return r<BigInt(0)&&hh(`expected ${t} to be a CBOR unsigned integer, got ${r}`),r}(bh(t,"timestamp","attestation payload"),"timestamp");if(n>Nh)throw new _h("unexpected-shape",`attestation payload timestamp ${n} is out of range (must be a plausible millisecond-since-epoch value)`);const o=vh(bh(t,"pcrs","attestation payload"),"pcrs"),i=new Map;for(const[e,t]of o){const r=Number(Sh(e,"pcrs key"));i.set(r,gh(t,`pcrs[${r}]`))}return{moduleId:s,digest:a,timestamp:n,pcrs:i,certificate:gh(bh(t,"certificate","attestation payload"),"certificate"),cabundle:mh(bh(t,"cabundle","attestation payload"),"cabundle").map(((e,t)=>gh(e,`cabundle[${t}]`))),publicKey:Ah(bh(t,"public_key","attestation payload"),"public_key"),userData:Ah(bh(t,"user_data","attestation payload"),"user_data"),nonce:Ah(bh(t,"nonce","attestation payload"),"nonce")}}))}
|
|
13
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Lh=jr(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"));fs({a:Lh.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:Lh,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},_r);const Bh=jr(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),Uh=fs({a:Bh.create(BigInt("-3")),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Fp:Bh,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},Ir),qh=jr(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));fs({a:qh.create(BigInt("-3")),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Fp:qh,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1),lowS:!1,allowedPrivateKeyLengths:[130,131,132]},kr);
|
|
14
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
15
|
+
const Mh=Uh;function Vh(e,t,r,s){try{const a=Ir(t);return Mh.verify(e,a,r,{lowS:!1,format:s})}catch(e){return!1}}const Fh=48,$h="1.2.840.10045.4.3.3",Wh="1.2.840.10045.2.1",jh="1.3.132.0.34";function Gh(e){throw new kh("malformed-certificate",e)}class Hh{constructor(e,t,r){this.buf=e,this.pos=t,this.end=r}hasMore(){return this.pos<this.end}peekTag(){return this.hasMore()||Gh("expected another DER field, found none"),this.buf[this.pos]}readTlv(e){const{tlv:t,next:r}=function(e,t){t>=e.length&&Gh("unexpected end of DER input");const r=e[t];31&~r||Gh("high-tag-number DER tags are not supported");let s=t+1;s>=e.length&&Gh("unexpected end of DER input (length byte)");const a=e[s++];let n;if(128&a){const t=127&a;0===t&&Gh("indefinite-length DER encoding is not supported"),t>4&&Gh("DER length encoding is implausibly large"),s+t>e.length&&Gh("unexpected end of DER input (long-form length)"),n=0;for(let r=0;r<t;r++)n=256*n+e[s++]}else n=a;const o=s,i=o+n;return i>e.length&&Gh("DER length exceeds available bytes"),{tlv:{tag:r,tlvStart:t,contentStart:o,contentEnd:i},next:i}}(this.buf,this.pos);return r>this.end&&Gh("DER field extends past its enclosing structure"),void 0!==e&&t.tag!==e&&Gh(`expected DER tag 0x${e.toString(16)}, got 0x${t.tag.toString(16)}`),this.pos=r,t}into(e){return new Hh(this.buf,e.contentStart,e.contentEnd)}content(e){return this.buf.subarray(e.contentStart,e.contentEnd)}raw(e){return this.buf.subarray(e.tlvStart,e.contentEnd)}}function Yh(e){0===e.length&&Gh("empty OBJECT IDENTIFIER");const t=e[0];let r,s;t<40?(r=0,s=t):t<80?(r=1,s=t-40):(r=2,s=t-80);const a=[r,s];let n=0;for(let t=1;t<e.length;t++)n=128*n+(127&e[t]),128&e[t]||(a.push(n),n=0);return a.join(".")}function zh(e,t,r){const s=e.content(t);0===s.length&&Gh(`${r}: empty BIT STRING`);const a=s[0];return 0!==a&&Gh(`${r}: BIT STRING has ${a} unused bits, expected a byte-aligned value`),s.subarray(1)}const Jh=[31,28,31,30,31,30,31,31,30,31,30,31];function Xh(e,t,r,s,a,n,o){(t<1||t>12)&&Gh(`${o}: month ${t} is out of range`),(r<1||r>function(e,t){return 2===t&&function(e){return e%4==0&&e%100!=0||e%400==0}(e)?29:Jh[t-1]}(e,t))&&Gh(`${o}: day ${r} is out of range for ${e}-${String(t).padStart(2,"0")}`),(s<0||s>23)&&Gh(`${o}: hour ${s} is out of range`),(a<0||a>59)&&Gh(`${o}: minute ${a} is out of range`),(n<0||n>59)&&Gh(`${o}: second ${n} is out of range`)}function Zh(e,t){const r=new TextDecoder("ascii").decode(t);if(23===e){const e=/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(r);e||Gh(`malformed UTCTime "${r}"`);const t=Number(e[1]),s=t>=50?1900+t:2e3+t,a=Number(e[2]),n=Number(e[3]),o=Number(e[4]),i=Number(e[5]),c=Number(e[6]);return Xh(s,a,n,o,i,c,"UTCTime"),new Date(Date.UTC(s,a-1,n,o,i,c))}if(24===e){const e=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(r);e||Gh(`malformed GeneralizedTime "${r}"`);const t=Number(e[1]),s=Number(e[2]),a=Number(e[3]),n=Number(e[4]),o=Number(e[5]),i=Number(e[6]);return Xh(t,s,a,n,o,i,"GeneralizedTime"),new Date(Date.UTC(t,s-1,a,n,o,i))}Gh(`expected UTCTime or GeneralizedTime, got DER tag 0x${e.toString(16)}`)}function Qh(e){const t=new Hh(e,0,e.length),r=t.readTlv(Fh),s=t.into(r);if(!s.hasMore()||1!==s.peekTag())return!1;const a=s.readTlv(1);return 0!==s.content(a)[0]}function ep(e){const t=new Hh(e,0,e.length),r=t.readTlv(3),s=t.content(r);if(s.length<2)return!1;return!!(4&s[1])}function tp(e,t){const r=e.into(t),s=r.readTlv(6),a=Yh(r.content(s));if(!r.hasMore())return{oid:a};const n=r.readTlv();return 6===n.tag?{oid:a,curveOid:Yh(r.content(n))}:{oid:a}}function rp(e){var t;const r=new Hh(e,0,e.length),s=r.readTlv(Fh);s.contentEnd!==e.length&&Gh("trailing bytes after the Certificate SEQUENCE");const a=r.into(s),n=a.readTlv(Fh),o=a.raw(n),i=a.readTlv(Fh),c=tp(a,i),d=a.readTlv(3),l=zh(a,d,"Certificate.signatureValue");if(a.hasMore()&&Gh("trailing data inside Certificate SEQUENCE after signatureValue"),c.oid!==$h)throw new kh("unsupported-key-algorithm",`certificate signatureAlgorithm is ${c.oid}, only ecdsa-with-SHA384 (${$h}) is supported`);const u=r.into(n);160===u.peekTag()&&u.readTlv(),u.readTlv(2);const h=u.readTlv(Fh);tp(u,h).oid!==c.oid&&Gh("TBSCertificate.signature does not match the outer Certificate.signatureAlgorithm");const p=u.readTlv(Fh),f=u.raw(p),y=u.readTlv(Fh),g=u.into(y),w=g.readTlv(),m=Zh(w.tag,g.content(w)),v=g.readTlv(),S=Zh(v.tag,g.content(v)),A=u.readTlv(Fh),b=u.raw(A),E=u.readTlv(Fh),_=u.into(E),k=_.readTlv(Fh),I=tp(_,k);if(I.oid!==Wh)throw new kh("unsupported-key-algorithm",`certificate public key algorithm is ${I.oid}, only id-ecPublicKey (${Wh}) is supported`);if(I.curveOid!==jh)throw new kh("unsupported-key-algorithm",`certificate EC curve is ${null!==(t=I.curveOid)&&void 0!==t?t:"(none/implicit)"}, only secp384r1 (${jh}) is supported`);const T=_.readTlv(3),P=zh(_,T,"SubjectPublicKeyInfo.subjectPublicKey");if(97!==P.length||4!==P[0])throw new kh("unsupported-key-algorithm",`expected a 97-byte uncompressed P-384 point (0x04 prefix), got ${P.length} bytes`);let C;for(;u.hasMore();){const e=u.readTlv();163===e.tag&&(C=e)}const{isCa:x,keyCertSignAsserted:K}=C?function(e,t){let r=!1,s=null;const a=e.into(t),n=a.readTlv(Fh),o=a.into(n);for(;o.hasMore();){const e=o.readTlv(Fh),t=o.into(e),a=t.readTlv(6),n=Yh(t.content(a));t.hasMore()&&1===t.peekTag()&&t.readTlv(1);const i=t.readTlv(4),c=t.content(i);"2.5.29.19"===n?r=Qh(c):"2.5.29.15"===n&&(s=ep(c))}return{isCa:r,keyCertSignAsserted:s}}(u,C):{isCa:!1,keyCertSignAsserted:null};return{tbsRaw:o,signatureAlgorithmOid:c.oid,signatureValueRaw:l,issuerRaw:f,subjectRaw:b,notBefore:m,notAfter:S,publicKeyAlgorithmOid:I.oid,publicKeyCurveOid:I.curveOid,publicKeyPoint:P,isCa:x,keyCertSignAsserted:K}}function sp(e){try{return rp(e)}catch(e){if(e instanceof kh)throw e;Gh(`failed to parse X.509 certificate: ${e.message}`)}}function ap(e,t){if(!Number.isFinite(t)||!Number.isFinite(new Date(t).getTime()))throw new kh("invalid-clock",`certificate validity check requires a finite clock value, got ${t}`);const r=new Date(t);if(t<e.notBefore.getTime())throw new kh("certificate-not-yet-valid",`certificate is not valid until ${e.notBefore.toISOString()} (now: ${r.toISOString()})`);if(r.getTime()>e.notAfter.getTime())throw new kh("certificate-expired",`certificate expired at ${e.notAfter.toISOString()} (now: ${r.toISOString()})`)}function np(e,t){return e.signatureAlgorithmOid===$h&&Vh(e.signatureValueRaw,e.tbsRaw,t.publicKeyPoint,"der")}function op(e,t){if(!e.isCa)throw new kh("not-a-certificate-authority",`${t} does not carry a basicConstraints extension asserting cA=TRUE, so it cannot be trusted to sign other certificates`);if(!1===e.keyCertSignAsserted)throw new kh("not-a-certificate-authority",`${t} has a keyUsage extension that does not assert keyCertSign, so it cannot be trusted to sign other certificates`)}function ip(e,t,r){return{pcr0:Fd(e),pcr1:Fd(t),pcr2:Fd(r)}}const cp=[ip("0x111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111","0x121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212","0x131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313"),ip("0x212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121","0x222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222","0x232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323")];function dp(e,t){const r=e.get(t);if(!r)throw new Th("pcr-missing",`attestation document does not report PCR${t}`);return r}exports.WallabyApiClient=e.A,exports.WallabyHttpClient=e.H,exports.AndroidVersionNotSupportedError=$,exports.AttestationChainError=kh,exports.AttestationDecodeError=_h,exports.AttestationNonceError=Ph,exports.AttestationPcrError=Th,exports.AttestationSignatureError=Ih,exports.AttestationVerificationError=Eh,exports.AuthenticatorGeneralError=se,exports.AuthenticatorMissingDiscoverableCredentialSupportError=ae,exports.AuthenticatorMissingUserVerificationSupportError=ne,exports.AuthenticatorNoSupportedPubKeyCredParamsAlgError=ce,exports.AuthenticatorNotRegisteredError={error:"ERROR_AUTHENTICATOR_NOT_REGISTERED",message:"Authenticator is not registered."},exports.AuthenticatorPreviouslyRegisteredError=oe,exports.AutoRegisterUserVerificationFailureError=de,exports.BadConfiguration=Y,exports.CeremonyAbortedError=Z,exports.IOSVersionNotSupportedError=F,exports.InterruptedError=J,exports.InvalidChallengeError=G,exports.InvalidDomainError=Q,exports.InvalidRpIdError=ee,exports.InvalidStateError=ie,exports.InvalidUserIdError=H,exports.InvalidUserIdLengthError=te,exports.MalformedPubKeyCredParamsError=re,exports.NativeError=(e="An unknown error occurred")=>({error:"Unknown",message:e}),exports.NoCredentialsError=z,exports.NotAllowedError={error:"NotAllowedError",message:"CredentialContainer request is not allowed."},exports.PasskeyErrorCodes=ue,exports.PassthroughSeeCausePropertyError=le,exports.RequestFailedError=W,exports.TimeoutError=X,exports.UnknownError=V,exports.UserCancelledError=j,exports.Wallaby=class{constructor(e,t={}){this.wallet=new Cd(e,t),this.walletData=new xd(e,t),this.utils=new Kd(e,t),this.auth=new Id(e,t),this.system=new Rd(e,t),this.transactions=new Dd(e,t),this.swap=new Nd(e,t),this.httpApi=new Od(e,t)}get version(){return Ae}},exports.WallabyError=M,exports.createIdentity=Ms,exports.decryptWithPrivateKey=Aa,exports.encryptWithPublicKey=Sa,exports.hash=_a,exports.isValidSeedPhrase=ja,exports.keccak256=ba,exports.normalizeSeedPhrase=Wa,exports.publicKeyByPrivateKey=bs,exports.recoverPublicKey=(e,t)=>{const r=qt(e),s=r.substring(0,r.length-2),a="1c"===r.slice(-2)?1:0;let n=Ve(Ea(Bt(s),a,Bt(qt(t)),!1));return n=n.slice(2),n},exports.sign=Vs,exports.verification=kl,exports.verifyAttestationDocument=function(e,t,r={}){var s;const a=null!==(s=r.now)&&void 0!==s?s:Date.now(),{protectedHeaderBytes:n,payloadBytes:o,signatureBytes:i}=Kh(e),c=Dh(o),d=bd("-----BEGIN CERTIFICATE-----\nMIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTEL\nMAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYD\nVQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4\nMTQyODA1WjBJMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQL\nDANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEG\nBSuBBAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSksfbb\n48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ3BABIeTPYwEoCWZE\nh8l5YoQwTcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkF\nR+eWw5b6cp3PmanfS5YwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYC\nMQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPW\nrfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6N\nIwLz3/Y=\n-----END CERTIFICATE-----".replace(/-----BEGIN [^-]+-----/,"").replace(/-----END [^-]+-----/,"").replace(/\s+/g,"")),l=function(e,t,r,s){if(0===r.length)throw new kh("root-not-pinned","No pinned Nitro root certificate is configured — see aws-root-cert.ts before using this in production");const a=sp(e);ap(a,s);const n=sp(r);op(n,"the configured pinned Nitro root certificate");const o=t.map((e=>sp(e))).filter((e=>!jd(e.subjectRaw,n.subjectRaw))),i=new Set;let c=a;const d=o.length+1;for(let e=0;e<d;e++){let e=-1;for(let t=0;t<o.length;t++)if(!i.has(t)&&jd(o[t].subjectRaw,c.issuerRaw)){e=t;break}if(-1===e)break;const t=o[e];if(i.add(e),!np(c,t))throw new kh("chain-signature-invalid","a certificate in the document did not verify against the next certificate in its chain");ap(t,s),op(t,"a certificate in the attestation document's chain"),c=t}if(!jd(c.issuerRaw,n.subjectRaw))throw new kh("root-mismatch","the topmost certificate reachable from this document's own certificate/cabundle was not issued by the pinned Nitro root");if(!np(c,n))throw new kh("chain-signature-invalid","the topmost certificate's signature does not verify against the pinned Nitro root's public key");return a}(c.certificate,c.cabundle,d,a);if(!Vh(i,Oh(n,o),l.publicKeyPoint,"compact"))throw new Ih("invalid-signature","COSE_Sign1 signature does not verify against the leaf certificate public key");if(!(cp.length>0))throw new Th("measurements-not-pinned","No pinned PCR measurements are configured — see pinned-measurements.ts before using this in production");const u={pcr0:dp(c.pcrs,0),pcr1:dp(c.pcrs,1),pcr2:dp(c.pcrs,2)};if(h=u,!cp.some((e=>jd(e.pcr0,h.pcr0)&&jd(e.pcr1,h.pcr1)&&jd(e.pcr2,h.pcr2))))throw new Th("pcr-mismatch","attestation document PCR0/PCR1/PCR2 triple is not on the pinned allowlist");var h;if(null===c.nonce)throw new Ph("nonce-missing","attestation document does not include a nonce");if(!function(e,t){const r=Math.max(e.length,t.length);let s=e.length^t.length;for(let a=0;a<r;a++)s|=(a<e.length?e[a]:0)^(a<t.length?t[a]:0);return 0===s}(c.nonce,t))throw new Ph("nonce-mismatch","attestation document nonce does not match the expected value");const p={};for(const[e,t]of c.pcrs)p[e]=$d(t);return{verified:!0,documentInfo:{moduleId:c.moduleId,timestamp:Number(c.timestamp),pcrs:p,publicKey:c.publicKey,userData:c.userData,nonce:c.nonce}}},exports.verifyCallAgainstIntent=function(e,t,r,s,a){if(r.chainName!==e)throw new Error(`verifyCallAgainstIntent: intent is for chain "${r.chainName}" but the call is for "${e}" — refusing to verify across chains`);if(e===exports.BlockchainName.Polymesh)return _l(t,r,s,a);throw new Error(`verifyCallAgainstIntent: no verifier registered for chain "${e}"`)};//# sourceMappingURL=index.cjs.map
|