UNPKG

@particle-network/auth-core

Version:
4 lines 184 kB
{ "version": 3, "sources": ["../src/api/apiError.ts", "../src/api/authType.ts", "../src/api/types/apiData.ts", "../src/api/types/rpcData.ts", "../src/api/types/index.ts", "../src/utils/validate.ts", "../src/types/authCoreEvent.ts", "../src/types/cloudflare.ts", "../src/types/rpcMethods.ts", "../src/types/wallet.ts", "../src/types/index.ts", "../src/core/analyticsApi.ts", "../src/config/index.ts", "../src/storage/encryptedStorage.ts", "../src/utils/index.ts", "../src/utils/eventUtils.ts", "../src/storage/userStorage.ts", "../src/storage/index.ts", "../src/utils/tron/crypto.ts", "../src/utils/tron/base58.ts", "../src/utils/chainUtils.ts", "../src/utils/ethereumUtils.ts", "../src/core/connectApi.ts", "../src/api/client.ts", "../src/api/pnApi.ts", "../src/core/authCore.ts", "../src/core/ethereumProvider.ts", "../src/api/evmApi.ts", "../src/utils/sigUtils.ts", "../src/core/threshSig.ts", "../src/api/kms.ts", "../src/core/masterPassword.ts", "../src/core/wallet.ts", "../src/core/solanaWallet.ts", "../src/api/solanaApi.ts", "../src/utils/solanaUtils.ts", "../src/core/securityApi.ts"], "sourcesContent": ["/**\n * Particle Network api error code\n */\nexport enum ApiError {\n SystemError = 10001,\n ParamError = 10002,\n AuthorizationError = 10004,\n InvalidToken = 10005,\n MacError = 10009,\n\n InvalidCode = 20101,\n ResendCode = 20103,\n\n SecurityAccountFrozen = 50010,\n WrongPaymentPassword = 50102,\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isApiError(err: any): boolean {\n return err && err.message && typeof err.error_code === 'number' && err.error_code > 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isRpcError(err: any): boolean {\n return err && err.message && typeof err.code === 'number';\n}\n", "export enum AuthType {\n email = 'email',\n phone = 'phone',\n facebook = 'facebook',\n google = 'google',\n apple = 'apple',\n twitter = 'twitter',\n discord = 'discord',\n github = 'github',\n twitch = 'twitch',\n microsoft = 'microsoft',\n linkedin = 'linkedin',\n\n // headless\n jwt = 'jwt',\n telegram = 'telegram',\n}\n\nexport type SocialAuthType =\n | 'facebook'\n | 'google'\n | 'apple'\n | 'twitter'\n | 'discord'\n | 'github'\n | 'twitch'\n | 'microsoft'\n | 'linkedin';\n\nexport interface LoginWithSocial {\n authType: SocialAuthType;\n redirectUrl?: string;\n appState?: string;\n prompt?: 'none' | 'consent' | 'select_account';\n}\n\nexport const isSocialAuthType = (authType: any): authType is SocialAuthType => {\n return [\n AuthType.facebook,\n AuthType.google,\n AuthType.apple,\n AuthType.twitter,\n AuthType.discord,\n AuthType.github,\n AuthType.twitch,\n AuthType.microsoft,\n AuthType.linkedin,\n ].includes(authType);\n};\n", "import { type SocialAuthType } from '../authType';\n\nexport type BooleanResult = {\n success: boolean;\n};\n\nexport interface DeviceInfo {\n user_agent: string;\n device: string;\n createdAt: string;\n updated_at: string;\n user_uuid: string;\n project_uuid: string;\n project_app_uuid: string;\n login_channel: string;\n login_name: string;\n isCurrent?: boolean;\n location: {\n ip: string;\n country_code: string;\n country_name?: string;\n city: string;\n continent: string;\n longitude: string;\n latitude: string;\n };\n project_app_name: string;\n}\n\nexport type PhoneCaptchaRequest = {\n phone: string;\n cf_turnstile_response: string;\n};\n\nexport type EmailCaptchaRequest = {\n email: string;\n};\n\nexport type CaptchaRequest = PhoneCaptchaRequest | EmailCaptchaRequest;\n\nexport type LoginRequest = { code: string; phone: string } | { code: string; email: string };\n\nexport type LoginBindPhoneRequest = {\n phone: string;\n code: string;\n security_account_verify_token: string;\n};\n\nexport type LoginBindEmailRequest = {\n email: string;\n code: string;\n security_account_verify_token: string;\n};\n\nexport type LoginBindRequest = LoginBindPhoneRequest | LoginBindEmailRequest;\n\nexport type LoginBindThirdpartyRequest = {\n provider: SocialAuthType;\n thirdparty_code: string;\n security_account_verify_token: string;\n version?: 'v1' | 'v2';\n};\n\nexport interface ThirdpartyUserInfo {\n provider: string;\n user_info: {\n id: string;\n email: string;\n name: string;\n picture: string;\n };\n}\n\nexport interface SecurityAccount {\n email?: string;\n phone?: string;\n has_set_payment_password: boolean;\n has_set_master_password: boolean;\n payment_password_updated_at?: string;\n}\n\nexport interface OriginalUserInfo {\n uuid: string;\n phone?: string;\n email?: string;\n name?: string;\n avatar?: string;\n created_at: string;\n updated_at: string;\n mac_key: string;\n token: string;\n wallets: WalletInfo[];\n cognito_result: CognitoResult;\n thirdparty_user_info?: ThirdpartyUserInfo;\n security_account: SecurityAccount;\n facebook_id?: string;\n facebook_email?: string;\n google_id?: string;\n google_email?: string;\n apple_id?: string;\n apple_email?: string;\n discord_id?: string;\n discord_email?: string;\n github_id?: string;\n github_email?: string;\n linkedin_id?: string;\n linkedin_email?: string;\n microsoft_id?: string;\n microsoft_email?: string;\n twitch_id?: string;\n twitch_email?: string;\n twitter_id?: string;\n twitter_email?: string;\n jwt_id?: string;\n telegram_id?: string;\n telegram_phone?: string;\n}\n\nexport interface UserInfo extends Omit<OriginalUserInfo, 'mac_key' | 'cognito_result' | 'wallets'> {\n wallets: Pick<WalletInfo, 'uuid' | 'chain_name' | 'public_address'>[];\n}\n\nexport type UserInfoSync = Omit<OriginalUserInfo, 'token' | 'mac_key' | 'cognito_result' | 'thirdparty_user_info'>;\n\nexport enum WalletEncryptedType {\n KMS_AES = 0,\n KMS_AES_WITH_DATA_KEY_AND_DEFAULT_MASTER_PASSWORD = 1,\n KMS_AES_WITH_DATA_KEY_AND_MASTER_PASSWORD = 2,\n}\n\nexport type WalletInfo = {\n uuid: string;\n chain_name: string;\n public_address?: string;\n encrypted_data: string;\n encrypted_type?: WalletEncryptedType;\n encrypted_kms_data_key?: string;\n};\n\nexport type CognitoResult = {\n region: string;\n identity_id: string;\n id_token: string;\n kms_key_id: string;\n};\n\nexport interface UserWalletRequestParam {\n encrypted_type: number;\n encrypted_kms_data_key: string;\n wallets: {\n wallet_uuid: string;\n encrypted_data: string;\n public_address?: string;\n }[];\n}\n\nexport interface LoginAccount {\n id_combined: string;\n user_uuid: string;\n provider: string;\n created_at: string;\n}\n\nexport interface SmartAccount {\n smartAccountAddress: string;\n}\n\nexport interface ThirdpartyAuthUrlResult {\n provider: SocialAuthType;\n auth_url: string;\n nonce: string;\n signature: string;\n state: string;\n}\n\nexport interface ServerError {\n error_code: number;\n message: string;\n}\n", "export type PrefixedHexString = string;\nexport type Base58String = string;\n\nexport type RpcInput = {\n id: string;\n jsonrpc: string;\n method: string;\n params?: unknown[];\n chainId?: number;\n};\n\nexport type RpcOutput<T> = {\n jsonrpc: string;\n id: string;\n result: T;\n};\n\nexport type SolanaDeserializeTransactionResult = {\n instructions: SolanaDeserializeInstruction[];\n estimatedChanges: EstimatedChanges;\n estimatedLamportsFee: number;\n};\n\nexport type SolanaDeserializeInstruction = {\n type: string;\n programId: string;\n data: string;\n};\n\nexport type EstimatedChanges = {\n sols: SolChangeInfo[];\n nfts: TokenChangeInfo[];\n tokens: SplTokenChangeInfo[];\n};\n\nexport type SolChangeInfo = {\n address: string;\n lamportsChange: number;\n};\n\nexport type TokenChangeInfo = {\n name: string;\n symbol: string;\n image: string;\n mint: string;\n associatedTokenAddress: string;\n amountChange: number;\n};\n\nexport type SplTokenChangeInfo = {\n decimals: number;\n} & TokenChangeInfo;\n\nexport enum SolanaEnhancedMethod {\n enhancedDeserializeTransaction = 'enhancedDeserializeTransaction',\n}\n\nexport enum EvmEnhancedMethod {\n deserializeTransaction = 'particle_deserializeTransaction',\n deserializeTypedData = 'particle_deserializeTypedData',\n suggestedGasFees = 'particle_suggestedGasFees',\n getPrice = 'particle_getPrice',\n getPendingTransactionsByAddress = 'particle_getPendingTransactionsByAddress',\n}\n\nexport enum TransactionSmartType {\n NativeTransfer = 'native_transfer',\n ERC20_TRANSFER = 'erc20_transfer',\n ERC20_APPROVE = 'erc20_approve',\n ERC721_TRANFER = 'erc721_transfer',\n ERC1155_TRANFER = 'erc1155_transfer',\n SEAPORT_FULFILL_ORDER = 'seaport_fulfill_order',\n SEAPORT_CANCEL_ORDER = 'seaport_cancel_order',\n SEAPORT_NFT_LISTING = 'seaport_nft_listing',\n OTHER = 'other',\n}\n\nexport type NftPrice = {\n address: string;\n amount: string;\n decimals: number;\n symbol: string;\n};\n\nexport type SecurityDetection = {\n type: string;\n risks?: string[];\n warnings?: string[];\n};\n\nexport type EVMDeserializeTransactionResult = {\n type?: TransactionSmartType;\n estimatedChanges: EVMEstimatedChange;\n data: EVMData;\n toTag?: string;\n price?: NftPrice;\n securityDetection?: SecurityDetection[];\n};\n\nexport type EVMEstimatedChange = {\n natives: EVMNativeChange[];\n nfts: EVMNFTChange[];\n tokens: EVMTokenChange[];\n};\n\n//\u5341\u8FDB\u5236\u6570\u5B57\u5B57\u7B26\u4E32\nexport type DecimalString = string;\n\nexport type EVMNativeChange = {\n address: PrefixedHexString;\n nativeChange: DecimalString;\n};\n\nexport type EVMNFTChange = {\n name: string;\n symbol: string;\n image: string;\n address: string;\n fromAddress: string;\n amountChange: number;\n tokenId: string;\n amount?: string;\n isSemiFungible?: boolean;\n description?: string;\n};\n\nexport type EVMTokenChange = {\n decimals: number;\n name: string;\n symbol: string;\n image: string;\n address: string;\n fromAddress: string;\n amountChange: number;\n};\n\nexport interface Consideration {\n address: string;\n amount: string;\n decimals: number;\n recipient: string;\n symbol: string;\n}\nexport interface EVMData {\n from: PrefixedHexString;\n chainId: PrefixedHexString;\n nonce: PrefixedHexString;\n maxPriorityFeePerGas: PrefixedHexString;\n maxFeePerGas: PrefixedHexString;\n gasPrice: PrefixedHexString;\n gasLimit: PrefixedHexString;\n to: PrefixedHexString;\n value: PrefixedHexString;\n data: PrefixedHexString;\n v?: PrefixedHexString;\n r?: PrefixedHexString;\n s?: PrefixedHexString;\n function?: EVMFunction;\n offer?: EVMNFTChange[];\n offerer?: string;\n consideration?: Consideration[];\n startTime?: string;\n endTime?: string;\n}\n\nexport interface TransactionData extends EVMData {\n type: PrefixedHexString;\n gas: PrefixedHexString; //gasLimit\n action: string; // use for particle cancel or speed up transaction\n function?: never;\n}\n\nexport interface EVMFunction {\n name: string;\n params: EVMParam[];\n}\n\nexport interface EVMParam {\n name: string;\n value: unknown;\n type: string;\n}\n\nexport interface GasFeeResult {\n low: GasFeeLevel;\n medium: GasFeeLevel;\n high: GasFeeLevel;\n baseFee: string;\n}\n\nexport interface GasFeeLevel {\n maxPriorityFeePerGas: string;\n maxFeePerGas: string;\n minWaitTime: number;\n maxWaitTime: number;\n}\n\nexport interface TokenPrice {\n address: string;\n currencies: Currency[];\n}\n\nexport interface Currency {\n type: string;\n price: number;\n marketCap: number;\n '24hChange': number;\n '24hVol': number;\n lastUpdatedAt: number;\n}\n\nexport interface RecentBlockhash {\n value: {\n blockhash: string;\n };\n}\n\nexport interface GasFee {\n fee?: string;\n maxFee: string;\n}\n\nexport interface TotalAmount {\n amount?: string;\n maxAmount: string;\n}\n\nexport enum GasFeeMode {\n custom = 'custom',\n low = 'low',\n medium = 'medium',\n high = 'high',\n}\n\nexport interface TxData {\n /**\n * The transaction's nonce.\n */\n nonce?: PrefixedHexString | number;\n /**\n * The transaction's gas price.\n */\n gasPrice?: PrefixedHexString | number;\n gas?: PrefixedHexString | number;\n /**\n * The transaction's gas limit.\n */\n gasLimit?: PrefixedHexString | number;\n\n from: PrefixedHexString;\n /**\n * The transaction's the address is sent to.\n */\n to?: PrefixedHexString;\n /**\n * The amount of Ether sent.\n */\n value?: PrefixedHexString | number;\n /**\n * This will contain the data of the message or the init of a contract.\n */\n data?: PrefixedHexString;\n type?: PrefixedHexString | number;\n\n chainId?: PrefixedHexString | number;\n\n /**\n * use for particle cancel or speed up transaction\n */\n action?: 'normal' | 'cancel' | 'speedup'; // use for particle cancel or speed up transaction\n gasLevel?: 'custom' | 'low' | 'medium' | 'high'; // use for gas fee level\n}\n\n/**\n * {@link EIP1559TxData} data.\n */\nexport interface EIP1559TxData extends TxData {\n /**\n * The transaction's gas price. This property is not used for EIP1559\n * transactions and should always be undefined for this specific transaction type.\n */\n gasPrice?: never;\n /**\n * The maximum inclusion fee per gas (this fee is given to the miner)\n */\n maxPriorityFeePerGas?: PrefixedHexString | number;\n /**\n * The maximum total fee\n */\n maxFeePerGas?: PrefixedHexString | number;\n}\n\nexport type EVMTransaction = {\n nonce?: PrefixedHexString;\n gasPrice?: PrefixedHexString;\n gasLimit?: PrefixedHexString;\n from: PrefixedHexString;\n to?: PrefixedHexString;\n value?: PrefixedHexString;\n data?: PrefixedHexString;\n type?: PrefixedHexString;\n chainId?: PrefixedHexString;\n maxPriorityFeePerGas?: PrefixedHexString;\n maxFeePerGas?: PrefixedHexString;\n action?: 'normal' | 'cancel' | 'speedup'; // use for particle cancel or speed up transaction\n gasLevel?: GasFeeMode; // use for gas fee level\n};\n", "import type { OriginalUserInfo, UserInfo } from './apiData';\n\nexport * from './apiData';\nexport * from './rpcData';\n\nexport const mapToUserInfo = (originalUserInfo: OriginalUserInfo): UserInfo => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, camelcase\n const { mac_key, cognito_result, wallets, ...userInfo } = originalUserInfo;\n return {\n ...userInfo,\n wallets: wallets.map((wallet) => {\n // eslint-disable-next-line camelcase\n const { uuid, chain_name, public_address } = wallet;\n // eslint-disable-next-line camelcase\n return { uuid, chain_name, public_address };\n }),\n };\n};\n", "export const check = <T>(condition: T, throwError?: unknown) => {\n if (!condition) {\n if (throwError) {\n if (typeof throwError === 'string') {\n throw new Error(throwError);\n }\n throw throwError;\n } else {\n throw new Error('Required conditions not met');\n }\n }\n};\n\nexport const requireNotNullish = <T>(x: T, throwError?: unknown): NonNullable<T> => {\n if (x !== undefined && x !== null) {\n return x;\n }\n if (throwError) {\n if (typeof throwError === 'string') {\n throw new Error(throwError);\n } else {\n throw throwError;\n }\n }\n throw new Error('Param is null or undefined');\n};\n\nexport function isNullish(x: unknown): boolean {\n return x === undefined || x === null;\n}\n", "export enum AuthCoreEvent {\n RequestEthereumAccount = 'requestEthereumAccount', // request connect event\n RequestSolanaAccount = 'requestSolanaAccount', // request connect event\n ParticleAuthConnect = 'particleAuthConnect', // connect auth core succss event, emit before restore wallet\n ParticleAuthDisconnect = 'particleAuthDisconnect', // disconnect event\n UserInfoChanged = 'userInfoChanged', // disconnect event\n MasterPasswordChanged = 'masterPasswordChanged', // master password changed event\n ParticleWalletRestored = 'particleWalletRestored', // wallet restored event\n}\n", "export interface CloudflareOptions {\n getContainer?: HTMLElement | (() => HTMLElement) | false;\n theme?: 'light' | 'dark';\n language?: string;\n}\n\nexport enum IframeEvent {\n CloudflareToken = 'particle-auth-core-cloudflareToken',\n}\n", "export enum SolanaRpcMethod {\n signTransaction = 'signTransaction',\n signAndSendTransaction = 'signAndSendTransaction',\n signMessage = 'signMessage',\n signAllTransactions = 'signAllTransactions',\n}\n\nexport enum EvmRpcMethod {\n /* unsupport methods start */\n ethSignTransaction = 'eth_signTransaction',\n ethSign = 'eth_sign',\n walletWatchAsset = 'wallet_watchAsset', //EIP-747\n /* unsupport methods end */\n\n ethRequestAccounts = 'eth_requestAccounts', //EIP-1102\n ethAccounts = 'eth_accounts',\n ethChainId = 'eth_chainId',\n ethSendTransaction = 'eth_sendTransaction',\n ethSignTypedData = 'eth_signTypedData',\n ethSignTypedDataV1 = 'eth_signTypedData_v1',\n ethSignTypedDataV3 = 'eth_signTypedData_v3',\n ethSignTypedDataV4 = 'eth_signTypedData_v4',\n personalSign = 'personal_sign',\n\n ethSignTypedDataV4Uniq = 'eth_signTypedData_v4_uniq', //particle mpc signature uniq\n personalSignUniq = 'personal_sign_uniq', //particle mpc signature uniq\n\n walletSwitchEthereumChain = 'wallet_switchEthereumChain', //EIP-3326\n walletAddEthereumChain = 'wallet_addEthereumChain', //EIP-3085\n}\n", "export enum WalletType {\n EVM = 'evm_chain',\n Solana = 'solana',\n}\n\nexport type ERC4337Options = {\n name: string;\n version: string;\n};\n", "export type { MessageTypes, TypedDataV1, TypedMessage } from '@metamask/eth-sig-util';\nexport * from './authCoreEvent';\nexport * from './cloudflare';\nexport * from './connectParam';\nexport * from './eip1193';\nexport * from './rpcMethods';\nexport * from './wallet';\n\nexport enum SignTypedDataVersion {\n V1 = 'V1',\n V3 = 'V3',\n V4 = 'V4',\n}\n", "import { BI, type SendActiveParams, type SendRecordsParams } from '@particle-network/analytics';\nimport globalConfig from '../config';\nimport { isServer } from '../utils';\n\ndeclare global {\n interface Window {\n __particleAnalytics?: BI;\n }\n}\n\nconst getBI = () => {\n try {\n if (!window.__particleAnalytics) {\n window.__particleAnalytics = new BI({\n /* eslint-disable camelcase */\n sdk_api_domain: globalConfig.env.baseUrl,\n device_id: globalConfig.deviceId,\n sdk_version: globalConfig.version,\n project_config: {\n project_uuid: globalConfig.authOptions.projectId,\n project_key: globalConfig.authOptions.clientKey,\n project_app_uuid: globalConfig.authOptions.appId,\n },\n /* eslint-enable camelcase */\n });\n }\n } catch (error) {\n console.log('getBI', error);\n }\n return window.__particleAnalytics;\n};\n\nexport const analyticsRecord = (params: SendRecordsParams) => {\n if (!isServer()) {\n getBI()?.records(params);\n }\n};\n\nexport const analyticsActive = (params: SendActiveParams) => {\n if (!isServer()) {\n getBI()?.active(params);\n }\n};\n", "import { v4 as uuid } from 'uuid';\nimport { encryptedStorage } from '../storage';\nimport { isServer } from '../utils';\nimport { check } from '../utils/validate';\nimport type { AuthOptions } from './../core/authCore';\n\ntype Env = {\n basicUsername: string;\n basicPassword: string;\n baseUrl: string;\n rpcUrl: string;\n authCore: string;\n};\n\nclass GlobalConfig {\n #authOptions: AuthOptions | undefined;\n\n initialized = false;\n\n paymentToken: string | undefined; // use for sign when user has payment password.\n\n #devEnv: Env = {\n basicUsername: 'test_user',\n basicPassword: 'test_pass',\n baseUrl: 'https://api-debug.particle.network',\n rpcUrl: 'https://rpc-debug.particle.network',\n authCore: 'https://core-debug.particle.network',\n };\n\n #stagingEnv: Env = {\n basicUsername: 'PcJBtrqq69TDpQtY',\n basicPassword: 'oGjPXSgKP9QtmxWQUkrfrUvvmsG62t',\n baseUrl: 'https://api.particle.network',\n rpcUrl: 'https://rpc.particle.network',\n authCore: 'https://core.particle.network',\n };\n\n #productionEnv: Env = {\n basicUsername: 'PcJBtrqq69TDpQtY',\n basicPassword: 'oGjPXSgKP9QtmxWQUkrfrUvvmsG62t',\n baseUrl: 'https://api.particle.network',\n rpcUrl: 'https://rpc.particle.network',\n authCore: 'https://core.particle.network',\n };\n\n init(authOptions: AuthOptions) {\n this.#authOptions = authOptions;\n this.initialized = true;\n }\n\n get authOptions(): AuthOptions {\n check(this.#authOptions, 'Please init AuthCore first!');\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.#authOptions!;\n }\n\n get version() {\n // replace when build\n return 'web_' + '3.0.0-alpha.3';\n }\n\n get deviceId() {\n if (typeof window === 'undefined') {\n return uuid();\n } else {\n const storeKey = 'pn_device_id';\n let deviceId = encryptedStorage.getItem(storeKey);\n if (!deviceId) {\n deviceId = uuid();\n encryptedStorage.setItem(storeKey, deviceId);\n }\n return deviceId;\n }\n }\n\n get env() {\n if (!isServer() && window.__PARTICLE_ENVIRONMENT__ === 'development') {\n return this.#devEnv;\n } else if (!isServer() && window.__PARTICLE_ENVIRONMENT__ === 'staging') {\n return this.#stagingEnv;\n } else {\n return this.#productionEnv;\n }\n }\n}\n\nconst globalConfig = new GlobalConfig();\nexport default globalConfig;\n", "import aes from 'crypto-js/aes.js';\nimport utf8 from 'crypto-js/enc-utf8.js';\nimport md5 from 'crypto-js/md5.js';\nimport { isServer } from '../utils';\nimport { check } from '../utils/validate';\n/**\n * auth core data storage, default use localStorage\n */\nclass EncryptedStorage {\n #KEY_PREFIX = 'particle-auth-core/';\n\n #appId = '';\n\n #secretKey = '';\n\n #wrapKey(key: string): string {\n check(this.#appId, 'please init AuthCore first!');\n\n return md5(`${this.#appId}/${key}`).toString().toLowerCase();\n }\n\n #encrypt(plaintext: string): string {\n check(this.#secretKey, 'please init AuthCore first!');\n\n const ciphertext = aes.encrypt(plaintext, this.#secretKey).toString();\n return ciphertext;\n }\n\n #decrypt(ciphertext: string): string {\n check(this.#secretKey, 'please init AuthCore first!');\n\n const bytes = aes.decrypt(ciphertext, this.#secretKey);\n const plaintext = bytes.toString(utf8);\n return plaintext;\n }\n\n init(appId: string) {\n this.#appId = appId;\n\n let hostname = 'particle.network';\n if (typeof window !== 'undefined') {\n hostname = window.location.origin;\n }\n this.#secretKey = md5(`${hostname}/${this.#appId}`).toString().toLowerCase();\n }\n\n clear(): void {\n const removeKeys: string[] = [];\n const length = localStorage.length;\n for (let i = 0; i < length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(this.#KEY_PREFIX)) {\n removeKeys.push(key);\n }\n }\n removeKeys.forEach((key) => localStorage.removeItem(key));\n }\n\n getItem(key: string): string | null {\n if (typeof window === 'undefined') {\n return null;\n }\n const value = localStorage.getItem(this.getStorageKey(key));\n if (value != null && value.length > 0) {\n return this.#decrypt(value);\n }\n return value;\n }\n\n removeItem(key: string) {\n localStorage.removeItem(this.getStorageKey(key));\n }\n\n setItem(key: string, value: string) {\n if (isServer()) {\n return;\n }\n let cipherValue = value;\n if (value.length > 0) {\n cipherValue = this.#encrypt(value);\n }\n localStorage.setItem(this.getStorageKey(key), cipherValue);\n }\n\n getStorageKey(key: string): string {\n return this.#KEY_PREFIX + this.#wrapKey(key);\n }\n}\nconst encryptedStorage = new EncryptedStorage();\n\nexport default encryptedStorage;\n", "export const isServer = () => typeof window === 'undefined';\n", "import EventEmitter from 'events';\n\nconst events = new EventEmitter();\nevents.setMaxListeners(500);\n\nexport default events;\n", "import type { AuthType } from '../api/authType';\nimport { mapToUserInfo } from '../api/types';\nimport { AuthCoreEvent } from '../types';\nimport { WalletType } from '../types/wallet';\nimport events from '../utils/eventUtils';\nimport type { CognitoResult, OriginalUserInfo, SecurityAccount, WalletInfo } from './../api/types/apiData';\nimport storage from './encryptedStorage';\n\nconst userStorage = {\n setUserInfo(info: OriginalUserInfo | undefined) {\n const localUserInfo = this.getUserInfo();\n if (info) {\n storage.setItem('user_info', JSON.stringify(info));\n } else {\n storage.removeItem('user_info');\n }\n if (JSON.stringify(localUserInfo) !== JSON.stringify(info)) {\n events.emit(AuthCoreEvent.UserInfoChanged, info ? mapToUserInfo(info) : undefined);\n }\n },\n\n getUserInfo(): OriginalUserInfo | undefined {\n const info = storage.getItem('user_info');\n if (info) {\n return JSON.parse(info);\n }\n return undefined;\n },\n\n isLogin(): boolean {\n return Boolean(this.getUserInfo());\n },\n\n getUserToken(): string | undefined {\n const info = this.getUserInfo();\n if (info) {\n return info.token;\n }\n return undefined;\n },\n\n getCognitoResult(): CognitoResult | undefined {\n const info = this.getUserInfo();\n if (info) {\n return info.cognito_result;\n }\n return undefined;\n },\n\n getSecurityAccount(): SecurityAccount | undefined {\n const info = this.getUserInfo();\n if (info) {\n return info.security_account;\n }\n return undefined;\n },\n\n setLatestAuthType(authType: string | AuthType) {\n localStorage.setItem('particle-auth/latest-auth-type', authType === 'twitterv1' ? 'twitter' : authType);\n },\n\n getLatestAuthType(): AuthType | null {\n if (typeof window !== 'undefined') {\n const type = localStorage.getItem('particle-auth/latest-auth-type');\n return type as AuthType;\n }\n return null;\n },\n\n updateWallet(info: WalletInfo) {\n const userInfo = this.getUserInfo();\n if (userInfo) {\n for (let i = 0; i < userInfo.wallets.length; i++) {\n if (userInfo.wallets[i].uuid === info.uuid) {\n userInfo.wallets[i] = info;\n this.setUserInfo(userInfo);\n break;\n }\n }\n }\n },\n\n updateCognitoResult(result: CognitoResult) {\n const userInfo = this.getUserInfo();\n if (userInfo) {\n // eslint-disable-next-line camelcase\n userInfo.cognito_result = result;\n this.setUserInfo(userInfo);\n }\n },\n\n updateSecurityAccount(account: SecurityAccount) {\n const userInfo = this.getUserInfo();\n if (userInfo) {\n // eslint-disable-next-line camelcase\n userInfo.security_account = account;\n this.setUserInfo(userInfo);\n }\n },\n\n hasPaymentPassword(): boolean {\n return Boolean(this.getSecurityAccount()?.has_set_payment_password);\n },\n\n hasMasterPassword(): boolean {\n return Boolean(this.getSecurityAccount()?.has_set_master_password);\n },\n\n getEVMWallet(): WalletInfo | undefined {\n const userInfo = this.getUserInfo();\n return userInfo?.wallets.find((wallet) => wallet.chain_name === WalletType.EVM);\n },\n\n getSolanaWallet(): WalletInfo | undefined {\n const userInfo = this.getUserInfo();\n return userInfo?.wallets.find((wallet) => wallet.chain_name === WalletType.Solana);\n },\n};\n\nexport default userStorage;\n", "import encryptedStorage from './encryptedStorage';\nimport userStorage from './userStorage';\n\nenum PreferenceKey {\n LocalKey = 'local_key',\n EvmChainId = 'evm_chain_id',\n SolanaChainId = 'solana_chain_id',\n}\nexport { PreferenceKey, encryptedStorage, userStorage };\n\nexport const getCurrentEvmChainId = () => {\n return Number(encryptedStorage.getItem(PreferenceKey.EvmChainId));\n};\n\nexport const setCurrentEvmChainId = (id: number) => {\n encryptedStorage.setItem(PreferenceKey.EvmChainId, id.toString());\n};\n\nexport const getCurrentSolanaChainId = () => {\n return Number(encryptedStorage.getItem(PreferenceKey.SolanaChainId));\n};\n\nexport const setCurrentSolanaChainId = (id: number) => {\n encryptedStorage.setItem(PreferenceKey.SolanaChainId, id.toString());\n};\n", "import hex from 'crypto-js/enc-hex.js';\nimport sha256Hex from 'crypto-js/sha256.js';\nimport { decode58, encode58 } from './base58';\n\nconst sha256 = (msg: string) => hex.stringify(sha256Hex(hex.parse(msg)));\n\nexport const fromHex = (hex: string): string => {\n const addr = `41${hex.substring(2)}`;\n const doubleSha256 = sha256(sha256(addr));\n const checkSum = doubleSha256.substring(0, 8);\n const address = Buffer.from(addr + checkSum, 'hex');\n\n return encode58(address);\n};\n\nexport const toHex = (base58Sting: string): string => {\n if (base58Sting.length <= 4) throw new Error('Invalid address provided');\n\n let address = Buffer.from(decode58(base58Sting)).toString('hex');\n\n const checkSum = address.substring(address.length - 8, address.length);\n address = address.substring(0, address.length - 8);\n\n const checkSum1 = sha256(sha256(address)).substring(0, 8);\n\n if (`${checkSum}` === `${checkSum1}`) return `0x${address.substring(2)}`;\n\n throw new Error('Invalid address provided');\n};\n", "const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst ALPHABET_MAP = ALPHABET.split('').reduce((acc: { [k: string]: number }, x, i) => {\n acc[x] = i;\n return acc;\n}, {});\n\nconst BASE = 58;\n\nexport const encode58 = (buffer: Buffer): string => {\n if (buffer.length === 0) return '';\n\n const digits = [0];\n\n for (let i = 0; i < buffer.length; i++) {\n for (let j = 0; j < digits.length; j++) digits[j] <<= 8;\n\n digits[0] += buffer[i];\n let carry = 0;\n\n for (let j = 0; j < digits.length; ++j) {\n digits[j] += carry;\n carry = (digits[j] / BASE) | 0;\n digits[j] %= BASE;\n }\n\n while (carry) {\n digits.push(carry % BASE);\n carry = (carry / BASE) | 0;\n }\n }\n\n for (let i = 0; buffer[i] === 0 && i < buffer.length - 1; i++) digits.push(0);\n\n return [...digits]\n .reverse()\n .map((digit) => ALPHABET[digit])\n .join('');\n};\n\nexport const decode58 = (data: string): number[] => {\n if (data.length === 0) return [];\n\n const bytes = [0];\n\n for (let i = 0; i < data.length; i++) {\n const c = data[i];\n\n if (!(c in ALPHABET_MAP)) throw new Error('Non-base58 character');\n\n for (let j = 0; j < bytes.length; j++) bytes[j] *= BASE;\n\n bytes[0] += ALPHABET_MAP[c];\n let carry = 0;\n\n for (let j = 0; j < bytes.length; ++j) {\n bytes[j] += carry;\n carry = bytes[j] >> 8;\n bytes[j] &= 0xff;\n }\n\n while (carry) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n for (let i = 0; data[i] === '1' && i < data.length - 1; i++) bytes.push(0);\n\n return bytes.reverse();\n};\n", "import type { Chain as ViemChain } from 'viem';\nimport { defineChain } from 'viem';\nimport type { EIP1559TxData, TxData } from '../api/types';\nimport { fromHex as tronAddressFromHex, toHex as tronAddressToHex } from './tron/crypto';\n\nexport const defaultTokenIcon = 'https://static.particle.network/token-list/defaultToken/default.png';\n\nexport const solana = defineChain({\n id: 101,\n name: 'Solana',\n nativeCurrency: {\n decimals: 9,\n name: 'Solana SOL',\n symbol: 'SOL',\n },\n rpcUrls: {\n default: {\n http: ['https://api.mainnet-beta.solana.com'],\n },\n },\n blockExplorers: {\n default: { name: 'Explorer', url: 'https://solscan.io' },\n },\n custom: {\n chainType: 'solana',\n },\n});\n\nexport type Chain = {\n id: number;\n name: string;\n};\n\nlet _getChains: () => readonly ViemChain[] = () => [];\n\nexport function setChainProvider(fn: () => readonly ViemChain[]) {\n _getChains = fn;\n}\n\nexport function isTron(chain: string | number | Chain): boolean {\n let chainInfo;\n if (typeof chain === 'string' || typeof chain === 'number') {\n chainInfo = getEVMChainInfoById(Number(chain));\n } else {\n chainInfo = getEVMChainInfoById(chain.id);\n }\n return chainInfo !== undefined && chainInfo.name.toLowerCase() === 'tron';\n}\n\nexport { tronAddressFromHex, tronAddressToHex };\n\nexport function getChainInfo(chain: Chain): ViemChain | undefined {\n const { id } = chain;\n return _getChains().find((c: ViemChain) => c.id === id);\n}\n\nexport const getChainType = (chain: ViemChain): 'evm' | 'solana' => {\n return (chain?.custom?.chainType as unknown as 'evm' | 'solana') || 'evm';\n};\n\nexport const getEvmChains = () => {\n return _getChains().filter((c: ViemChain) => getChainType(c) === 'evm');\n};\n\nexport const getSolanaChains = () => {\n return _getChains().filter((c: ViemChain) => getChainType(c) === 'solana');\n};\n\nexport const getEVMChainInfoById = (id: number) => {\n return getEvmChains()?.find((c: ViemChain) => c.id === id);\n};\n\nexport const getChainIcon = (chain: ViemChain | Chain): string => {\n if (chain && typeof chain !== 'number' && typeof (chain as ViemChain)?.custom?.icon === 'string') {\n return (chain as ViemChain).custom?.icon as string;\n }\n const chainId = typeof chain === 'number' ? chain : chain.id;\n if (isSolanaChain(chainId)) {\n return `https://static.particle.network/chains/solana/icons/${chainId}.png`;\n }\n return `https://static.particle.network/chains/evm/icons/${chainId}.png`;\n};\n\nexport const isChainSupportEIP1559 = (data: TxData | EIP1559TxData) => {\n if ('maxFeePerGas' in data || 'maxPriorityFeePerGas' in data) {\n return true;\n }\n return false;\n};\n\nexport const getSolanaChainInfoById = (id: number) => {\n return getSolanaChains()?.find((c: ViemChain) => c.id === id);\n};\n\nexport const isSolanaChain = (chain: Chain | number) => {\n const id = typeof chain === 'number' ? chain : chain.id;\n return id === 101 || id === 102 || id === 103;\n};\n", "import { EvmRpcMethod, SignTypedDataVersion } from '../types';\n\nexport const ethereumUtils = {\n getSignTypedVersion(method: string): SignTypedDataVersion {\n if (method === EvmRpcMethod.ethSignTypedData || method === EvmRpcMethod.ethSignTypedDataV1) {\n return SignTypedDataVersion.V1;\n } else if (method === EvmRpcMethod.ethSignTypedDataV3) {\n return SignTypedDataVersion.V3;\n } else {\n return SignTypedDataVersion.V4;\n }\n },\n\n isUniq(method: string): boolean {\n return method === EvmRpcMethod.personalSignUniq || method === EvmRpcMethod.ethSignTypedDataV4Uniq;\n },\n\n isSignTypedDataV1(method: string): boolean {\n return method === EvmRpcMethod.ethSignTypedDataV1 || method === EvmRpcMethod.ethSignTypedData;\n },\n};\n", "import base64url from 'base64url';\nimport type { LoginWithSocial, SocialAuthType } from '../api/authType';\nimport { AuthType } from '../api/authType';\nimport pnApi from '../api/pnApi';\nimport {\n mapToUserInfo,\n type CaptchaRequest,\n type LoginRequest,\n type OriginalUserInfo,\n type UserInfo,\n} from '../api/types';\nimport globalConfig from '../config';\nimport { encryptedStorage, userStorage } from '../storage';\nimport type { CloudflareOptions, ERC4337Options } from '../types';\nimport { AuthCoreEvent } from '../types/authCoreEvent';\nimport { type ConnectParam } from '../types/connectParam';\nimport { WalletType } from '../types/wallet';\nimport { getChainType } from '../utils/chainUtils';\nimport events from '../utils/eventUtils';\nimport { check, requireNotNullish } from '../utils/validate';\nimport { particleAuth } from './authCore';\nimport { clearLocalKey } from './masterPassword';\nimport wallet from './wallet';\n\n/**\n * get cloudflare turnstile response\n */\nexport const getCloudflareTurnstileResponse = async (options?: CloudflareOptions): Promise<string> => {\n const iframe = document.createElement('iframe');\n const theme = 'light';\n const language = options?.language || 'en';\n iframe.src = `${globalConfig.env.authCore}/cloudflare.html?language=${language}&theme=${theme}&_=0.1.1`;\n\n iframe.classList.add('particle-cloudflare-iframe');\n\n const style: Record<string, string> = {\n position: 'absolute',\n zIndex: '999',\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n border: 'none',\n background: 'none',\n width: '300px',\n height: '65px',\n left: '50%',\n top: '50%',\n transform: 'translate(-50%, -50%)',\n colorScheme: 'none',\n };\n\n for (const key in style) {\n iframe.style[key as any] = style[key];\n }\n\n const container = options?.getContainer\n ? typeof options.getContainer === 'function'\n ? options.getContainer()\n : options.getContainer\n : document.body;\n\n container.appendChild(iframe);\n\n return new Promise((resolve, reject) => {\n const listener = (event: MessageEvent) => {\n if (event.data.type === 'particle-auth-core-cloudflareToken') {\n window.removeEventListener('message', listener);\n container.removeChild(iframe);\n const token = event.data.token;\n if (token) {\n resolve(event.data.token);\n } else {\n reject('Validation failed');\n }\n }\n };\n window.addEventListener('message', listener);\n });\n};\n\nexport const getSocialAuthUrl = async (parms: LoginWithSocial) => {\n const { authType, appState, prompt } = parms;\n let { redirectUrl } = parms;\n\n if (!redirectUrl) {\n redirectUrl = window.location.href;\n }\n\n const { auth_url: thirdpartyAuthUrl, state } = await pnApi.getThirdpartyAuthUrl(\n authType as SocialAuthType,\n redirectUrl,\n appState,\n prompt\n );\n\n if (authType === 'twitter') {\n const dataStr = JSON.stringify({\n authType,\n redirectUrl,\n thirdpartyAuthUrl,\n state,\n });\n const data = base64url(dataStr);\n return `${globalConfig.env.authCore}/oauth.html?data=${data}`;\n }\n\n return thirdpartyAuthUrl;\n};\n\n/**\n * Third-Party Authentication Initiator\n * This function facilitates third-party authentication by obtaining the authentication URL based on the specified social authentication type and redirecting the user's browser to the generated URL.\n * If no redirect URL is provided, the function defaults to the current window location.\n * @param parms\n */\nexport const thirdpartyAuth = async (parms: LoginWithSocial) => {\n const url = await getSocialAuthUrl(parms);\n sessionStorage.setItem('auth-core-oauth-start', 'true');\n window.location.href = url;\n};\n\n/**\n * get connect phone / email captcha\n * @param param phone or email\n * @returns success(boolean)\n */\nexport const getConnectCaptcha = async (param: CaptchaRequest): Promise<boolean> => {\n check(globalConfig.initialized, 'Please init AuthCore first!');\n const result = await pnApi.sendCaptcha(param);\n return result;\n};\n\n/**\n * connect to auth core, login or register\n * @param param phone or email or jwt or social\n * @returns user info\n */\nexport const connect = async (param: ConnectParam): Promise<UserInfo> => {\n check(globalConfig.initialized, 'Please init AuthCore first!');\n const chainInfo = param.chain;\n if (chainInfo) {\n check(\n particleAuth.chains.find((chain) => chain.id === chainInfo.id && chain.name === chainInfo.name),\n `The chain ${JSON.stringify(param.chain)} is not supported`\n );\n delete param.chain;\n }\n\n let userInfo: OriginalUserInfo;\n let latestAuthType: AuthType;\n if ('phone' in param && 'code' in param && param.phone && param.code) {\n // connect with phone\n userInfo = await pnApi.login(param as LoginRequest);\n latestAuthType = AuthType.phone;\n } else if ('email' in param && 'code' in param && param.email && param.code) {\n // connect with phone\n userInfo = await pnApi.login(param as LoginRequest);\n latestAuthType = AuthType.email;\n } else if ('provider' in param && param.provider && 'thirdpartyCode' in param && param.thirdpartyCode) {\n // connect with provider\n userInfo = await pnApi.loginWithThirdparty({ provider: param.provider, thirdpartyCode: param.thirdpartyCode });\n latestAuthType = param.provider as AuthType;\n } else if (\n 'socialType' in param &&\n param.socialType &&\n 'code' in param &&\n param.code &&\n 'nonce' in param &&\n param.nonce\n ) {\n // connect with social\n userInfo = await pnApi.loginWithThirdpartyV2(param.socialType, param.code, param.nonce);\n latestAuthType = param.socialType as AuthType;\n } else {\n throw new Error('invalid connect param');\n }\n\n //\u767B\u5F55\u65F6\u751F\u6210\u94B1\u5305\uFF0C\u5982\u679C\u4E4B\u524D\u8BBE\u7F6E\u8FC7\u4E3B\u5BC6\u7801\uFF0C\u6E05\u9664\u672C\u5730localKey\n clearLocalKey();\n userStorage.setUserInfo(userInfo);\n try {\n await wallet.gen(\n chainInfo ? (getChainType(chainInfo) === 'evm' ? WalletType.EVM : WalletType.Solana) : WalletType.EVM\n );\n } catch (error) {\n userStorage.setUserInfo(undefined);\n throw error;\n }\n console.log('auth-core: connect success and save userInfo', userInfo);\n // Save the authType of the last login\n userStorage.setLatestAuthType(latestAuthType);\n\n if (chainInfo) {\n events.emit('connectWithChain', chainInfo);\n }\n\n const info = mapToUserInfo(userInfo);\n onConnect(info, param);\n return info;\n};\n\n/**\n * disconnect from auth core, remove all local data.\n */\nexport const disconnect = async () => {\n try {\n await pnApi.logout();\n } catch (error) {\n //ignore\n }\n encryptedStorage.clear();\n onDisconnect();\n};\n\nconst onConnect = (userInfo: UserInfo, param: ConnectParam) => {\n if ('socialType' in param && param.socialType && 'code' in param && param.code && 'nonce' in param && param.nonce) {\n if (typeof window !== 'undefined') {\n if ((window as any).particle?.ethereum) {\n (window as any).particle.ethereum.isSocialConnecting = false;\n }\n if ((window as any).particle?.solana) {\n (window as any).particle.solana.isSocialConnecting = false;\n }\n window.dispatchEvent(\n new CustomEvent('particle:socialConnectCompleted', {\n detail: Object.freeze(userInfo),\n })\n );\n }\n }\n\n setTimeout(() => events.emit(AuthCoreEvent.ParticleAuthConnect, userInfo), 0);\n};\n\nconst onDisconnect = () => {\n setTimeout(() => events.emit(AuthCoreEvent.ParticleAuthDisconnect), 0);\n};\n\n/**\n * check if connected\n * @returns true is connected\n */\nexport const isConnected = (): boolean => {\n return Boolean(getUserInfo());\n};\n\n/**\n * get user info from local storage, if not exist, return undefined\n * @returns user info\n */\nexport const getUserInfo = (): UserInfo | undefined => {\n const originalUserInfo = userStorage.getUserInfo();\n return originalUserInfo ? mapToUserInfo(originalUserInfo) : undefined;\n};\n\n/**\n * sync user info from server, if master password changed, will emit {@link AuthCoreEvent.MasterPasswordChanged} event\n * @returns user info\n */\nexport const syncUserInfo = async (): Promise<UserInfo> => {\n const userInfo = userStorage.getUserInfo();\n if (!userInfo) {\n throw new Error('Please connect first!');\n }\n const result = await pnApi.syncUserInfo();\n const masterPasswordChange = result.wallets.some((wallet) => {\n const localWallet = userInfo.wallets.find((item) => item.uuid == wallet.uuid);\n return !localWallet || localWallet.encrypted_data !== wallet.encrypted_data;\n });\n if (masterPasswordChange) {\n console.log('master password changed');\n clearLocalKey();\n setTimeout(() => events.emit(AuthCoreEvent.MasterPasswordChanged), 0);\n }\n\n const newUserInfo = { ...userInfo, ...result };\n userStorage.setUserInfo(newUserInfo);\n return mapToUserInfo(newUserInfo);\n};\n\n/**\n * get latest auth type, if not exist, return null\n * @returns AuthType\n */\nexport const getLatestAuthType = (): AuthType | null => {\n return userStorage.getLatestAuthType();\n};\n\n/**\n * get smart account address\n * @param options version, name, chainId\n * @returns\n */\nexport const getSmartAccountAddress = async (options: ERC4337Options) => {\n check(isConnected(), 'Please connect first!');\n const ownerAddress = requireNotNullish(particleAuth.ethereum.selectedAddress, 'Please create wallet first!');\n\n const { version, name } = options;\n const localKey = `auth_core_erc4337_${name}_${version}_${ownerAddress}`;\n const localAAAddress = localStorage.getItem(localKey);\n if (localAAAddress) {\n return localAAAddress;\n }\n const accounts = await particleAuth.ethereum.request({\n method: 'particle_aa_getSmartAccount',\n params: [{ version, name, ownerAddress }],\n });\n const smartAccountAddress = accounts[0].smartAccountAddress;\n localStorage.setItem(localKey, smartAccountAddress);\n return smartAccountAddress;\n};\n", "/* eslint-disable camelcase */\nimport axios from 'axios';\nimport sha256 from 'crypto-js/sha256.js';\nimport stringify from 'fast-json-stable-stringify';\nimport { v4 as uuid } from 'uuid';\nimport globalConfig from '../config';\nimport { encryptedStorage, userStorage } from '../storage';\nimport { AuthCoreEvent } from '../types';\nimport events from '../utils/eventUtils';\nimport { ApiError, isApiError, isRpcError } from './apiError';\n\n// Set config defaults when creating the instance\nconst client = axios.create({\n baseURL: globalConfig.env.baseUrl,\n timeout: 60000,\n validateStatus: function (status) {\n return status >= 200 && status <= 500;\n },\n withCredentials: false,\n});\n\n// Add a request interceptor\nclient.interceptors.request.use((config) => {\n const noneAuth = config.headers && config.headers['Auth-Type'] === 'None';\n if (noneAuth) {\n return config;\n }\n let macKey = '';\n const basicAuth = config.headers && config.headers['Auth-Type'] === 'Basic';\n if (basicAuth) {\n if (!isChainRpcRequest(config.baseURL)) {\n if (config.baseURL !== globalConfig.env.baseUrl) {\n config.baseURL = globalConfig.env.baseUrl;\n }\n const auth = {\n username: globalConfig.env.basicUsername,\n password: globalConfig.env.basicPassword,\n };\n macKey = sha256(auth.username + auth.password)\n .toString()\n .toLowerCase();\n config.auth = auth;\n }\n } else {\n //token auth\n const userInfo = userStorage.getUserInfo();\n if (!userInfo) {\n throw new Error('Please connect AuthCore first!');\n }\n const token = userInfo.token;\n macKey = userInfo.mac_key;\n config.headers.Authorization = `Bearer ${token}`;\n if (config.baseURL !== globalConfig.env.baseUrl) {\n config.baseURL = globalConfig.env.baseUrl;\n }\n }\n\n if (!config.params) {\n config.params = {};\n }\n\n if (isChainRpcRequest(config.baseURL)) {\n config.params = {\n ...config.params,\n chainId: config.data?.chainId || 1, // default chainId is 1 (Ethereum Mainnet)\n projectUuid: globalConfig.authOptions.projectId,\n projectKey: globalConfig.authOptions.clientKey,\n method: config.data?.method,\n };\n delete config.data.chainId;\n } else {\n const timestamp: number = Math.round(new Date().getTime() / 1000);\n const randomStr: string = uuid();\n config.params = {\n ...config.params,\n timestamp,\n random_str: randomStr,\n device_id: globalConfig.deviceId,\n sdk_version: globalConfig.version,\n project_uuid: globalConfig.authOptions.projectId,\n project_client_key: globalConfig.authOptions.clientKey,\n project_app_uuid: globalConfig.authOptions.appId,\n };\n\n const merged = { ...config.params };\n if (config.data) {\n Object.assign(merged, { ...config.data });\n }\n merged['mac_key'] = macKey;\n const mac = stringify(merged);\n config.params.mac = sha256(mac).toString().toLowerCase();\n }\n\n return config;\n});\n\nclient.interceptors.response.use((response) => {\n const data = response.data;\n if (response.status < 300 || response.status === 304) {\n if (isApiError(data)) {\n if (data.error_code === ApiError.InvalidToken) {\n // token invalid, clear user info\n encryptedStorage.clear();\n setTimeout(() => events.emit(AuthCoreEvent.ParticleAuthDisconnect, data), 0);\n }\n return Promise.reject(data);\n } else if (data.error && isRpcError(data.error)) {\n return Promise.reject(data.error);\n }\n return Promise.resolve(response);\n }\n\n console.log('http response error', response);\n // http error, reject it.\n return Promise.reject({\n code: response.status,\n message: response.statusText || 'Network Error',\n data: response.data,\n });\n});\n\nconst isChainRpcRequest = (baseUrl?: string) => {\n return baseUrl?.includes('rpc');\n};\n\nexport default client;\n", "import { userStorage } from '../storage';\nimport type { AuthType, SocialAuthType } from './authType';\nimport client from './client';\nimport type {\n CaptchaRequest,\n CognitoResult,\n DeviceInfo,\n LoginAccount,\n LoginBindRequest,\n LoginBindThirdpartyRequest,\n LoginRequest,\n OriginalUserInfo,\n SecurityAccount,\n ThirdpartyAuthUrlResult,\n UserInfoSync,\n UserWalletRequestParam,\n} from './types';\n\nconst pnApi = {\n /**\n * send auth code\n * @param data phone or email\n */\n async sendCaptcha(data: CaptchaRequest): Promise<boolean> {\n const response = await client.post('/code', data, {\n headers: {\n 'Auth-Type': 'Basic',\n },\n });\n return response.data.success;\n },\n\n /**\n * login\n