@gala-chain/gala-core-sdk 1.0.0 → 1.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -7
- package/dist/bridge.cjs +6 -1
- package/dist/bridge.cjs.map +1 -1
- package/dist/bridge.mjs +7 -2
- package/dist/bridge.mjs.map +1 -1
- package/dist/browser/bridge.js +1 -1
- package/dist/browser/bridge.js.map +1 -1
- package/dist/browser/classes/error_catalog.js.map +1 -1
- package/dist/browser/classes/error_phase_table.js.map +1 -1
- package/dist/browser/classes/error_phases.js.map +1 -1
- package/dist/browser/classes/gala_sdk_error.js +1 -1
- package/dist/browser/classes/gala_sdk_error.js.map +1 -1
- package/dist/browser/classes/signers.js +1 -1
- package/dist/browser/classes/signers.js.map +1 -1
- package/dist/browser/config/environments.js.map +1 -1
- package/dist/browser/index.js +1 -1
- package/dist/browser/providers.js.map +1 -1
- package/dist/browser/react.js.map +1 -1
- package/dist/browser/reads/gateway_reads.js +1 -1
- package/dist/browser/reads/gateway_reads.js.map +1 -1
- package/dist/browser/reads/parse.js.map +1 -1
- package/dist/browser/reads/request.js.map +1 -1
- package/dist/browser/reads/types.js.map +1 -1
- package/dist/browser/utils/axios_requestor.js.map +1 -1
- package/dist/browser/utils/chain_dto_signing.js.map +1 -1
- package/dist/browser/utils/class_key.js.map +1 -1
- package/dist/browser/utils/dto_operation.js +2 -0
- package/dist/browser/utils/dto_operation.js.map +1 -0
- package/dist/browser/utils/eip712.js.map +1 -1
- package/dist/browser/utils/error_brand.js.map +1 -1
- package/dist/browser/utils/eth_address.js.map +1 -1
- package/dist/browser/utils/ethers_provider.js.map +1 -1
- package/dist/browser/utils/failure_outcomes.js.map +1 -1
- package/dist/browser/utils/failure_view.js.map +1 -1
- package/dist/browser/utils/fetch_failure.js.map +1 -1
- package/dist/browser/utils/pre_send.js +1 -1
- package/dist/browser/utils/pre_send.js.map +1 -1
- package/dist/browser/utils/signing.js.map +1 -1
- package/dist/browser/utils/transport.js +1 -1
- package/dist/browser/utils/transport.js.map +1 -1
- package/dist/browser/utils/typed_data.js.map +1 -1
- package/dist/browser/utils/unique_key.js.map +1 -1
- package/dist/browser/utils/unique_key_syntax.js.map +1 -1
- package/dist/browser/utils/wallet_keys.js.map +1 -1
- package/dist/browser/utils/wallet_rejection.js.map +1 -1
- package/dist/browser/version.js +1 -1
- package/dist/browser/version.js.map +1 -1
- package/dist/browser/wallet.js.map +1 -1
- package/dist/browser/writes/gateway_writes.js +1 -1
- package/dist/browser/writes/gateway_writes.js.map +1 -1
- package/dist/browser/writes/identity.js.map +1 -1
- package/dist/browser/writes/lock.js.map +1 -1
- package/dist/browser/writes/submit.js +1 -1
- package/dist/browser/writes/submit.js.map +1 -1
- package/dist/browser/writes/token_ref.js.map +1 -1
- package/dist/browser/writes/transfer.js.map +1 -1
- package/dist/browser/writes/types.js.map +1 -1
- package/dist/index.cjs +119 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +95 -3
- package/dist/index.d.ts +95 -3
- package/dist/index.mjs +117 -9
- package/dist/index.mjs.map +1 -1
- package/package.json +30 -30
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/defineProperty.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPrimitive.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPropertyKey.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/typeof.js +0 -0
package/dist/bridge.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge.cjs","names":["BigNumber","stringifyTokenClassKey","stringifyTokenClassKey","GalaSDKError","isEthereumAddress","PublicKey","GalaSDKError","GalaSDKError","validateTimeoutMs","galaChainUserRef","normalizeTokenKey","GalaSDKError","GalaSDKError","GalaSDKError","GalaSDKError","isGalaError","isWalletUserRejection","walletDeclineCode","createUniqueKey","serialize","GalaSDKError","GalaSDKError","BigNumber","GalaSDKError","GalaSDKError","Contract","GalaSDKError","JsonRpcProvider","EthersWallet","galaChainUserRef","Signature","PublicKey","GalaSDKError","AccountLayout","base58","Keypair","EthersWallet","Connection","galaChainUserRef","TOKEN_PROGRAM_ID","ASSOCIATED_TOKEN_PROGRAM_ID","MintLayout","LAMPORTS_PER_SOL","Transaction","ComputeBudgetProgram","TransactionExpiredBlockheightExceededError","TransactionInstruction","SystemProgram","splitClassKey","GalaSDKError","centralStringify","isTokenClassKey","GalaSDKError","galaChainUserRef","GALA_CHAIN_ENVIRONMENTS","isGalaError","GalaSDKError","GalaSDKError","stringifyTokenClassKey","galaChainUserRef","createUniqueKey","signPreSend","Keypair","base58"],"sources":["../src/bridge/types/bridge.dto.ts","../src/bridge/types/eip712.ts","../src/bridge/internal/values.ts","../src/bridge/constants/tokens.ts","../src/bridge/utils/bridgeErrors.ts","../src/bridge/utils/RateLimiter.ts","../src/bridge/utils/retry.ts","../src/bridge/GalaConnectClient.ts","../src/bridge/utils/addressValidation.ts","../src/bridge/utils/balanceHelpers.ts","../src/bridge/utils/bridgePayload.ts","../src/bridge/utils/eip712Helpers.ts","../src/bridge/utils/bridgeOutHelpers.ts","../src/bridge/utils/bridgeStatusParser.ts","../src/bridge/utils/strategyDelegation.ts","../src/bridge/utils/tokenMetadataResolver.ts","../src/bridge/utils/tokenMath.ts","../src/bridge/strategies/BridgeStrategy.ts","../src/bridge/strategies/EthereumBridgeStrategy.ts","../src/bridge/strategies/SolanaBridgeStrategy.ts","../src/bridge/utils/tokenIdUtils.ts","../src/bridge/BridgeService.ts","../src/bridge/tokens/tokenPages.ts","../src/bridge/tokens/BridgeableTokenService.ts","../src/bridge/tokens/WrappableTokenService.ts","../src/bridge/tokens/WrapService.ts","../src/bridge/solanaWallet.ts","../src/bridge/utils/address-formatter.ts"],"sourcesContent":["/**\n * Bridge DTOs and Interfaces\n *\n * Type definitions for cross-chain bridging operations between\n * GalaChain, Ethereum, and Solana.\n */\n\nimport type { HttpRequestor, TokenClassKeyInput as TokenId } from '../../index.js';\n\n/**\n * Supported external networks for bridging\n */\nexport type ExternalNetwork = 'Ethereum' | 'Solana';\n\n/**\n * Token descriptor for GalaChain tokens\n */\nexport interface BridgeTokenDescriptor {\n collection: string;\n category: string;\n type: string;\n additionalKey: string;\n}\n\n/**\n * Token descriptor with instance (for specific token instances)\n */\nexport interface BridgeTokenInstance extends BridgeTokenDescriptor {\n instance: string;\n}\n\n/**\n * Ethereum token configuration\n */\nexport interface EthereumTokenConfig {\n symbol: string;\n amount: string;\n contractAddress: string;\n bridgeUsesPermit?: boolean;\n decimals?: number;\n}\n\n/**\n * Solana token configuration\n */\nexport interface SolanaTokenConfig {\n symbol: string;\n amount: string;\n mintAddress: string;\n isNative?: boolean;\n decimals?: number;\n}\n\n/**\n * Bridge token configuration from GalaConnect API\n */\nexport interface BridgeConfigurationToken extends BridgeTokenDescriptor {\n symbol: string;\n decimals: number;\n verified?: boolean;\n channel?: string;\n canBridgeTo?: Array<{\n network: string;\n symbol: string;\n destinationChainIds: string[];\n }>;\n otherNetworks?: Array<{\n network: string;\n symbol: string;\n contractAddress: string;\n canBridgeTo?: Array<{\n network: string;\n symbol: string;\n destinationChainIds: string[];\n }>;\n }>;\n}\n\n/**\n * Bridge token metadata for internal use\n *\n * Lightweight metadata for bridging operations,\n * distinct from blockchain metadata or cache entries.\n *\n * @since 6.10.0 - Renamed from TokenMetadata for clarity\n */\nexport interface BridgeTokenMetadata {\n /** Token descriptor (collection, category, type, additionalKey) */\n descriptor: BridgeTokenDescriptor;\n /** Token decimal places */\n decimals: number;\n /** GalaChain channel (optional) */\n channel?: string;\n}\n\n/**\n * External token information (for exchange rates)\n */\nexport interface ExternalTokenInfo {\n name: string;\n symbol: string;\n}\n\n/**\n * GALA exchange rate from oracle\n */\nexport interface GalaExchangeRate {\n identity: string;\n oracle: string;\n source: string;\n sourceUrl: string;\n timestamp: number | string;\n baseToken?: BridgeTokenInstance;\n exchangeRate: string;\n externalQuoteToken?: ExternalTokenInfo;\n}\n\n/**\n * Base token cross rate\n */\nexport interface BaseTokenCrossRate {\n identity: string;\n oracle: string;\n source: string;\n sourceUrl: string;\n timestamp: number | string;\n exchangeRate: string;\n externalBaseToken?: ExternalTokenInfo;\n externalQuoteToken?: ExternalTokenInfo;\n signature: string;\n}\n\n/**\n * Quote token cross rate\n */\nexport interface QuoteTokenCrossRate {\n identity: string;\n oracle: string;\n source: string;\n sourceUrl: string;\n timestamp: number | string;\n baseToken?: BridgeTokenInstance;\n exchangeRate: string;\n externalQuoteToken?: ExternalTokenInfo;\n signature: string;\n}\n\n/**\n * GALA exchange cross rate (for non-GALA tokens)\n */\nexport interface GalaExchangeCrossRate {\n baseTokenCrossRate?: BaseTokenCrossRate;\n crossRate: string;\n externalCrossRateToken?: ExternalTokenInfo;\n identity: string;\n oracle: string;\n quoteTokenCrossRate?: QuoteTokenCrossRate;\n source: string;\n timestamp: number | string;\n}\n\n/**\n * Destination chain transaction fee structure\n */\nexport interface DestinationChainTxFee {\n bridgeToken: BridgeTokenDescriptor;\n bridgeTokenIsNonFungible: boolean;\n estimatedPricePerTxFeeUnit: string;\n estimatedTotalTxFeeInExternalToken: string;\n estimatedTotalTxFeeInGala: string;\n estimatedTxFeeUnitsTotal: string;\n galaDecimals: number | string;\n galaExchangeRate?: GalaExchangeRate;\n galaExchangeCrossRate?: GalaExchangeCrossRate;\n timestamp: number | string;\n signingIdentity: string;\n signature: string;\n}\n\n/**\n * Bridge fee estimate returned to SDK users\n */\nexport interface BridgeFeeEstimate {\n /** Estimated fee in GALA */\n estimatedFeeInGala: string;\n /** Estimated fee in the external chain's native token */\n estimatedFeeInExternalToken: string;\n /** Token used for bridge fees */\n feeToken: BridgeTokenDescriptor;\n /** Gas price per unit */\n pricePerUnit: string;\n /** Total estimated gas units */\n estimatedGasUnits: string;\n /** GALA exchange rate at time of estimate */\n exchangeRate: string;\n /** Timestamp of the estimate */\n timestamp: number;\n /** Raw fee response for advanced usage */\n raw: DestinationChainTxFee;\n}\n\n/**\n * Bridge request DTO for outbound bridges\n */\nexport interface BridgeRequestDto {\n uniqueKey?: string;\n tokenInstance: BridgeTokenInstance;\n destinationChainId: number | string;\n quantity: string;\n recipient: string;\n destinationChainTxFee: DestinationChainTxFee;\n}\n\n/**\n * Bridge status codes\n */\nexport enum BridgeStatusCode {\n PENDING = 0,\n SUBMITTED = 1,\n CONFIRMED = 2,\n PROCESSING = 3,\n FINALIZING = 4,\n COMPLETED = 5,\n FAILED = 6,\n /** Delivery failed - tokens left source chain but failed to arrive on destination */\n DELIVERY_FAILED = 7,\n}\n\n/**\n * Bridge status response (normalized)\n */\nexport interface BridgeStatus {\n /** Numeric status code */\n status: BridgeStatusCode;\n /** Human-readable status description */\n statusDescription: string;\n /** Source chain */\n fromChain: string;\n /** Destination chain */\n toChain: string;\n /** Amount being bridged */\n quantity: string;\n /** Transaction hash on emitter chain */\n transactionHash: string;\n /** Token being bridged */\n tokenInstance?: BridgeTokenInstance;\n /** Whether the bridge is complete */\n isComplete: boolean;\n /** Whether the bridge failed */\n isFailed: boolean;\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Solana transaction status from RPC query\n *\n * Used by `getSolanaTransactionStatus()` to report the confirmation\n * status of Solana transactions (airdrops, bridges, etc.)\n */\nexport interface SolanaTransactionStatus {\n /**\n * Whether the transaction has been successfully processed on-chain.\n * - true: Transaction executed successfully\n * - false: Transaction not found, still pending, or failed\n */\n confirmed: boolean;\n\n /**\n * Detailed status of the transaction:\n * - 'confirmed': Transaction confirmed by supermajority of cluster\n * - 'finalized': Transaction finalized (maximum certainty)\n * - 'processed': Transaction processed by connected node\n * - 'not_found': Transaction not yet visible on-chain\n * - 'failed': Transaction was processed but failed (see error field)\n */\n status: 'confirmed' | 'finalized' | 'processed' | 'not_found' | 'failed';\n\n /**\n * Block slot number where transaction was processed.\n * Present when transaction has been found on-chain.\n */\n slot?: number;\n\n /**\n * Error details if transaction failed.\n * Contains JSON-stringified Solana error object.\n */\n error?: string;\n}\n\n/**\n * Ethereum transaction status from RPC query\n *\n * Used by `getEthereumTransactionStatus()` to report the confirmation\n * status of Ethereum transactions (bridges, transfers, etc.)\n */\nexport interface EthereumTransactionStatus {\n /**\n * Whether the transaction has been successfully processed on-chain.\n * - true: Transaction confirmed and executed successfully\n * - false: Transaction not found, still pending, or failed\n */\n confirmed: boolean;\n\n /**\n * Detailed status of the transaction:\n * - 'pending': Transaction in mempool, not yet mined\n * - 'confirmed': Transaction mined in block\n * - 'finalized': Transaction finalized (12+ confirmations for safety)\n * - 'not_found': Transaction not yet visible on-chain\n * - 'failed': Transaction mined but execution failed (reverted)\n */\n status: 'pending' | 'confirmed' | 'finalized' | 'not_found' | 'failed';\n\n /**\n * Block number where transaction was mined.\n * Present when transaction has been found on-chain.\n */\n blockNumber?: number;\n\n /**\n * Number of confirmations since block inclusion.\n * Calculated as (currentBlockNumber - blockNumber + 1).\n * Higher values indicate stronger finality.\n */\n confirmations?: number;\n\n /**\n * Transaction hash (normalized to lowercase).\n */\n transactionHash: string;\n\n /**\n * Gas used by transaction (if mined).\n */\n gasUsed?: string;\n\n /**\n * Effective gas price in wei (if mined).\n */\n effectiveGasPrice?: string;\n\n /**\n * Error details if transaction failed.\n * Contains the revert reason or execution error.\n */\n error?: string;\n}\n\n/**\n * Bridge transaction result\n */\nexport interface BridgeTransaction {\n /** Direction of the bridge */\n direction: 'outbound' | 'inbound';\n /** Source chain */\n fromChain: string;\n /** Destination chain */\n toChain: string;\n /** Transaction hash */\n transactionHash: string;\n /** Token symbol */\n tokenSymbol: string;\n /** Amount bridged */\n amount: string;\n /** Fee paid (in GALA for outbound, native token for inbound) */\n feePaid?: string;\n /** Timestamp when transaction was submitted */\n timestamp: number;\n /** Bridge status tracking URL */\n statusUrl: string;\n}\n\n/**\n * Bridge leg result (for round-trip tracking)\n */\nexport interface BridgeLegResult {\n direction: 'Outbound' | 'Inbound';\n fromChain: string;\n toChain: string;\n startTimestamp: number;\n endTimestamp?: number;\n durationMs?: number;\n feePaid?: string;\n feeToken?: string;\n transactionHash?: string;\n additionalInfo?: Record<string, unknown>;\n error?: string;\n}\n\n/**\n * Token round-trip result\n */\nexport interface TokenRoundTripResult {\n token: string;\n network: ExternalNetwork;\n amount: string;\n legs: BridgeLegResult[];\n outboundCompleted: boolean;\n inboundCompleted: boolean;\n roundTripDurationMs?: number;\n totalFees?: Array<{ amount: string; token: string; context: string }>;\n failures?: string[];\n}\n\n/**\n * Supported bridge token info for discovery\n */\nexport interface BridgeToken {\n /** Token symbol (e.g., 'GALA', 'GWETH') */\n symbol: string;\n /** Token name */\n name?: string;\n /** Token decimals */\n decimals: number;\n /** Whether verified by Gala */\n verified: boolean;\n /** Supported destination chains */\n supportedChains: ExternalNetwork[];\n /** GalaChain token descriptor */\n galaChainDescriptor: BridgeTokenDescriptor;\n /** External chain addresses */\n externalAddresses: {\n ethereum?: string;\n solana?: string;\n };\n}\n\n/**\n * Bridge SDK configuration\n */\nexport interface BridgeConfig {\n /** GalaConnect API base URL */\n galaConnectBaseUrl: string;\n /** GalaChain API base URL (optional, defaults to galaConnectBaseUrl) */\n galaChainApiBaseUrl?: string;\n /** Ethereum RPC URL (optional, defaults to public endpoint) */\n ethereumRpcUrl?: string;\n /** Solana RPC URL (optional, defaults to public endpoint) */\n solanaRpcUrl?: string;\n /** Ethereum bridge contract address (optional, defaults to mainnet) */\n ethereumBridgeContract?: string;\n /** Solana bridge program ID (optional, defaults to mainnet) */\n solanaBridgeProgram?: string;\n /** Ethereum private key for inbound bridges (optional) */\n ethereumPrivateKey?: string;\n /** Solana private key (base58) for inbound bridges (optional) */\n solanaPrivateKey?: string;\n /** Rate limit for API calls (requests per second) */\n rateLimit?: number;\n /** Status polling interval in milliseconds */\n pollInterval?: number;\n /** Status polling timeout in milliseconds */\n pollTimeout?: number;\n}\n\n/**\n * Parameters for estimating bridge fees\n *\n * @example Using string tokenId (pipe-delimited)\n * ```typescript\n * const fee = await sdk.estimateBridgeFee({\n * tokenId: 'GALA|Unit|none|none',\n * destinationChain: 'Ethereum',\n * });\n * ```\n *\n * @example Using TokenClassKey object\n * ```typescript\n * const fee = await sdk.estimateBridgeFee({\n * tokenId: { collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' },\n * destinationChain: 'Ethereum',\n * });\n * ```\n */\nexport interface EstimateBridgeFeeParams {\n /**\n * Token identifier - accepts pipe-delimited string or TokenClassKey object.\n *\n * Get from `fetchAllBridgeableTokensByNetwork()` result's `stringifiedTokenClassKey` field,\n * or construct manually: `{ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }`\n */\n tokenId: TokenId;\n /** Destination chain (the fee is a per-transfer cost: it does not depend on the amount) */\n destinationChain: ExternalNetwork;\n}\n\n/**\n * Parameters for bridging out (GalaChain -> External)\n *\n * @example Bridge GALA to Ethereum\n * ```typescript\n * const result = await sdk.bridgeOut({\n * tokenId: 'GALA|Unit|none|none',\n * amount: '100',\n * destinationChain: 'Ethereum',\n * recipientAddress: '0x1234...abcd',\n * });\n * ```\n */\nexport interface BridgeOutParams {\n /**\n * Token identifier - accepts pipe-delimited string or TokenClassKey object.\n *\n * Get from `fetchAllBridgeableTokensByNetwork()` result's `stringifiedTokenClassKey` field,\n * or construct manually: `{ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }`\n */\n tokenId: TokenId;\n /** Amount to bridge */\n amount: string;\n /** Destination chain */\n destinationChain: ExternalNetwork;\n /** Recipient address on destination chain */\n recipientAddress: string;\n /** Optional slippage tolerance for fee (0-1, e.g., 0.01 for 1%) */\n feeSlippageTolerance?: number;\n /**\n * @internal Resolved token symbol (set by BridgeService, not user-provided)\n */\n tokenSymbol?: string;\n}\n\n/**\n * Parameters for bridging in (External -> GalaChain)\n *\n * @example Bridge GALA from Ethereum to GalaChain\n * ```typescript\n * const result = await sdk.bridgeIn({\n * tokenId: 'GALA|Unit|none|none',\n * amount: '100',\n * sourceChain: 'Ethereum',\n * sourcePrivateKey: '0xabc...', // Ethereum wallet private key\n * });\n * ```\n */\nexport interface BridgeInParams {\n /**\n * Token identifier - accepts pipe-delimited string or TokenClassKey object.\n *\n * Get from `fetchAllBridgeableTokensByNetwork()` result's `stringifiedTokenClassKey` field,\n * or construct manually: `{ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }`\n */\n tokenId: TokenId;\n /** Amount to bridge */\n amount: string;\n /** Source chain */\n sourceChain: ExternalNetwork;\n /** Private key for source chain wallet (overrides config) */\n sourcePrivateKey?: string;\n /** Recipient GalaChain address (optional, defaults to SDK wallet) */\n recipientAddress?: string;\n /**\n * @internal Resolved token symbol (set by BridgeService, not user-provided)\n */\n tokenSymbol?: string;\n}\n\n/**\n * Options for waiting on bridge completion\n */\nexport interface WaitForBridgeOptions {\n /** Polling interval in milliseconds (default: 15000) */\n pollInterval?: number;\n /** Timeout in milliseconds (default: 45 minutes) */\n timeout?: number;\n /** Callback for status updates */\n onStatusUpdate?: (status: BridgeStatus) => void;\n}\n\n// ============================================================================\n// GalaConnect API Response Types\n// ============================================================================\n\n/**\n * Configuration for GalaConnect client\n */\nexport interface GalaConnectConfig {\n /** GalaConnect API base URL */\n baseUrl?: string;\n /** GalaChain API base URL */\n galachainBaseUrl?: string;\n /**\n * The wallet's GalaChain user reference: an Ethereum account (`eth|...`, `0x...`, bare hex; sent\n * as `eth|<checksummed>`) or a `client|` alias; `''` for a client with no wallet.\n */\n walletAddress: string;\n /** Sends the HTTP requests (default: the global `fetch`) */\n httpRequestor?: HttpRequestor;\n /**\n * How long one request may take, in milliseconds (default 30 000; `Infinity` for no limit). A\n * read that runs out is `REQUEST_TIMEOUT`, a write `BRIDGE_WRITE_OUTCOME_UNKNOWN`.\n */\n requestTimeoutMs?: number;\n /** Requests per second (rate limiting) */\n requestsPerSecond?: number;\n /**\n * Enable automatic retry for transient failures (default: true)\n *\n * When enabled, requests that fail due to network errors or\n * server errors (5xx, 429) will be automatically retried with\n * exponential backoff.\n */\n enableRetry?: boolean;\n /**\n * Maximum number of retry attempts (default: 3)\n *\n * Only used when enableRetry is true.\n */\n maxRetries?: number;\n /**\n * Initial delay in milliseconds before first retry (default: 1000)\n *\n * Subsequent retries use exponential backoff (delay doubles each time).\n */\n retryInitialDelayMs?: number;\n /**\n * Callback invoked before each retry attempt.\n *\n * Useful for logging or monitoring retry behavior.\n *\n * @param error - The error that triggered the retry\n * @param attempt - Current attempt number (1-based)\n * @param delayMs - Delay before next attempt in milliseconds\n */\n onRetry?: (error: unknown, attempt: number, delayMs: number) => void;\n}\n\n/**\n * Bridge fee response from GalaConnect API\n */\nexport interface BridgeFeeResponse {\n bridgeToken: BridgeTokenDescriptor;\n bridgeTokenIsNonFungible: boolean;\n estimatedPricePerTxFeeUnit: string;\n estimatedTotalTxFeeInExternalToken: string;\n estimatedTotalTxFeeInGala: string;\n estimatedTxFeeUnitsTotal: string;\n galaDecimals: number;\n galaExchangeRate: GalaExchangeRate;\n galaExchangeCrossRate?: GalaExchangeCrossRate;\n timestamp: number;\n signingIdentity: string;\n signature: string;\n}\n\n/**\n * Response from RequestTokenBridgeOut API\n *\n * Note: The GalaConnect API may return additional undocumented fields.\n * The index signature ensures compatibility with Record<string, unknown>\n * while preserving type safety for known fields.\n *\n * Known fields may appear in different casings (e.g., Data/data, Hash/hash)\n * due to API response inconsistencies across different endpoints.\n */\nexport interface RequestBridgeOutResponse {\n Data?: string;\n data?: { Data?: string } | string;\n Hash?: string;\n hash?: string;\n Status?: number;\n status?: number;\n message?: string;\n /** Index signature for API compatibility (additional undocumented fields) */\n [key: string]: unknown;\n}\n\n/**\n * Response from BridgeTokenOut API\n */\nexport interface BridgeTokenOutResponse {\n Data?: {\n chainId: number;\n emitter: string;\n nonce: string;\n sequence: string;\n payload: string;\n };\n Hash?: string;\n hash?: string;\n Status?: number;\n status?: number;\n message?: string;\n}\n\n/**\n * Response from bridge status API.\n *\n * Note: The API returns a flat response structure (no data wrapper).\n */\nexport interface BridgeStatusResponse {\n /** Status code (0-6 mapping to BridgeStatusCode) */\n status: number;\n /** Human-readable status description */\n statusDescription: string;\n /** Source chain (e.g., \"GC\" for GalaChain) */\n fromChain: string;\n /** Destination chain (e.g., \"Ethereum\") */\n toChain: string;\n /** Amount being bridged */\n quantity: string;\n /** Transaction hash on the emitter (source) chain */\n emitterTransactionHash: string;\n /** Token instance being bridged */\n tokenInstance: BridgeTokenInstance;\n /** Transaction hash on the receiver (destination) chain, if available */\n receiverTransactionHash?: string;\n}\n\n/**\n * Response from bridge transaction registration API\n */\nexport interface BridgeTransactionRegistrationResponse {\n status: number;\n message: string;\n error: boolean;\n data?: Record<string, unknown>;\n}\n\n/**\n * Token balance entry from FetchBalances\n */\nexport interface TokenBalanceEntry {\n tokenInstance: BridgeTokenInstance;\n balance: string;\n locked?: string;\n}\n\n/**\n * Response from FetchBalances API\n */\nexport interface FetchBalancesResponse {\n status: number;\n message: string;\n error: boolean;\n data?: {\n balances: TokenBalanceEntry[];\n };\n}\n\n// ============================================================================\n// External Chain Wallet Balance Types\n// ============================================================================\n\n/**\n * Balance for a single token on an external chain (Ethereum or Solana)\n *\n * Represents either a native token (ETH/SOL) or a token contract (ERC-20/SPL).\n *\n * @example\n * ```typescript\n * // Native ETH balance\n * const ethBalance: ExternalChainBalance = {\n * symbol: 'ETH',\n * quantity: '1.500000000000000000',\n * decimals: 18,\n * contractAddress: null,\n * isNative: true,\n * };\n *\n * // ERC-20 GALA balance\n * const galaBalance: ExternalChainBalance = {\n * symbol: 'GALA',\n * quantity: '1000.00000000',\n * decimals: 8,\n * contractAddress: '0x15D4c048F83bd7e37d49eA4C83a07267Ec4203dA',\n * isNative: false,\n * };\n * ```\n */\nexport interface ExternalChainBalance {\n /** Token symbol (e.g., \"GALA\", \"GWETH\", \"ETH\", \"SOL\") */\n symbol: string;\n /** Balance as decimal string (e.g., \"123.45678901\") */\n quantity: string;\n /** Token decimals */\n decimals: number;\n /** Contract address (ERC-20) or mint address (SPL), null for native tokens */\n contractAddress: string | null;\n /** Whether this is the native token (ETH/SOL) */\n isNative: boolean;\n}\n\n/**\n * Complete Ethereum wallet balance result\n *\n * Returns native ETH balance plus all supported ERC-20 token balances:\n * GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC\n *\n * @example\n * ```typescript\n * const result = await sdk.fetchEthereumWalletBalance('0x...');\n * console.log(`ETH: ${result.native.quantity}`);\n * console.log(`Tokens: ${result.tokens.map(t => `${t.symbol}: ${t.quantity}`).join(', ')}`);\n * ```\n */\nexport interface EthereumWalletBalanceResult {\n /** Wallet address queried (0x format) */\n address: string;\n /** Native ETH balance */\n native: ExternalChainBalance;\n /** ERC-20 token balances (GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC) */\n tokens: ExternalChainBalance[];\n /** Query timestamp (epoch ms) */\n timestamp: number;\n}\n\n/**\n * Complete Solana wallet balance result\n *\n * Returns native SOL balance plus all supported SPL token balances:\n * GALA, GSOL\n *\n * @example\n * ```typescript\n * const result = await sdk.fetchSolanaWalletBalance('9WzDXw...');\n * console.log(`SOL: ${result.native.quantity}`);\n * console.log(`Tokens: ${result.tokens.map(t => `${t.symbol}: ${t.quantity}`).join(', ')}`);\n * ```\n */\nexport interface SolanaWalletBalanceResult {\n /** Wallet address queried (base58 format) */\n address: string;\n /** Native SOL balance */\n native: ExternalChainBalance;\n /** SPL token balances (GALA, GSOL) */\n tokens: ExternalChainBalance[];\n /** Query timestamp (epoch ms) */\n timestamp: number;\n}\n","/**\n * EIP-712 Typed Data Schemas for GalaChain Bridge\n *\n * These schemas define the structure for typed data signing\n * required by the GalaChain bridge.\n */\n\n/**\n * GalaConnect typed data domain\n */\nexport const GALA_BRIDGE_TYPED_DATA_DOMAIN = {\n name: 'GalaConnect',\n chainId: 1,\n} as const;\n\n/**\n * EIP-712 type definition\n */\nexport interface TypedDataField {\n name: string;\n type: string;\n}\n\n// ============================================================================\n// Common Type Definitions (shared between legacy and cross-rate schemas)\n// ============================================================================\n\n/**\n * Common GalaTransaction fields (identical in both schemas)\n */\nconst GALA_TRANSACTION_TYPE: TypedDataField[] = [\n { name: 'destinationChainId', type: 'uint256' },\n { name: 'destinationChainTxFee', type: 'destinationChainTxFee' },\n { name: 'quantity', type: 'string' },\n { name: 'recipient', type: 'string' },\n { name: 'tokenInstance', type: 'tokenInstance' },\n { name: 'uniqueKey', type: 'string' },\n];\n\n/**\n * Bridge token descriptor (GalaChain token class key)\n */\nconst BRIDGE_TOKEN_TYPE: TypedDataField[] = [\n { name: 'collection', type: 'string' },\n { name: 'category', type: 'string' },\n { name: 'type', type: 'string' },\n { name: 'additionalKey', type: 'string' },\n];\n\n/**\n * Token instance with instance field (for specific token instances)\n */\nconst TOKEN_INSTANCE_TYPE: TypedDataField[] = [\n { name: 'collection', type: 'string' },\n { name: 'category', type: 'string' },\n { name: 'type', type: 'string' },\n { name: 'additionalKey', type: 'string' },\n { name: 'instance', type: 'string' },\n];\n\n/**\n * External token info (name and symbol only)\n */\nconst EXTERNAL_TOKEN_TYPE: TypedDataField[] = [\n { name: 'name', type: 'string' },\n { name: 'symbol', type: 'string' },\n];\n\n// ============================================================================\n// Schema-Specific Type Definitions\n// ============================================================================\n\n/**\n * Legacy typed data types (for tokens with direct GALA exchange rate)\n */\nexport const LEGACY_TYPED_DATA_TYPES: Record<string, TypedDataField[]> = {\n GalaTransaction: GALA_TRANSACTION_TYPE,\n destinationChainTxFee: [\n { name: 'bridgeToken', type: 'bridgeToken' },\n { name: 'bridgeTokenIsNonFungible', type: 'bool' },\n { name: 'estimatedPricePerTxFeeUnit', type: 'string' },\n { name: 'estimatedTotalTxFeeInExternalToken', type: 'string' },\n { name: 'estimatedTotalTxFeeInGala', type: 'string' },\n { name: 'estimatedTxFeeUnitsTotal', type: 'string' },\n { name: 'galaDecimals', type: 'uint256' },\n { name: 'galaExchangeRate', type: 'galaExchangeRate' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'signingIdentity', type: 'string' },\n { name: 'signature', type: 'string' },\n ],\n bridgeToken: BRIDGE_TOKEN_TYPE,\n galaExchangeRate: [\n { name: 'identity', type: 'string' },\n { name: 'oracle', type: 'string' },\n { name: 'source', type: 'string' },\n { name: 'sourceUrl', type: 'string' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'baseToken', type: 'baseToken' },\n { name: 'exchangeRate', type: 'string' },\n { name: 'externalQuoteToken', type: 'externalQuoteToken' },\n ],\n baseToken: TOKEN_INSTANCE_TYPE,\n externalQuoteToken: EXTERNAL_TOKEN_TYPE,\n tokenInstance: TOKEN_INSTANCE_TYPE,\n};\n\n/**\n * Cross-rate typed data types (for tokens requiring cross-rate calculation)\n */\nexport const CROSS_RATE_TYPED_DATA_TYPES: Record<string, TypedDataField[]> = {\n GalaTransaction: GALA_TRANSACTION_TYPE,\n destinationChainTxFee: [\n { name: 'bridgeToken', type: 'bridgeToken' },\n { name: 'bridgeTokenIsNonFungible', type: 'bool' },\n { name: 'estimatedPricePerTxFeeUnit', type: 'string' },\n { name: 'estimatedTotalTxFeeInExternalToken', type: 'string' },\n { name: 'estimatedTotalTxFeeInGala', type: 'string' },\n { name: 'estimatedTxFeeUnitsTotal', type: 'string' },\n { name: 'galaDecimals', type: 'uint256' },\n { name: 'galaExchangeCrossRate', type: 'galaExchangeCrossRate' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'signingIdentity', type: 'string' },\n { name: 'signature', type: 'string' },\n ],\n bridgeToken: BRIDGE_TOKEN_TYPE,\n galaExchangeCrossRate: [\n { name: 'baseTokenCrossRate', type: 'baseTokenCrossRate' },\n { name: 'crossRate', type: 'string' },\n { name: 'externalCrossRateToken', type: 'externalCrossRateToken' },\n { name: 'identity', type: 'string' },\n { name: 'oracle', type: 'string' },\n { name: 'quoteTokenCrossRate', type: 'quoteTokenCrossRate' },\n { name: 'source', type: 'string' },\n { name: 'timestamp', type: 'uint256' },\n ],\n baseTokenCrossRate: [\n { name: 'identity', type: 'string' },\n { name: 'oracle', type: 'string' },\n { name: 'source', type: 'string' },\n { name: 'sourceUrl', type: 'string' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'exchangeRate', type: 'string' },\n { name: 'externalBaseToken', type: 'externalBaseToken' },\n { name: 'externalQuoteToken', type: 'externalQuoteToken' },\n { name: 'signature', type: 'string' },\n ],\n externalBaseToken: EXTERNAL_TOKEN_TYPE,\n externalQuoteToken: EXTERNAL_TOKEN_TYPE,\n externalCrossRateToken: EXTERNAL_TOKEN_TYPE,\n quoteTokenCrossRate: [\n { name: 'identity', type: 'string' },\n { name: 'oracle', type: 'string' },\n { name: 'source', type: 'string' },\n { name: 'sourceUrl', type: 'string' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'baseToken', type: 'baseToken' },\n { name: 'exchangeRate', type: 'string' },\n { name: 'externalQuoteToken', type: 'externalQuoteToken' },\n { name: 'signature', type: 'string' },\n ],\n baseToken: TOKEN_INSTANCE_TYPE,\n tokenInstance: TOKEN_INSTANCE_TYPE,\n};\n\n/**\n * Get the appropriate typed data types based on whether cross-rate is used\n *\n * @param hasCrossRate - Whether the fee uses cross-rate calculation\n * @returns The appropriate typed data types for EIP-712 signing\n */\nexport function getGalaBridgeTypedDataTypes(\n hasCrossRate: boolean,\n): Record<string, TypedDataField[]> {\n return hasCrossRate ? CROSS_RATE_TYPED_DATA_TYPES : LEGACY_TYPED_DATA_TYPES;\n}\n","/**\n * The small value helpers the bridge code used from launchpad-sdk's utils (`safe-parsers`,\n * `primitives`, `error-utils`, `tokenNameNormalizer`, `token-stringification`, `numeric-wrappers`,\n * `bignumber-helpers`), copied with the same behaviour. Internal to `./bridge`: never exported.\n */\nimport BigNumber from 'bignumber.js';\nimport type { GalaChainTokenClassKey } from '../../index.js';\n\n/** `null` or `undefined`. */\nexport function isNullish(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** `null`, `undefined` or `''`. */\nexport function isEmptyValue(value: unknown): value is null | undefined | '' {\n return value === null || value === undefined || value === '';\n}\n\n/** A string with something other than whitespace in it. */\nexport function isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/**\n * The fields of `value` when it is an object, else none: how an answer is read without trusting\n * its shape (an empty answer, `null`, a string all have no fields).\n */\nexport function fieldsOf(value: unknown): Record<string, unknown> {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};\n}\n\n/** A non-null object that is not an array. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Whether `record` has a string at each of `required`, and at each of `optional` either nothing\n * or a value of the type named for it.\n */\nexport function hasFields(\n record: Record<string, unknown>,\n required: readonly string[],\n optional: Readonly<Record<string, 'string' | 'number' | 'boolean' | 'object'>> = {},\n): boolean {\n return (\n required.every((key) => typeof record[key] === 'string') &&\n Object.entries(optional).every(([key, kind]) => {\n const value = record[key];\n return value === undefined || (kind === 'object' ? isRecord(value) : typeof value === kind);\n })\n );\n}\n\n/** A finite number. */\nexport function isValidNumber(value: unknown): value is number {\n if (typeof value !== 'number') return false;\n return !isNaN(value) && isFinite(value);\n}\n\n/**\n * An integer from a number (floored), a bigint or a decimal string (`parseInt`), or `fallback`\n * for nullish, `NaN` and unparseable input.\n */\nexport function safeParseInt(\n value: string | number | bigint | null | undefined,\n fallback: number,\n): number {\n if (isNullish(value)) {\n return fallback;\n }\n if (typeof value === 'bigint') {\n return Number(value);\n }\n if (typeof value === 'number') {\n return isNaN(value) ? fallback : Math.floor(value);\n }\n const parsed = parseInt(String(value), 10);\n return isNaN(parsed) ? fallback : parsed;\n}\n\n/** A finite float (`parseFloat`), or `fallback` for empty, `NaN` and infinite input. */\nexport function safeParseFloat(value: string | number | null | undefined, fallback = 0): number {\n if (isEmptyValue(value)) {\n return fallback;\n }\n if (typeof value === 'number') {\n return isNaN(value) || !isFinite(value) ? fallback : value;\n }\n const parsed = parseFloat(value);\n return isNaN(parsed) || !isFinite(parsed) ? fallback : parsed;\n}\n\n/** `JSON.parse(value)`, or `fallback` for empty or invalid JSON. */\nexport function safeParseJson<T>(value: string | null | undefined, fallback: T): T {\n if (isEmptyValue(value)) {\n return fallback;\n }\n try {\n return JSON.parse(value) as T;\n } catch {\n return fallback;\n }\n}\n\n/** A BigNumber of `value`, or of `fallback` for empty, `NaN` or infinite input. */\nexport function toBigNumber(\n value: string | number | BigNumber | null | undefined,\n fallback: string | number = '0',\n): BigNumber {\n if (isEmptyValue(value)) {\n return new BigNumber(fallback);\n }\n if (BigNumber.isBigNumber(value)) {\n return value.isNaN() ? new BigNumber(fallback) : value;\n }\n try {\n const parsed = new BigNumber(value);\n return parsed.isNaN() || !parsed.isFinite() ? new BigNumber(fallback) : parsed;\n } catch {\n // `BigNumber.DEBUG = true` (an app setting on the shared bignumber.js) makes a non-number throw.\n return new BigNumber(fallback);\n }\n}\n\n/** `true` when an error is an `Error`. */\nexport function isError(error: unknown): error is Error {\n return error instanceof Error;\n}\n\n/** The message of an error, of an object with a string `message`, a string, or `String(error)`. */\nexport function getErrorMessage(error: unknown): string {\n if (isError(error)) {\n return error.message;\n }\n if (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n return typeof error === 'string' ? error : String(error);\n}\n\n/** The string or number `code` of an error object, if it has one. */\nexport function getErrorCode(error: unknown): string | number | undefined {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (typeof error.code === 'string' || typeof error.code === 'number')\n ) {\n return error.code;\n }\n return undefined;\n}\n\n/** A token symbol (or a token map key) as compared: trimmed, upper case. */\nexport function normalizeTokenSymbol(symbol: string): string {\n return symbol.trim().toUpperCase();\n}\n\n/** The pipe-delimited form of a class key: `collection|category|type|additionalKey`. */\nexport function stringifyTokenClassKey(token: GalaChainTokenClassKey): string {\n return `${token.collection}|${token.category}|${token.type}|${token.additionalKey}`;\n}\n","/**\n * Bridge Token Constants\n *\n * Static token configurations and chain IDs for bridging.\n */\n\nimport { normalizeTokenSymbol, stringifyTokenClassKey } from '../internal/values.js';\nimport type {\n BridgeTokenDescriptor,\n BridgeTokenMetadata,\n EthereumTokenConfig,\n SolanaTokenConfig,\n} from '../types/bridge.dto.js';\n\n/**\n * Chain IDs used by the external bridge system (Ethereum/Solana)\n */\nexport const CHAIN_IDS = {\n GALA_CHAIN: 1,\n ETHEREUM: 2,\n SOLANA: 1002,\n} as const;\n\n/**\n * Internal GalaChain Channel IDs (for wrap/unwrap operations)\n *\n * Different from external CHAIN_IDS used for Ethereum/Solana bridges.\n * These represent internal GalaChain channels for cross-channel token transfers.\n *\n * @example\n * ```typescript\n * // Wrap: MUSIC (music channel) → GMUSIC (asset channel)\n * destinationChainId: GALACHAIN_CHANNELS.ASSET\n *\n * // Unwrap: GMUSIC (asset channel) → MUSIC (music channel)\n * destinationChainId: GALACHAIN_CHANNELS.MUSIC\n * ```\n */\nexport const GALACHAIN_CHANNELS = {\n /** Asset channel - where wrapped tokens (GMUSIC, GWETH, GALA, etc.) live */\n ASSET: 1,\n /** Music channel - where native MUSIC token lives (legacy) */\n MUSIC: 3,\n} as const;\n\n/** Type for internal GalaChain channel IDs */\nexport type GalaChainChannel = (typeof GALACHAIN_CHANNELS)[keyof typeof GALACHAIN_CHANNELS];\n\n/**\n * Check if a number is a valid GalaChain channel ID\n *\n * @param channel - Channel ID to validate\n * @returns True if valid GalaChain channel\n */\nexport function isValidGalaChainChannel(channel: number): channel is GalaChainChannel {\n return Object.values(GALACHAIN_CHANNELS).includes(channel as GalaChainChannel);\n}\n\n/**\n * Rate limit for GalaConnect API (requests per second)\n */\nexport const DEFAULT_RATE_LIMIT_RPS = 12;\n\n/**\n * Default polling interval for bridge status (15 seconds)\n */\nexport const DEFAULT_POLL_INTERVAL_MS = 15_000;\n\n/**\n * Default polling timeout (45 minutes)\n */\nexport const DEFAULT_POLL_TIMEOUT_MS = 45 * 60 * 1_000;\n\n/**\n * Delay before registering inbound bridge transactions (30 seconds)\n */\nexport const REGISTRATION_DELAY_MS = 30_000;\n\n/**\n * Solana compute budget settings\n */\nexport const SOLANA_COMPUTE = {\n UNIT_LIMIT: 200_000,\n UNIT_PRICE_MICROLAMPORTS: 375_000,\n} as const;\n\n/**\n * Default Ethereum RPC URL (public endpoint)\n *\n * **WARNING: Public RPC Endpoint Limitations**\n *\n * This is a free public endpoint with the following limitations:\n * - **Rate Limits**: Typically 10-25 requests/second (varies by provider load)\n * - **Reliability**: No SLA, may experience downtime during high network activity\n * - **Privacy**: Requests may be logged by the provider\n * - **Features**: May not support all RPC methods (e.g., trace_* calls)\n * - **Monitoring**: No error tracking, request analytics, or debugging tools available\n *\n * **For Production Use**, provide your own RPC URL from:\n * - Infura: https://infura.io (free tier: 100k requests/day)\n * - Alchemy: https://alchemy.com (free tier: 300M compute units/month)\n * - QuickNode: https://quicknode.com\n * - Your own Ethereum node\n *\n * @example\n * ```typescript\n * const bridgeService = new BridgeService({\n * ethereumRpcUrl: 'https://mainnet.infura.io/v3/YOUR_API_KEY',\n * // ... other config\n * });\n * ```\n */\nexport const DEFAULT_ETHEREUM_RPC_URL = 'https://ethereum.publicnode.com';\n\n/**\n * Default Solana RPC URL (public endpoint)\n *\n * **WARNING: Public RPC Endpoint Limitations**\n *\n * This is the official Solana public RPC with the following limitations:\n * - **Rate Limits**: Aggressive rate limiting (may return 429 errors under load)\n * - **Reliability**: Best-effort availability, no SLA\n * - **Performance**: Higher latency than dedicated endpoints\n * - **Features**: Some methods may be disabled or limited\n * - **Monitoring**: No error tracking, request analytics, or debugging tools available\n *\n * **For Production Use**, provide your own RPC URL from:\n * - Helius: https://helius.dev (free tier: 500k credits/month)\n * - QuickNode: https://quicknode.com\n * - Triton: https://triton.one\n * - Your own Solana validator\n *\n * @example\n * ```typescript\n * const bridgeService = new BridgeService({\n * solanaRpcUrl: 'https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY',\n * // ... other config\n * });\n * ```\n */\nexport const DEFAULT_SOLANA_RPC_URL = 'https://api.mainnet-beta.solana.com';\n\n/**\n * Default Ethereum bridge contract address (mainnet)\n */\nexport const DEFAULT_ETHEREUM_BRIDGE_CONTRACT = '0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9';\n\n/**\n * Ethereum bridge contract address for Sepolia testnet\n */\nexport const ETHEREUM_BRIDGE_CONTRACT_SEPOLIA = '0x6a1734E09f3099a3675645D214ce547080ea67e0';\n\n/**\n * Default Solana bridge program ID (mainnet)\n */\nexport const DEFAULT_SOLANA_BRIDGE_PROGRAM = 'AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS';\n\n/**\n * GalaConnect production base URL (DEX API platform)\n */\nexport const GALACONNECT_PRODUCTION_URL = 'https://dex-api-platform-dex-prod-gala.gala.com';\n\n/**\n * Ethereum tokens for bridging - Production (Mainnet)\n */\nexport const ETHEREUM_TOKENS_PROD: (EthereumTokenConfig & { decimals: number })[] = [\n {\n symbol: 'GALA',\n amount: '1',\n contractAddress: '0xd1d2Eb1B1e90B638588728b4130137D262C87cae',\n bridgeUsesPermit: true,\n decimals: 8,\n },\n {\n symbol: 'GWETH',\n amount: '0.0001',\n contractAddress: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n bridgeUsesPermit: false,\n decimals: 18,\n },\n {\n symbol: 'GUSDC',\n amount: '1',\n contractAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GUSDT',\n amount: '1',\n contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GWTRX',\n amount: '1',\n contractAddress: '0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GWBTC',\n amount: '0.00001',\n contractAddress: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599',\n bridgeUsesPermit: false,\n decimals: 8,\n },\n];\n\n/**\n * Ethereum tokens for bridging - Stage (Sepolia testnet)\n *\n * Note: GWTRX is not available on Sepolia\n */\nexport const ETHEREUM_TOKENS_STAGE: (EthereumTokenConfig & { decimals: number })[] = [\n {\n symbol: 'GALA',\n amount: '1',\n contractAddress: '0x9fBFf09325C1967A135AC9b4860b1cf89aca52DA',\n bridgeUsesPermit: true,\n decimals: 8,\n },\n {\n symbol: 'GWETH',\n amount: '0.0001',\n contractAddress: '0xC3F00B9CbC4221D85A66EEbe928551d0d8dD9158',\n bridgeUsesPermit: false,\n decimals: 18,\n },\n {\n symbol: 'GUSDC',\n amount: '1',\n contractAddress: '0x081e78E33bfa612b23A99ef61e7c194649AA318E',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GUSDT',\n amount: '1',\n contractAddress: '0x461e3595f087bfb0E32B6e44BCbF4C74D99B0001',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GWBTC',\n amount: '0.00001',\n contractAddress: '0x5f69276935EF17e5aF5289b60aFBf6d48B344770',\n bridgeUsesPermit: false,\n decimals: 8,\n },\n];\n\n/** Bridge environment type for token selection */\nexport type BridgeEnvironment = 'prod' | 'stage';\n\n/**\n * Get Ethereum tokens by environment\n *\n * @param environment - Target environment (PROD or STAGE)\n * @returns Token configurations for the specified environment\n */\nexport function getEthereumTokensByEnvironment(\n environment: BridgeEnvironment,\n): (EthereumTokenConfig & { decimals: number })[] {\n return environment === 'prod' ? ETHEREUM_TOKENS_PROD : ETHEREUM_TOKENS_STAGE;\n}\n\n/**\n * Get Ethereum bridge contract address by environment\n *\n * @param environment - Target environment (PROD or STAGE)\n * @returns Bridge contract address for the specified environment\n */\nexport function getEthereumBridgeContractByEnvironment(environment: BridgeEnvironment): string {\n return environment === 'prod'\n ? DEFAULT_ETHEREUM_BRIDGE_CONTRACT\n : ETHEREUM_BRIDGE_CONTRACT_SEPOLIA;\n}\n\n/**\n * Default supported Solana tokens for bridging\n */\nexport const DEFAULT_SOLANA_TOKENS: (SolanaTokenConfig & { decimals: number })[] = [\n {\n symbol: 'GALA',\n amount: '1',\n mintAddress: 'eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6',\n isNative: false,\n decimals: 8,\n },\n {\n symbol: 'GSOL',\n amount: '0.001',\n mintAddress: 'So11111111111111111111111111111111111111111',\n isNative: true,\n decimals: 9,\n },\n];\n\n/**\n * Static token metadata for common bridge tokens\n *\n * This avoids API calls for well-known tokens.\n */\nexport const STATIC_TOKEN_METADATA: Record<string, BridgeTokenMetadata> = {\n GALA: {\n descriptor: { collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 8,\n channel: 'asset',\n },\n GWETH: {\n descriptor: { collection: 'GWETH', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 18,\n channel: 'asset',\n },\n GUSDC: {\n descriptor: { collection: 'GUSDC', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 6,\n channel: 'asset',\n },\n GUSDT: {\n descriptor: { collection: 'GUSDT', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 6,\n channel: 'asset',\n },\n GWTRX: {\n descriptor: { collection: 'GWTRX', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 6,\n channel: 'asset',\n },\n GWBTC: {\n descriptor: { collection: 'GWBTC', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 8,\n channel: 'asset',\n },\n GSOL: {\n descriptor: { collection: 'GSOL', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 9,\n channel: 'asset',\n },\n};\n\n/**\n * Ethereum ERC-20 ABI for bridge operations\n */\nexport const ERC20_ABI = [\n 'function decimals() view returns (uint8)',\n 'function balanceOf(address owner) view returns (uint256)',\n 'function approve(address spender, uint256 value) returns (bool)',\n 'function allowance(address owner, address spender) view returns (uint256)',\n 'function transfer(address to, uint256 value) returns (bool)',\n 'function name() view returns (string)',\n 'function nonces(address owner) view returns (uint256)',\n 'function permit(address owner,address spender,uint256 value,uint256 deadline,uint8 v,bytes32 r,bytes32 s)',\n] as const;\n\n/**\n * Ethereum bridge contract ABI\n */\nexport const BRIDGE_CONTRACT_ABI = [\n 'function bridgeOut(address token,uint256 amount,uint256 tokenId,uint16 destinationChainId,bytes recipient) external',\n 'function bridgeOutWithPermit(address token,uint256 amount,uint16 destinationChainId,bytes recipient,uint256 deadline,uint8 v,bytes32 r,bytes32 s) external',\n] as const;\n\n/**\n * Solana bridge instruction discriminators. Plain bytes: importing `./bridge` touches no `Buffer`\n * (React Native has none at load).\n */\nexport const SOLANA_DISCRIMINATORS = {\n BRIDGE_OUT: Uint8Array.from([27, 194, 57, 119, 215, 165, 247, 150]),\n BRIDGE_OUT_NATIVE: Uint8Array.from([243, 44, 75, 224, 249, 206, 98, 79]),\n} as const;\n\n/**\n * Get token metadata by symbol\n */\nexport function getStaticTokenMetadata(symbol: string): BridgeTokenMetadata | undefined {\n const upperSymbol = normalizeTokenSymbol(symbol);\n\n // Exact symbol only: a symbol is never rewritten (no \"USDC\" -> \"GUSDC\" guessing).\n return STATIC_TOKEN_METADATA[upperSymbol];\n}\n\n/**\n * Get Ethereum token config by symbol (mainnet tokens; see `getEthereumTokensByEnvironment`)\n */\nexport function getEthereumTokenConfig(symbol: string): EthereumTokenConfig | undefined {\n const upperSymbol = normalizeTokenSymbol(symbol);\n return ETHEREUM_TOKENS_PROD.find((t) => normalizeTokenSymbol(t.symbol) === upperSymbol);\n}\n\n/**\n * Get Solana token config by symbol\n */\nexport function getSolanaTokenConfig(symbol: string): SolanaTokenConfig | undefined {\n const upperSymbol = normalizeTokenSymbol(symbol);\n return DEFAULT_SOLANA_TOKENS.find((t) => normalizeTokenSymbol(t.symbol) === upperSymbol);\n}\n\n/**\n * Format a BridgeTokenDescriptor as a pipe-separated string\n * Uses centralized stringification from token-stringification.ts\n */\nexport function formatTokenDescriptor(descriptor: BridgeTokenDescriptor): string {\n return stringifyTokenClassKey(descriptor);\n}\n","/**\n * Bridge validation helpers: each refusal is a `GalaSDKError` with a catalog code (no English\n * message is built here).\n */\n\nimport { PublicKey } from '@solana/web3.js';\nimport { isAddress as isEthereumAddress } from 'ethers';\n\nimport { GalaSDKError } from '../../index.js';\nimport { fieldsOf } from '../internal/values.js';\n\n// ==========================================================================\n// Token Symbol Validation\n// ==========================================================================\n\n/**\n * Validate that a token symbol was resolved (BridgeService resolves `tokenId` to it before it\n * calls a strategy; a strategy called directly needs it set).\n *\n * @param symbol - The resolved token symbol (may be undefined)\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`tokenSymbol`, `missing`) if undefined or empty\n * @returns The validated symbol (type-narrowed to string)\n *\n * @example\n * ```typescript\n * const tokenSymbol = assertTokenSymbolResolved(params.tokenSymbol);\n * ```\n */\nexport function assertTokenSymbolResolved(symbol: string | undefined): string {\n if (symbol === undefined || symbol === '') {\n throw new GalaSDKError('INVALID_TOKEN_REFERENCE', { field: 'tokenSymbol', reason: 'missing' });\n }\n return symbol;\n}\n\n// ==========================================================================\n// Bridge Response Validation\n// ==========================================================================\n\n/**\n * Assert that GalaChain did not refuse a bridge write: an answer with a numeric `Status` other\n * than 1 is its refusal, `BRIDGE_REQUEST_REJECTED` (`chainStatus`, its `ErrorKey` and `Message`;\n * the chain's own `ErrorCode` as `status` when the answer has one, which is what says whether the\n * refusal is definite: a 409 is a uniqueKey already consumed). Any other answer passes.\n *\n * @param method - The write (`RequestTokenBridgeOut`, `BridgeTokenOut`)\n * @param answer - GalaConnect's answer\n * @param uniqueKey - The write's uniqueKey, when it has one\n */\nexport function assertRequestAccepted(method: string, answer: unknown, uniqueKey?: string): void {\n const fields = fieldsOf(answer);\n const chainStatus = fields['Status'];\n if (typeof chainStatus !== 'number' || chainStatus === 1) {\n return;\n }\n const text = (key: string): string => {\n const value = fields[key];\n return typeof value === 'string' ? value : '';\n };\n const errorCode = fields['ErrorCode'];\n throw new GalaSDKError(\n 'BRIDGE_REQUEST_REJECTED',\n { method, chainStatus, errorKey: text('ErrorKey'), serverMessage: text('Message') },\n {\n write: true,\n body: answer,\n ...(typeof errorCode === 'number' && { status: errorCode }),\n ...(uniqueKey !== undefined && { uniqueKey }),\n },\n );\n}\n\n/**\n * Assert that a bridge request ID was returned from RequestTokenBridgeOut.\n *\n * @param bridgeRequestId - The extracted bridge request ID (may be undefined)\n * @throws GalaSDKError `BRIDGE_RESPONSE_INVALID` if undefined or empty (the request may have been\n * registered)\n * @returns The validated bridge request ID\n */\nexport function assertBridgeRequestId(bridgeRequestId: string | undefined): string {\n if (bridgeRequestId === undefined || bridgeRequestId === '') {\n throw new GalaSDKError('BRIDGE_RESPONSE_INVALID', {\n method: 'RequestTokenBridgeOut',\n missing: 'bridge request id',\n });\n }\n return bridgeRequestId;\n}\n\n/**\n * Extract and validate the transaction hash from a BridgeTokenOut response.\n *\n * Handles multiple response formats (Hash vs hash).\n *\n * @param response - The BridgeTokenOut API response (any value: an empty answer is `undefined`)\n * @throws GalaSDKError `BRIDGE_RESPONSE_INVALID` if there is no non-empty string `Hash` or `hash`\n * (the bridge-out may have been submitted)\n * @returns The validated transaction hash\n */\nexport function extractBridgeOutTransactionHash(response: unknown): string {\n const fields = fieldsOf(response);\n const transactionHash = [fields['Hash'], fields['hash']].find(\n (value): value is string => typeof value === 'string' && value !== '',\n );\n if (transactionHash === undefined) {\n throw new GalaSDKError('BRIDGE_RESPONSE_INVALID', {\n method: 'BridgeTokenOut',\n missing: 'transaction hash',\n });\n }\n return transactionHash;\n}\n\n// ==========================================================================\n// Address Validation with Errors\n// ==========================================================================\n\n/**\n * Validate an Ethereum address.\n *\n * @param address - The address to validate\n * @param context - The field it is (default `address`), e.g. `recipient`\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if it is not a valid Ethereum address\n *\n * @example\n * ```typescript\n * validateEthereumAddressOrThrow(recipientAddress, 'recipient');\n * ```\n */\nexport function validateEthereumAddressOrThrow(address: string, context?: string): void {\n if (!isEthereumAddress(address)) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', {\n field: context ?? 'address',\n value: String(address),\n });\n }\n}\n\n/**\n * Validate a Solana address.\n *\n * @param address - The address to validate\n * @param context - The field it is (default `address`), e.g. `recipient`\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if it is not a valid Solana address\n * @returns The validated PublicKey object\n *\n * @example\n * ```typescript\n * const pubkey = validateSolanaAddressOrThrow(recipientAddress, 'recipient');\n * ```\n */\nexport function validateSolanaAddressOrThrow(address: string, context?: string): PublicKey {\n try {\n return new PublicKey(address);\n } catch {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', {\n field: context ?? 'address',\n value: String(address),\n });\n }\n}\n\n/**\n * Parse a Solana address to a PublicKey.\n *\n * @param address - The address to parse\n * @returns The PublicKey object\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if the address is invalid\n */\nexport function parseSolanaAddressOrThrow(address: string): PublicKey {\n return validateSolanaAddressOrThrow(address);\n}\n\n// ==========================================================================\n// Configuration Options\n// ==========================================================================\n\n/**\n * An RPC URL option: an `http:` or `https:` URL.\n *\n * @param value - The option's value\n * @param option - The option's name (for the refusal)\n * @returns The URL as given\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`option`) otherwise\n */\nexport function assertHttpUrlOption(value: string, option: string): string {\n let protocol = '';\n try {\n protocol = new URL(value).protocol;\n } catch {\n // not a URL at all: refused below\n }\n if (protocol !== 'http:' && protocol !== 'https:') {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option });\n }\n return value;\n}\n\n/**\n * An Ethereum address option (a contract or an account).\n *\n * @param value - The option's value\n * @param option - The option's name (for the refusal)\n * @returns The address as given\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`option`) for what is not an Ethereum address\n */\nexport function assertEthereumAddressOption(value: string, option: string): string {\n if (typeof value !== 'string' || !isEthereumAddress(value)) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option });\n }\n return value;\n}\n\n/**\n * A Solana public key option (a program id).\n *\n * @param value - The option's value (base58)\n * @param option - The option's name (for the refusal)\n * @returns The public key\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`option`) for what is not a 32-byte base58 key\n */\nexport function solanaPublicKeyOption(value: string, option: string): PublicKey {\n try {\n if (typeof value === 'string' && value !== '') return new PublicKey(value);\n } catch {\n // not a public key: refused below\n }\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option });\n}\n","/**\n * Rate Limiter\n *\n * Serializes API calls and keeps a minimum interval between their starts, so the backend is\n * never sent more than `requestsPerSecond` requests.\n */\n\nimport { GalaSDKError } from '../../index.js';\n\n/**\n * Rate limiter that ensures a minimum interval between requests. Tasks run one at a time, in the\n * order they were scheduled; the interval is measured between task starts.\n */\nexport class RateLimiter {\n private readonly minIntervalMs: number;\n private lastTimestamp = 0;\n private pendingPromise: Promise<void> = Promise.resolve();\n\n /**\n * Create a new rate limiter\n *\n * @param requestsPerSecond - Maximum requests per second\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`requestsPerSecond`) unless it is a number above\n * zero (`NaN` would silently disable the limit)\n */\n constructor(requestsPerSecond: number) {\n if (!(requestsPerSecond > 0)) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'requestsPerSecond' });\n }\n this.minIntervalMs = 1000 / requestsPerSecond;\n }\n\n /**\n * Schedule a task to run within rate limits. Tasks run serially, inside the chain, so\n * concurrent callers can never exceed the limit.\n *\n * @param task - The async task to execute\n * @returns The result of the task; its failure (whatever it threw) as the rejection\n */\n schedule<T>(task: () => Promise<T>): Promise<T> {\n const run = this.pendingPromise.then(async () => {\n const waitTime = this.minIntervalMs - (Date.now() - this.lastTimestamp);\n if (waitTime > 0) {\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n this.lastTimestamp = Date.now();\n return task();\n });\n // The next task waits for this one to settle, whether it succeeded or not; a settled chain\n // link holds no reference to earlier ones.\n this.pendingPromise = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n","/**\n * Retry Utility\n *\n * Provides exponential backoff retry logic for transient network failures.\n */\n\nimport { getErrorCode, getErrorMessage } from '../internal/values.js';\n\n/**\n * Configuration options for retry behavior.\n */\nexport interface RetryOptions {\n /**\n * Maximum number of retry attempts (default: 3)\n */\n maxRetries?: number;\n\n /**\n * Initial delay in milliseconds before first retry (default: 1000)\n */\n initialDelayMs?: number;\n\n /**\n * Maximum delay in milliseconds between retries (default: 30000)\n */\n maxDelayMs?: number;\n\n /**\n * Multiplier for exponential backoff (default: 2)\n */\n backoffMultiplier?: number;\n\n /**\n * Jitter factor to add randomness to delays (0-1, default: 0.1)\n * Helps prevent thundering herd problems.\n */\n jitterFactor?: number;\n\n /**\n * Custom function to determine if an error should trigger a retry.\n * Default: retries on network errors and 5xx/429 status codes.\n */\n shouldRetry?: (error: unknown, attempt: number) => boolean;\n\n /**\n * Callback invoked before each retry attempt.\n * Useful for logging or metrics.\n */\n onRetry?: (error: unknown, attempt: number, delayMs: number) => void;\n}\n\n/**\n * Default retry options.\n */\nconst DEFAULT_RETRY_OPTIONS: Required<Omit<RetryOptions, 'onRetry' | 'shouldRetry'>> = {\n maxRetries: 3,\n initialDelayMs: 1000,\n maxDelayMs: 30_000,\n backoffMultiplier: 2,\n jitterFactor: 0.1,\n};\n\n/**\n * HTTP status codes that should trigger a retry.\n */\nconst RETRYABLE_STATUS_CODES = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/**\n * Error messages that indicate transient network issues.\n */\nconst RETRYABLE_ERROR_PATTERNS = [\n /ECONNRESET/i,\n /ECONNREFUSED/i,\n /ETIMEDOUT/i,\n /ENOTFOUND/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /network/i,\n /timeout/i,\n /aborted/i,\n];\n\n/**\n * Determines if an error is retryable based on its characteristics.\n *\n * @param error - The error to evaluate\n * @returns True if the error should trigger a retry\n */\nexport function isRetryableError(error: unknown): boolean {\n // Check for HTTP status codes\n if (error !== null && error !== undefined && typeof error === 'object') {\n const errorObj = error as Record<string, unknown>;\n\n // Check status property (common in HTTP errors)\n if (typeof errorObj['status'] === 'number') {\n return RETRYABLE_STATUS_CODES.has(errorObj['status']);\n }\n\n // Check statusCode property (alternative naming)\n if (typeof errorObj['statusCode'] === 'number') {\n return RETRYABLE_STATUS_CODES.has(errorObj['statusCode']);\n }\n\n // Check code property (Node.js errors)\n const code = getErrorCode(error);\n if (typeof code === 'string') {\n if (\n code === 'ECONNRESET' ||\n code === 'ECONNREFUSED' ||\n code === 'ETIMEDOUT' ||\n code === 'ENOTFOUND' ||\n code === 'EAI_AGAIN'\n ) {\n return true;\n }\n }\n }\n\n // Check error message for retryable patterns\n const message = getErrorMessage(error);\n return RETRYABLE_ERROR_PATTERNS.some((pattern) => pattern.test(message));\n}\n\n/**\n * Calculates the delay before the next retry attempt using exponential backoff with jitter.\n *\n * @param attempt - Current attempt number (1-based)\n * @param options - Retry configuration options\n * @returns Delay in milliseconds\n */\nexport function calculateRetryDelay(\n attempt: number,\n options: Required<Omit<RetryOptions, 'onRetry' | 'shouldRetry'>>,\n): number {\n // Calculate base delay with exponential backoff\n const baseDelay = options.initialDelayMs * Math.pow(options.backoffMultiplier, attempt - 1);\n\n // Apply maximum cap\n const cappedDelay = Math.min(baseDelay, options.maxDelayMs);\n\n // Add jitter to prevent thundering herd\n const jitter = cappedDelay * options.jitterFactor * Math.random();\n\n return Math.floor(cappedDelay + jitter);\n}\n\n/**\n * Executes an async function with exponential backoff retry logic.\n *\n * @param fn - The async function to execute\n * @param options - Retry configuration options\n * @returns The result of the function\n * @throws The last error if all retries are exhausted\n *\n * @example\n * ```typescript\n * const result = await withRetry(\n * () => fetch('https://api.example.com/data'),\n * {\n * maxRetries: 3,\n * onRetry: (error, attempt, delay) => {\n * console.log(`Retry ${attempt} after ${delay}ms: ${error}`);\n * },\n * }\n * );\n * ```\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const resolvedOptions = {\n ...DEFAULT_RETRY_OPTIONS,\n ...options,\n };\n\n const shouldRetry = options.shouldRetry ?? ((error: unknown) => isRetryableError(error));\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= resolvedOptions.maxRetries + 1; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n\n // Check if we've exhausted retries\n if (attempt > resolvedOptions.maxRetries) {\n break;\n }\n\n // Check if error is retryable\n if (!shouldRetry(error, attempt)) {\n break;\n }\n\n // Calculate delay for next retry\n const delayMs = calculateRetryDelay(attempt, resolvedOptions);\n\n // Invoke onRetry callback if provided\n if (options.onRetry) {\n options.onRetry(error, attempt, delayMs);\n }\n\n // Wait before retrying\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n\n // All retries exhausted or non-retryable error\n throw lastError;\n}\n\n/**\n * Simple delay utility for async operations.\n *\n * @param ms - Delay duration in milliseconds\n * @returns Promise that resolves after the specified delay\n *\n * @example\n * ```typescript\n * // Wait 1 second before continuing\n * await delay(1000);\n *\n * // Wait before registration\n * await delay(REGISTRATION_DELAY_MS);\n * ```\n */\nexport function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * GalaConnect Bridge Client\n *\n * HTTP client for the GalaConnect bridge API (the DEX API platform) and the gateway balance read\n * the bridge uses: rate limiting, the wallet header, and the retry policy, moved from launchpad-sdk\n * with the same requests on the wire (recorded vectors: tests/fixtures/galaconnect-wire-recorded.json).\n *\n * Failures are `GalaSDKError`s:\n * - an HTTP status other than 2xx: `GALACONNECT_HTTP_ERROR` (`status`, the body as `error.body`);\n * - no answer (the request failed in transit): a read's `TRANSPORT_ERROR` (`write: false`), a\n * write's `BRIDGE_WRITE_OUTCOME_UNKNOWN` (the request may have reached GalaConnect);\n * - no complete answer within `requestTimeoutMs`: a read's `REQUEST_TIMEOUT` (`write: false`), a\n * write's `BRIDGE_WRITE_OUTCOME_UNKNOWN` (that timeout as cause);\n * - an answer that is not the JSON the call needs: a read's `BRIDGE_READ_RESPONSE_INVALID`, a\n * write's `BRIDGE_RESPONSE_INVALID`.\n * The writes are `requestBridgeOut`, `bridgeTokenOut` and `registerBridgeTransaction`; every\n * other call is a read (`error.write === false`). A write's error carries the payload's\n * `uniqueKey` when it has one.\n */\n\nimport { GalaSDKError, galaChainUserRef, validateTimeoutMs, type HttpRequestor } from '../index.js';\nimport { GALACONNECT_PRODUCTION_URL } from './constants/tokens.js';\nimport { safeParseJson } from './internal/values.js';\nimport { assertHttpUrlOption } from './utils/bridgeErrors.js';\nimport type {\n BridgeConfigurationToken,\n BridgeFeeResponse,\n BridgeStatusResponse,\n BridgeTokenDescriptor,\n BridgeTokenOutResponse,\n BridgeTransactionRegistrationResponse,\n FetchBalancesResponse,\n GalaConnectConfig,\n RequestBridgeOutResponse,\n} from './types/index.js';\nimport { RateLimiter } from './utils/RateLimiter.js';\nimport { isRetryableError, withRetry, type RetryOptions } from './utils/retry.js';\n\nconst DEFAULT_CONFIG: Required<\n Omit<GalaConnectConfig, 'walletAddress' | 'onRetry' | 'httpRequestor'>\n> = {\n baseUrl: GALACONNECT_PRODUCTION_URL,\n galachainBaseUrl: 'https://galachain-gateway-chain-platform-galachain-mainnet.gala.com',\n requestsPerSecond: 12,\n requestTimeoutMs: 30_000,\n enableRetry: true,\n maxRetries: 3,\n retryInitialDelayMs: 1000,\n};\n\n/** The longest server text an error keeps (`serverMessage`, a raw body). */\nconst MAX_ERROR_BODY_LENGTH = 500;\n\n/** One call: the path, and whether it is a write (with the payload's uniqueKey, if any). */\ninterface Operation {\n readonly path: string;\n readonly write: boolean;\n readonly uniqueKey?: string | undefined;\n}\n\n/** A response, read once. */\ninterface Answer {\n readonly ok: boolean;\n readonly status: number;\n readonly text: string;\n}\n\n/** The error context of a failure of `op`: read or write, and the write's uniqueKey. */\nfunction contextOf(op: Operation): { write: boolean; uniqueKey?: string } {\n return op.uniqueKey === undefined\n ? { write: op.write }\n : { write: true, uniqueKey: op.uniqueKey };\n}\n\n/** The `uniqueKey` a write payload carries, when it carries one. */\nfunction uniqueKeyOf(payload: Record<string, unknown>): string | undefined {\n const key = payload['uniqueKey'];\n return typeof key === 'string' && key !== '' ? key : undefined;\n}\n\n/** `GALACONNECT_HTTP_ERROR` for an answer of status `status` and body text `text`. */\nfunction httpFailure(op: Operation, url: string, status: number, text: string): GalaSDKError {\n const body: unknown = safeParseJson(text, { rawBody: text.slice(0, MAX_ERROR_BODY_LENGTH) });\n return new GalaSDKError(\n 'GALACONNECT_HTTP_ERROR',\n { method: op.path, status, serverMessage: text.slice(0, MAX_ERROR_BODY_LENGTH) },\n { ...contextOf(op), status, body, url },\n );\n}\n\n/** The failure of a request that got no (complete) answer: a read is transient, a write unknown. */\nfunction transportFailure(op: Operation, url: string, cause: unknown): GalaSDKError {\n return op.write\n ? new GalaSDKError(\n 'BRIDGE_WRITE_OUTCOME_UNKNOWN',\n { method: op.path },\n { ...contextOf(op), url, cause },\n )\n : new GalaSDKError('TRANSPORT_ERROR', { url }, { write: false, url, cause });\n}\n\n/**\n * A request that ran out of time: a read is `REQUEST_TIMEOUT` (`write: false`), a write\n * `BRIDGE_WRITE_OUTCOME_UNKNOWN` (it may have reached GalaConnect) with that timeout as cause.\n */\nfunction timeoutFailure(\n op: Operation,\n url: string,\n timeoutMs: number,\n cause: unknown,\n): GalaSDKError {\n const timeout = new GalaSDKError(\n 'REQUEST_TIMEOUT',\n { url, timeoutMs },\n { ...contextOf(op), url, cause },\n );\n return op.write ? transportFailure(op, url, timeout) : timeout;\n}\n\n/** An answer that is not the JSON `op` needs. */\nfunction invalidAnswer(op: Operation, url: string): GalaSDKError {\n return op.write\n ? new GalaSDKError(\n 'BRIDGE_RESPONSE_INVALID',\n { method: op.path, missing: 'JSON answer' },\n { ...contextOf(op), url },\n )\n : new GalaSDKError('BRIDGE_READ_RESPONSE_INVALID', { method: op.path }, { write: false, url });\n}\n\n/**\n * The JSON of a 2xx answer to `op` (`undefined` for an empty one).\n *\n * @throws GalaSDKError `GALACONNECT_HTTP_ERROR` for another status; for an answer that is not\n * JSON, a read's `BRIDGE_READ_RESPONSE_INVALID` or a write's `BRIDGE_RESPONSE_INVALID`\n */\nfunction readJson(op: Operation, url: string, answer: Answer): unknown {\n if (!answer.ok) {\n throw httpFailure(op, url, answer.status, answer.text);\n }\n if (answer.text === '') {\n return undefined;\n }\n try {\n return JSON.parse(answer.text) as unknown;\n } catch {\n throw invalidAnswer(op, url);\n }\n}\n\n/**\n * Whether a failed attempt of `op` is sent again (with retries on). A 429 was refused before\n * anything was done: sent again, a write too. A read is also sent again after a 5xx or a\n * transport failure whose own error is retryable (a connection reset, a DNS failure, a timeout);\n * a WRITE never is, because it may have been applied (its error says so, with its uniqueKey). An\n * attempt fails only with the `GalaSDKError` of `httpFailure`, `transportFailure` or\n * `timeoutFailure` (`request` wraps every failure).\n */\nfunction shouldRetryAttempt(error: unknown, op: Operation): boolean {\n const failure = error as GalaSDKError;\n if (failure.code === 'GALACONNECT_HTTP_ERROR') {\n return failure.status === 429 || (!op.write && isRetryableError({ status: failure.status }));\n }\n return !op.write && isRetryableError(failure.cause);\n}\n\n/**\n * GalaConnect API client\n *\n * Handles all HTTP communication with the GalaConnect bridge API.\n */\nexport class GalaConnectClient {\n private readonly baseUrl: string;\n private readonly galachainBaseUrl: string;\n private readonly walletAddress: string;\n private readonly rateLimiter: RateLimiter;\n private readonly defaultHeaders: Record<string, string>;\n private readonly retryOptions: RetryOptions | null;\n private readonly requestor: HttpRequestor;\n private readonly requestTimeoutMs: number;\n\n /**\n * Creates a new GalaConnect client.\n *\n * @param config - Client configuration (`httpRequestor` defaults to the global `fetch`).\n * `walletAddress` is sent (the `X-Wallet-Address` header, the gateway balance read's `owner`)\n * in the gateway's spelling: an Ethereum account in any form as `eth|<checksummed>`, a `client|`\n * alias as written; `''` is a client with no wallet (the public token lists).\n * @throws GalaSDKError `INVALID_TIMEOUT` for a `requestTimeoutMs` that is not a positive number\n * of milliseconds or `Infinity`; `INVALID_BRIDGE_OPTION` (`baseUrl`, `galachainBaseUrl`) for a\n * URL that is not http(s); (`requestsPerSecond`) for a rate that is not above zero;\n * `INVALID_WALLET_ADDRESS` (`walletAddress`) for a wallet address that is no user reference\n */\n constructor(config: GalaConnectConfig) {\n this.requestTimeoutMs = validateTimeoutMs(\n config.requestTimeoutMs ?? DEFAULT_CONFIG.requestTimeoutMs,\n 'requestTimeoutMs',\n );\n // A malformed URL is refused here: sent, it would fail as if in transit (a write: outcome unknown)\n this.baseUrl = assertHttpUrlOption(config.baseUrl ?? DEFAULT_CONFIG.baseUrl, 'baseUrl');\n this.galachainBaseUrl = assertHttpUrlOption(\n config.galachainBaseUrl ?? DEFAULT_CONFIG.galachainBaseUrl,\n 'galachainBaseUrl',\n );\n // Sent to the gateway as is, so spelled the one way it accepts ('' = no wallet: public reads).\n this.walletAddress =\n config.walletAddress === '' ? '' : galaChainUserRef(config.walletAddress, 'walletAddress');\n this.rateLimiter = new RateLimiter(\n config.requestsPerSecond ?? DEFAULT_CONFIG.requestsPerSecond,\n );\n this.requestor = config.httpRequestor ?? ((url, init) => globalThis.fetch(url, init));\n this.defaultHeaders = {\n 'Content-Type': 'application/json',\n 'X-Wallet-Address': this.walletAddress,\n };\n\n const enableRetry = config.enableRetry ?? DEFAULT_CONFIG.enableRetry;\n this.retryOptions = enableRetry\n ? {\n maxRetries: config.maxRetries ?? DEFAULT_CONFIG.maxRetries,\n initialDelayMs: config.retryInitialDelayMs ?? DEFAULT_CONFIG.retryInitialDelayMs,\n // Only include onRetry if defined (exactOptionalPropertyTypes compliance)\n ...(config.onRetry && { onRetry: config.onRetry }),\n }\n : null;\n }\n\n /**\n * Get the base URL for constructing status URLs.\n *\n * @returns The GalaConnect API base URL\n */\n public getBaseUrl(): string {\n return this.baseUrl;\n }\n\n /**\n * Get bridge configurations for tokens matching a prefix.\n *\n * Returns detailed token information including:\n * - Token class key (collection, category, type, additionalKey)\n * - Supported bridge routes\n * - External network contract addresses\n *\n * @param searchPrefix - Token symbol prefix to search (e.g., 'GALA', 'GUS')\n * @returns Array of matching token configurations\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` unless the answer has `data.tokens` (an array)\n */\n async getBridgeConfigurations(searchPrefix: string): Promise<BridgeConfigurationToken[]> {\n const op: Operation = { path: '/v1/connect/bridge-configurations', write: false };\n const url = new URL(op.path, this.baseUrl);\n url.searchParams.set('searchprefix', searchPrefix);\n const answer = await this.send(url.toString(), { method: 'GET' }, op);\n if (!answer.ok) {\n throw httpFailure(op, url.toString(), answer.status, answer.text);\n }\n const json = safeParseJson<{ data?: { tokens?: unknown } } | null>(answer.text, null);\n const tokens = json?.data?.tokens;\n if (!Array.isArray(tokens)) {\n throw invalidAnswer(op, url.toString());\n }\n return tokens as BridgeConfigurationToken[];\n }\n\n /**\n * A GET of the DEX API platform (`baseUrl`): `url` with `params` as its query, the JSON answer\n * (a `DexApiReader`, which the token services read the token lists through). A read: a failure\n * is `GALACONNECT_HTTP_ERROR`, `TRANSPORT_ERROR`, `REQUEST_TIMEOUT` or, for an answer that is\n * not JSON, `BRIDGE_READ_RESPONSE_INVALID`, each with `write: false`.\n *\n * @param config - The path and its query\n * @returns The parsed JSON answer (`undefined` for an empty one)\n */\n async request<T>(config: {\n method: 'GET';\n url: string;\n params: Record<string, string | number | boolean>;\n }): Promise<T> {\n const op: Operation = { path: config.url, write: false };\n const url = new URL(config.url, this.baseUrl);\n for (const [name, value] of Object.entries(config.params)) {\n url.searchParams.set(name, String(value));\n }\n return readJson(\n op,\n url.toString(),\n await this.send(url.toString(), { method: 'GET' }, op),\n ) as T;\n }\n\n /**\n * Fetch bridge fee estimate for a token transfer.\n *\n * @param payload - Fee request parameters\n * @returns Fee estimate with breakdown\n */\n async fetchBridgeFee(payload: {\n chainId: string;\n bridgeToken: BridgeTokenDescriptor;\n }): Promise<BridgeFeeResponse> {\n // Fee endpoint is on the DEX API platform (baseUrl), not GalaChain Gateway\n // It's a public endpoint that doesn't require wallet authentication\n return this.postJson<BridgeFeeResponse>({ path: '/v1/bridge/fee', write: false }, payload, {\n skipWalletHeader: true,\n });\n }\n\n /**\n * Request token bridge out (initiate GalaChain → External transfer).\n *\n * This is the first step in the bridge out process:\n * 1. RequestBridgeOut - Lock tokens on GalaChain\n * 2. BridgeTokenOut - Generate wormhole message\n *\n * @param payload - Bridge out request parameters\n * @returns Response with transaction data\n */\n async requestBridgeOut(payload: Record<string, unknown>): Promise<RequestBridgeOutResponse> {\n return this.postJson<RequestBridgeOutResponse>(\n { path: '/v1/RequestTokenBridgeOut', write: true, uniqueKey: uniqueKeyOf(payload) },\n payload,\n );\n }\n\n /**\n * Execute bridge token out (generate wormhole message).\n *\n * This is the second step in the bridge out process.\n * Called after RequestBridgeOut succeeds.\n *\n * @param payload - Bridge token out parameters\n * @returns Response with wormhole message data\n */\n async bridgeTokenOut(payload: Record<string, unknown>): Promise<BridgeTokenOutResponse> {\n return this.postJson<BridgeTokenOutResponse>(\n { path: '/v1/BridgeTokenOut', write: true, uniqueKey: uniqueKeyOf(payload) },\n payload,\n );\n }\n\n /**\n * Get the status of a bridge transaction.\n *\n * @param hash - Transaction hash to check\n * @returns Current status with details\n */\n async getBridgeStatus(hash: string): Promise<BridgeStatusResponse> {\n return this.postJson<BridgeStatusResponse>(\n { path: '/v1/bridge/status', write: false },\n { hash },\n );\n }\n\n /**\n * Register a bridge transaction (for External → GalaChain transfers).\n *\n * Called after depositing tokens to the bridge contract on the external chain.\n * Notifies GalaConnect to process the inbound transfer.\n *\n * @param payload - Transaction registration data\n * @returns Registration response\n */\n async registerBridgeTransaction(\n payload: Record<string, unknown>,\n ): Promise<BridgeTransactionRegistrationResponse> {\n return this.postJson<BridgeTransactionRegistrationResponse>(\n { path: '/v1/bridge/transaction', write: true, uniqueKey: uniqueKeyOf(payload) },\n payload,\n );\n }\n\n /**\n * Fetch token balances for the wallet.\n *\n * @param channel - Token channel (default: 'asset')\n * @returns Balance response with token holdings\n */\n async fetchBalances(channel = 'asset'): Promise<FetchBalancesResponse> {\n return this.postJson<FetchBalancesResponse>(\n { path: '/v1/FetchBalances', write: false },\n { owner: this.walletAddress, channel },\n { baseUrl: this.galachainBaseUrl },\n );\n }\n\n /**\n * POSTs `body` (bigints as decimal strings) as JSON and reads the JSON answer; an empty answer\n * is `undefined`.\n */\n private async postJson<T>(\n op: Operation,\n body: unknown,\n options: { baseUrl?: string; skipWalletHeader?: boolean } = {},\n ): Promise<T> {\n const url = new URL(op.path, options.baseUrl ?? this.baseUrl).toString();\n // Build headers - optionally skip wallet header for public endpoints\n const headers: Record<string, string> = options.skipWalletHeader\n ? { 'Content-Type': 'application/json', 'X-Wallet-Address': '' } // Empty string = skip\n : this.defaultHeaders;\n const answer = await this.send(\n url,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body, (_, value: unknown) =>\n typeof value === 'bigint' ? value.toString() : value,\n ),\n },\n op,\n );\n return readJson(op, url, answer) as T;\n }\n\n /**\n * Sends one request through the rate limiter (and, with retries on, again after a retryable\n * failure) and reads the answer once.\n */\n private async send(url: string, init: RequestInit, op: Operation): Promise<Answer> {\n const attempt = (): Promise<Answer> =>\n this.rateLimiter.schedule(async () => {\n const headers: Record<string, string> = {\n ...this.defaultHeaders,\n ...(init.headers as Record<string, string> | undefined),\n };\n // An empty X-Wallet-Address opts out of the header (public endpoints).\n if (headers['X-Wallet-Address'] === '') {\n delete headers['X-Wallet-Address'];\n }\n let answer: Answer;\n // One limit for the answer AND its body: a body that stalls is aborted too.\n const controller = new AbortController();\n const timer =\n this.requestTimeoutMs === Infinity\n ? undefined\n : setTimeout(() => controller.abort(), this.requestTimeoutMs);\n try {\n const response = await this.requestor(url, {\n ...init,\n headers,\n signal: controller.signal,\n });\n answer = { ok: response.ok, status: response.status, text: await response.text() };\n } catch (error: unknown) {\n throw controller.signal.aborted\n ? timeoutFailure(op, url, this.requestTimeoutMs, error)\n : transportFailure(op, url, error);\n } finally {\n clearTimeout(timer);\n }\n // With retries on, a 429 or 5xx is thrown here so the retry wrapper decides whether to\n // send it again (see shouldRetryAttempt).\n if (this.retryOptions && !answer.ok && (answer.status === 429 || answer.status >= 500)) {\n throw httpFailure(op, url, answer.status, answer.text);\n }\n return answer;\n });\n return this.retryOptions\n ? withRetry(attempt, {\n ...this.retryOptions,\n shouldRetry: (error: unknown) => shouldRetryAttempt(error, op),\n })\n : attempt();\n }\n}\n","/**\n * Address Validation Utilities\n *\n * Shared functions for validating Ethereum addresses, keys and transaction hashes, and the bridge\n * token configuration lookups. A GalaChain user reference is spelled by the root's\n * `galaChainUserRef` (the one implementation the gateway reads, writes and the bridge share).\n */\n\nimport { isAddress as isEthereumAddress } from 'ethers';\n\nimport { GalaSDKError } from '../../index.js';\nimport { normalizeTokenSymbol as normalizeTokenKey } from '../internal/values.js';\n\n/**\n * Validate an Ethereum address format.\n *\n * @param address - Address to validate\n * @returns True if valid Ethereum address\n *\n * @example\n * ```typescript\n * isValidEthereumAddress('0x1234567890123456789012345678901234567890'); // true\n * isValidEthereumAddress('invalid'); // false\n * ```\n */\nexport function isValidEthereumAddress(address: string): boolean {\n return isEthereumAddress(address);\n}\n\n/**\n * Validate Ethereum private key format.\n *\n * Checks for 0x-prefixed 64-character hex string format.\n * Does NOT validate the key on-chain, just format checking.\n *\n * @param privateKey - Private key to validate\n * @returns True if key matches expected format\n *\n * @example\n * ```typescript\n * isValidEthereumPrivateKeyFormat('0x1234...abcd'); // true (if 64 hex chars)\n * isValidEthereumPrivateKeyFormat('1234...abcd'); // false (missing 0x)\n * ```\n */\nexport function isValidEthereumPrivateKeyFormat(privateKey: string): boolean {\n return /^0x[a-fA-F0-9]{64}$/.test(privateKey);\n}\n\n/**\n * Validate Ethereum transaction hash format.\n *\n * Checks for 0x-prefixed 64-character hex string format.\n *\n * @param hash - Transaction hash to validate\n * @returns True if hash matches expected format\n *\n * @example\n * ```typescript\n * isValidEthereumTransactionHash('0x1234...abcd'); // true (if 64 hex chars)\n * isValidEthereumTransactionHash('1234...abcd'); // false (missing 0x)\n * ```\n */\nexport function isValidEthereumTransactionHash(hash: string): boolean {\n return /^0x[a-fA-F0-9]{64}$/.test(hash);\n}\n\n// ==========================================================================\n// Token Configuration Utilities\n// ==========================================================================\n\n/**\n * Generic token configuration type for bridge tokens.\n * Both EthereumTokenConfig and SolanaTokenConfig share these base fields.\n */\nexport interface BaseTokenConfig {\n /** Token symbol (e.g., 'GALA', 'GWETH') */\n symbol: string;\n /** Token decimals */\n decimals?: number;\n}\n\n/**\n * Create a token config lookup map from an array of configs.\n *\n * Normalizes symbols to uppercase for case-insensitive lookup.\n *\n * @param configs - Array of token configurations\n * @returns Map keyed by uppercase symbol\n *\n * @example\n * ```typescript\n * const configs = [{ symbol: 'GALA', decimals: 8 }, { symbol: 'GWETH', decimals: 18 }];\n * const map = createTokenConfigMap(configs);\n * map.get('gala'); // undefined (use uppercase)\n * map.get('GALA'); // { symbol: 'GALA', decimals: 8 }\n * ```\n */\nexport function createTokenConfigMap<T extends BaseTokenConfig>(configs: T[]): Map<string, T> {\n const map = new Map<string, T>();\n for (const config of configs) {\n map.set(normalizeTokenKey(config.symbol), config);\n }\n return map;\n}\n\n/**\n * Get a token config from a map by symbol (case-insensitive).\n *\n * @param configs - Token config map\n * @param symbol - Token symbol to look up\n * @returns Token config or undefined if not found\n */\nexport function getTokenConfig<T extends BaseTokenConfig>(\n configs: Map<string, T>,\n symbol: string,\n): T | undefined {\n return configs.get(normalizeTokenKey(symbol));\n}\n\n/**\n * Validate that a token is supported and return its config.\n *\n * Throws a descriptive error if the token is not found.\n *\n * @param configs - Token config map\n * @param symbol - Token symbol to validate\n * @param network - Network name for error message (e.g., 'Ethereum', 'Solana')\n * @returns Token config\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` if the token is not supported\n *\n * @example\n * ```typescript\n * const config = requireTokenConfig(ethTokens, 'GALA', 'Ethereum');\n * ```\n */\nexport function requireTokenConfig<T extends BaseTokenConfig>(\n configs: Map<string, T>,\n symbol: string,\n network: string,\n): T {\n const config = getTokenConfig(configs, symbol);\n if (!config) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network, symbol });\n }\n return config;\n}\n\n/**\n * Validate Ethereum private key format and throw descriptive error if invalid.\n *\n * Use this for constructor validation where a descriptive error is needed.\n *\n * @param privateKey - Private key to validate\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` (`bad_encoding`) if the format is invalid; the key is\n * never part of the error\n *\n * @example\n * ```typescript\n * validateEthereumPrivateKeyFormat(config.ethereumPrivateKey);\n * ```\n */\nexport function validateEthereumPrivateKeyFormat(\n privateKey: string | undefined,\n): asserts privateKey is string {\n if (privateKey === undefined || !isValidEthereumPrivateKeyFormat(privateKey)) {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n}\n\n/**\n * Validate Ethereum transaction hash format and throw descriptive error if invalid.\n *\n * Use this for parameter validation where a descriptive error is needed.\n *\n * @param hash - Transaction hash to validate\n * @throws GalaSDKError `INVALID_TRANSACTION_HASH` if the format is invalid\n *\n * @example\n * ```typescript\n * validateEthereumTransactionHashFormat(transactionHash);\n * ```\n */\nexport function validateEthereumTransactionHashFormat(hash: string): void {\n if (!isValidEthereumTransactionHash(hash)) {\n throw new GalaSDKError('INVALID_TRANSACTION_HASH', {\n network: 'Ethereum',\n value: String(hash),\n });\n }\n}\n","/**\n * Balance Query Helpers\n *\n * Consolidated utilities for building ExternalChainBalance and BridgeTransaction response objects.\n * Eliminates DRY violations across BridgeService and bridge strategy methods.\n *\n * @module bridge/utils/balanceHelpers\n */\n\nimport { GalaSDKError } from '../../index.js';\nimport type {\n BridgeRequestDto,\n BridgeTransaction,\n DestinationChainTxFee,\n ExternalChainBalance,\n ExternalNetwork,\n} from '../types/index.js';\nimport type { EthereumTokenConfig, SolanaTokenConfig } from '../types/index.js';\n\n// ==========================================================================\n// Balance Response Builders\n// ==========================================================================\n\n/**\n * Build an ExternalChainBalance for a native token (ETH or SOL).\n *\n * @param symbol - Native token symbol ('ETH' or 'SOL')\n * @param quantity - Balance as decimal string\n * @param decimals - Token decimals (18 for ETH, 9 for SOL)\n * @returns ExternalChainBalance with isNative: true, contractAddress: null\n *\n * @example\n * ```typescript\n * const ethBalance = buildNativeBalance('ETH', '1.5', 18);\n * // { symbol: 'ETH', quantity: '1.5', decimals: 18, contractAddress: null, isNative: true }\n * ```\n */\nexport function buildNativeBalance(\n symbol: 'ETH' | 'SOL',\n quantity: string,\n decimals: number,\n): ExternalChainBalance {\n return {\n symbol,\n quantity,\n decimals,\n contractAddress: null,\n isNative: true,\n };\n}\n\n/**\n * Build an ExternalChainBalance for an Ethereum ERC-20 token.\n *\n * @param tokenConfig - Ethereum token configuration\n * @param quantity - Balance as decimal string\n * @returns ExternalChainBalance with contractAddress and isNative: false\n *\n * @example\n * ```typescript\n * const galaBalance = buildEthereumTokenBalance(\n * { symbol: 'GALA', contractAddress: '0x15D4...', decimals: 8 },\n * '1000.00000000'\n * );\n * ```\n */\nexport function buildEthereumTokenBalance(\n tokenConfig: EthereumTokenConfig,\n quantity: string,\n): ExternalChainBalance {\n return {\n symbol: tokenConfig.symbol,\n quantity,\n decimals: tokenConfig.decimals ?? 18,\n contractAddress: tokenConfig.contractAddress,\n isNative: false,\n };\n}\n\n/**\n * Build an ExternalChainBalance for a Solana SPL token.\n *\n * @param tokenConfig - Solana token configuration\n * @param quantity - Balance as decimal string\n * @returns ExternalChainBalance with mintAddress as contractAddress\n *\n * @example\n * ```typescript\n * const galaBalance = buildSolanaTokenBalance(\n * { symbol: 'GALA', mintAddress: 'GALAxw...', decimals: 8 },\n * '500.00000000'\n * );\n * ```\n */\nexport function buildSolanaTokenBalance(\n tokenConfig: SolanaTokenConfig,\n quantity: string,\n): ExternalChainBalance {\n return {\n symbol: tokenConfig.symbol,\n quantity,\n decimals: tokenConfig.decimals ?? 9,\n contractAddress: tokenConfig.mintAddress,\n isNative: tokenConfig.isNative ?? false,\n };\n}\n\n// ==========================================================================\n// Token Config Validation\n// ==========================================================================\n\n/**\n * Find and validate a token config from an array.\n *\n * @param tokens - Array of token configurations\n * @param symbol - Token symbol to find\n * @param network - Network name for error message ('Ethereum' or 'Solana')\n * @returns Token config\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` if not found\n *\n * @example\n * ```typescript\n * const config = findTokenConfigOrThrow(ethereumTokens, 'GALA', 'Ethereum');\n * ```\n */\nexport function findTokenConfigOrThrow<T extends { symbol: string }>(\n tokens: T[],\n symbol: string,\n network: string,\n): T {\n const tokenConfig = tokens.find((t) => t.symbol === symbol);\n if (!tokenConfig) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network, symbol });\n }\n return tokenConfig;\n}\n\n// ==========================================================================\n// Strategy Assertion Helpers\n// ==========================================================================\n\n/**\n * Assert that a strategy exists and return it typed.\n *\n * @param strategy - Strategy from map (may be undefined)\n * @param network - Network type ('Ethereum' or 'Solana')\n * @returns The strategy (type-narrowed to non-undefined)\n * @throws GalaSDKError `BRIDGE_NOT_CONFIGURED` if strategy is undefined\n *\n * @example\n * ```typescript\n * const strategy = this.strategies.get('Ethereum');\n * const ethStrategy = assertStrategyExists(strategy, 'Ethereum') as EthereumBridgeStrategy;\n * ```\n */\nexport function assertStrategyExists<T>(\n strategy: T | undefined,\n network: 'Ethereum' | 'Solana',\n): T {\n if (strategy === undefined) {\n throw new GalaSDKError('BRIDGE_NOT_CONFIGURED', { network });\n }\n return strategy;\n}\n\n// ==========================================================================\n// Bridge Transaction Response Builders\n// ==========================================================================\n\n/**\n * Parameters for building a bridge outbound transaction response.\n */\nexport interface BridgeOutboundTransactionParams {\n /** Destination chain ('Ethereum' | 'Solana') */\n toChain: ExternalNetwork;\n /** Transaction hash */\n transactionHash: string;\n /** Token symbol (e.g., 'GALA', 'GWETH') */\n tokenSymbol: string;\n /** Amount transferred (decimal string) */\n amount: string;\n /** Fee paid in GALA */\n feePaid: string;\n /** Base URL for status endpoint */\n baseUrl: string;\n}\n\n/**\n * Build a BridgeTransaction response for outbound transfers (GalaChain -> External).\n *\n * Eliminates duplicate response construction in EthereumBridgeStrategy and SolanaBridgeStrategy.\n *\n * @param params - Transaction parameters\n * @returns Complete BridgeTransaction object\n *\n * @example\n * ```typescript\n * return buildBridgeOutboundTransaction({\n * toChain: 'Ethereum',\n * transactionHash: '0x123...',\n * tokenSymbol: 'GALA',\n * amount: '100',\n * feePaid: '0.5',\n * baseUrl: 'https://api.gala.com',\n * });\n * ```\n */\nexport function buildBridgeOutboundTransaction(\n params: BridgeOutboundTransactionParams,\n): BridgeTransaction {\n return {\n direction: 'outbound',\n fromChain: 'GalaChain',\n toChain: params.toChain,\n transactionHash: params.transactionHash,\n tokenSymbol: params.tokenSymbol,\n amount: params.amount,\n feePaid: params.feePaid,\n timestamp: Date.now(),\n statusUrl: `${params.baseUrl}/v1/bridge/transaction?hash=${params.transactionHash}`,\n };\n}\n\n/**\n * Parameters for building a bridge inbound transaction response.\n */\nexport interface BridgeInboundTransactionParams {\n /** Source chain ('Ethereum' | 'Solana') */\n fromChain: ExternalNetwork;\n /** Transaction hash */\n transactionHash: string;\n /** Token symbol (e.g., 'GALA', 'GWETH') */\n tokenSymbol: string;\n /** Amount transferred (decimal string) */\n amount: string;\n /** Base URL for status endpoint */\n baseUrl: string;\n}\n\n/**\n * Build a BridgeTransaction response for inbound transfers (External -> GalaChain).\n *\n * Eliminates duplicate response construction in EthereumBridgeStrategy and SolanaBridgeStrategy.\n *\n * @param params - Transaction parameters\n * @returns Complete BridgeTransaction object\n *\n * @example\n * ```typescript\n * return buildBridgeInboundTransaction({\n * fromChain: 'Ethereum',\n * transactionHash: '0x123...',\n * tokenSymbol: 'GALA',\n * amount: '100',\n * baseUrl: 'https://api.gala.com',\n * });\n * ```\n */\nexport function buildBridgeInboundTransaction(\n params: BridgeInboundTransactionParams,\n): BridgeTransaction {\n return {\n direction: 'inbound',\n fromChain: params.fromChain,\n toChain: 'GalaChain',\n transactionHash: params.transactionHash,\n tokenSymbol: params.tokenSymbol,\n amount: params.amount,\n timestamp: Date.now(),\n statusUrl: `${params.baseUrl}/v1/bridge/transaction?hash=${params.transactionHash}`,\n };\n}\n\n// ==========================================================================\n// Bridge Request DTO Builders\n// ==========================================================================\n\n/**\n * Parameters for building a bridge request DTO.\n */\nexport interface BridgeRequestDtoParams {\n /** Destination chain ID (number) */\n destinationChainId: number;\n /** Bridge fee response from GalaConnect (used as destinationChainTxFee) */\n bridgeFee: DestinationChainTxFee;\n /** Amount to bridge (decimal string) */\n amount: string;\n /** Recipient address on destination chain */\n recipientAddress: string;\n /** Token metadata descriptor */\n tokenDescriptor: {\n collection: string;\n category: string;\n type: string;\n additionalKey: string;\n };\n}\n\n/**\n * Build a BridgeRequestDto for the GalaConnect RequestTokenBridgeOut API.\n *\n * Eliminates duplicate DTO construction across strategies (~10 lines each).\n *\n * @param params - Request parameters\n * @returns BridgeRequestDto ready for signing\n *\n * @example\n * ```typescript\n * const dto = buildBridgeRequestDto({\n * destinationChainId: CHAIN_IDS.ETHEREUM,\n * bridgeFee,\n * amount: '100',\n * recipientAddress: '0x1234...',\n * tokenDescriptor: metadata.descriptor,\n * });\n * ```\n */\nexport function buildBridgeRequestDto(params: BridgeRequestDtoParams): BridgeRequestDto {\n return {\n destinationChainId: params.destinationChainId,\n destinationChainTxFee: params.bridgeFee,\n quantity: params.amount,\n recipient: params.recipientAddress,\n tokenInstance: {\n ...params.tokenDescriptor,\n instance: '0',\n },\n };\n}\n","/**\n * Bridge Payload Utilities\n *\n * Shared utility functions for bridge payload construction and normalization.\n * These functions are used by both EthereumBridgeStrategy and SolanaBridgeStrategy\n * to ensure consistent, deterministic payload generation for EIP-712 signing.\n */\n\nimport { GalaSDKError, type GalaChainTokenClassKey } from '../../index.js';\nimport { fieldsOf, isRecord, safeParseFloat, safeParseInt } from '../internal/values.js';\nimport type {\n BridgeFeeEstimate,\n BridgeTokenMetadata,\n DestinationChainTxFee,\n} from '../types/index.js';\n\n/**\n * Normalize a DestinationChainTxFee response for deterministic signing.\n *\n * Converts string timestamps and decimals to numbers to ensure consistent\n * JSON serialization across different API response formats.\n *\n * @param raw - Raw fee response from GalaConnect API\n * @returns Normalized fee object with numeric timestamps\n */\nexport function normalizeDestinationChainTxFee(raw: DestinationChainTxFee): DestinationChainTxFee {\n const normalized: DestinationChainTxFee = {\n ...raw,\n galaDecimals:\n typeof raw.galaDecimals === 'string' ? safeParseInt(raw.galaDecimals, 0) : raw.galaDecimals,\n timestamp: typeof raw.timestamp === 'string' ? safeParseInt(raw.timestamp, 0) : raw.timestamp,\n };\n\n if (raw.galaExchangeRate) {\n normalized.galaExchangeRate = {\n ...raw.galaExchangeRate,\n timestamp:\n typeof raw.galaExchangeRate.timestamp === 'string'\n ? safeParseInt(raw.galaExchangeRate.timestamp, 0)\n : raw.galaExchangeRate.timestamp,\n };\n }\n\n if (raw.galaExchangeCrossRate) {\n const crossRate = raw.galaExchangeCrossRate;\n normalized.galaExchangeCrossRate = {\n ...crossRate,\n timestamp:\n typeof crossRate.timestamp === 'string'\n ? safeParseInt(crossRate.timestamp, 0)\n : crossRate.timestamp,\n };\n\n if (crossRate.baseTokenCrossRate) {\n normalized.galaExchangeCrossRate.baseTokenCrossRate = {\n ...crossRate.baseTokenCrossRate,\n timestamp:\n typeof crossRate.baseTokenCrossRate.timestamp === 'string'\n ? safeParseInt(crossRate.baseTokenCrossRate.timestamp, 0)\n : crossRate.baseTokenCrossRate.timestamp,\n };\n }\n\n if (crossRate.quoteTokenCrossRate) {\n normalized.galaExchangeCrossRate.quoteTokenCrossRate = {\n ...crossRate.quoteTokenCrossRate,\n timestamp:\n typeof crossRate.quoteTokenCrossRate.timestamp === 'string'\n ? safeParseInt(crossRate.quoteTokenCrossRate.timestamp, 0)\n : crossRate.quoteTokenCrossRate.timestamp,\n };\n }\n }\n\n return normalized;\n}\n\n/**\n * Remove undefined values from an object for deterministic JSON serialization.\n *\n * Creates a clean object without undefined properties, which ensures\n * consistent JSON.stringify output for signature verification.\n *\n * @param obj - Object potentially containing undefined values\n * @returns Clean object with undefined values removed\n */\nexport function sanitizeObject<T extends Record<string, unknown>>(obj: T): T {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined) {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = sanitizeObject(value as Record<string, unknown>);\n } else {\n result[key] = value;\n }\n }\n }\n return result as T;\n}\n\n/**\n * Extract the bridge request ID from a RequestTokenBridgeOut response.\n *\n * Handles multiple response formats from the GalaConnect API:\n * - `{ Data: \"...\" }` - Direct data field\n * - `{ data: \"...\" }` - Lowercase data field\n * - `{ data: { Data: \"...\" } }` - Nested data object\n *\n * @param response - Response from RequestTokenBridgeOut API call (any value: an empty answer is\n * `undefined`)\n * @returns Bridge request ID if found, undefined otherwise (also for an answer that is not an object)\n */\nexport function extractBridgeRequestId(response: unknown): string | undefined {\n const answer = fieldsOf(response);\n if (typeof answer['Data'] === 'string') {\n return answer['Data'];\n }\n const data = answer['data'];\n if (typeof data === 'string') {\n return data;\n }\n const nested = fieldsOf(data)['Data'];\n return typeof nested === 'string' ? nested : undefined;\n}\n\n/**\n * Validate a bridge amount for numeric validity and positivity.\n *\n * Prevents wasted gas on zero/negative/invalid amounts.\n *\n * @param amount - Amount string to validate\n * @throws GalaSDKError `INVALID_BRIDGE_AMOUNT` (`not_positive`) if it is not a number above zero\n * @returns Parsed numeric amount (as side effect of successful validation)\n *\n * @example\n * ```typescript\n * validateBridgeAmount('100.5'); // Returns: 100.5\n * validateBridgeAmount('0'); // Throws\n * validateBridgeAmount('abc'); // Throws\n * ```\n */\nexport function validateBridgeAmount(amount: string): number {\n const numericAmount = safeParseFloat(amount, -1);\n if (numericAmount <= 0) {\n throw new GalaSDKError('INVALID_BRIDGE_AMOUNT', {\n value: String(amount),\n reason: 'not_positive',\n });\n }\n return numericAmount;\n}\n\n/**\n * Build a BridgeTokenMetadata object from token descriptor and decimals.\n *\n * Consolidates the pattern of building bridge token metadata from API responses.\n *\n * @param tokenDescriptor - Token descriptor with collection, category, type, additionalKey\n * @param decimals - Token decimals\n * @param channel - Optional channel identifier for multi-channel tokens\n * @returns BridgeTokenMetadata object\n *\n * @example\n * ```typescript\n * const metadata = buildTokenMetadata(\n * { collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' },\n * 8\n * );\n * ```\n */\nexport function buildTokenMetadata(\n tokenDescriptor: GalaChainTokenClassKey,\n decimals: number,\n channel?: string,\n): BridgeTokenMetadata {\n return {\n descriptor: {\n collection: tokenDescriptor.collection,\n category: tokenDescriptor.category,\n type: tokenDescriptor.type,\n additionalKey: tokenDescriptor.additionalKey,\n },\n decimals,\n // Only include channel if defined (exactOptionalPropertyTypes compliance)\n ...(channel !== undefined ? { channel } : {}),\n };\n}\n\n/**\n * The fee GalaConnect answered, if it is one a bridge-out can carry: an object with the GALA fee\n * (a string) and an exchange rate or a cross rate (which picks the typed data). Anything else (an\n * empty answer included) is `BRIDGE_READ_RESPONSE_INVALID` (a read: nothing was signed or sent).\n */\nexport function assertUsableFee<T>(fee: T): T {\n const answer: unknown = fee;\n if (\n !isRecord(answer) ||\n typeof answer['estimatedTotalTxFeeInGala'] !== 'string' ||\n !(isRecord(answer['galaExchangeRate']) || isRecord(answer['galaExchangeCrossRate']))\n ) {\n throw readAnswerInvalid('/v1/bridge/fee');\n }\n return fee;\n}\n\n/**\n * The bridge status GalaConnect answered, if it is an object (an empty answer is not).\n *\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` otherwise\n */\nexport function assertStatusAnswer<T>(status: T): T {\n if (!isRecord(status)) {\n throw readAnswerInvalid('/v1/bridge/status');\n }\n return status;\n}\n\n/** `BRIDGE_READ_RESPONSE_INVALID` for the GalaConnect read `method`. */\nfunction readAnswerInvalid(method: string): GalaSDKError {\n return new GalaSDKError('BRIDGE_READ_RESPONSE_INVALID', { method }, { write: false });\n}\n\n/**\n * Build a fee payload object from a DestinationChainTxFee response.\n *\n * Consolidates the pattern of extracting fee information from API responses.\n * Normalizes timestamp to ensure it is always a number.\n *\n * @param feeResponse - Raw fee response from GalaConnect API\n * @returns Fee payload with all relevant fields\n *\n * @example\n * ```typescript\n * const feePayload = buildFeePayload({\n * estimatedTotalTxFeeInGala: '100',\n * estimatedTotalTxFeeInExternalToken: '0.005',\n * ...\n * });\n * ```\n */\nexport function buildFeePayload(feeResponse: DestinationChainTxFee): BridgeFeeEstimate {\n const timestamp =\n typeof feeResponse.timestamp === 'string'\n ? safeParseInt(feeResponse.timestamp, 0)\n : feeResponse.timestamp;\n\n return {\n estimatedFeeInGala: feeResponse.estimatedTotalTxFeeInGala,\n estimatedFeeInExternalToken: feeResponse.estimatedTotalTxFeeInExternalToken,\n feeToken: feeResponse.bridgeToken,\n pricePerUnit: feeResponse.estimatedPricePerTxFeeUnit,\n estimatedGasUnits: feeResponse.estimatedTxFeeUnitsTotal,\n exchangeRate: feeResponse.galaExchangeRate?.exchangeRate ?? '0',\n timestamp,\n raw: feeResponse,\n };\n}\n","/**\n * EIP-712 Signing Helpers\n *\n * The signed bridge-out payload (`RequestTokenBridgeOut`) both bridge strategies submit. Moved\n * from launchpad-sdk byte for byte: the signature, the `prefix` and the key order are pinned by\n * launchpad's recorded vectors (tests/fixtures/bridge-out-recorded.json).\n *\n * @module bridge/utils/eip712Helpers\n */\n\nimport type { Signer } from 'ethers';\n\nimport {\n createUniqueKey,\n GalaSDKError,\n isGalaError,\n isWalletUserRejection,\n serialize,\n walletDeclineCode,\n} from '../../index.js';\nimport { GALA_BRIDGE_TYPED_DATA_DOMAIN, getGalaBridgeTypedDataTypes } from '../types/eip712.js';\nimport type { BridgeRequestDto } from '../types/index.js';\nimport { normalizeDestinationChainTxFee, sanitizeObject } from './bridgePayload.js';\n\n/** What signs the bridge-out typed data: an ethers `Wallet`, or any ethers `Signer`. */\nexport type BridgeTypedDataSigner = Pick<Signer, 'signTypedData'>;\n\n/**\n * Configuration for building bridge out payloads\n */\nexport interface BuildBridgeOutPayloadConfig {\n /** Signs the EIP-712 typed data (the Ethereum wallet) */\n wallet: BridgeTypedDataSigner;\n}\n\n/** The signed `RequestTokenBridgeOut` body; its `uniqueKey` is the bridge-out's handle. */\nexport type SignedBridgeOutPayload = Record<string, unknown> & { readonly uniqueKey: string };\n\n/** The prefix of a generated bridge-out `uniqueKey`. */\nconst BRIDGE_UNIQUE_KEY_PREFIX = 'galaconnect-operation-';\n\n/**\n * The destination chain id as the number the payload signs: a positive safe integer, or a string\n * of decimal digits that is one. Anything else is `INVALID_BRIDGE_OPTION` (`destinationChainId`):\n * a chain id is never guessed, since a wrong one sends the tokens to another chain.\n */\nfunction destinationChainIdOf(value: number | string): number {\n const id = typeof value === 'string' && /^\\d+$/u.test(value) ? Number(value) : value;\n if (typeof id !== 'number' || !Number.isSafeInteger(id) || id <= 0) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'destinationChainId' });\n }\n return id;\n}\n\n/** The method a bridge-out signing failure names. */\nconst BRIDGE_OUT_METHOD = 'RequestTokenBridgeOut';\n\n/**\n * Signs the bridge-out typed data with the app's signer. Whatever the signer throws that is not\n * already an SDK error (a declined or locked wallet, a message ethers cannot encode) is\n * `SIGNING_FAILED` (`user_rejected` or `failed`, the original as `cause`), and so is a signature\n * that is not a string: nothing was sent, so a retry is safe.\n */\nasync function signBridgeOut(\n wallet: BridgeTypedDataSigner,\n types: ReturnType<typeof getGalaBridgeTypedDataTypes>,\n message: Record<string, unknown>,\n): Promise<string> {\n let signature: unknown;\n try {\n signature = await wallet.signTypedData(GALA_BRIDGE_TYPED_DATA_DOMAIN, types, message);\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n {\n method: BRIDGE_OUT_METHOD,\n reason: isWalletUserRejection(cause) ? 'user_rejected' : 'failed',\n },\n { cause, walletCode: walletDeclineCode(cause) },\n );\n }\n if (typeof signature !== 'string') {\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n { method: BRIDGE_OUT_METHOD, reason: 'failed' },\n { cause: signature },\n );\n }\n return signature;\n}\n\n/**\n * Build an EIP-712 signed bridge out payload.\n *\n * The payload is signed using EIP-712 typed data signing and includes:\n * - The message to be signed\n * - The EIP-712 signature\n * - The typed data types and domain for verification\n * - An Ethereum signed message `prefix` over the deterministic JSON of the typed data (its number\n * is the UTF-16 length of that string, as launchpad-sdk always sent it; the typed-data hash does\n * not cover it)\n *\n * @param dto - Bridge request (a `uniqueKey` is generated when it has none)\n * @param config - The signer\n * @returns The payload for `GalaConnectClient.requestBridgeOut`\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`destinationChainId`) for a chain id that is not a\n * positive integer; `CSPRNG_UNAVAILABLE` when a key must be generated and the platform has no\n * `crypto.getRandomValues`; `SIGNING_FAILED` when the signer fails (see `signBridgeOut`)\n */\nexport async function buildBridgeOutPayload(\n dto: BridgeRequestDto,\n config: BuildBridgeOutPayloadConfig,\n): Promise<SignedBridgeOutPayload> {\n const { wallet } = config;\n\n // Normalize destination chain ID to number (refused, never defaulted, when it is not one)\n const destinationChainId = destinationChainIdOf(dto.destinationChainId);\n\n // Generate unique key for idempotency\n const uniqueKey = dto.uniqueKey ?? createUniqueKey(BRIDGE_UNIQUE_KEY_PREFIX);\n\n // Normalize fee object for deterministic signing\n const normalizedFee = normalizeDestinationChainTxFee(dto.destinationChainTxFee);\n const hasCrossRate = Boolean(normalizedFee.galaExchangeCrossRate);\n\n // Remove unused rate object (either galaExchangeRate or galaExchangeCrossRate)\n const sanitizedFeeObj = hasCrossRate\n ? { ...normalizedFee, galaExchangeRate: undefined }\n : { ...normalizedFee, galaExchangeCrossRate: undefined };\n\n // Build the message payload\n const message = {\n destinationChainId,\n destinationChainTxFee: sanitizeObject(sanitizedFeeObj),\n quantity: dto.quantity,\n recipient: dto.recipient,\n tokenInstance: dto.tokenInstance,\n uniqueKey,\n };\n\n // Get appropriate typed data types based on fee structure\n const typedDataTypes = getGalaBridgeTypedDataTypes(hasCrossRate);\n\n // Sign with EIP-712\n const signature = await signBridgeOut(wallet, typedDataTypes, message);\n\n // Deterministic JSON (core's serialize: byte-identical to json-stringify-deterministic for JSON)\n const deterministicPayload = serialize({\n domain: GALA_BRIDGE_TYPED_DATA_DOMAIN,\n message,\n primaryType: 'GalaTransaction',\n types: typedDataTypes,\n });\n\n // Create Ethereum signed message prefix\n const prefix = `\\u0019Ethereum Signed Message:\\n${deterministicPayload.length}`;\n\n return {\n ...message,\n signature,\n prefix,\n types: typedDataTypes,\n domain: GALA_BRIDGE_TYPED_DATA_DOMAIN,\n };\n}\n","/**\n * Bridge Out Flow Helpers\n *\n * The bridge-out flow (GalaChain to an external chain) both strategies run: fee, signed\n * `RequestTokenBridgeOut`, then `BridgeTokenOut`.\n *\n * @module bridge/utils/bridgeOutHelpers\n */\n\nimport { GalaSDKError, type BridgeOutStep } from '../../index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport type { BridgeOutParams, BridgeTransaction, ExternalNetwork } from '../types/index.js';\nimport { buildBridgeOutboundTransaction, buildBridgeRequestDto } from './balanceHelpers.js';\nimport {\n assertBridgeRequestId,\n assertRequestAccepted,\n assertTokenSymbolResolved,\n extractBridgeOutTransactionHash,\n} from './bridgeErrors.js';\nimport { assertUsableFee, extractBridgeRequestId, validateBridgeAmount } from './bridgePayload.js';\nimport { buildBridgeOutPayload, type BridgeTypedDataSigner } from './eip712Helpers.js';\nimport type { TokenMetadataResolver } from './tokenMetadataResolver.js';\n\n/**\n * Configuration for executing bridge out flow\n */\nexport interface BridgeOutFlowConfig {\n /** GalaConnect client for API calls */\n galaConnectClient: GalaConnectClient;\n /** Token metadata resolver */\n tokenMetadataResolver: TokenMetadataResolver;\n /** Signs the EIP-712 bridge-out payload (the Ethereum wallet) */\n ethereumWallet: BridgeTypedDataSigner;\n /** Destination chain ID */\n destinationChainId: number;\n /** Destination chain name */\n destinationChain: ExternalNetwork;\n /** Function to validate recipient address for the destination chain */\n validateRecipientAddress: (address: string, label: string) => void;\n}\n\n/**\n * A bridge-out (an external one, or a cross-channel wrap / unwrap) after GalaConnect accepted its\n * `RequestTokenBridgeOut` (the tokens may be locked): the bridge request id from that answer,\n * `BridgeTokenOut` from `bridgeFromChannel` (GalaChain refusing it is `BRIDGE_REQUEST_REJECTED`),\n * and what `readResult` reads from its answer. Any failure here is `BRIDGE_OUT_OUTCOME_UNKNOWN`\n * (`step`, the `bridgeRequestId` once known, the request's `uniqueKey`, the failure as `cause`),\n * whatever the failure itself was: a `BridgeTokenOut` 429 or 4xx must not read as \"not queued\",\n * since bridging again would lock the tokens a second time. With the `bridgeRequestId`,\n * `BridgeTokenOut` can be sent again to finish this bridge-out.\n *\n * @param readResult - Reads the transaction id from the `BridgeTokenOut` answer (throws when the\n * answer is not usable)\n */\nexport async function completeBridgeOut(\n galaConnectClient: GalaConnectClient,\n requestResponse: unknown,\n uniqueKey: string,\n bridgeFromChannel: string,\n readResult: (bridgeOutResponse: unknown, bridgeRequestId: string) => string,\n): Promise<string> {\n let step: BridgeOutStep = 'request_id';\n let bridgeRequestId = '';\n try {\n bridgeRequestId = assertBridgeRequestId(extractBridgeRequestId(requestResponse));\n step = 'bridge_token_out';\n const bridgeOutResponse = await galaConnectClient.bridgeTokenOut({\n bridgeFromChannel,\n bridgeRequestId,\n });\n assertRequestAccepted('BridgeTokenOut', bridgeOutResponse);\n step = 'transaction_hash';\n return readResult(bridgeOutResponse, bridgeRequestId);\n } catch (cause: unknown) {\n throw new GalaSDKError(\n 'BRIDGE_OUT_OUTCOME_UNKNOWN',\n { step, bridgeRequestId },\n { uniqueKey, cause },\n );\n }\n}\n\n/**\n * Execute the bridge out flow (GalaChain → External chain).\n *\n * Every check runs before anything is signed or sent: the symbol, the amount, the recipient.\n * Then: token metadata, the fee, the signed `RequestTokenBridgeOut`, the bridge request id from\n * its answer, `BridgeTokenOut`, and the transaction hash from that answer.\n *\n * @param params - Bridge out parameters\n * @param config - Flow configuration\n * @returns Bridge transaction result\n * @throws GalaSDKError `BRIDGE_OUT_OUTCOME_UNKNOWN` for any failure after `RequestTokenBridgeOut`\n * was accepted (see `completeBridgeOut`); before it, the failing step's own error\n */\nexport async function executeBridgeOutFlow(\n params: BridgeOutParams,\n config: BridgeOutFlowConfig,\n): Promise<BridgeTransaction> {\n const { amount, recipientAddress, tokenSymbol: resolvedSymbol } = params;\n const {\n galaConnectClient,\n tokenMetadataResolver,\n ethereumWallet,\n destinationChainId,\n destinationChain,\n validateRecipientAddress,\n } = config;\n\n // 1. Validate that BridgeService resolved the symbol\n const tokenSymbol = assertTokenSymbolResolved(resolvedSymbol);\n\n // 2. Validate amount (prevents wasted fees on zero/negative amounts)\n validateBridgeAmount(amount);\n\n // 3. Validate recipient address using chain-specific validation\n validateRecipientAddress(recipientAddress, 'recipient');\n\n // 4. Fetch token metadata\n const metadata = await tokenMetadataResolver.getTokenMetadata(tokenSymbol);\n\n // 5. Fetch bridge fee (the oracle-signed fee the payload carries)\n const bridgeFee = assertUsableFee(\n await galaConnectClient.fetchBridgeFee({\n chainId: destinationChain,\n bridgeToken: metadata.descriptor,\n }),\n );\n\n // 6. Build bridge request DTO using shared helper\n const dtoPayload = buildBridgeRequestDto({\n destinationChainId,\n bridgeFee,\n amount,\n recipientAddress,\n tokenDescriptor: metadata.descriptor,\n });\n\n // 7. Sign and build payload using shared EIP-712 helper\n const signedPayload = await buildBridgeOutPayload(dtoPayload, {\n wallet: ethereumWallet,\n });\n\n // 8. Submit RequestTokenBridgeOut (its own errors carry the payload's uniqueKey)\n const requestResponse = await galaConnectClient.requestBridgeOut(signedPayload);\n // GalaChain refusing the request locked nothing: its own refusal, with the key\n assertRequestAccepted('RequestTokenBridgeOut', requestResponse, signedPayload.uniqueKey);\n\n // 9-11. From here the request is accepted and the tokens may be locked: every failure is\n // BRIDGE_OUT_OUTCOME_UNKNOWN (never a retryable refusal, which would lock them twice).\n const transactionHash = await completeBridgeOut(\n galaConnectClient,\n requestResponse,\n signedPayload.uniqueKey,\n 'asset',\n extractBridgeOutTransactionHash,\n );\n\n // 12. Build and return transaction response\n return buildBridgeOutboundTransaction({\n toChain: destinationChain,\n transactionHash,\n tokenSymbol,\n amount,\n feePaid: bridgeFee.estimatedTotalTxFeeInGala,\n baseUrl: galaConnectClient.getBaseUrl(),\n });\n}\n","/**\n * Bridge Status Parser\n *\n * Shared utility for parsing bridge status responses.\n * Consolidates duplicate status parsing logic from both bridge strategies.\n *\n * @module bridge/utils/bridgeStatusParser\n */\n\nimport { safeParseInt } from '../internal/values.js';\nimport { BridgeStatusCode } from '../types/index.js';\nimport type { BridgeStatus, BridgeStatusResponse } from '../types/index.js';\n\n/**\n * Terminal status codes that indicate a bridge operation is complete.\n */\nexport const TERMINAL_STATUS_CODES = {\n COMPLETED: BridgeStatusCode.COMPLETED,\n FAILED: BridgeStatusCode.FAILED,\n DELIVERY_FAILED: BridgeStatusCode.DELIVERY_FAILED,\n} as const;\n\n/**\n * Parse a bridge status response into a BridgeStatus object.\n *\n * This consolidates the duplicate `getStatus()` result parsing from\n * EthereumBridgeStrategy and SolanaBridgeStrategy.\n *\n * Safely parses the numeric status code using {@link safeParseInt} to handle\n * edge cases where the API returns unexpected values (strings, null, undefined).\n *\n * @param response - Raw response from GalaConnect getBridgeStatus API\n * @returns Parsed BridgeStatus object with normalized fields\n *\n * @example\n * ```typescript\n * const response = await galaConnectClient.getBridgeStatus(hash);\n * const status = parseBridgeStatusResponse(response);\n * if (status.isComplete) {\n * console.log('Bridge completed successfully!');\n * }\n * ```\n */\nexport function parseBridgeStatusResponse(response: BridgeStatusResponse): BridgeStatus {\n // Safely parse status code from API response, defaulting to 0 (UNKNOWN) if invalid\n const rawStatus = response.status;\n const statusCode = safeParseInt(rawStatus, 0);\n\n return {\n status: statusCode,\n statusDescription: response.statusDescription,\n fromChain: response.fromChain,\n toChain: response.toChain,\n quantity: response.quantity,\n transactionHash: response.emitterTransactionHash,\n tokenInstance: response.tokenInstance,\n isComplete: statusCode === Number(TERMINAL_STATUS_CODES.COMPLETED),\n isFailed:\n statusCode === Number(TERMINAL_STATUS_CODES.FAILED) ||\n statusCode === Number(TERMINAL_STATUS_CODES.DELIVERY_FAILED),\n };\n}\n","/**\n * Strategy Delegation Utilities\n *\n * The helpers BridgeService and both strategies share: typed strategy lookup, the fee estimate,\n * the status read, and the token-config queries.\n *\n * @module bridge/utils/strategyDelegation\n */\n\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport type { BridgeStrategy } from '../strategies/BridgeStrategy.js';\nimport type { EthereumBridgeStrategy } from '../strategies/EthereumBridgeStrategy.js';\nimport type { SolanaBridgeStrategy } from '../strategies/SolanaBridgeStrategy.js';\nimport { normalizeTokenSymbol } from '../internal/values.js';\nimport type { BridgeFeeEstimate, BridgeStatus, ExternalNetwork } from '../types/index.js';\nimport { assertStrategyExists } from './balanceHelpers.js';\nimport { assertStatusAnswer, assertUsableFee, buildFeePayload } from './bridgePayload.js';\nimport { parseBridgeStatusResponse } from './bridgeStatusParser.js';\nimport type { TokenMetadataResolver } from './tokenMetadataResolver.js';\n\n// ==========================================================================\n// Type-Safe Strategy Access\n// ==========================================================================\n\n/**\n * The Ethereum strategy, typed.\n *\n * @throws GalaSDKError `BRIDGE_NOT_CONFIGURED` (`Ethereum`) when there is none\n */\nexport function getEthereumStrategy(\n strategies: Map<ExternalNetwork, BridgeStrategy>,\n): EthereumBridgeStrategy {\n return assertStrategyExists(strategies.get('Ethereum'), 'Ethereum') as EthereumBridgeStrategy;\n}\n\n/**\n * The Solana strategy, typed.\n *\n * @throws GalaSDKError `BRIDGE_NOT_CONFIGURED` (`Solana`) when there is none\n */\nexport function getSolanaStrategy(\n strategies: Map<ExternalNetwork, BridgeStrategy>,\n): SolanaBridgeStrategy {\n return assertStrategyExists(strategies.get('Solana'), 'Solana') as SolanaBridgeStrategy;\n}\n\n// ==========================================================================\n// Address Resolution Helpers\n// ==========================================================================\n\n/**\n * The address to act on: the one given, else the strategy's own wallet address.\n */\nexport function resolveTargetAddress(\n providedAddress: string | undefined,\n strategy: { getWalletAddress(): string },\n): string {\n return providedAddress ?? strategy.getWalletAddress();\n}\n\n/**\n * The bridge fee estimate for a token (the fee does not depend on the amount).\n *\n * @param client - GalaConnect client\n * @param resolver - Token metadata resolver\n * @param chainId - Destination chain name (`Ethereum`, `Solana`)\n * @param tokenSymbol - Token symbol\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` for a fee answer without the GALA fee and a rate\n */\nexport async function estimateStrategyFee(\n client: GalaConnectClient,\n resolver: TokenMetadataResolver,\n chainId: string,\n tokenSymbol: string,\n): Promise<BridgeFeeEstimate> {\n const metadata = await resolver.getTokenMetadata(tokenSymbol);\n const feeResponse = await client.fetchBridgeFee({\n chainId,\n bridgeToken: metadata.descriptor,\n });\n return buildFeePayload(assertUsableFee(feeResponse));\n}\n\n/**\n * The status of a bridge transaction, from GalaConnect.\n *\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` for an answer that is not an object\n */\nexport async function getStrategyStatus(\n client: GalaConnectClient,\n transactionHash: string,\n): Promise<BridgeStatus> {\n const response = await client.getBridgeStatus(transactionHash);\n return parseBridgeStatusResponse(assertStatusAnswer(response));\n}\n\n/**\n * The configured token symbols (the map's normalized keys).\n */\nexport function getConfiguredTokenSymbols(tokenConfigs: ReadonlyMap<string, unknown>): string[] {\n return Array.from(tokenConfigs.keys());\n}\n\n/**\n * Whether a token symbol is configured (compared normalized: trimmed, upper case).\n */\nexport function isConfiguredToken(\n tokenConfigs: ReadonlyMap<string, unknown>,\n tokenSymbol: string,\n): boolean {\n return tokenConfigs.has(normalizeTokenSymbol(tokenSymbol));\n}\n","/**\n * Token Metadata Resolver\n *\n * Resolves (and caches) the GalaChain class key and decimals of a bridge token by symbol: the\n * static metadata of the well-known tokens first, else GalaConnect's verified bridge\n * configuration. Used by both bridge strategies.\n *\n * @module bridge/utils/tokenMetadataResolver\n */\n\nimport { GalaSDKError } from '../../index.js';\nimport { STATIC_TOKEN_METADATA } from '../constants/index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport { normalizeTokenSymbol } from '../internal/values.js';\nimport type { BridgeConfigurationToken, BridgeTokenMetadata } from '../types/index.js';\nimport { buildTokenMetadata } from './bridgePayload.js';\n\n/** The GalaConnect call a configuration comes from (the `method` of its errors). */\nconst CONFIGURATIONS_PATH = '/v1/connect/bridge-configurations';\n\n/**\n * Configuration for TokenMetadataResolver\n */\nexport interface TokenMetadataResolverConfig {\n /** GalaConnect client for API lookups */\n galaConnectClient: GalaConnectClient;\n}\n\n/** True when `token` has a usable class key (four strings) and decimals (an integer, 0 or more). */\nfunction isUsableConfiguration(token: BridgeConfigurationToken): boolean {\n return (\n [token.collection, token.category, token.type, token.additionalKey].every(\n (part) => typeof part === 'string',\n ) &&\n Number.isSafeInteger(token.decimals) &&\n token.decimals >= 0 &&\n (token.channel === undefined || typeof token.channel === 'string')\n );\n}\n\n/**\n * Token Metadata Resolver\n *\n * Provides cached token metadata resolution with fallback to API lookup.\n */\nexport class TokenMetadataResolver {\n private readonly galaConnectClient: GalaConnectClient;\n private readonly cache = new Map<string, BridgeTokenMetadata>();\n\n /**\n * Creates a new TokenMetadataResolver.\n *\n * @param config - Resolver configuration\n */\n constructor(config: TokenMetadataResolverConfig) {\n this.galaConnectClient = config.galaConnectClient;\n }\n\n /**\n * Get token metadata by symbol.\n *\n * Resolution order:\n * 1. In-memory cache\n * 2. Static metadata (well-known tokens like GALA, GUSDC)\n * 3. GalaConnect API lookup (the verified configuration of exactly this symbol)\n *\n * @param symbol - Token symbol (e.g., 'GALA', 'GUSDC')\n * @returns Token metadata including descriptor and decimals\n * @throws GalaSDKError `BRIDGE_TOKEN_NOT_FOUND` when GalaConnect has no verified configuration\n * for the symbol; `BRIDGE_READ_RESPONSE_INVALID` when the configuration has no usable class key\n * or decimals; the `GalaConnectClient` read errors\n */\n async getTokenMetadata(symbol: string): Promise<BridgeTokenMetadata> {\n const normalizedSymbol = normalizeTokenSymbol(symbol);\n\n // 1. Check in-memory cache\n const cached = this.cache.get(normalizedSymbol);\n if (cached) {\n return cached;\n }\n\n // 2. Check static metadata for well-known tokens\n const staticMetadata = STATIC_TOKEN_METADATA[normalizedSymbol];\n if (staticMetadata !== undefined) {\n this.cache.set(normalizedSymbol, staticMetadata);\n return staticMetadata;\n }\n\n // 3. Fetch from API\n const metadata = await this.fetchFromApi(symbol);\n this.cache.set(normalizedSymbol, metadata);\n return metadata;\n }\n\n /**\n * Fetch token metadata from GalaConnect API.\n */\n private async fetchFromApi(symbol: string): Promise<BridgeTokenMetadata> {\n const tokens = await this.galaConnectClient.getBridgeConfigurations(symbol);\n const token = tokens.find(\n (t) =>\n typeof t.symbol === 'string' &&\n normalizeTokenSymbol(t.symbol) === normalizeTokenSymbol(symbol) &&\n t.verified === true,\n );\n\n if (!token) {\n throw new GalaSDKError('BRIDGE_TOKEN_NOT_FOUND', { symbol }, { write: false });\n }\n if (!isUsableConfiguration(token)) {\n throw new GalaSDKError(\n 'BRIDGE_READ_RESPONSE_INVALID',\n { method: CONFIGURATIONS_PATH },\n { write: false },\n );\n }\n\n return buildTokenMetadata(\n {\n collection: token.collection,\n category: token.category,\n type: token.type,\n additionalKey: token.additionalKey,\n },\n token.decimals,\n token.channel,\n );\n }\n}\n","/**\n * Token Math Utilities\n *\n * Utilities for converting between decimal and base unit representations.\n */\n\nimport BigNumber from 'bignumber.js';\n\nimport { GalaSDKError } from '../../index.js';\nimport { toBigNumber } from '../internal/values.js';\n\n/** The finite number `amount` spells, or `undefined`. */\nfunction finiteDecimal(amount: string): BigNumber | undefined {\n if (typeof amount !== 'string' || amount === '') {\n return undefined;\n }\n try {\n const value = new BigNumber(amount);\n return value.isFinite() ? value : undefined;\n } catch {\n // `BigNumber.DEBUG = true` (an app setting on the shared bignumber.js) makes a non-number throw.\n return undefined;\n }\n}\n\n/**\n * Convert a decimal amount to base units (smallest denomination)\n *\n * @param amount - The decimal amount as a string (e.g., \"1.5\")\n * @param decimals - The number of decimal places\n * @returns The amount in base units as a bigint\n * @throws GalaSDKError `INVALID_BRIDGE_AMOUNT`: `not_a_number`, or `too_many_decimals` when it\n * cannot be represented with the given decimals (it is never rounded)\n */\nexport function toBaseUnits(amount: string, decimals: number): bigint {\n const value = finiteDecimal(amount);\n if (value === undefined) {\n throw new GalaSDKError('INVALID_BRIDGE_AMOUNT', {\n value: String(amount),\n reason: 'not_a_number',\n });\n }\n const scaled = value.multipliedBy(toBigNumber(10).pow(decimals));\n if (!scaled.isInteger()) {\n throw new GalaSDKError('INVALID_BRIDGE_AMOUNT', { value: amount, reason: 'too_many_decimals' });\n }\n return BigInt(scaled.toFixed(0));\n}\n\n/**\n * Convert base units to a decimal string\n *\n * @param amount - The amount in base units\n * @param decimals - The number of decimal places\n * @returns The decimal string representation with the fraction's trailing zeros removed\n */\nexport function fromBaseUnits(amount: bigint, decimals: number): string {\n const value = toBigNumber(amount.toString());\n return trimFraction(value.dividedBy(toBigNumber(10).pow(decimals)).toFixed(decimals));\n}\n\n/**\n * Drops the trailing zeros of a FRACTION (and a point left bare): \"1.500\" is \"1.5\", \"100.00\" is\n * \"100\", and a whole number keeps every digit (\"100\" stays \"100\").\n */\nfunction trimFraction(text: string): string {\n return text.includes('.') ? text.replace(/\\.?0+$/u, '') : text;\n}\n\n/**\n * Threshold below which we use scientific notation (1 millionth).\n * Numbers smaller than this are hard to read in decimal form.\n */\nconst SCIENTIFIC_NOTATION_THRESHOLD = 0.000001;\n\n/**\n * Format a token amount for display\n *\n * @param amount - The decimal amount as a string\n * @param maxDecimals - Maximum decimals to display (default: 6)\n * @returns Formatted string with appropriate precision\n */\nexport function formatTokenAmount(amount: string, maxDecimals = 6): string {\n // An amount that is not a finite number reads as 0 (toBigNumber's fallback).\n const value = toBigNumber(amount);\n\n // For very small numbers (< 0.000001), use scientific notation for clarity\n if (value.abs().lt(SCIENTIFIC_NOTATION_THRESHOLD) && !value.isZero()) {\n return value.toExponential(2);\n }\n\n // Determine appropriate decimal places\n const decimals = Math.min(\n maxDecimals,\n value.abs().lt(1) ? maxDecimals : value.abs().lt(100) ? 4 : 2,\n );\n\n return trimFraction(value.toFixed(decimals));\n}\n\n/**\n * Compare two token amounts\n *\n * @param a - First amount\n * @param b - Second amount\n * @returns -1 if a < b, 0 if a == b, 1 if a > b\n */\nexport function compareAmounts(a: string, b: string): -1 | 0 | 1 {\n const valueA = toBigNumber(a);\n const valueB = toBigNumber(b);\n // BigNumber.comparedTo always returns exactly -1, 0, or 1 (not arbitrary numbers)\n return valueA.comparedTo(valueB) as -1 | 0 | 1;\n}\n","/**\n * Bridge Strategy Interface\n *\n * Defines the contract for chain-specific bridge implementations.\n * Each external chain (Ethereum, Solana) implements this interface\n * to handle its unique signing, transaction, and status tracking logic.\n */\n\nimport { GalaSDKError } from '../../index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport {\n type BridgeFeeEstimate,\n type BridgeInParams,\n type BridgeOutParams,\n type BridgeStatus,\n BridgeStatusCode,\n type BridgeTransaction,\n type ExternalNetwork,\n} from '../types/index.js';\nimport { delay } from '../utils/retry.js';\nimport {\n getConfiguredTokenSymbols,\n getStrategyStatus,\n isConfiguredToken,\n} from '../utils/strategyDelegation.js';\n\n/** How a strategy waits (a poll interval, a wait before a step). Default: a timer. */\nexport type BridgeSleep = (ms: number) => Promise<void>;\n\n/**\n * Strategy interface for chain-specific bridge operations.\n *\n * The Bridge SDK uses the Strategy pattern to abstract chain-specific logic:\n * - EthereumBridgeStrategy: Handles ERC-20 approvals, ethers.js signing\n * - SolanaBridgeStrategy: Handles SPL token accounts, @solana/web3.js signing\n *\n * Each strategy encapsulates:\n * - Fee estimation for the target chain\n * - Outbound transfers (GalaChain → External)\n * - Inbound transfers (External → GalaChain)\n * - Status polling and transaction tracking\n */\nexport interface BridgeStrategy {\n /**\n * The external network this strategy handles.\n */\n readonly network: ExternalNetwork;\n\n /**\n * Estimate bridge fees for a transfer (a per-transfer cost: it does not depend on the amount).\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GUSDC')\n * @returns Fee estimate with breakdown\n */\n estimateFee(tokenSymbol: string): Promise<BridgeFeeEstimate>;\n\n /**\n * Bridge tokens OUT from GalaChain to external chain.\n *\n * Flow:\n * 1. Lock tokens on GalaChain (via GalaConnect)\n * 2. Wait for bridge confirmation\n * 3. Receive wrapped tokens on external chain\n *\n * @param params - Bridge out parameters\n * @returns Transaction details with tracking info\n */\n bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction>;\n\n /**\n * Bridge tokens IN from external chain to GalaChain.\n *\n * Flow:\n * 1. Approve bridge contract (if needed)\n * 2. Deposit tokens to bridge contract\n * 3. Register the deposit with GalaConnect\n * 4. Receive native tokens on GalaChain\n *\n * @param params - Bridge in parameters\n * @returns Transaction details with tracking info\n */\n bridgeIn(params: BridgeInParams): Promise<BridgeTransaction>;\n\n /**\n * Get the current status of a bridge transaction.\n *\n * @param transactionHash - The bridge transaction hash\n * @returns Current status with details\n */\n getStatus(transactionHash: string): Promise<BridgeStatus>;\n\n /**\n * Wait for a bridge transaction to complete.\n *\n * Polls the transaction status until it reaches a terminal state\n * (completed or failed) or the timeout is reached.\n *\n * @param transactionHash - The bridge transaction hash\n * @param options - Polling options\n * @returns Final status when complete\n * @throws GalaSDKError `BRIDGE_STATUS_TIMEOUT` if the timeout is reached first;\n * `INVALID_BRIDGE_OPTION` for a poll interval or timeout that is not a finite number, 0 or more\n */\n waitForCompletion(transactionHash: string, options?: WaitOptions): Promise<BridgeStatus>;\n\n /**\n * Get the list of supported tokens for this chain.\n *\n * @returns Array of token symbols supported by this bridge\n */\n getSupportedTokens(): string[];\n\n /**\n * Check if a specific token is supported for bridging.\n *\n * @param tokenSymbol - Token symbol to check\n * @returns True if token can be bridged\n */\n isTokenSupported(tokenSymbol: string): boolean;\n\n /**\n * Validate a recipient address for the external chain.\n *\n * @param address - Address to validate\n * @returns True if address is valid for this chain\n */\n isValidAddress(address: string): boolean;\n}\n\n/**\n * Options for waiting on bridge completion.\n */\nexport interface WaitOptions {\n /**\n * Polling interval in milliseconds.\n * @default 15000 (15 seconds)\n */\n pollInterval?: number;\n\n /**\n * Maximum time to wait in milliseconds.\n * @default 2700000 (45 minutes)\n */\n timeout?: number;\n\n /**\n * Callback for status updates during polling.\n */\n onStatusUpdate?: (status: BridgeStatus) => void;\n}\n\n/** The statuses after which a bridge transaction changes no more. */\nconst TERMINAL_STATUSES: ReadonlySet<BridgeStatusCode> = new Set([\n BridgeStatusCode.COMPLETED,\n BridgeStatusCode.FAILED,\n BridgeStatusCode.DELIVERY_FAILED,\n]);\n\n/**\n * Base class providing common functionality for bridge strategies.\n *\n * Concrete strategies extend this class and implement chain-specific logic.\n */\nexport abstract class BaseBridgeStrategy implements BridgeStrategy {\n abstract readonly network: ExternalNetwork;\n\n /** How this strategy waits between polls (and before a step it must wait for). */\n protected readonly sleep: BridgeSleep;\n\n /**\n * @param sleep - How the strategy waits (default: a timer)\n */\n protected constructor(sleep: BridgeSleep = delay) {\n this.sleep = sleep;\n }\n\n abstract estimateFee(tokenSymbol: string): Promise<BridgeFeeEstimate>;\n abstract bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction>;\n abstract bridgeIn(params: BridgeInParams): Promise<BridgeTransaction>;\n abstract getStatus(transactionHash: string): Promise<BridgeStatus>;\n abstract getSupportedTokens(): string[];\n abstract isTokenSupported(tokenSymbol: string): boolean;\n abstract isValidAddress(address: string): boolean;\n\n /**\n * Default implementation of waitForCompletion with polling.\n *\n * Strategies can override this if they have chain-specific\n * event subscription capabilities.\n */\n async waitForCompletion(\n transactionHash: string,\n options: WaitOptions = {},\n ): Promise<BridgeStatus> {\n const {\n pollInterval = 15000,\n timeout = 45 * 60 * 1000, // 45 minutes\n onStatusUpdate,\n } = options;\n // A NaN timeout would never be exceeded (an endless poll); refused, like a negative one.\n for (const [option, value] of [\n ['pollInterval', pollInterval],\n ['timeout', timeout],\n ] as const) {\n if (!Number.isFinite(value) || value < 0) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option });\n }\n }\n\n const startTime = Date.now();\n\n while (true) {\n const status = await this.getStatus(transactionHash);\n\n if (onStatusUpdate) {\n onStatusUpdate(status);\n }\n\n // Check for terminal states (COMPLETED, FAILED, or DELIVERY_FAILED)\n if (TERMINAL_STATUSES.has(status.status)) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > timeout) {\n throw new GalaSDKError(\n 'BRIDGE_STATUS_TIMEOUT',\n { transactionHash, timeoutMs: timeout, lastStatus: status.status },\n { write: false },\n );\n }\n\n // Wait before next poll\n await this.sleep(pollInterval);\n }\n }\n}\n\n/**\n * Base implementation for strategies backed by a configured token map.\n *\n * @typeParam TTokenConfig - Chain-specific token configuration type.\n */\nexport abstract class ConfiguredBridgeStrategy<TTokenConfig> extends BaseBridgeStrategy {\n protected readonly galaConnectClient: GalaConnectClient;\n protected readonly tokenConfigs: Map<string, TTokenConfig>;\n\n /**\n * Create a configured strategy base.\n *\n * @param galaConnectClient - Client used for bridge requests.\n * @param tokenConfigs - Normalized token configuration map.\n * @param sleep - How the strategy waits (default: a timer).\n */\n protected constructor(\n galaConnectClient: GalaConnectClient,\n tokenConfigs: Map<string, TTokenConfig>,\n sleep?: BridgeSleep,\n ) {\n super(sleep);\n this.galaConnectClient = galaConnectClient;\n this.tokenConfigs = tokenConfigs;\n }\n\n /**\n * Get the current status of a bridge transaction.\n *\n * @param transactionHash - Transaction hash to check.\n * @returns Current bridge status.\n */\n async getStatus(transactionHash: string): Promise<BridgeStatus> {\n return getStrategyStatus(this.galaConnectClient, transactionHash);\n }\n\n /**\n * Get the configured symbols supported by this strategy.\n *\n * @returns Supported token symbols.\n */\n getSupportedTokens(): string[] {\n return getConfiguredTokenSymbols(this.tokenConfigs);\n }\n\n /**\n * Check whether a token symbol is configured for this strategy.\n *\n * @param tokenSymbol - Token symbol to check.\n * @returns True when the token is configured.\n */\n isTokenSupported(tokenSymbol: string): boolean {\n return isConfiguredToken(this.tokenConfigs, tokenSymbol);\n }\n}\n","/**\n * Ethereum Bridge Strategy\n *\n * Handles bridging between GalaChain and Ethereum:\n * - Outbound (GalaChain → Ethereum): the EIP-712 signed bridge-out through GalaConnect\n * - Inbound (Ethereum → GalaChain): ERC-20 approve or permit, the bridge contract deposit, and the\n * registration with GalaConnect\n *\n * Failures are `GalaSDKError`s. Everything before the deposit transaction is sent is a refusal\n * that left nothing behind (a bad amount, key or token, a read that failed, a balance that is too\n * low); once the deposit is being sent, every failure is `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN` (with the\n * transaction hash when it is known): the funds may have left the wallet, so another deposit must\n * not be sent before this one is checked.\n */\n\nimport {\n Contract,\n type ContractTransactionResponse,\n JsonRpcProvider,\n Signature,\n Wallet as EthersWallet,\n} from 'ethers';\n\nimport { GalaSDKError, galaChainUserRef, type BridgeDepositStep } from '../../index.js';\nimport {\n BRIDGE_CONTRACT_ABI,\n CHAIN_IDS,\n DEFAULT_ETHEREUM_RPC_URL,\n ERC20_ABI,\n} from '../constants/index.js';\nimport { ETHEREUM_TOKENS_PROD } from '../constants/tokens.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport { getErrorMessage } from '../internal/values.js';\nimport type {\n BridgeFeeEstimate,\n BridgeInParams,\n BridgeOutParams,\n BridgeTokenMetadata,\n BridgeTransaction,\n EthereumTokenConfig,\n EthereumTransactionStatus,\n ExternalNetwork,\n} from '../types/index.js';\nimport {\n createTokenConfigMap,\n requireTokenConfig,\n validateEthereumPrivateKeyFormat,\n validateEthereumTransactionHashFormat,\n} from '../utils/addressValidation.js';\nimport { buildBridgeInboundTransaction } from '../utils/balanceHelpers.js';\nimport {\n assertEthereumAddressOption,\n assertHttpUrlOption,\n assertTokenSymbolResolved,\n validateEthereumAddressOrThrow,\n} from '../utils/bridgeErrors.js';\nimport { executeBridgeOutFlow } from '../utils/bridgeOutHelpers.js';\nimport { validateBridgeAmount } from '../utils/bridgePayload.js';\nimport { estimateStrategyFee } from '../utils/strategyDelegation.js';\nimport { TokenMetadataResolver } from '../utils/tokenMetadataResolver.js';\nimport { fromBaseUnits, toBaseUnits } from '../utils/tokenMath.js';\nimport { type BridgeSleep, ConfiguredBridgeStrategy } from './BridgeStrategy.js';\n\n/** A contract runner: the wallet (to send) or the provider (to read). */\ntype Runner = ConstructorParameters<typeof Contract>[2];\n\n/**\n * {@link ERC20_ABI}'s functions as ethers decodes them (every `uint` a `bigint`, `string` a\n * string): an ethers `Contract` has a method per ABI function, typed only as \"any method\".\n */\ninterface Erc20Contract {\n decimals(): Promise<bigint>;\n balanceOf(owner: string): Promise<bigint>;\n allowance(owner: string, spender: string): Promise<bigint>;\n name(): Promise<string>;\n nonces(owner: string): Promise<bigint>;\n approve(spender: string, value: bigint): Promise<ContractTransactionResponse>;\n}\n\n/** {@link BRIDGE_CONTRACT_ABI}'s functions as ethers sends them. */\ninterface BridgeContract {\n bridgeOut(\n token: string,\n amount: bigint,\n tokenId: number,\n destinationChainId: number,\n recipient: Uint8Array,\n ): Promise<ContractTransactionResponse>;\n bridgeOutWithPermit(\n token: string,\n amount: bigint,\n destinationChainId: number,\n recipient: Uint8Array,\n deadline: bigint,\n v: number,\n r: string,\n s: string,\n ): Promise<ContractTransactionResponse>;\n}\n\n/** The ERC-20 token at `address`. */\nfunction erc20At(address: string, runner: Runner): Erc20Contract {\n return new Contract(address, ERC20_ABI, runner) as unknown as Erc20Contract;\n}\n\n/**\n * An Ethereum read before anything is sent: its failure (the node down or refusing, an answer\n * ethers cannot decode) is `BRIDGE_CHAIN_READ_FAILED` (`call`, the failure as `cause`).\n */\nasync function chainRead<T>(call: string, read: () => Promise<T>): Promise<T> {\n try {\n return await read();\n } catch (cause: unknown) {\n throw new GalaSDKError(\n 'BRIDGE_CHAIN_READ_FAILED',\n { network: 'Ethereum', call },\n { write: false, cause },\n );\n }\n}\n\n/** `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN` for an Ethereum deposit that failed at `step`. */\nfunction depositOutcomeUnknown(\n step: BridgeDepositStep,\n transactionHash: string,\n cause: unknown,\n): GalaSDKError {\n return new GalaSDKError(\n 'BRIDGE_DEPOSIT_OUTCOME_UNKNOWN',\n { network: 'Ethereum', step, transactionHash },\n { cause },\n );\n}\n\n/**\n * Configuration for Ethereum bridge strategy.\n */\nexport interface EthereumBridgeConfig {\n /** GalaConnect API client */\n galaConnectClient: GalaConnectClient;\n /** GalaChain wallet address (`eth|<40 hex>`; `eth|0x...` is refused) */\n galaChainWalletAddress: string;\n /** Ethereum private key for signing */\n ethereumPrivateKey: string;\n /** Ethereum RPC URL (default: {@link DEFAULT_ETHEREUM_RPC_URL}) */\n ethereumRpcUrl?: string;\n /**\n * Ethereum bridge contract address: where inbound deposits (and their approvals and permits) go.\n * Required: there is no default (`getEthereumBridgeContractByEnvironment` gives the deployed one).\n */\n ethereumBridgeContract: string;\n /** Ethereum wallet address (derived from private key if not provided) */\n ethereumWalletAddress?: string;\n /** Token configurations (default: {@link ETHEREUM_TOKENS_PROD}) */\n tokenConfigs?: EthereumTokenConfig[];\n /** How the strategy waits (the delay before an inbound registration). Default: a timer. */\n sleep?: BridgeSleep;\n}\n\n/** Registration delay before notifying GalaConnect of inbound bridge */\nconst REGISTRATION_DELAY_MS = 30_000;\n\n/** An Ethereum address as `isValidAddress` accepts it: `0x` and 40 hex digits. */\nconst ETHEREUM_ADDRESS = /^0x[0-9a-fA-F]{40}$/u;\n\n/**\n * Bridge strategy for GalaChain ↔ Ethereum transfers.\n *\n * Supports 6 tokens: GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC\n */\nexport class EthereumBridgeStrategy extends ConfiguredBridgeStrategy<EthereumTokenConfig> {\n readonly network: ExternalNetwork = 'Ethereum';\n\n /**\n * Ethereum finality threshold (number of confirmations).\n * 12+ confirmations is the practical finality threshold for Ethereum mainnet.\n */\n static readonly ETHEREUM_FINALITY_THRESHOLD = 12;\n\n private readonly galaChainWalletAddress: string;\n private readonly ethereumProvider: JsonRpcProvider;\n private readonly ethereumWallet: EthersWallet;\n private readonly ethereumBridgeContract: string;\n private readonly ethereumWalletAddress: string;\n private readonly tokenMetadataResolver: TokenMetadataResolver;\n\n /**\n * Creates a new Ethereum bridge strategy.\n *\n * @param config - Strategy configuration\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` if ethereumPrivateKey is not 0x and 64 hex digits;\n * `INVALID_BRIDGE_OPTION` (the option) for a bridge contract or wallet address that is not an\n * Ethereum address (the contract is required), or an RPC URL that is not http(s)\n */\n constructor(config: EthereumBridgeConfig) {\n const tokens = config.tokenConfigs ?? ETHEREUM_TOKENS_PROD;\n super(config.galaConnectClient, createTokenConfigMap(tokens), config.sleep);\n for (const token of tokens) assertEthereumAddressOption(token.contractAddress, 'tokenConfigs');\n\n this.galaChainWalletAddress = config.galaChainWalletAddress;\n\n // Validate private key format before use (prevents malformed key crashes)\n validateEthereumPrivateKeyFormat(config.ethereumPrivateKey);\n // Every address and URL option is checked here: a malformed one is refused now, by name,\n // never as a library error at the first request (or after an allowance was granted).\n const ethereumBridgeContract = assertEthereumAddressOption(\n config.ethereumBridgeContract,\n 'ethereumBridgeContract',\n );\n const rpcUrl = assertHttpUrlOption(\n config.ethereumRpcUrl ?? DEFAULT_ETHEREUM_RPC_URL,\n 'ethereumRpcUrl',\n );\n if (config.ethereumWalletAddress !== undefined) {\n assertEthereumAddressOption(config.ethereumWalletAddress, 'ethereumWalletAddress');\n }\n\n // Initialize Ethereum provider and wallet\n this.ethereumProvider = new JsonRpcProvider(rpcUrl);\n this.ethereumWallet = new EthersWallet(config.ethereumPrivateKey, this.ethereumProvider);\n\n this.ethereumWalletAddress = config.ethereumWalletAddress ?? this.ethereumWallet.address;\n this.ethereumBridgeContract = ethereumBridgeContract;\n\n this.tokenMetadataResolver = new TokenMetadataResolver({\n galaConnectClient: this.galaConnectClient,\n });\n }\n\n /**\n * Estimate bridge fees for a transfer to Ethereum.\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GWETH')\n * @returns Fee estimate with breakdown (it does not depend on the amount)\n */\n async estimateFee(tokenSymbol: string): Promise<BridgeFeeEstimate> {\n return estimateStrategyFee(\n this.galaConnectClient,\n this.tokenMetadataResolver,\n 'Ethereum',\n tokenSymbol,\n );\n }\n\n /**\n * Bridge tokens from GalaChain to Ethereum.\n *\n * @param params - Bridge out parameters\n * @returns Transaction details\n */\n async bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction> {\n return executeBridgeOutFlow(params, {\n galaConnectClient: this.galaConnectClient,\n tokenMetadataResolver: this.tokenMetadataResolver,\n ethereumWallet: this.ethereumWallet,\n destinationChainId: CHAIN_IDS.ETHEREUM,\n destinationChain: 'Ethereum',\n validateRecipientAddress: validateEthereumAddressOrThrow,\n });\n }\n\n /**\n * Bridge tokens from Ethereum to GalaChain.\n *\n * @param params - Bridge in parameters\n * @returns Transaction details\n * @throws GalaSDKError before the deposit is sent: the input's refusal, `BRIDGE_CHAIN_READ_FAILED`,\n * `INSUFFICIENT_BRIDGE_BALANCE`; once it is being sent: `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`\n */\n async bridgeIn(params: BridgeInParams): Promise<BridgeTransaction> {\n const { amount, sourcePrivateKey, recipientAddress, tokenSymbol: resolvedSymbol } = params;\n\n // Validate that BridgeService resolved the symbol\n const tokenSymbol = assertTokenSymbolResolved(resolvedSymbol);\n\n // Validate amount (prevents wasted gas on zero/negative amounts)\n validateBridgeAmount(amount);\n\n // Validate sourcePrivateKey format if provided\n const hasSourceKey = sourcePrivateKey !== undefined && sourcePrivateKey !== '';\n if (hasSourceKey) {\n validateEthereumPrivateKeyFormat(sourcePrivateKey);\n }\n\n // The GalaChain recipient, normalized (eth|<checksummed> or a client| alias) before anything\n // is read\n const recipient = galaChainUserRef(recipientAddress ?? this.galaChainWalletAddress, 'address');\n\n // Use provided private key or fall back to configured wallet\n const wallet = hasSourceKey\n ? new EthersWallet(sourcePrivateKey, this.ethereumProvider)\n : this.ethereumWallet;\n\n const tokenConfig = requireTokenConfig(this.tokenConfigs, tokenSymbol, 'Ethereum');\n const metadata = await this.tokenMetadataResolver.getTokenMetadata(tokenSymbol);\n\n // Get token contract\n const tokenContract = erc20At(tokenConfig.contractAddress, wallet);\n\n // Get decimals (a uint8, from the token itself) and calculate base units\n const decimals = Number(await chainRead('decimals', () => tokenContract.decimals()));\n const amountBaseUnits = toBaseUnits(amount, decimals);\n\n // Check balance\n const currentBalance = await chainRead('balanceOf', () =>\n tokenContract.balanceOf(wallet.address),\n );\n if (currentBalance < amountBaseUnits) {\n throw new GalaSDKError('INSUFFICIENT_BRIDGE_BALANCE', {\n network: 'Ethereum',\n symbol: tokenSymbol,\n needed: fromBaseUnits(amountBaseUnits, decimals),\n available: fromBaseUnits(currentBalance, decimals),\n });\n }\n\n const txHash = await this.executeBridgeDeposit({\n wallet,\n tokenContract,\n tokenConfig,\n amountBaseUnits,\n decimals,\n recipient,\n metadata,\n });\n\n return buildBridgeInboundTransaction({\n fromChain: 'Ethereum',\n transactionHash: txHash,\n tokenSymbol,\n amount,\n baseUrl: this.galaConnectClient.getBaseUrl(),\n });\n }\n\n /**\n * Validate an Ethereum address.\n *\n * @param address - Address to validate\n * @returns True if `0x` and 40 hex digits\n */\n isValidAddress(address: string): boolean {\n return ETHEREUM_ADDRESS.test(address);\n }\n\n // ==========================================================================\n // Wallet Info Methods\n // ==========================================================================\n\n /**\n * Get the configured Ethereum wallet address.\n *\n * @returns Ethereum wallet address (0x format)\n */\n getWalletAddress(): string {\n return this.ethereumWalletAddress;\n }\n\n // ==========================================================================\n // Balance Checking Methods\n // ==========================================================================\n\n /**\n * Get ERC-20 token balance for an Ethereum address.\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GWETH', 'GUSDC')\n * @param address - Optional Ethereum address (defaults to configured wallet)\n * @returns Token balance as decimal string (e.g., \"123.45678901\")\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN`, `INVALID_WALLET_ADDRESS`,\n * `BRIDGE_CHAIN_READ_FAILED`\n */\n async getEthereumTokenBalance(tokenSymbol: string, address?: string): Promise<string> {\n const tokenConfig = requireTokenConfig(this.tokenConfigs, tokenSymbol, 'Ethereum');\n const targetAddress = address ?? this.ethereumWalletAddress;\n validateEthereumAddressOrThrow(targetAddress);\n\n const tokenContract = erc20At(tokenConfig.contractAddress, this.ethereumProvider);\n const balanceBaseUnits = await chainRead('balanceOf', () =>\n tokenContract.balanceOf(targetAddress),\n );\n\n // The configured decimals, else the token's own (never an assumed 18).\n const decimals =\n tokenConfig.decimals ?? Number(await chainRead('decimals', () => tokenContract.decimals()));\n return fromBaseUnits(balanceBaseUnits, decimals);\n }\n\n /**\n * Get native ETH balance for an Ethereum address.\n *\n * @param address - Optional Ethereum address (defaults to configured wallet)\n * @returns ETH balance as decimal string (18 decimals)\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if address invalid\n */\n async getEthereumNativeBalance(address?: string): Promise<string> {\n const targetAddress = address ?? this.ethereumWalletAddress;\n validateEthereumAddressOrThrow(targetAddress);\n const balanceWei: bigint = await this.ethereumProvider.getBalance(targetAddress);\n return fromBaseUnits(balanceWei, 18);\n }\n\n // ==========================================================================\n // Transaction Status Methods\n // ==========================================================================\n\n /**\n * Get the status of an Ethereum transaction by hash.\n *\n * Queries Ethereum RPC directly using `getTransactionReceipt()` and `getTransaction()`. An RPC\n * failure is answered as `not_found` with the failure in `error`.\n *\n * @param transactionHash - Ethereum transaction hash (0x-prefixed, 64 hex characters)\n * @returns Transaction status with confirmation details\n * @throws GalaSDKError `INVALID_TRANSACTION_HASH` if hash format is invalid\n */\n async getEthereumTransactionStatus(transactionHash: string): Promise<EthereumTransactionStatus> {\n validateEthereumTransactionHashFormat(transactionHash);\n\n // Normalize hash to lowercase for consistency\n const normalizedHash = transactionHash.toLowerCase();\n\n try {\n // Try to get transaction receipt (only exists if mined)\n const receipt = await this.ethereumProvider.getTransactionReceipt(normalizedHash);\n\n if (receipt) {\n const currentBlock = await this.ethereumProvider.getBlockNumber();\n const confirmations = currentBlock - receipt.blockNumber + 1;\n\n if (receipt.status !== 1) {\n // Transaction was mined but reverted\n return {\n confirmed: false,\n status: 'failed',\n blockNumber: receipt.blockNumber,\n confirmations,\n transactionHash: normalizedHash,\n gasUsed: receipt.gasUsed.toString(),\n effectiveGasPrice: receipt.gasPrice.toString(),\n error: 'Transaction reverted during execution',\n };\n }\n\n const isFinalized = confirmations >= EthereumBridgeStrategy.ETHEREUM_FINALITY_THRESHOLD;\n return {\n confirmed: true,\n status: isFinalized ? 'finalized' : 'confirmed',\n blockNumber: receipt.blockNumber,\n confirmations,\n transactionHash: normalizedHash,\n gasUsed: receipt.gasUsed.toString(),\n effectiveGasPrice: receipt.gasPrice.toString(),\n };\n }\n\n // No receipt - check if transaction exists in mempool (pending)\n const transaction = await this.ethereumProvider.getTransaction(normalizedHash);\n if (transaction) {\n return {\n confirmed: false,\n status: 'pending',\n transactionHash: normalizedHash,\n };\n }\n\n return {\n confirmed: false,\n status: 'not_found',\n transactionHash: normalizedHash,\n error: 'Transaction not found on Ethereum network',\n };\n } catch (error: unknown) {\n return {\n confirmed: false,\n status: 'not_found',\n transactionHash: normalizedHash,\n error: `Failed to query transaction status: ${getErrorMessage(error)}`,\n };\n }\n }\n\n // ==========================================================================\n // Private Methods\n // ==========================================================================\n\n /**\n * Execute bridge deposit on Ethereum: prepare it (reads, an approval or a permit), send it, wait\n * for its receipt, wait {@link REGISTRATION_DELAY_MS}, register it with GalaConnect. From the\n * send on, every failure is `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`.\n */\n private async executeBridgeDeposit(params: {\n wallet: EthersWallet;\n tokenContract: Erc20Contract;\n tokenConfig: EthereumTokenConfig;\n amountBaseUnits: bigint;\n decimals: number;\n recipient: string;\n metadata: BridgeTokenMetadata;\n }): Promise<string> {\n const bridgeContract = new Contract(\n this.ethereumBridgeContract,\n BRIDGE_CONTRACT_ABI,\n params.wallet,\n ) as unknown as BridgeContract;\n\n const recipientBytes = new TextEncoder().encode(params.recipient);\n\n const sendDeposit = params.tokenConfig.bridgeUsesPermit\n ? await this.prepareBridgeWithPermit(\n params.wallet,\n params.tokenContract,\n params.tokenConfig,\n bridgeContract,\n params.amountBaseUnits,\n recipientBytes,\n )\n : await this.prepareBridgeWithApproval(\n params.wallet,\n params.tokenContract,\n bridgeContract,\n params.tokenConfig,\n params.amountBaseUnits,\n recipientBytes,\n );\n\n let tx: ContractTransactionResponse;\n try {\n tx = await sendDeposit();\n } catch (cause: unknown) {\n throw depositOutcomeUnknown('send', '', cause);\n }\n\n // wait() (one confirmation) resolves once the deposit is mined and throws when it reverted.\n try {\n await tx.wait();\n } catch (cause: unknown) {\n throw depositOutcomeUnknown('confirmation', tx.hash, cause);\n }\n\n try {\n await this.sleep(REGISTRATION_DELAY_MS);\n await this.galaConnectClient.registerBridgeTransaction({\n quantity: fromBaseUnits(params.amountBaseUnits, params.decimals),\n tokenInstance: {\n collection: params.metadata.descriptor.collection,\n category: params.metadata.descriptor.category,\n type: params.metadata.descriptor.type,\n additionalKey: params.metadata.descriptor.additionalKey,\n instance: '0',\n },\n fromChain: 'Ethereum',\n toChain: 'GC',\n hash: tx.hash,\n });\n } catch (cause: unknown) {\n throw depositOutcomeUnknown('registration', tx.hash, cause);\n }\n\n return tx.hash;\n }\n\n /**\n * Bridge using ERC-20 Permit for gas-less approval: reads the chain id, the token name and the\n * permit nonce, signs the permit, and returns the deposit send (not yet sent).\n */\n private async prepareBridgeWithPermit(\n wallet: EthersWallet,\n tokenContract: Erc20Contract,\n tokenConfig: EthereumTokenConfig,\n bridgeContract: BridgeContract,\n amountBaseUnits: bigint,\n recipientBytes: Uint8Array,\n ): Promise<() => Promise<ContractTransactionResponse>> {\n const network = await chainRead('chainId', () => this.ethereumProvider.getNetwork());\n const name = await chainRead('name', () => tokenContract.name());\n const nonce = await chainRead('nonces', () => tokenContract.nonces(wallet.address));\n const deadline = BigInt(Math.floor(Date.now() / 1000) + 60 * 60);\n\n // Sign permit\n const signature = await wallet.signTypedData(\n {\n name,\n version: '1',\n chainId: Number(network.chainId),\n verifyingContract: tokenConfig.contractAddress,\n },\n {\n Permit: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n ],\n },\n {\n owner: wallet.address,\n spender: this.ethereumBridgeContract,\n value: amountBaseUnits,\n nonce,\n deadline,\n },\n );\n\n const splitSig = Signature.from(signature);\n\n return () =>\n bridgeContract.bridgeOutWithPermit(\n tokenConfig.contractAddress,\n amountBaseUnits,\n CHAIN_IDS.GALA_CHAIN,\n recipientBytes,\n deadline,\n splitSig.v,\n splitSig.r,\n splitSig.s,\n );\n }\n\n /**\n * Bridge using traditional ERC-20 approval: reads the allowance, sends (and waits for) an\n * approval when it is too low, and returns the deposit send (not yet sent).\n */\n private async prepareBridgeWithApproval(\n wallet: EthersWallet,\n tokenContract: Erc20Contract,\n bridgeContract: BridgeContract,\n tokenConfig: EthereumTokenConfig,\n amountBaseUnits: bigint,\n recipientBytes: Uint8Array,\n ): Promise<() => Promise<ContractTransactionResponse>> {\n const allowance = await chainRead('allowance', () =>\n tokenContract.allowance(wallet.address, this.ethereumBridgeContract),\n );\n\n // An approval moves no funds: if it fails, a retry of the whole bridge-in is safe.\n if (allowance < amountBaseUnits) {\n const approveTx = await tokenContract.approve(this.ethereumBridgeContract, amountBaseUnits);\n await approveTx.wait();\n }\n\n return () =>\n bridgeContract.bridgeOut(\n tokenConfig.contractAddress,\n amountBaseUnits,\n 0, // tokenId (0 for fungible)\n CHAIN_IDS.GALA_CHAIN,\n recipientBytes,\n );\n }\n}\n","/**\n * Solana Bridge Strategy\n *\n * Handles bridging between GalaChain and Solana:\n * - Outbound (GalaChain → Solana): the EIP-712 signed bridge-out through GalaConnect\n * - Inbound (Solana → GalaChain): the bridge program deposit (SPL or native SOL) and the\n * registration with GalaConnect\n *\n * Failures are `GalaSDKError`s. Everything before the deposit transaction is sent is a refusal\n * that left nothing behind; once it is being sent, every failure is\n * `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN` (with the transaction signature): the funds may have left the\n * wallet, so another deposit must not be sent before this one is checked.\n *\n * React Native: nothing here needs a `Buffer` global (instruction data and seeds are\n * `Uint8Array`s); `@solana/web3.js` brings its own `buffer` package.\n */\n\nimport {\n AccountLayout,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n MintLayout,\n TOKEN_PROGRAM_ID,\n} from '@solana/spl-token';\nimport {\n ComputeBudgetProgram,\n Connection,\n Keypair,\n LAMPORTS_PER_SOL,\n PublicKey,\n SystemProgram,\n Transaction,\n TransactionExpiredBlockheightExceededError,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { base58 } from '@scure/base';\nimport { Wallet as EthersWallet } from 'ethers';\n\nimport { GalaSDKError, galaChainUserRef, type BridgeDepositStep } from '../../index.js';\nimport {\n CHAIN_IDS,\n DEFAULT_SOLANA_BRIDGE_PROGRAM,\n DEFAULT_SOLANA_RPC_URL,\n DEFAULT_SOLANA_TOKENS,\n SOLANA_COMPUTE,\n SOLANA_DISCRIMINATORS,\n} from '../constants/index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport type {\n BridgeFeeEstimate,\n BridgeInParams,\n BridgeOutParams,\n BridgeTokenMetadata,\n BridgeTransaction,\n ExternalNetwork,\n SolanaTokenConfig,\n SolanaTransactionStatus,\n} from '../types/index.js';\nimport {\n createTokenConfigMap,\n requireTokenConfig,\n validateEthereumPrivateKeyFormat,\n} from '../utils/addressValidation.js';\nimport { buildBridgeInboundTransaction } from '../utils/balanceHelpers.js';\nimport {\n assertHttpUrlOption,\n assertTokenSymbolResolved,\n parseSolanaAddressOrThrow,\n solanaPublicKeyOption,\n validateSolanaAddressOrThrow,\n} from '../utils/bridgeErrors.js';\nimport { executeBridgeOutFlow } from '../utils/bridgeOutHelpers.js';\nimport { validateBridgeAmount } from '../utils/bridgePayload.js';\nimport { estimateStrategyFee } from '../utils/strategyDelegation.js';\nimport { TokenMetadataResolver } from '../utils/tokenMetadataResolver.js';\nimport { fromBaseUnits, toBaseUnits } from '../utils/tokenMath.js';\nimport { type BridgeSleep, ConfiguredBridgeStrategy } from './BridgeStrategy.js';\n\n/**\n * Configuration for Solana bridge strategy.\n */\nexport interface SolanaBridgeConfig {\n /** GalaConnect API client */\n galaConnectClient: GalaConnectClient;\n /** GalaChain wallet address (`eth|<40 hex>`; `eth|0x...` is refused) */\n galaChainWalletAddress: string;\n /** Ethereum private key for EIP-712 signing (GalaChain uses Ethereum signatures) */\n ethereumPrivateKey: string;\n /** Solana private key in base58 format */\n solanaPrivateKeyBase58: string;\n /** Solana RPC URL (default: {@link DEFAULT_SOLANA_RPC_URL}); unused when `solanaConnection` is given */\n solanaRpcUrl?: string;\n /** The Solana connection to use (default: one to `solanaRpcUrl`, commitment `confirmed`) */\n solanaConnection?: Connection;\n /** Solana bridge program ID (default: {@link DEFAULT_SOLANA_BRIDGE_PROGRAM}) */\n solanaBridgeProgram?: string;\n /** Token configurations (default: {@link DEFAULT_SOLANA_TOKENS}) */\n tokenConfigs?: SolanaTokenConfig[];\n /** How the strategy waits (the backoff before a resend). Default: a timer. */\n sleep?: BridgeSleep;\n}\n\n/** The type `@solana/web3.js` gives instruction data (a Node `Buffer`). */\ntype InstructionData = NonNullable<ConstructorParameters<typeof TransactionInstruction>[0]['data']>;\n\n/**\n * Instruction data as the bytes `@solana/web3.js` reads: it types the field as a `Buffer` but only\n * ever reads it as bytes (it base58-encodes it when it compiles the message), so a `Uint8Array`\n * goes in as it is and no `Buffer` global is needed. The recorded Solana vectors pin the signed\n * transactions byte for byte.\n */\nfunction instructionData(...parts: readonly Uint8Array[]): InstructionData {\n const length = parts.reduce((total, part) => total + part.length, 0);\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n bytes.set(part, offset);\n offset += part.length;\n }\n return bytes as unknown as InstructionData;\n}\n\n/** `value` as 8 little-endian bytes (a u64). */\nfunction u64LittleEndian(value: bigint): Uint8Array {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setBigUint64(0, value, true);\n return bytes;\n}\n\n/** `value` as 4 little-endian bytes (a u32). */\nfunction u32LittleEndian(value: number): Uint8Array {\n const bytes = new Uint8Array(4);\n new DataView(bytes.buffer).setUint32(0, value, true);\n return bytes;\n}\n\n/** The UTF-8 bytes of `text` (a PDA seed, a recipient). */\nfunction utf8(text: string): Uint8Array {\n return new TextEncoder().encode(text);\n}\n\n/**\n * Derive Associated Token Account address synchronously using PDA derivation.\n */\nfunction getAssociatedTokenAddressSync(\n mint: PublicKey,\n owner: PublicKey,\n tokenProgramId: PublicKey,\n associatedTokenProgramId: PublicKey,\n): PublicKey {\n const [address] = PublicKey.findProgramAddressSync(\n [owner.toBytes(), tokenProgramId.toBytes(), mint.toBytes()],\n associatedTokenProgramId,\n );\n return address;\n}\n\n/** `BRIDGE_CHAIN_READ_FAILED` for a Solana read `call` that failed or answered something unusable. */\nfunction readFailed(call: string, cause?: unknown): GalaSDKError {\n return new GalaSDKError(\n 'BRIDGE_CHAIN_READ_FAILED',\n { network: 'Solana', call },\n { write: false, cause },\n );\n}\n\n/**\n * The amount of the token account at `address`, or `undefined` when there is no such account.\n *\n * @throws GalaSDKError `BRIDGE_CHAIN_READ_FAILED` when the account is not a token account of\n * `tokenProgramId`\n */\nasync function getTokenAccountAmount(\n connection: Connection,\n address: PublicKey,\n tokenProgramId: PublicKey,\n): Promise<bigint | undefined> {\n const accountInfo = await connection.getAccountInfo(address);\n if (!accountInfo) {\n return undefined;\n }\n if (!accountInfo.owner.equals(tokenProgramId)) {\n throw readFailed('token account');\n }\n return AccountLayout.decode(accountInfo.data).amount;\n}\n\n/** A Solana keypair from a base58 secret key, or `INVALID_PRIVATE_KEY` (nothing of the key shown). */\nfunction keypairFromBase58(secretKeyBase58: string): Keypair {\n let secretKey: Uint8Array;\n try {\n secretKey = base58.decode(secretKeyBase58);\n } catch {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n // Solana keypairs are 64 bytes (secret and public half)\n if (secretKey.length !== 64) {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'wrong_length' });\n }\n try {\n return Keypair.fromSecretKey(secretKey);\n } catch {\n // The public half does not match the secret half.\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n}\n\n/**\n * Where a Solana deposit is: whether a deposit was sent at all, the step it reached, and the\n * signature of the last one signed.\n */\ninterface DepositProgress {\n sent: boolean;\n step: BridgeDepositStep;\n signature: string;\n}\n\n/**\n * Cached Solana bridge account addresses.\n */\ninterface SolanaBridgeAccounts {\n mintLookup: PublicKey;\n tokenBridge: PublicKey;\n bridgeTokenAccount: PublicKey;\n}\n\n/** The most sends of one deposit (each after the previous provably expired unlanded). */\nconst MAX_DEPOSIT_SENDS = 3;\n\n/** A Solana signature as `getSolanaTransactionStatus` accepts it: 80 to 90 base58 characters. */\nconst SOLANA_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{80,90}$/u;\n\n/**\n * Bridge strategy for GalaChain ↔ Solana transfers.\n *\n * Supports 2 tokens: GALA, GSOL\n */\nexport class SolanaBridgeStrategy extends ConfiguredBridgeStrategy<SolanaTokenConfig> {\n readonly network: ExternalNetwork = 'Solana';\n\n private readonly galaChainWalletAddress: string;\n private readonly ethereumWallet: EthersWallet;\n private readonly solanaConnection: Connection;\n private readonly solanaKeypair: Keypair;\n private readonly solanaBridgeProgramId: PublicKey;\n private readonly solanaBridgeTokenAuthority: PublicKey;\n private readonly solanaBridgeConfigPda: PublicKey;\n private readonly solanaNativeBridgePda: PublicKey;\n private readonly solanaBridgeAccountCache = new Map<string, SolanaBridgeAccounts>();\n private readonly tokenMetadataResolver: TokenMetadataResolver;\n\n /**\n * Creates a new Solana bridge strategy.\n *\n * @param config - Strategy configuration\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` if a key is invalid (nothing of it is shown);\n * `INVALID_BRIDGE_OPTION` (the option) for an RPC URL that is not http(s) or a bridge program\n * that is not a Solana public key\n */\n constructor(config: SolanaBridgeConfig) {\n const tokens = config.tokenConfigs ?? DEFAULT_SOLANA_TOKENS;\n super(config.galaConnectClient, createTokenConfigMap(tokens), config.sleep);\n for (const token of tokens) solanaPublicKeyOption(token.mintAddress, 'tokenConfigs');\n\n this.galaChainWalletAddress = config.galaChainWalletAddress;\n\n // The Ethereum wallet only signs the EIP-712 bridge-out: it needs no provider.\n validateEthereumPrivateKeyFormat(config.ethereumPrivateKey);\n this.ethereumWallet = new EthersWallet(config.ethereumPrivateKey);\n\n // Every URL and program id option is checked here: a malformed one is refused now, by name,\n // never as a library error.\n const rpcUrl = assertHttpUrlOption(\n config.solanaRpcUrl ?? DEFAULT_SOLANA_RPC_URL,\n 'solanaRpcUrl',\n );\n this.solanaConnection = config.solanaConnection ?? new Connection(rpcUrl, 'confirmed');\n this.solanaKeypair = keypairFromBase58(config.solanaPrivateKeyBase58);\n\n // Initialize bridge program PDAs\n this.solanaBridgeProgramId = solanaPublicKeyOption(\n config.solanaBridgeProgram ?? DEFAULT_SOLANA_BRIDGE_PROGRAM,\n 'solanaBridgeProgram',\n );\n [this.solanaBridgeTokenAuthority] = PublicKey.findProgramAddressSync(\n [utf8('bridge_token_authority')],\n this.solanaBridgeProgramId,\n );\n [this.solanaBridgeConfigPda] = PublicKey.findProgramAddressSync(\n [utf8('configv1')],\n this.solanaBridgeProgramId,\n );\n [this.solanaNativeBridgePda] = PublicKey.findProgramAddressSync(\n [utf8('native_sol_bridge')],\n this.solanaBridgeProgramId,\n );\n\n this.tokenMetadataResolver = new TokenMetadataResolver({\n galaConnectClient: this.galaConnectClient,\n });\n }\n\n /**\n * Estimate bridge fees for a transfer to Solana.\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GSOL')\n * @returns Fee estimate with breakdown (it does not depend on the amount)\n */\n async estimateFee(tokenSymbol: string): Promise<BridgeFeeEstimate> {\n return estimateStrategyFee(\n this.galaConnectClient,\n this.tokenMetadataResolver,\n 'Solana',\n tokenSymbol,\n );\n }\n\n /**\n * Bridge tokens from GalaChain to Solana.\n *\n * @param params - Bridge out parameters\n * @returns Transaction details\n */\n async bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction> {\n return executeBridgeOutFlow(params, {\n galaConnectClient: this.galaConnectClient,\n tokenMetadataResolver: this.tokenMetadataResolver,\n ethereumWallet: this.ethereumWallet,\n destinationChainId: CHAIN_IDS.SOLANA,\n destinationChain: 'Solana',\n validateRecipientAddress: validateSolanaAddressOrThrow,\n });\n }\n\n /**\n * Bridge tokens from Solana to GalaChain.\n *\n * @param params - Bridge in parameters\n * @returns Transaction details\n * @throws GalaSDKError before the deposit is sent: the input's refusal (`INVALID_PRIVATE_KEY` for\n * a bad `sourcePrivateKey`), `UNSUPPORTED_BRIDGE_TOKEN`, `BRIDGE_CHAIN_READ_FAILED`; once it is\n * being sent: `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`\n */\n async bridgeIn(params: BridgeInParams): Promise<BridgeTransaction> {\n const { amount, sourcePrivateKey, recipientAddress, tokenSymbol: resolvedSymbol } = params;\n\n // Validate that BridgeService resolved the symbol\n const tokenSymbol = assertTokenSymbolResolved(resolvedSymbol);\n\n // Validate amount (prevents wasted fees on zero/negative amounts)\n validateBridgeAmount(amount);\n\n // Use provided private key or fall back to configured keypair\n const keypair =\n sourcePrivateKey !== undefined && sourcePrivateKey !== ''\n ? keypairFromBase58(sourcePrivateKey)\n : this.solanaKeypair;\n\n // The GalaChain recipient, normalized (eth|<checksummed> or a client| alias) before anything\n // is read or sent\n const recipient = galaChainUserRef(recipientAddress ?? this.galaChainWalletAddress, 'address');\n\n const tokenConfig = requireTokenConfig(this.tokenConfigs, tokenSymbol, 'Solana');\n const metadata = await this.tokenMetadataResolver.getTokenMetadata(tokenSymbol);\n const amountBaseUnits = toBaseUnits(amount, metadata.decimals);\n\n const signature = await this.executeSolanaBridgeOut({\n keypair,\n tokenConfig,\n metadata,\n amountBaseUnits,\n recipient,\n amount,\n });\n\n return buildBridgeInboundTransaction({\n fromChain: 'Solana',\n transactionHash: signature,\n tokenSymbol,\n amount,\n baseUrl: this.galaConnectClient.getBaseUrl(),\n });\n }\n\n /**\n * Validate a Solana address.\n *\n * @param address - Address to validate\n * @returns True if a valid Solana public key\n */\n isValidAddress(address: string): boolean {\n try {\n new PublicKey(address);\n return true;\n } catch {\n return false;\n }\n }\n\n // ==========================================================================\n // Wallet Info Methods\n // ==========================================================================\n\n /**\n * Get the configured Solana wallet address.\n *\n * @returns Solana wallet address (base58)\n */\n getWalletAddress(): string {\n return this.solanaKeypair.publicKey.toBase58();\n }\n\n // ==========================================================================\n // Balance Checking Methods\n // ==========================================================================\n\n /**\n * Get SPL token balance for a Solana address (native SOL for a native token).\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GSOL')\n * @param address - Optional Solana address (defaults to configured wallet)\n * @returns Token balance as decimal string (\"0\" when the address has no token account)\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN`, `INVALID_WALLET_ADDRESS`,\n * `BRIDGE_CHAIN_READ_FAILED` (the failure as `cause`)\n */\n async getSolanaTokenBalance(tokenSymbol: string, address?: string): Promise<string> {\n const tokenConfig = requireTokenConfig(this.tokenConfigs, tokenSymbol, 'Solana');\n\n if (tokenConfig.isNative) {\n return this.getSolanaNativeBalance(address);\n }\n\n const targetAddress = address ?? this.solanaKeypair.publicKey.toBase58();\n const ownerPublicKey = parseSolanaAddressOrThrow(targetAddress);\n\n const ataAddress = getAssociatedTokenAddressSync(\n new PublicKey(tokenConfig.mintAddress),\n ownerPublicKey,\n TOKEN_PROGRAM_ID,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n );\n\n let amount: bigint | undefined;\n try {\n amount = await getTokenAccountAmount(this.solanaConnection, ataAddress, TOKEN_PROGRAM_ID);\n } catch (error: unknown) {\n throw error instanceof GalaSDKError ? error : readFailed('token account', error);\n }\n\n // No token account = zero balance; the configured decimals, else the mint's own (never an\n // assumed 8).\n const decimals =\n tokenConfig.decimals ?? (await this.mintDecimals(new PublicKey(tokenConfig.mintAddress)));\n return fromBaseUnits(amount ?? 0n, decimals);\n }\n\n /**\n * The decimals of an SPL mint, from its account.\n *\n * @throws GalaSDKError `BRIDGE_CHAIN_READ_FAILED` (`mint`) when there is no such mint of the token\n * program, or it cannot be read\n */\n private async mintDecimals(mint: PublicKey): Promise<number> {\n let mintAccount: Awaited<ReturnType<Connection['getAccountInfo']>>;\n try {\n mintAccount = await this.solanaConnection.getAccountInfo(mint);\n } catch (error: unknown) {\n throw readFailed('mint', error);\n }\n if (!mintAccount?.owner.equals(TOKEN_PROGRAM_ID)) {\n throw readFailed('mint');\n }\n return MintLayout.decode(mintAccount.data).decimals;\n }\n\n /**\n * Get native SOL balance for a Solana address.\n *\n * @param address - Optional Solana address (defaults to configured wallet)\n * @returns SOL balance as decimal string (9 decimals)\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if address invalid\n */\n async getSolanaNativeBalance(address?: string): Promise<string> {\n const targetAddress = address ?? this.solanaKeypair.publicKey.toBase58();\n const publicKey = parseSolanaAddressOrThrow(targetAddress);\n const balanceLamports = await this.solanaConnection.getBalance(publicKey, 'confirmed');\n return fromBaseUnits(BigInt(balanceLamports), 9);\n }\n\n /**\n * Request a devnet SOL airdrop (devnet RPC only).\n *\n * Does not wait for confirmation; returns the airdrop signature.\n *\n * @param amount - SOL to request (0.00001 to 2)\n * @param address - Optional recipient (defaults to configured wallet)\n * @returns Airdrop transaction signature\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`airdropAmount` out of range, `solanaRpcUrl` not\n * devnet), `INVALID_WALLET_ADDRESS`\n */\n async requestDevnetAirdrop(amount: number = 1, address?: string): Promise<string> {\n // 1. Validate amount FIRST (cheap, common error)\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount < 0.00001 || amount > 2) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'airdropAmount' });\n }\n\n // 2. Validate address format SECOND (cheap, fails early for typos)\n const publicKey =\n address !== undefined && address !== ''\n ? parseSolanaAddressOrThrow(address)\n : this.solanaKeypair.publicKey;\n\n // 3. Validate environment LAST (before the RPC call)\n if (!this.solanaConnection.rpcEndpoint.includes('devnet')) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'solanaRpcUrl' });\n }\n\n const lamports = Math.floor(amount * LAMPORTS_PER_SOL);\n return this.solanaConnection.requestAirdrop(publicKey, lamports);\n }\n\n /**\n * Get the status of a Solana transaction by signature.\n *\n * @param signature - Transaction signature (base58)\n * @returns Transaction status\n * @throws GalaSDKError `INVALID_TRANSACTION_HASH` if the signature is not 80 to 90 base58 characters\n */\n async getSolanaTransactionStatus(signature: string): Promise<SolanaTransactionStatus> {\n if (typeof signature !== 'string' || !SOLANA_SIGNATURE.test(signature)) {\n throw new GalaSDKError('INVALID_TRANSACTION_HASH', {\n network: 'Solana',\n value: String(signature),\n });\n }\n\n const result = await this.solanaConnection.getSignatureStatuses([signature]);\n const status = result.value[0];\n\n // Transaction not yet visible on-chain (still propagating or invalid)\n if (!status) {\n return { confirmed: false, status: 'not_found' };\n }\n\n // Transaction was processed but failed: on-chain, but it did not succeed\n if (status.err !== null && status.err !== undefined) {\n return {\n confirmed: false,\n status: 'failed',\n slot: status.slot,\n error: JSON.stringify(status.err),\n };\n }\n\n return {\n confirmed: true,\n status: status.confirmationStatus ?? 'processed',\n slot: status.slot,\n };\n }\n\n // ==========================================================================\n // Private Methods\n // ==========================================================================\n\n /**\n * Execute the Solana deposit (the bridge program's bridge-out instruction) and register it with\n * GalaConnect. From the send on, every failure is `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`.\n */\n private async executeSolanaBridgeOut(params: {\n keypair: Keypair;\n tokenConfig: SolanaTokenConfig;\n metadata: BridgeTokenMetadata;\n amountBaseUnits: bigint;\n recipient: string;\n amount: string;\n }): Promise<string> {\n const mint = new PublicKey(params.tokenConfig.mintAddress);\n const recipientBytes = utf8(params.recipient);\n const instructionArguments = [\n u64LittleEndian(params.amountBaseUnits),\n u32LittleEndian(recipientBytes.length),\n recipientBytes,\n ] as const;\n\n const bridgeInstruction = params.tokenConfig.isNative\n ? this.buildNativeBridgeInstruction(params.keypair.publicKey, instructionArguments)\n : this.buildTokenBridgeInstruction(\n params.keypair.publicKey,\n getAssociatedTokenAddressSync(\n mint,\n params.keypair.publicKey,\n TOKEN_PROGRAM_ID,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n ),\n mint,\n await this.getSolanaBridgeAccounts(mint, params.tokenConfig.symbol),\n instructionArguments,\n );\n\n const transaction = new Transaction();\n transaction.add(\n ComputeBudgetProgram.setComputeUnitPrice({\n microLamports: SOLANA_COMPUTE.UNIT_PRICE_MICROLAMPORTS,\n }),\n ComputeBudgetProgram.setComputeUnitLimit({\n units: SOLANA_COMPUTE.UNIT_LIMIT,\n }),\n bridgeInstruction,\n );\n transaction.feePayer = params.keypair.publicKey;\n\n const progress: DepositProgress = { sent: false, step: 'send', signature: '' };\n try {\n const signature = await this.sendAndConfirm(transaction, params.keypair, progress);\n\n progress.step = 'registration';\n await this.galaConnectClient.registerBridgeTransaction({\n quantity: params.amount,\n tokenInstance: {\n collection: params.metadata.descriptor.collection,\n category: params.metadata.descriptor.category,\n type: params.metadata.descriptor.type,\n additionalKey: params.metadata.descriptor.additionalKey,\n instance: '0',\n },\n fromChain: 'Solana',\n toChain: 'GC',\n hash: signature,\n });\n return signature;\n } catch (cause: unknown) {\n // Nothing sent yet: the failure is the read's own (nothing is pending).\n if (!progress.sent) {\n throw cause;\n }\n throw new GalaSDKError(\n 'BRIDGE_DEPOSIT_OUTCOME_UNKNOWN',\n { network: 'Solana', step: progress.step, transactionHash: progress.signature },\n { cause },\n );\n }\n }\n\n /**\n * Sign, send and confirm the deposit. It is sent AGAIN (re-signed under a fresh blockhash, up to\n * {@link MAX_DEPOSIT_SENDS} sends; `attempt` counts them) only when the previous one provably can never land: its confirmation\n * failed with web3.js's `TransactionExpiredBlockheightExceededError` (the chain is past the\n * blockhash's last valid block height) AND a status read that searches the history finds no\n * trace of it. A send or confirmation that fails any other way (a timeout, a dropped connection,\n * a preflight refusal, a status read that fails) is never sent again: with its blockhash still\n * valid it may land, and a second deposit would land too.\n *\n * `progress` follows it: whether anything was sent, the step reached, and the signature of the\n * deposit last signed. A failure before the first send (the blockhash read) is\n * `BRIDGE_CHAIN_READ_FAILED`.\n */\n private async sendAndConfirm(\n transaction: Transaction,\n keypair: Keypair,\n progress: DepositProgress,\n attempt = 1,\n ): Promise<string> {\n let latestBlockhash: Awaited<ReturnType<Connection['getLatestBlockhash']>>;\n try {\n latestBlockhash = await this.solanaConnection.getLatestBlockhash('confirmed');\n } catch (cause: unknown) {\n throw readFailed('latest blockhash', cause);\n }\n\n // Set the blockhash and sign (a fresh signature: a different transaction)\n transaction.recentBlockhash = latestBlockhash.blockhash;\n transaction.feePayer = keypair.publicKey;\n transaction.signatures = [];\n transaction.sign(keypair);\n // sign() has just set the fee payer's signature.\n progress.signature = base58.encode(transaction.signature as Uint8Array);\n progress.step = 'send';\n progress.sent = true;\n\n const signature = await this.solanaConnection.sendRawTransaction(transaction.serialize(), {\n skipPreflight: false,\n preflightCommitment: 'confirmed',\n });\n progress.step = 'confirmation';\n\n try {\n await this.solanaConnection.confirmTransaction(\n {\n signature,\n blockhash: latestBlockhash.blockhash,\n lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,\n },\n 'confirmed',\n );\n return signature;\n } catch (error: unknown) {\n if (!(error instanceof TransactionExpiredBlockheightExceededError)) {\n throw error;\n }\n // Expired: it can no longer land. Done if it did; sent again only if it never did.\n const {\n value: [status],\n } = await this.solanaConnection.getSignatureStatuses([signature], {\n searchTransactionHistory: true,\n });\n if (status) {\n const landed =\n status.err === null &&\n (status.confirmationStatus === 'confirmed' || status.confirmationStatus === 'finalized');\n if (landed) {\n return signature;\n }\n throw error;\n }\n if (attempt >= MAX_DEPOSIT_SENDS) {\n throw error;\n }\n }\n\n // Wait before sending again, with exponential backoff\n await this.sleep(Math.min(1000 * Math.pow(2, attempt - 1), 5000));\n return this.sendAndConfirm(transaction, keypair, progress, attempt + 1);\n }\n\n /**\n * Build native SOL bridge instruction.\n */\n private buildNativeBridgeInstruction(\n payer: PublicKey,\n instructionArguments: readonly Uint8Array[],\n ): TransactionInstruction {\n return new TransactionInstruction({\n programId: this.solanaBridgeProgramId,\n keys: [\n { pubkey: payer, isSigner: true, isWritable: true },\n { pubkey: this.solanaBridgeTokenAuthority, isSigner: false, isWritable: true },\n { pubkey: this.solanaNativeBridgePda, isSigner: false, isWritable: false },\n { pubkey: this.solanaBridgeConfigPda, isSigner: false, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data: instructionData(SOLANA_DISCRIMINATORS.BRIDGE_OUT_NATIVE, ...instructionArguments),\n });\n }\n\n /**\n * Build SPL token bridge instruction.\n */\n private buildTokenBridgeInstruction(\n payer: PublicKey,\n userTokenAccount: PublicKey,\n mint: PublicKey,\n accounts: SolanaBridgeAccounts,\n instructionArguments: readonly Uint8Array[],\n ): TransactionInstruction {\n return new TransactionInstruction({\n programId: this.solanaBridgeProgramId,\n keys: [\n { pubkey: payer, isSigner: true, isWritable: true },\n { pubkey: userTokenAccount, isSigner: false, isWritable: true },\n { pubkey: mint, isSigner: false, isWritable: true },\n { pubkey: accounts.mintLookup, isSigner: false, isWritable: false },\n { pubkey: accounts.tokenBridge, isSigner: false, isWritable: false },\n { pubkey: accounts.bridgeTokenAccount, isSigner: false, isWritable: true },\n { pubkey: this.solanaBridgeTokenAuthority, isSigner: false, isWritable: false },\n { pubkey: this.solanaBridgeConfigPda, isSigner: false, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n ],\n data: instructionData(SOLANA_DISCRIMINATORS.BRIDGE_OUT, ...instructionArguments),\n });\n }\n\n /**\n * The bridge program accounts of a mint (cached per mint): its mint lookup PDA, the token bridge\n * the lookup names, and the bridge's token account.\n *\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` when the program has no lookup for the mint;\n * `BRIDGE_CHAIN_READ_FAILED` when the lookup is not the program's or is too short\n */\n private async getSolanaBridgeAccounts(\n mint: PublicKey,\n symbol: string,\n ): Promise<SolanaBridgeAccounts> {\n const cacheKey = mint.toBase58();\n const cached = this.solanaBridgeAccountCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const [mintLookup] = PublicKey.findProgramAddressSync(\n [utf8('mint_lookup_v1'), mint.toBytes()],\n this.solanaBridgeProgramId,\n );\n\n const lookupAccount = await this.solanaConnection.getAccountInfo(mintLookup, 'confirmed');\n if (!lookupAccount) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network: 'Solana', symbol });\n }\n if (!lookupAccount.owner.equals(this.solanaBridgeProgramId) || lookupAccount.data.length < 40) {\n throw readFailed('mint lookup');\n }\n\n // Extract token bridge address (bytes 8-40)\n const tokenBridge = new PublicKey(lookupAccount.data.subarray(8, 40));\n\n const bridgeTokenAccount = getAssociatedTokenAddressSync(\n mint,\n this.solanaBridgeTokenAuthority,\n TOKEN_PROGRAM_ID,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n );\n\n const result: SolanaBridgeAccounts = { mintLookup, tokenBridge, bridgeTokenAccount };\n this.solanaBridgeAccountCache.set(cacheKey, result);\n return result;\n }\n}\n","/**\n * Token ID Utilities\n *\n * Parsing a token reference (a pipe-delimited string or a class key object) to its class key, with\n * core's one class-key splitter (`splitClassKey`) and object guard (`isTokenClassKey`).\n */\n\nimport {\n GalaSDKError,\n isTokenClassKey,\n splitClassKey,\n type GalaChainTokenClassKey,\n type TokenClassKeyInput as TokenId,\n} from '../../index.js';\nimport { stringifyTokenClassKey as centralStringify } from '../internal/values.js';\n\n/**\n * Result of parsing a TokenId\n */\nexport interface ParsedTokenId {\n /** Full TokenClassKey structure */\n tokenClassKey: GalaChainTokenClassKey;\n /** Pipe-delimited string format (e.g., \"GALA|Unit|none|none\") */\n stringified: string;\n}\n\n/**\n * Parse a pipe-delimited token string to TokenClassKey. The last three segments are the category,\n * type and additional key; everything before them is the collection (core's `splitClassKey`).\n *\n * @param tokenString - Pipe-delimited string (e.g., \"GALA|Unit|none|none\")\n * @returns TokenClassKey object\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`tokenId`, `bad_class_key`) for anything else\n *\n * @example\n * ```typescript\n * const key = parseTokenString('GALA|Unit|none|none');\n * // { collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }\n * ```\n */\nexport function parseTokenString(tokenString: string): GalaChainTokenClassKey {\n const key = typeof tokenString === 'string' ? splitClassKey(tokenString, '|') : undefined;\n if (key === undefined) {\n throw new GalaSDKError('INVALID_TOKEN_REFERENCE', {\n field: 'tokenId',\n reason: 'bad_class_key',\n });\n }\n return key;\n}\n\n/**\n * Stringify TokenClassKey to pipe-delimited format\n *\n * @param key - TokenClassKey object\n * @returns Pipe-delimited string\n *\n * @example\n * ```typescript\n * stringifyTokenClassKey({ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' });\n * // 'GALA|Unit|none|none'\n * ```\n */\nexport function stringifyTokenClassKey(key: GalaChainTokenClassKey): string {\n return centralStringify(key);\n}\n\n/**\n * Parse a TokenId (string or object) to TokenClassKey and stringified form.\n *\n * @param tokenId - Token identifier (pipe-delimited string or TokenClassKey object)\n * @returns Parsed token with TokenClassKey and stringified form\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`tokenId`, `bad_class_key`) if it is neither\n *\n * @example\n * ```typescript\n * parseTokenId('GALA|Unit|none|none');\n * parseTokenId({ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' });\n * ```\n */\nexport function parseTokenId(tokenId: TokenId): ParsedTokenId {\n let tokenClassKey: GalaChainTokenClassKey;\n\n if (typeof tokenId === 'string') {\n tokenClassKey = parseTokenString(tokenId);\n } else if (isTokenClassKey(tokenId)) {\n tokenClassKey = tokenId;\n } else {\n throw new GalaSDKError('INVALID_TOKEN_REFERENCE', {\n field: 'tokenId',\n reason: 'bad_class_key',\n });\n }\n\n const stringified = stringifyTokenClassKey(tokenClassKey);\n\n return { tokenClassKey, stringified };\n}\n","/**\n * Bridge Service\n *\n * Main orchestrator for cross-chain bridging operations: a unified API for bridging tokens between\n * GalaChain and Ethereum or Solana, over the two strategies.\n *\n * Failures are `GalaSDKError`s (the strategies' and GalaConnect's, passed through as they are).\n */\n\nimport type { Connection } from '@solana/web3.js';\n\nimport {\n GALA_CHAIN_ENVIRONMENTS,\n GalaSDKError,\n galaChainUserRef,\n type HttpRequestor,\n} from '../index.js';\nimport {\n type BridgeEnvironment,\n DEFAULT_SOLANA_BRIDGE_PROGRAM,\n DEFAULT_SOLANA_TOKENS,\n getEthereumBridgeContractByEnvironment,\n getEthereumTokensByEnvironment,\n STATIC_TOKEN_METADATA,\n} from './constants/index.js';\nimport { GalaConnectClient } from './GalaConnectClient.js';\nimport type { BridgeSleep, BridgeStrategy, WaitOptions } from './strategies/BridgeStrategy.js';\nimport { EthereumBridgeStrategy } from './strategies/EthereumBridgeStrategy.js';\nimport { SolanaBridgeStrategy } from './strategies/SolanaBridgeStrategy.js';\nimport type { BridgeableNetwork } from './types/bridgeable-token.dto.js';\nimport type {\n BridgeConfig,\n BridgeFeeEstimate,\n BridgeInParams,\n BridgeOutParams,\n BridgeStatus,\n BridgeToken,\n BridgeTransaction,\n EstimateBridgeFeeParams,\n EthereumTransactionStatus,\n EthereumWalletBalanceResult,\n ExternalChainBalance,\n ExternalNetwork,\n SolanaTransactionStatus,\n SolanaWalletBalanceResult,\n WaitForBridgeOptions,\n} from './types/index.js';\nimport { validateBridgeAmount } from './utils/bridgePayload.js';\nimport {\n buildEthereumTokenBalance,\n buildNativeBalance,\n buildSolanaTokenBalance,\n findTokenConfigOrThrow,\n} from './utils/balanceHelpers.js';\nimport {\n getEthereumStrategy,\n getSolanaStrategy,\n getStrategyStatus,\n resolveTargetAddress,\n} from './utils/strategyDelegation.js';\nimport { parseTokenId } from './utils/tokenIdUtils.js';\n\n/**\n * What resolves a token id to the token bridgeable to a network (its symbol): the\n * `BridgeableTokenService`, or anything with its `getTokenByTokenId`.\n */\nexport interface BridgeTokenLookup {\n getTokenByTokenId(\n tokenId: string,\n network: BridgeableNetwork,\n ): Promise<{ readonly symbol: string } | undefined>;\n}\n\n/**\n * Extended bridge configuration with wallet keys.\n */\nexport interface BridgeServiceConfig extends Omit<BridgeConfig, 'galaConnectBaseUrl'> {\n /** GalaConnect (DEX API platform) base URL (default: the environment's `dexApiBaseUrl`) */\n galaConnectBaseUrl?: string;\n /** GalaChain wallet address (eth|..., 0x..., or a client| alias) */\n galaChainWalletAddress: string;\n /** Ethereum private key for signing (required for all operations) */\n ethereumPrivateKey: string;\n /** Environment - affects default URLs (stage: Sepolia and devnet, prod: mainnet). Default prod. */\n environment?: BridgeEnvironment;\n /**\n * Resolves a `tokenId` to the token bridgeable to a network (the `BridgeableTokenService`).\n * Every method that takes a `tokenId` goes through it, so it is required: a missing lookup is\n * refused at construction (`INVALID_BRIDGE_OPTION`), not at the first call.\n */\n bridgeableTokenService: BridgeTokenLookup;\n /** Sends the GalaConnect requests (default: the global `fetch`) */\n httpRequestor?: HttpRequestor;\n /** The Solana connection the Solana strategy uses (default: one to `solanaRpcUrl`) */\n solanaConnection?: Connection;\n /** How the strategies wait (a poll interval, the wait before an inbound registration) */\n sleep?: BridgeSleep;\n}\n\n/**\n * Bridge-specific RPC URLs by environment (the GalaConnect and gateway URLs are the environment's\n * `GALA_CHAIN_ENVIRONMENTS` ones).\n */\nconst BRIDGE_RPC_URLS: Readonly<Record<BridgeEnvironment, { ethereum: string; solana: string }>> = {\n prod: {\n ethereum: 'https://eth.gala.games', // Gala-hosted Ethereum mainnet RPC\n solana: 'https://api.mainnet-beta.solana.com',\n },\n stage: {\n ethereum: 'https://dev.eth.gala.games', // Gala-hosted Ethereum Sepolia RPC\n solana: 'https://api.devnet.solana.com',\n },\n};\n\n/**\n * Default configuration values for bridge-specific settings.\n */\nconst DEFAULTS = {\n rateLimit: 12,\n pollInterval: 15000,\n pollTimeout: 45 * 60 * 1000,\n};\n\n/**\n * The explicit GalaChain class key of a supported bridge token, read from the curated\n * STATIC_TOKEN_METADATA table. A class key is never built from a symbol (collection and symbol\n * disagree for many tokens), so a supported token without a table row fails loudly.\n *\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` without a table row\n */\nfunction requireBridgeTokenDescriptor(\n symbol: string,\n network: ExternalNetwork,\n): BridgeToken['galaChainDescriptor'] {\n const metadata = STATIC_TOKEN_METADATA[symbol];\n if (metadata === undefined) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network, symbol });\n }\n return { ...metadata.descriptor };\n}\n\n/**\n * Bridge Service - Main entry point for cross-chain operations.\n *\n * Supports bridging between:\n * - GalaChain ↔ Ethereum (6 tokens: GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC)\n * - GalaChain ↔ Solana (2 tokens: GALA, GSOL)\n *\n * @example\n * ```typescript\n * const bridgeService = new BridgeService({\n * galaChainWalletAddress: 'eth|1234...',\n * ethereumPrivateKey: '0xabcd...',\n * solanaPrivateKey: 'base58EncodedKey...',\n * bridgeableTokenService,\n * });\n *\n * const fee = await bridgeService.estimateBridgeFee({\n * tokenId: 'GALA|Unit|none|none',\n * destinationChain: 'Ethereum',\n * });\n * ```\n */\nexport class BridgeService {\n private readonly environment: BridgeEnvironment;\n private readonly pollInterval: number;\n private readonly pollTimeout: number;\n private readonly galaConnectClient: GalaConnectClient;\n private readonly strategies: Map<ExternalNetwork, BridgeStrategy>;\n private readonly bridgeableTokenService: BridgeTokenLookup;\n\n /**\n * @param config - Bridge service configuration\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`bridgeableTokenService`) without a token lookup;\n * `INVALID_WALLET_ADDRESS` (`galaChainWalletAddress`) for a wallet address that is not a\n * GalaChain one; the strategies' refusals of a bad key\n */\n constructor(config: BridgeServiceConfig) {\n // The type requires it; a plain-JavaScript caller (or a cast) that leaves it out fails here,\n // not at the first tokenId call.\n if (\n typeof (config.bridgeableTokenService as BridgeTokenLookup | undefined)?.getTokenByTokenId !==\n 'function'\n ) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'bridgeableTokenService' });\n }\n const galaChainWalletAddress = galaChainUserRef(\n config.galaChainWalletAddress,\n 'galaChainWalletAddress',\n );\n\n this.environment = config.environment ?? 'prod';\n const urls = GALA_CHAIN_ENVIRONMENTS[this.environment];\n const rpcUrls = BRIDGE_RPC_URLS[this.environment];\n this.pollInterval = config.pollInterval ?? DEFAULTS.pollInterval;\n this.pollTimeout = config.pollTimeout ?? DEFAULTS.pollTimeout;\n\n // GalaConnect Bridge API is served from the DEX API platform (the environment's dexApiBaseUrl)\n this.galaConnectClient = new GalaConnectClient({\n baseUrl: config.galaConnectBaseUrl ?? urls.dexApiBaseUrl,\n galachainBaseUrl: config.galaChainApiBaseUrl ?? urls.gatewayBaseUrl,\n walletAddress: galaChainWalletAddress,\n requestsPerSecond: config.rateLimit ?? DEFAULTS.rateLimit,\n ...(config.httpRequestor !== undefined && { httpRequestor: config.httpRequestor }),\n });\n this.bridgeableTokenService = config.bridgeableTokenService;\n\n const sleep = config.sleep !== undefined ? { sleep: config.sleep } : {};\n this.strategies = new Map<ExternalNetwork, BridgeStrategy>([\n [\n 'Ethereum',\n new EthereumBridgeStrategy({\n galaConnectClient: this.galaConnectClient,\n galaChainWalletAddress,\n ethereumPrivateKey: config.ethereumPrivateKey,\n ethereumRpcUrl: config.ethereumRpcUrl ?? rpcUrls.ethereum,\n ethereumBridgeContract:\n config.ethereumBridgeContract ??\n getEthereumBridgeContractByEnvironment(this.environment),\n tokenConfigs: getEthereumTokensByEnvironment(this.environment),\n ...sleep,\n }),\n ],\n ]);\n\n // The Solana strategy only with a Solana key\n if (config.solanaPrivateKey !== undefined && config.solanaPrivateKey !== '') {\n this.strategies.set(\n 'Solana',\n new SolanaBridgeStrategy({\n galaConnectClient: this.galaConnectClient,\n galaChainWalletAddress,\n ethereumPrivateKey: config.ethereumPrivateKey,\n solanaPrivateKeyBase58: config.solanaPrivateKey,\n solanaRpcUrl: config.solanaRpcUrl ?? rpcUrls.solana,\n solanaBridgeProgram: config.solanaBridgeProgram ?? DEFAULT_SOLANA_BRIDGE_PROGRAM,\n tokenConfigs: DEFAULT_SOLANA_TOKENS,\n ...(config.solanaConnection !== undefined && {\n solanaConnection: config.solanaConnection,\n }),\n ...sleep,\n }),\n );\n }\n }\n\n /**\n * Resolve a tokenId to its symbol through the bridgeable token lookup (which also proves the\n * token is bridgeable to the network).\n *\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` when the token is not bridgeable to the\n * network; the token id's own refusal\n */\n private async resolveTokenSymbol(\n tokenId: Parameters<typeof parseTokenId>[0],\n network: ExternalNetwork,\n ): Promise<string> {\n const stringifiedTokenId = parseTokenId(tokenId).stringified;\n const bridgeableNetwork: BridgeableNetwork = network === 'Ethereum' ? 'ETHEREUM' : 'SOLANA';\n const token = await this.bridgeableTokenService.getTokenByTokenId(\n stringifiedTokenId,\n bridgeableNetwork,\n );\n if (!token) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network, symbol: stringifiedTokenId });\n }\n return token.symbol;\n }\n\n /**\n * Estimate the fee of a bridge-out (a per-transfer cost: it does not depend on the amount).\n *\n * @param params - Token and destination chain\n * @returns Fee estimate\n */\n async estimateBridgeFee(params: EstimateBridgeFeeParams): Promise<BridgeFeeEstimate> {\n const strategy = this.getStrategy(params.destinationChain);\n const symbol = await this.resolveTokenSymbol(params.tokenId, params.destinationChain);\n return strategy.estimateFee(symbol);\n }\n\n /**\n * Bridge tokens out from GalaChain to an external chain.\n *\n * @param params - Bridge out parameters\n * @returns Transaction details\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` (`recipientAddress`) for a recipient that is not\n * an address of the destination chain; `UNSUPPORTED_BRIDGE_TOKEN` for a token the chain's\n * strategy does not bridge; the strategy's failures\n */\n async bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction> {\n // Every refusal of the caller's own input comes before the token-list read\n const strategy = this.getStrategy(params.destinationChain);\n if (!strategy.isValidAddress(params.recipientAddress)) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', {\n field: 'recipientAddress',\n value: String(params.recipientAddress),\n });\n }\n validateBridgeAmount(params.amount);\n const symbol = await this.resolveTokenSymbol(params.tokenId, params.destinationChain);\n this.assertTokenSupported(strategy, symbol);\n return strategy.bridgeOut({ ...params, tokenSymbol: symbol });\n }\n\n /**\n * Bridge tokens in from an external chain to GalaChain.\n *\n * @param params - Bridge in parameters\n * @returns Transaction details\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` for a token the chain's strategy does not\n * bridge; the strategy's failures\n */\n async bridgeIn(params: BridgeInParams): Promise<BridgeTransaction> {\n // Every refusal of the caller's own input comes before the token-list read\n const strategy = this.getStrategy(params.sourceChain);\n validateBridgeAmount(params.amount);\n const symbol = await this.resolveTokenSymbol(params.tokenId, params.sourceChain);\n this.assertTokenSupported(strategy, symbol);\n return strategy.bridgeIn({ ...params, tokenSymbol: symbol });\n }\n\n /**\n * Get the status of a bridge transaction (GalaConnect tracks both chains: one read).\n *\n * @param transactionHash - Transaction hash\n * @returns Current status\n */\n async getBridgeStatus(transactionHash: string): Promise<BridgeStatus> {\n return getStrategyStatus(this.galaConnectClient, transactionHash);\n }\n\n /**\n * Wait for a bridge transaction to reach a final status (completed, failed, delivery failed).\n *\n * @param transactionHash - Transaction hash\n * @param options - Polling options (defaults: the service's pollInterval and pollTimeout)\n * @returns Final status\n * @throws GalaSDKError `BRIDGE_STATUS_TIMEOUT` when the timeout comes first\n */\n async waitForBridgeCompletion(\n transactionHash: string,\n options?: WaitForBridgeOptions,\n ): Promise<BridgeStatus> {\n const waitOptions: WaitOptions = {\n pollInterval: options?.pollInterval ?? this.pollInterval,\n timeout: options?.timeout ?? this.pollTimeout,\n ...(options?.onStatusUpdate && { onStatusUpdate: options.onStatusUpdate }),\n };\n return this.getStrategy('Ethereum').waitForCompletion(transactionHash, waitOptions);\n }\n\n /**\n * Get the bridge tokens (for one chain, or all).\n *\n * @param chain - Optional chain filter\n * @returns Supported tokens with their chains and addresses\n */\n getSupportedBridgeTokens(chain?: ExternalNetwork): BridgeToken[] {\n const tokens: BridgeToken[] = [];\n\n if (chain === undefined || chain === 'Ethereum') {\n for (const config of getEthereumTokensByEnvironment(this.environment)) {\n tokens.push({\n symbol: config.symbol,\n decimals: config.decimals,\n verified: true,\n supportedChains: ['Ethereum'],\n galaChainDescriptor: requireBridgeTokenDescriptor(config.symbol, 'Ethereum'),\n externalAddresses: { ethereum: config.contractAddress },\n });\n }\n }\n\n if (chain === undefined || chain === 'Solana') {\n for (const config of DEFAULT_SOLANA_TOKENS) {\n const existing = tokens.find((token) => token.symbol === config.symbol);\n if (existing) {\n existing.supportedChains.push('Solana');\n existing.externalAddresses.solana = config.mintAddress;\n } else {\n tokens.push({\n symbol: config.symbol,\n decimals: config.decimals,\n verified: true,\n supportedChains: ['Solana'],\n galaChainDescriptor: requireBridgeTokenDescriptor(config.symbol, 'Solana'),\n externalAddresses: { solana: config.mintAddress },\n });\n }\n }\n }\n\n return tokens;\n }\n\n /**\n * Get the chains this service can bridge with (Solana only with a Solana key).\n */\n getSupportedBridgeChains(): ExternalNetwork[] {\n return Array.from(this.strategies.keys());\n }\n\n /**\n * Whether a token symbol is bridgeable (with `chain`, or with any configured chain).\n */\n isTokenSupported(tokenSymbol: string, chain?: ExternalNetwork): boolean {\n const strategies =\n chain === undefined ? [...this.strategies.values()] : [this.strategies.get(chain)];\n return strategies.some((strategy) => strategy?.isTokenSupported(tokenSymbol) === true);\n }\n\n /**\n * Whether an address is valid for a chain (false for a chain that is not configured).\n */\n isValidAddress(address: string, chain: ExternalNetwork): boolean {\n return this.strategies.get(chain)?.isValidAddress(address) ?? false;\n }\n\n // ==========================================================================\n // Balance and status reads of the external chains\n // ==========================================================================\n\n /** An ERC-20 balance (decimal string) of the Ethereum wallet or `address`. */\n async getEthereumTokenBalance(tokenSymbol: string, address?: string): Promise<string> {\n return getEthereumStrategy(this.strategies).getEthereumTokenBalance(tokenSymbol, address);\n }\n\n /** The ETH balance (decimal string) of the Ethereum wallet or `address`. */\n async getEthereumNativeBalance(address?: string): Promise<string> {\n return getEthereumStrategy(this.strategies).getEthereumNativeBalance(address);\n }\n\n /** An SPL balance (decimal string) of the Solana wallet or `address`. */\n async getSolanaTokenBalance(tokenSymbol: string, address?: string): Promise<string> {\n return getSolanaStrategy(this.strategies).getSolanaTokenBalance(tokenSymbol, address);\n }\n\n /** The SOL balance (decimal string) of the Solana wallet or `address`. */\n async getSolanaNativeBalance(address?: string): Promise<string> {\n return getSolanaStrategy(this.strategies).getSolanaNativeBalance(address);\n }\n\n /** One ERC-20 balance of the Ethereum wallet or `address`, with its token's details. */\n async fetchEthereumWalletTokenBalance(\n symbol: string,\n address?: string,\n ): Promise<ExternalChainBalance> {\n const ethStrategy = getEthereumStrategy(this.strategies);\n const tokenConfig = findTokenConfigOrThrow(\n getEthereumTokensByEnvironment(this.environment),\n symbol,\n 'Ethereum',\n );\n const targetAddress = resolveTargetAddress(address, ethStrategy);\n const balance = await ethStrategy.getEthereumTokenBalance(symbol, targetAddress);\n return buildEthereumTokenBalance(tokenConfig, balance);\n }\n\n /** The ETH balance of the Ethereum wallet or `address`. */\n async fetchEthereumWalletNativeBalance(address?: string): Promise<ExternalChainBalance> {\n const ethStrategy = getEthereumStrategy(this.strategies);\n const targetAddress = resolveTargetAddress(address, ethStrategy);\n const balance = await ethStrategy.getEthereumNativeBalance(targetAddress);\n return buildNativeBalance('ETH', balance, 18);\n }\n\n /** One SPL balance of the Solana wallet or `address`, with its token's details. */\n async fetchSolanaWalletTokenBalance(\n symbol: string,\n address?: string,\n ): Promise<ExternalChainBalance> {\n const solStrategy = getSolanaStrategy(this.strategies);\n const tokenConfig = findTokenConfigOrThrow(DEFAULT_SOLANA_TOKENS, symbol, 'Solana');\n const targetAddress = resolveTargetAddress(address, solStrategy);\n const balance = await solStrategy.getSolanaTokenBalance(symbol, targetAddress);\n return buildSolanaTokenBalance(tokenConfig, balance);\n }\n\n /** The SOL balance of the Solana wallet or `address`. */\n async fetchSolanaWalletNativeBalance(address?: string): Promise<ExternalChainBalance> {\n const solStrategy = getSolanaStrategy(this.strategies);\n const targetAddress = resolveTargetAddress(address, solStrategy);\n const balance = await solStrategy.getSolanaNativeBalance(targetAddress);\n return buildNativeBalance('SOL', balance, 9);\n }\n\n /** Request a devnet SOL airdrop (devnet only). */\n async requestSolanaDevnetAirdrop(amount?: number, address?: string): Promise<string> {\n return getSolanaStrategy(this.strategies).requestDevnetAirdrop(amount, address);\n }\n\n /** The status of a Solana transaction, from the Solana RPC. */\n async getSolanaTransactionStatus(signature: string): Promise<SolanaTransactionStatus> {\n return getSolanaStrategy(this.strategies).getSolanaTransactionStatus(signature);\n }\n\n /** The status of an Ethereum transaction, from the Ethereum RPC. */\n async getEthereumTransactionStatus(transactionHash: string): Promise<EthereumTransactionStatus> {\n return getEthereumStrategy(this.strategies).getEthereumTransactionStatus(transactionHash);\n }\n\n /** Every bridge-token balance and the ETH balance of the Ethereum wallet or `address`. */\n async fetchEthereumWalletAllBalances(address?: string): Promise<EthereumWalletBalanceResult> {\n const ethStrategy = getEthereumStrategy(this.strategies);\n const targetAddress = resolveTargetAddress(address, ethStrategy);\n const [nativeBalance, tokenBalances] = await Promise.all([\n ethStrategy.getEthereumNativeBalance(targetAddress),\n Promise.all(\n getEthereumTokensByEnvironment(this.environment).map(\n async (token): Promise<ExternalChainBalance> =>\n buildEthereumTokenBalance(\n token,\n await ethStrategy.getEthereumTokenBalance(token.symbol, targetAddress),\n ),\n ),\n ),\n ]);\n return {\n address: targetAddress,\n native: buildNativeBalance('ETH', nativeBalance, 18),\n tokens: tokenBalances,\n timestamp: Date.now(),\n };\n }\n\n /** Every bridge-token balance and the SOL balance of the Solana wallet or `address`. */\n async fetchSolanaWalletAllBalances(address?: string): Promise<SolanaWalletBalanceResult> {\n const solStrategy = getSolanaStrategy(this.strategies);\n const targetAddress = resolveTargetAddress(address, solStrategy);\n const [nativeBalance, tokenBalances] = await Promise.all([\n solStrategy.getSolanaNativeBalance(targetAddress),\n Promise.all(\n DEFAULT_SOLANA_TOKENS.map(async (token): Promise<ExternalChainBalance> =>\n buildSolanaTokenBalance(\n token,\n await solStrategy.getSolanaTokenBalance(token.symbol, targetAddress),\n ),\n ),\n ),\n ]);\n return {\n address: targetAddress,\n native: buildNativeBalance('SOL', nativeBalance, 9),\n tokens: tokenBalances,\n timestamp: Date.now(),\n };\n }\n\n /**\n * The strategy of `chain`.\n *\n * @throws GalaSDKError `BRIDGE_NOT_CONFIGURED` (Solana without a Solana key)\n */\n private getStrategy(chain: ExternalNetwork): BridgeStrategy {\n const strategy = this.strategies.get(chain);\n if (!strategy) {\n throw new GalaSDKError('BRIDGE_NOT_CONFIGURED', { network: chain });\n }\n return strategy;\n }\n\n /** @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` unless `strategy` bridges `symbol` */\n private assertTokenSupported(strategy: BridgeStrategy, symbol: string): void {\n if (!strategy.isTokenSupported(symbol)) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network: strategy.network, symbol });\n }\n }\n}\n","/**\n * The token lists of the DEX API platform (GalaConnect's `/v1/tokens`): one page, and every page\n * (offset pagination). What `BridgeableTokenService` and `WrappableTokenService` read through.\n *\n * @module bridge/tokens/tokenPages\n */\n\nimport { GalaSDKError, isGalaError } from '../../index.js';\nimport { fieldsOf, hasFields, isRecord } from '../internal/values.js';\n\n/** The DEX API platform path the token lists are read from. */\nexport const TOKENS_PATH = '/v1/tokens';\n\n/** The most tokens one page holds (the API's maximum page size); also the default page size. */\nexport const TOKEN_PAGE_MAX = 1000;\n\n/** The most pages one full read takes. */\nconst MAX_TOKEN_PAGES = 10_000;\n\n/** The query of a token list read. */\nexport type TokenListParams = Record<string, string | number | boolean>;\n\n/**\n * Sends a DEX API GET and resolves with its parsed JSON body: a `GalaConnectClient`, or any client\n * with this `request` (launchpad-sdk's `HttpClient`). A failure that is not a `GalaSDKError` is\n * read for an HTTP status (`status` or `statusCode`) to say what it was.\n */\nexport interface DexApiReader {\n request<T>(config: { method: 'GET'; url: string; params: TokenListParams }): Promise<T>;\n}\n\n/** One page: its tokens, and how many entries the API answered (the page is full or not). */\nexport interface TokenPage<T> {\n items: T[];\n rawCount: number;\n}\n\n/**\n * Whether an entry of the token list is a usable token: an object with the token strings (symbol,\n * name, class key and its four parts), integer decimals (0 or more), a boolean `verified`, and\n * `image` / `description` strings when present.\n */\nexport function isTokenEntry(entry: unknown): entry is Record<string, unknown> {\n return (\n isRecord(entry) &&\n hasFields(\n entry,\n [\n 'symbol',\n 'name',\n 'stringifiedTokenClassKey',\n 'collection',\n 'category',\n 'type',\n 'additionalKey',\n ],\n { image: 'string', description: 'string' },\n ) &&\n Number.isSafeInteger(entry['decimals']) &&\n (entry['decimals'] as number) >= 0 &&\n typeof entry['verified'] === 'boolean'\n );\n}\n\n/** The HTTP status a reader's failure carries (`status`, else `statusCode`), if any. */\nfunction statusOf(failure: unknown): number | undefined {\n const fields = fieldsOf(failure);\n const status = fields['status'] ?? fields['statusCode'];\n return typeof status === 'number' ? status : undefined;\n}\n\n/**\n * A failed token list read: a `GalaSDKError` as it is; a failure with an HTTP status\n * `GALACONNECT_HTTP_ERROR`; any other `TRANSPORT_ERROR`. All are reads (`write: false`), the\n * original as cause.\n */\nfunction readFailure(cause: unknown): Error {\n if (isGalaError(cause)) {\n return cause;\n }\n const status = statusOf(cause);\n return status === undefined\n ? new GalaSDKError('TRANSPORT_ERROR', { url: TOKENS_PATH }, { write: false, cause })\n : new GalaSDKError(\n 'GALACONNECT_HTTP_ERROR',\n { method: TOKENS_PATH, status, serverMessage: '' },\n { write: false, status, cause },\n );\n}\n\n/**\n * Reads one page of the token list: `params` plus `pageSize` (at most {@link TOKEN_PAGE_MAX}) and\n * `offset`, the API entries turned into tokens by `transform` (which leaves out an entry that is\n * not a usable token). `rawCount` counts every entry, so paging never depends on how many were\n * usable.\n *\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` for an answer without a `tokens` array; the\n * reader's failure (see `readFailure`)\n */\nexport async function fetchTokenPage<T>(\n reader: DexApiReader,\n params: TokenListParams,\n offset: number,\n limit: number,\n transform: (apiTokens: unknown[]) => T[],\n): Promise<TokenPage<T>> {\n let response: unknown;\n try {\n response = await reader.request<unknown>({\n method: 'GET',\n url: TOKENS_PATH,\n params: { ...params, pageSize: Math.min(limit, TOKEN_PAGE_MAX), offset },\n });\n } catch (cause: unknown) {\n throw readFailure(cause);\n }\n const tokens = fieldsOf(response)['tokens'];\n if (!Array.isArray(tokens)) {\n throw new GalaSDKError(\n 'BRIDGE_READ_RESPONSE_INVALID',\n { method: TOKENS_PATH },\n { write: false },\n );\n }\n return { items: transform(tokens as unknown[]), rawCount: tokens.length };\n}\n\n/**\n * Reads every page: full pages of {@link TOKEN_PAGE_MAX} from offset 0 until a page that is not\n * full.\n *\n * @throws GalaSDKError `PAGINATION_LIMIT_EXCEEDED` when {@link MAX_TOKEN_PAGES} pages are all full\n * (the list is longer than the cap): never a list cut short in silence\n */\nexport async function fetchAllTokenPages<T>(\n fetchPage: (offset: number, limit: number) => Promise<TokenPage<T>>,\n): Promise<T[]> {\n const all: T[] = [];\n for (let page = 0; page < MAX_TOKEN_PAGES; page++) {\n const result = await fetchPage(page * TOKEN_PAGE_MAX, TOKEN_PAGE_MAX);\n all.push(...result.items);\n if (result.rawCount !== TOKEN_PAGE_MAX) {\n return all;\n }\n }\n throw new GalaSDKError(\n 'PAGINATION_LIMIT_EXCEEDED',\n { method: TOKENS_PATH, maxPages: MAX_TOKEN_PAGES },\n { write: false },\n );\n}\n","/**\n * Bridgeable Token Service\n *\n * The tokens bridgeable to Ethereum or Solana, from the DEX API platform's token list\n * (`/v1/tokens?canBridgeTo=<network>`), cached per network, with lookups by symbol and token id.\n *\n * @module bridge/tokens/BridgeableTokenService\n */\n\nimport type { TokenClassKeyInput as TokenId } from '../../index.js';\nimport { hasFields, isRecord, normalizeTokenSymbol } from '../internal/values.js';\nimport type {\n BridgeableNetwork,\n BridgeableToken,\n BridgeableTokenApiResponse,\n FetchBridgeableTokensOptions,\n FetchBridgeableTokensResult,\n IsTokenBridgeableOptions,\n IsTokenBridgeableResult,\n} from '../types/bridgeable-token.dto.js';\nimport { parseTokenId, stringifyTokenClassKey } from '../utils/tokenIdUtils.js';\nimport {\n type DexApiReader,\n fetchAllTokenPages,\n fetchTokenPage,\n isTokenEntry,\n TOKEN_PAGE_MAX,\n type TokenPage,\n} from './tokenPages.js';\n\n/** What the bridgeable token cache holds, per network. */\nexport interface BridgeableTokenCacheStats {\n /** The networks with cached tokens */\n networks: BridgeableNetwork[];\n /** Cached tokens, all networks */\n totalItems: number;\n /** Cached tokens per network (0 for a network not read) */\n itemsByNetwork: Record<BridgeableNetwork, number>;\n /** When each cached network was read */\n fetchTimestamps: Partial<Record<BridgeableNetwork, number>>;\n /** `totalItems` */\n totalTokens: number;\n /** `itemsByNetwork` */\n tokensByNetwork: Record<BridgeableNetwork, number>;\n}\n\n/** One network's cached tokens. */\ninterface NetworkTokens {\n /** Every token, in the API's order */\n readonly tokens: readonly BridgeableToken[];\n /** By symbol (trimmed, upper case): the first token listed with it */\n readonly bySymbol: Map<string, BridgeableToken>;\n /** By token id, exactly (GalaChain class keys are case-sensitive) */\n readonly byTokenId: Map<string, BridgeableToken>;\n readonly fetchedAt: number;\n}\n\n/** The networks a token list is read for. */\nconst NETWORKS: readonly BridgeableNetwork[] = ['ETHEREUM', 'SOLANA'];\n\n/**\n * Whether a list entry is a usable bridgeable token: a token entry with `canBridgeTo` (objects with\n * a string `network`) and `otherNetworks` (objects with a string `network`, and a string\n * `contractAddress` and `symbol` and a number `allowanceStorageSlot` when present).\n */\nfunction isBridgeableEntry(entry: unknown): entry is BridgeableTokenApiResponse {\n if (!isTokenEntry(entry)) {\n return false;\n }\n const { canBridgeTo, otherNetworks } = entry;\n return (\n Array.isArray(canBridgeTo) &&\n canBridgeTo.every(\n (destination) => isRecord(destination) && hasFields(destination, ['network']),\n ) &&\n Array.isArray(otherNetworks) &&\n otherNetworks.every(\n (network) =>\n isRecord(network) &&\n hasFields(network, ['network'], {\n contractAddress: 'string',\n symbol: 'string',\n allowanceStorageSlot: 'number',\n }),\n )\n );\n}\n\n/** A bridgeable token from its API entry. */\nfunction toBridgeableToken(t: BridgeableTokenApiResponse): BridgeableToken {\n const ethereumNetwork = t.otherNetworks.find((n) => n.network === 'Ethereum');\n const solanaNetwork = t.otherNetworks.find((n) => n.network === 'Solana');\n\n // Supported chains from the canBridgeTo array (Ethereum and Solana only)\n const supportedChains = t.canBridgeTo\n .map((d) => d.network)\n .filter((n): n is 'Ethereum' | 'Solana' => n === 'Ethereum' || n === 'Solana');\n\n const token: BridgeableToken = {\n symbol: t.symbol,\n name: t.name,\n decimals: t.decimals,\n galaChainDescriptor: {\n collection: t.collection,\n category: t.category,\n type: t.type,\n additionalKey: t.additionalKey,\n },\n stringifiedTokenClassKey: t.stringifiedTokenClassKey,\n verified: t.verified,\n supportedChains,\n };\n\n // Optional fields only when defined (exactOptionalPropertyTypes)\n if (ethereumNetwork?.contractAddress !== undefined) {\n token.ethereumContractAddress = ethereumNetwork.contractAddress;\n }\n if (ethereumNetwork?.symbol !== undefined) {\n token.ethereumSymbol = ethereumNetwork.symbol;\n }\n if (ethereumNetwork?.allowanceStorageSlot !== undefined) {\n token.ethereumAllowanceSlot = ethereumNetwork.allowanceStorageSlot;\n }\n if (solanaNetwork?.contractAddress !== undefined) {\n token.solanaContractAddress = solanaNetwork.contractAddress;\n }\n if (solanaNetwork?.symbol !== undefined) {\n token.solanaSymbol = solanaNetwork.symbol;\n }\n if (t.image !== undefined) {\n token.image = t.image;\n }\n if (t.description !== undefined) {\n token.description = t.description;\n }\n return token;\n}\n\n/**\n * Service for the tokens bridgeable to Ethereum and Solana.\n *\n * Reads go through a {@link DexApiReader} (a `GalaConnectClient`, or launchpad-sdk's DEX API\n * `HttpClient`). Failures are `GalaSDKError`s: `BRIDGE_READ_RESPONSE_INVALID` for an answer\n * without a token list, `INVALID_TOKEN_REFERENCE` for a token id that is not one, and the read's\n * own (`GALACONNECT_HTTP_ERROR`, `TRANSPORT_ERROR`, ...).\n */\nexport class BridgeableTokenService {\n private readonly cache = new Map<BridgeableNetwork, NetworkTokens>();\n\n /**\n * @param dexApi - Reads the DEX API platform's token list\n */\n constructor(private readonly dexApi: DexApiReader) {}\n\n /** One page of the token list of `network`. */\n private fetchPage(\n network: BridgeableNetwork,\n offset: number,\n limit: number,\n ): Promise<TokenPage<BridgeableToken>> {\n return fetchTokenPage(\n this.dexApi,\n { canBridgeTo: network.toLowerCase() },\n offset,\n limit,\n (apiTokens) => apiTokens.filter(isBridgeableEntry).map(toBridgeableToken),\n );\n }\n\n /**\n * Caches the FULL token list of `network`, replacing what it held: every token (none is dropped\n * for sharing a symbol), by symbol (the first token listed with it), and by token id exactly\n * (the class key of its four parts: GalaChain class keys are case-sensitive).\n */\n private store(network: BridgeableNetwork, tokens: BridgeableToken[]): void {\n const bySymbol = new Map<string, BridgeableToken>();\n const byTokenId = new Map<string, BridgeableToken>();\n for (const token of tokens) {\n const symbol = normalizeTokenSymbol(token.symbol);\n if (!bySymbol.has(symbol)) {\n bySymbol.set(symbol, token);\n }\n byTokenId.set(stringifyTokenClassKey(token.galaChainDescriptor), token);\n }\n this.cache.set(network, { tokens, bySymbol, byTokenId, fetchedAt: Date.now() });\n }\n\n /** The cached tokens of `network`, read first when it has none. */\n private async tokensOf(network: BridgeableNetwork): Promise<NetworkTokens> {\n const cached = this.cache.get(network);\n if (cached !== undefined && cached.tokens.length > 0) {\n return cached;\n }\n await this.fetchAllBridgeableTokensByNetwork(network);\n return this.cache.get(network) as NetworkTokens;\n }\n\n /**\n * Fetch one page of the tokens bridgeable to a network. Not cached: the cache holds only the\n * full list (a page standing in for it would hide every token on the other pages).\n *\n * @param options - Network, offset (default 0) and limit (default and at most 1000)\n */\n async fetchBridgeableTokensByNetwork(\n options: FetchBridgeableTokensOptions,\n ): Promise<FetchBridgeableTokensResult> {\n const { network, offset = 0, limit = TOKEN_PAGE_MAX } = options;\n const { items: tokens } = await this.fetchPage(network, offset, limit);\n return { tokens, network, fetchedAt: Date.now(), tokenCount: tokens.length };\n }\n\n /**\n * Fetch every token bridgeable to a network (every page), or the cached ones.\n *\n * @param network - ETHEREUM or SOLANA\n */\n async fetchAllBridgeableTokensByNetwork(\n network: BridgeableNetwork,\n ): Promise<FetchBridgeableTokensResult> {\n const cached = this.cache.get(network);\n if (cached !== undefined && cached.tokens.length > 0) {\n const tokens = [...cached.tokens];\n return { tokens, network, fetchedAt: cached.fetchedAt, tokenCount: tokens.length };\n }\n const tokens = await fetchAllTokenPages((offset, limit) =>\n this.fetchPage(network, offset, limit),\n );\n this.store(network, tokens);\n return { tokens, network, fetchedAt: Date.now(), tokenCount: tokens.length };\n }\n\n /** Every token bridgeable to Ethereum. */\n async fetchAllTokensBridgeableToEthereum(): Promise<FetchBridgeableTokensResult> {\n return this.fetchAllBridgeableTokensByNetwork('ETHEREUM');\n }\n\n /** Every token bridgeable to Solana. */\n async fetchAllTokensBridgeableToSolana(): Promise<FetchBridgeableTokensResult> {\n return this.fetchAllBridgeableTokensByNetwork('SOLANA');\n }\n\n /**\n * Whether a token (by token id) is bridgeable to a network, with its symbol and contract\n * address there. The symbol is the cached token's, never derived from the token id.\n */\n async isTokenBridgeableToNetwork(\n options: IsTokenBridgeableOptions,\n ): Promise<IsTokenBridgeableResult> {\n const { tokenId, network } = options;\n // The id is checked before the list is read: a refused id costs no read, whatever the read does\n const key = parseTokenId(tokenId).stringified;\n const token = (await this.tokensOf(network)).byTokenId.get(key);\n\n const result: IsTokenBridgeableResult = { isBridgeable: token !== undefined, network };\n if (token !== undefined) {\n result.tokenSymbol = token.symbol;\n const contractAddress =\n network === 'ETHEREUM' ? token.ethereumContractAddress : token.solanaContractAddress;\n if (contractAddress !== undefined) {\n result.contractAddress = contractAddress;\n }\n }\n return result;\n }\n\n /** Whether a token is bridgeable to Ethereum. */\n async isTokenBridgeableToEthereum(tokenId: TokenId): Promise<IsTokenBridgeableResult> {\n return this.isTokenBridgeableToNetwork({ tokenId, network: 'ETHEREUM' });\n }\n\n /** Whether a token is bridgeable to Solana. */\n async isTokenBridgeableToSolana(tokenId: TokenId): Promise<IsTokenBridgeableResult> {\n return this.isTokenBridgeableToNetwork({ tokenId, network: 'SOLANA' });\n }\n\n /** The token bridgeable to `network` with `symbol` (any case; the first listed), if any. */\n async getTokenBySymbol(\n symbol: string,\n network: BridgeableNetwork,\n ): Promise<BridgeableToken | undefined> {\n return (await this.tokensOf(network)).bySymbol.get(normalizeTokenSymbol(symbol));\n }\n\n /**\n * The token bridgeable to `network` with the token id `tokenId` (a pipe class key, matched\n * exactly: class keys are case-sensitive), if any.\n */\n async getTokenByTokenId(\n tokenId: string,\n network: BridgeableNetwork,\n ): Promise<BridgeableToken | undefined> {\n return (await this.tokensOf(network)).byTokenId.get(tokenId);\n }\n\n /** The contract address on `network` of the token with `symbol`, if any. */\n async getContractAddress(\n symbol: string,\n network: BridgeableNetwork,\n ): Promise<string | undefined> {\n const token = await this.getTokenBySymbol(symbol, network);\n return network === 'ETHEREUM' ? token?.ethereumContractAddress : token?.solanaContractAddress;\n }\n\n /** The symbols of the tokens bridgeable to `network`. */\n async getSupportedTokenSymbols(network: BridgeableNetwork): Promise<string[]> {\n return (await this.tokensOf(network)).tokens.map((token) => token.symbol);\n }\n\n /** Read both networks' token lists. */\n async preload(): Promise<void> {\n await Promise.all(NETWORKS.map((network) => this.fetchAllBridgeableTokensByNetwork(network)));\n }\n\n /** What the cache holds. */\n getCacheStats(): BridgeableTokenCacheStats {\n const itemsByNetwork: Record<BridgeableNetwork, number> = { ETHEREUM: 0, SOLANA: 0 };\n const fetchTimestamps: Partial<Record<BridgeableNetwork, number>> = {};\n for (const [network, entry] of this.cache) {\n itemsByNetwork[network] = entry.tokens.length;\n fetchTimestamps[network] = entry.fetchedAt;\n }\n const totalItems = itemsByNetwork.ETHEREUM + itemsByNetwork.SOLANA;\n return {\n networks: [...this.cache.keys()],\n totalItems,\n itemsByNetwork,\n fetchTimestamps,\n totalTokens: totalItems,\n tokensByNetwork: itemsByNetwork,\n };\n }\n\n /** Forget the cached tokens of `network`, or of every network. */\n clearCache(network?: BridgeableNetwork): void {\n if (network === undefined) {\n this.cache.clear();\n } else {\n this.cache.delete(network);\n }\n }\n}\n","/**\n * Wrappable Token Service\n *\n * The tokens that can be wrapped or unwrapped (moved between the asset channel and their own\n * channel), from the DEX API platform's token list (`/v1/tokens?wrappable=true`), cached, with\n * lookups by token id.\n *\n * @module bridge/tokens/WrappableTokenService\n */\n\nimport type { TokenClassKeyInput as TokenId } from '../../index.js';\nimport { hasFields } from '../internal/values.js';\nimport type {\n FetchWrappableTokensOptions,\n FetchWrappableTokensResult,\n IsTokenWrappableResult,\n WrappableToken,\n WrappableTokenApiResponse,\n WrappableTokenCacheStats,\n} from '../types/wrappable-token.dto.js';\nimport { parseTokenId, stringifyTokenClassKey } from '../utils/tokenIdUtils.js';\nimport {\n type DexApiReader,\n fetchAllTokenPages,\n fetchTokenPage,\n isTokenEntry,\n TOKEN_PAGE_MAX,\n type TokenPage,\n} from './tokenPages.js';\n\n/**\n * Whether a list entry is a usable wrappable token: a token entry with the `wrap` counterpart (a\n * string) and a boolean `swappable`, and a string `channel`, a boolean `trending` and an object\n * `currentPrices` when present.\n */\nfunction isWrappableEntry(entry: unknown): entry is WrappableTokenApiResponse {\n return (\n isTokenEntry(entry) &&\n hasFields(entry, ['wrap'], {\n channel: 'string',\n trending: 'boolean',\n currentPrices: 'object',\n }) &&\n typeof entry['swappable'] === 'boolean'\n );\n}\n\n/** A wrappable token from its API entry. */\nfunction toWrappableToken(t: WrappableTokenApiResponse): WrappableToken {\n const token: WrappableToken = {\n symbol: t.symbol,\n name: t.name,\n decimals: t.decimals,\n galaChainDescriptor: {\n collection: t.collection,\n category: t.category,\n type: t.type,\n additionalKey: t.additionalKey,\n },\n stringifiedTokenClassKey: t.stringifiedTokenClassKey,\n wrapCounterpart: t.wrap,\n swappable: t.swappable,\n verified: t.verified,\n };\n\n // Optional fields only when defined (exactOptionalPropertyTypes)\n if (t.channel !== undefined && t.channel !== '') {\n token.channel = t.channel;\n }\n if (t.trending !== undefined) {\n token.trending = t.trending;\n }\n if (t.image !== undefined && t.image !== '') {\n token.image = t.image;\n }\n if (t.description !== undefined && t.description !== '') {\n token.description = t.description;\n }\n if (t.currentPrices !== undefined) {\n token.currentPrices = t.currentPrices;\n }\n return token;\n}\n\n/**\n * Service for the wrappable tokens.\n *\n * Reads go through a {@link DexApiReader} (a `GalaConnectClient`, or launchpad-sdk's DEX API\n * `HttpClient`). Failures are `GalaSDKError`s: `BRIDGE_READ_RESPONSE_INVALID` for an answer\n * without a token list, `INVALID_TOKEN_REFERENCE` for a token id that is not one, and the read's\n * own (`GALACONNECT_HTTP_ERROR`, `TRANSPORT_ERROR`, ...).\n */\nexport class WrappableTokenService {\n /** The cached tokens by token id: the class key of its four parts, exactly (case-sensitive). */\n private readonly byTokenId = new Map<string, WrappableToken>();\n private fetchedAt: number | null = null;\n\n /**\n * @param dexApi - Reads the DEX API platform's token list\n */\n constructor(private readonly dexApi: DexApiReader) {}\n\n /** One page of the wrappable token list. */\n private fetchPage(offset: number, limit: number): Promise<TokenPage<WrappableToken>> {\n return fetchTokenPage(this.dexApi, { wrappable: true }, offset, limit, (apiTokens) =>\n apiTokens.filter(isWrappableEntry).map(toWrappableToken),\n );\n }\n\n /** Caches the FULL token list, replacing what the cache held. */\n private store(tokens: WrappableToken[]): void {\n this.byTokenId.clear();\n for (const token of tokens) {\n this.byTokenId.set(stringifyTokenClassKey(token.galaChainDescriptor), token);\n }\n this.fetchedAt = Date.now();\n }\n\n /** The cached token with `tokenId` (any token id form), reading the list first when empty. */\n private async lookup(tokenId: TokenId): Promise<{ key: string; token?: WrappableToken }> {\n const key = parseTokenId(tokenId).stringified;\n if (this.byTokenId.size === 0) {\n await this.fetchAllWrappableTokens();\n }\n const token = this.byTokenId.get(key);\n return token === undefined ? { key } : { key, token };\n }\n\n /**\n * Fetch one page of the wrappable tokens. Not cached: the cache holds only the full list (a page\n * standing in for it would hide every token on the other pages).\n *\n * @param options - Offset (default 0) and limit (default and at most 1000)\n */\n async fetchWrappableTokens(\n options: FetchWrappableTokensOptions = {},\n ): Promise<FetchWrappableTokensResult> {\n const { offset = 0, limit = TOKEN_PAGE_MAX } = options;\n const { items: tokens } = await this.fetchPage(offset, limit);\n return { tokens, fetchedAt: Date.now(), tokenCount: tokens.length };\n }\n\n /** Fetch every wrappable token (every page), or the cached ones. */\n async fetchAllWrappableTokens(): Promise<FetchWrappableTokensResult> {\n if (this.byTokenId.size > 0) {\n const tokens = [...this.byTokenId.values()];\n return { tokens, fetchedAt: this.fetchedAt as number, tokenCount: tokens.length };\n }\n const tokens = await fetchAllTokenPages((offset, limit) => this.fetchPage(offset, limit));\n this.store(tokens);\n return { tokens, fetchedAt: Date.now(), tokenCount: tokens.length };\n }\n\n /** The wrappable token with `tokenId`, if any. */\n async getWrappableToken(tokenId: TokenId): Promise<WrappableToken | undefined> {\n return (await this.lookup(tokenId)).token;\n }\n\n /** The token a wrappable token wraps to or unwraps from, if both are wrappable. */\n async getWrapCounterpart(tokenId: TokenId): Promise<WrappableToken | undefined> {\n const token = await this.getWrappableToken(tokenId);\n return token === undefined ? undefined : this.getWrappableToken(token.wrapCounterpart);\n }\n\n /** Whether a token is wrappable, with its counterpart. */\n async isTokenWrappable(tokenId: TokenId): Promise<IsTokenWrappableResult> {\n const { key, token } = await this.lookup(tokenId);\n const result: IsTokenWrappableResult = { isWrappable: token !== undefined, tokenId: key };\n if (token !== undefined) {\n result.wrapCounterpart = token.wrapCounterpart;\n }\n return result;\n }\n\n /** What the cache holds. */\n getCacheStats(): WrappableTokenCacheStats {\n return {\n totalItems: this.byTokenId.size,\n tokenCount: this.byTokenId.size,\n isPopulated: this.byTokenId.size > 0,\n lastFetchedAt: this.fetchedAt,\n };\n }\n\n /** Forget the cached tokens. */\n clearCache(): void {\n this.byTokenId.clear();\n this.fetchedAt = null;\n }\n}\n","/**\n * Wrap Service\n *\n * Cross-channel wrap (a token from its own channel to the asset channel, e.g. MUSIC → GMUSIC) and\n * unwrap (back), through GalaConnect: the natively signed `RequestTokenBridgeOut`, then\n * `BridgeTokenOut` from the source channel.\n *\n * A wrap or unwrap that does not complete throws (nothing is returned as a \"failed\" result):\n * before anything is sent, the refusal of the input (`TOKEN_NOT_WRAPPABLE`,\n * `INVALID_WRAP_DIRECTION`, `INVALID_BRIDGE_AMOUNT`, `INVALID_WALLET_ADDRESS`,\n * `INVALID_BRIDGE_OPTION` without a signer, `SIGNING_FAILED`); GalaConnect's or GalaChain's refusal\n * of the request (`GALACONNECT_HTTP_ERROR`, `BRIDGE_REQUEST_REJECTED`, ...: nothing was locked);\n * and, once the request was accepted, `BRIDGE_OUT_OUTCOME_UNKNOWN` (the tokens may be locked: never\n * wrap again, finish or check this one).\n *\n * @module bridge/tokens/WrapService\n */\n\nimport {\n createUniqueKey,\n GalaSDKError,\n galaChainUserRef,\n signPreSend,\n type GalaChainSigner,\n type TokenClassKeyInput as TokenId,\n} from '../../index.js';\nimport { GALACHAIN_CHANNELS } from '../constants/index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport { fieldsOf, stringifyTokenClassKey } from '../internal/values.js';\nimport type {\n UnwrapTokenOptions,\n WrappableToken,\n WrapTokenOptions,\n WrapUnwrapFeeEstimate,\n WrapUnwrapResult,\n} from '../types/wrappable-token.dto.js';\nimport { assertRequestAccepted } from '../utils/bridgeErrors.js';\nimport { completeBridgeOut } from '../utils/bridgeOutHelpers.js';\nimport { validateBridgeAmount } from '../utils/bridgePayload.js';\nimport type { WrappableTokenService } from './WrappableTokenService.js';\n\n/** The asset channel's name. */\nconst ASSET_CHANNEL = 'asset';\n\n/** The channels a wrap moves between, by name: their GalaChain channel ids. */\nconst CHANNEL_IDS: Readonly<Record<string, number>> = {\n [ASSET_CHANNEL]: GALACHAIN_CHANNELS.ASSET,\n music: GALACHAIN_CHANNELS.MUSIC,\n};\n\n/** The prefix of a wrap or unwrap uniqueKey. */\nconst WRAP_UNIQUE_KEY_PREFIX = 'galaswap-operation-';\n\n/** Where a wrap or unwrap goes: the channel it leaves, and the channel (and its id) it goes to. */\ninterface ChannelRouting {\n sourceChannel: string;\n destinationChannel: string;\n destinationChannelId: number;\n}\n\n/**\n * The channel of a token, when it is one a wrap moves between.\n *\n * @throws GalaSDKError `TOKEN_NOT_WRAPPABLE` (`unknown_channel`) otherwise\n */\nfunction channelOf(token: WrappableToken): string {\n if (token.channel === undefined || CHANNEL_IDS[token.channel] === undefined) {\n throw new GalaSDKError('TOKEN_NOT_WRAPPABLE', {\n tokenId: token.stringifiedTokenClassKey,\n reason: 'unknown_channel',\n });\n }\n return token.channel;\n}\n\n/**\n * Configuration for the wrap service.\n */\nexport interface WrapServiceConfig {\n /** GalaConnect client (`RequestTokenBridgeOut` and `BridgeTokenOut`) */\n galaConnectClient: GalaConnectClient;\n /** Resolves the wrappable tokens (a WrappableTokenService) */\n wrappableTokenService: Pick<WrappableTokenService, 'getWrappableToken' | 'getWrapCounterpart'>;\n /** Signs the `RequestTokenBridgeOut` (a native GalaChain signature); required to wrap */\n signer?: GalaChainSigner | undefined;\n /** The GalaChain address the signer signs for (the default recipient); required to wrap */\n walletAddress?: string | undefined;\n}\n\n/**\n * Service for cross-channel wrap and unwrap.\n */\nexport class WrapService {\n private readonly galaConnectClient: GalaConnectClient;\n private readonly wrappableTokenService: WrapServiceConfig['wrappableTokenService'];\n private readonly signer: GalaChainSigner | undefined;\n private readonly walletAddress: string | undefined;\n\n /**\n * @param config - Wrap service configuration\n */\n constructor(config: WrapServiceConfig) {\n this.galaConnectClient = config.galaConnectClient;\n this.wrappableTokenService = config.wrappableTokenService;\n this.signer = config.signer;\n this.walletAddress = config.walletAddress;\n }\n\n /**\n * Wrap a token: from its own channel to the asset channel (e.g. MUSIC → GMUSIC).\n *\n * @param options - The token, the amount, an optional recipient\n * @returns The completed wrap\n */\n async wrapToken(options: WrapTokenOptions): Promise<WrapUnwrapResult> {\n return this.execute(options, 'wrap');\n }\n\n /**\n * Unwrap a token: from the asset channel back to its own channel (e.g. GMUSIC → MUSIC).\n *\n * @param options - The token, the amount, an optional recipient\n * @returns The completed unwrap\n */\n async unwrapToken(options: UnwrapTokenOptions): Promise<WrapUnwrapResult> {\n return this.execute(options, 'unwrap');\n }\n\n /**\n * The fee and authorization of a wrap. The fee is the constant \"0\" GALA launchpad-sdk reported\n * (the channel bridge charges no fee the SDK can see).\n *\n * @param tokenId - The token to wrap\n * @param amount - The amount (checked like a wrap's)\n */\n async estimateWrapFee(tokenId: TokenId, amount: string): Promise<WrapUnwrapFeeEstimate> {\n return this.estimate(tokenId, amount, 'wrap');\n }\n\n /**\n * The fee and authorization of an unwrap (see {@link estimateWrapFee}).\n *\n * @param tokenId - The token to unwrap\n * @param amount - The amount (checked like an unwrap's)\n */\n async estimateUnwrapFee(tokenId: TokenId, amount: string): Promise<WrapUnwrapFeeEstimate> {\n return this.estimate(tokenId, amount, 'unwrap');\n }\n\n /** The source token, on the right channel for `direction`. */\n private async sourceToken(\n tokenId: TokenId,\n direction: 'wrap' | 'unwrap',\n ): Promise<WrappableToken> {\n const token = await this.wrappableTokenService.getWrappableToken(tokenId);\n if (token === undefined) {\n throw new GalaSDKError('TOKEN_NOT_WRAPPABLE', {\n // an object id by its class key: the form the list is keyed by\n tokenId: typeof tokenId === 'string' ? tokenId : stringifyTokenClassKey(tokenId),\n reason: 'not_listed',\n });\n }\n const onAsset = token.channel === ASSET_CHANNEL;\n if (direction === 'wrap' ? onAsset : !onAsset) {\n throw new GalaSDKError('INVALID_WRAP_DIRECTION', { symbol: token.symbol, direction });\n }\n return token;\n }\n\n /** The fee estimate of a wrap or unwrap. */\n private async estimate(\n tokenId: TokenId,\n amount: string,\n direction: 'wrap' | 'unwrap',\n ): Promise<WrapUnwrapFeeEstimate> {\n validateBridgeAmount(amount);\n const source = await this.sourceToken(tokenId, direction);\n return {\n fee: '0',\n feeToken: 'GALA',\n authorizationType: direction === 'wrap' ? 'cross_channel_authorization' : 'automatic',\n feeChannel: direction === 'wrap' ? channelOf(source) : ASSET_CHANNEL,\n };\n }\n\n /** A wrap or unwrap: every check, the signed request, then BridgeTokenOut. */\n private async execute(\n options: WrapTokenOptions | UnwrapTokenOptions,\n direction: 'wrap' | 'unwrap',\n ): Promise<WrapUnwrapResult> {\n const { amount } = options;\n validateBridgeAmount(amount);\n if (this.signer === undefined) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'signer' });\n }\n if (this.walletAddress === undefined || this.walletAddress === '') {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'walletAddress' });\n }\n const senderAddress = galaChainUserRef(this.walletAddress, 'walletAddress');\n const recipient =\n options.recipient === undefined || options.recipient === ''\n ? senderAddress\n : galaChainUserRef(options.recipient, 'recipient');\n\n const source = await this.sourceToken(options.tokenId, direction);\n const destination = await this.wrappableTokenService.getWrapCounterpart(options.tokenId);\n if (destination === undefined) {\n throw new GalaSDKError('TOKEN_NOT_WRAPPABLE', {\n tokenId: source.wrapCounterpart,\n reason: 'no_counterpart',\n });\n }\n // Wrap: the source token's channel → asset; unwrap: asset → the destination token's channel\n // (each a channel a wrap moves between: never guessed).\n const routing: ChannelRouting =\n direction === 'wrap'\n ? {\n sourceChannel: channelOf(source),\n destinationChannel: ASSET_CHANNEL,\n destinationChannelId: GALACHAIN_CHANNELS.ASSET,\n }\n : {\n sourceChannel: ASSET_CHANNEL,\n destinationChannel: channelOf(destination),\n destinationChannelId: CHANNEL_IDS[channelOf(destination)] as number,\n };\n\n // The native GalaChain message: quantity is the decimal amount; `wrap` is always true (the\n // direction is the destination channel id).\n const uniqueKey = createUniqueKey(WRAP_UNIQUE_KEY_PREFIX);\n const message = {\n quantity: amount,\n tokenInstance: {\n collection: source.galaChainDescriptor.collection,\n category: source.galaChainDescriptor.category,\n type: source.galaChainDescriptor.type,\n additionalKey: source.galaChainDescriptor.additionalKey,\n instance: '0',\n },\n destinationChainId: routing.destinationChannelId,\n recipient,\n wrap: true,\n uniqueKey,\n };\n const requestBody = await signPreSend(this.signer, 'RequestTokenBridgeOut', message);\n\n const response = await this.galaConnectClient.requestBridgeOut(requestBody);\n // GalaChain refusing the request locked nothing: its own refusal, with the key\n assertRequestAccepted('RequestTokenBridgeOut', response, uniqueKey);\n\n const transactionId = await completeBridgeOut(\n this.galaConnectClient,\n response,\n uniqueKey,\n routing.sourceChannel,\n readWrapResult,\n );\n\n return {\n success: true,\n transactionId,\n fromToken: source.symbol,\n toToken: destination.symbol,\n amount,\n fromChannel: routing.sourceChannel,\n toChannel: routing.destinationChannel,\n completedAt: Date.now(),\n };\n }\n}\n\n/**\n * A wrap's `BridgeTokenOut` answer: it must say `Status` 1; its transaction id is its `Hash`, else\n * the bridge request id.\n *\n * @throws GalaSDKError `BRIDGE_RESPONSE_INVALID` without `Status` 1\n */\nfunction readWrapResult(bridgeOutResponse: unknown, bridgeRequestId: string): string {\n const fields = fieldsOf(bridgeOutResponse);\n if (fields['Status'] !== 1) {\n throw new GalaSDKError('BRIDGE_RESPONSE_INVALID', {\n method: 'BridgeTokenOut',\n missing: 'Status 1',\n });\n }\n const hash = fields['Hash'];\n return typeof hash === 'string' && hash !== '' ? hash : bridgeRequestId;\n}\n","/**\n * Solana wallet creation (for bridging to and from Solana).\n *\n * The Ethereum wallet helpers (`createWallet`, `validateWalletInput`, `getPublicKeyFromPrivateKey`,\n * `getEthereumAddressFromPrivateKey`) are the core root's: they need no Solana library.\n *\n * @module bridge/solanaWallet\n */\n\nimport { base58 } from '@scure/base';\nimport { Keypair } from '@solana/web3.js';\n\n/**\n * A generated Solana wallet.\n */\nexport interface GeneratedSolanaWallet {\n /** Base58-encoded 64-byte secret key (used for signing) */\n privateKey: string;\n /** Base58-encoded 32-byte public key */\n publicKey: string;\n /** Solana address (the public key: Solana addresses ARE public keys) */\n address: string;\n}\n\n/**\n * Creates a new random Solana wallet: an Ed25519 keypair, its secret key in base58 (the form the\n * Solana bridge strategy's `solanaPrivateKey` takes).\n *\n * @returns The generated wallet: secret key, public key, address\n *\n * @example\n * ```typescript\n * import { createSolanaWallet } from '@gala-chain/gala-core-sdk/bridge';\n *\n * const wallet = createSolanaWallet();\n * console.log(wallet.address); // base58 public key\n * ```\n */\nexport function createSolanaWallet(): GeneratedSolanaWallet {\n const keypair = Keypair.generate();\n const publicKey = keypair.publicKey.toBase58();\n return {\n privateKey: base58.encode(keypair.secretKey),\n publicKey,\n address: publicKey,\n };\n}\n","/**\n * Address Formatter - Utilities for converting between Ethereum and GalaChain address formats\n *\n * Consolidates scattered address format conversion patterns across the SDK.\n * Provides consistent address normalization for blockchain interoperability.\n *\n * @category Bridge Utilities\n * @since 6.15.0\n */\n\n/**\n * Removes \"0x\" prefix from Ethereum address hex values\n *\n * Consolidates 13 scattered instances of manual 0x removal patterns:\n * - .replace('0x', '')\n * - .slice(2)\n * - .substring(2) with startsWith check\n *\n * @param hex Hex value potentially with 0x prefix\n * @returns Hex value without 0x prefix\n * @example\n * stripHexPrefix('0x123abc') // '123abc'\n * stripHexPrefix('123abc') // '123abc'\n */\nexport function stripHexPrefix(hex: string): string {\n if (hex === '') return '';\n return hex.startsWith('0x') ? hex.slice(2) : hex;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwNA,IAAY,mBAAL;CACL;CACA;CACA;CACA;CACA;CACA;CACA;;CAEA;;AACF;;;;;;;;;;;;;ACxNA,MAAa,gCAAgC;CAC3C,MAAM;CACN,SAAS;AACX;;;;AAiBA,MAAM,wBAA0C;CAC9C;EAAE,MAAM;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WAAW,MAAM,KAAK,kBAAkB,iBAAiB,WAAW;EAE1E,sBAAsB,yBAAyB,UAAU,SAAS;EAUlE,OAAO;GACL,SAAS;GACT,qBAV0B,kBAC1B,KAAK,mBACL,UACA,WACA,QAAQ,eACR,cACF;GAKE,WAAW,OAAO;GAClB,SAAS,YAAY;GACrB;GACA,aAAa,QAAQ;GACrB,WAAW,QAAQ;GACnB,aAAa,KAAK,IAAI;EACxB;CACF;AACF;;;;;;;AAQA,SAAS,eAAe,mBAA4B,iBAAiC;CACnF,MAAM,SAAS,SAAS,iBAAiB;CACzC,IAAI,OAAO,cAAc,GACvB,MAAM,IAAIJ,uCAAa,2BAA2B;EAChD,QAAQ;EACR,SAAS;CACX,CAAC;CAEH,MAAM,OAAO,OAAO;CACpB,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AAC1D;;;;;;;;;;;;;;;;;;;;;;;;;;ACzPA,SAAgB,qBAA4C;CAC1D,MAAM,UAAUK,wBAAQ,SAAS;CACjC,MAAM,YAAY,QAAQ,UAAU,SAAS;CAC7C,OAAO;EACL,YAAYC,mBAAO,OAAO,QAAQ,SAAS;EAC3C;EACA,SAAS;CACX;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;ACtBA,SAAgB,eAAe,KAAqB;CAClD,IAAI,QAAQ,IAAI,OAAO;CACvB,OAAO,IAAI,WAAW,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI;AAC/C"}
|
|
1
|
+
{"version":3,"file":"bridge.cjs","names":["BigNumber","stringifyTokenClassKey","stringifyTokenClassKey","GalaSDKError","isEthereumAddress","PublicKey","GalaSDKError","GalaSDKError","validateTimeoutMs","galaChainUserRef","normalizeTokenKey","GalaSDKError","GalaSDKError","GalaSDKError","GalaSDKError","isGalaError","isWalletUserRejection","walletDeclineCode","createUniqueKey","dtoOperationOf","serialize","GalaSDKError","GalaSDKError","BigNumber","GalaSDKError","GalaSDKError","Contract","GalaSDKError","JsonRpcProvider","EthersWallet","galaChainUserRef","Signature","PublicKey","GalaSDKError","AccountLayout","base58","Keypair","EthersWallet","Connection","galaChainUserRef","TOKEN_PROGRAM_ID","ASSOCIATED_TOKEN_PROGRAM_ID","MintLayout","LAMPORTS_PER_SOL","Transaction","ComputeBudgetProgram","TransactionExpiredBlockheightExceededError","TransactionInstruction","SystemProgram","splitClassKey","GalaSDKError","centralStringify","isTokenClassKey","GalaSDKError","galaChainUserRef","GALA_CHAIN_ENVIRONMENTS","isGalaError","GalaSDKError","GalaSDKError","stringifyTokenClassKey","galaChainUserRef","createUniqueKey","signPreSend","Keypair","base58"],"sources":["../src/bridge/types/bridge.dto.ts","../src/bridge/types/eip712.ts","../src/bridge/internal/values.ts","../src/bridge/constants/tokens.ts","../src/bridge/utils/bridgeErrors.ts","../src/bridge/utils/RateLimiter.ts","../src/bridge/utils/retry.ts","../src/bridge/GalaConnectClient.ts","../src/bridge/utils/addressValidation.ts","../src/bridge/utils/balanceHelpers.ts","../src/bridge/utils/bridgePayload.ts","../src/bridge/utils/eip712Helpers.ts","../src/bridge/utils/bridgeOutHelpers.ts","../src/bridge/utils/bridgeStatusParser.ts","../src/bridge/utils/strategyDelegation.ts","../src/bridge/utils/tokenMetadataResolver.ts","../src/bridge/utils/tokenMath.ts","../src/bridge/strategies/BridgeStrategy.ts","../src/bridge/strategies/EthereumBridgeStrategy.ts","../src/bridge/strategies/SolanaBridgeStrategy.ts","../src/bridge/utils/tokenIdUtils.ts","../src/bridge/BridgeService.ts","../src/bridge/tokens/tokenPages.ts","../src/bridge/tokens/BridgeableTokenService.ts","../src/bridge/tokens/WrappableTokenService.ts","../src/bridge/tokens/WrapService.ts","../src/bridge/solanaWallet.ts","../src/bridge/utils/address-formatter.ts"],"sourcesContent":["/**\n * Bridge DTOs and Interfaces\n *\n * Type definitions for cross-chain bridging operations between\n * GalaChain, Ethereum, and Solana.\n */\n\nimport type { HttpRequestor, TokenClassKeyInput as TokenId } from '../../index.js';\n\n/**\n * Supported external networks for bridging\n */\nexport type ExternalNetwork = 'Ethereum' | 'Solana';\n\n/**\n * Token descriptor for GalaChain tokens\n */\nexport interface BridgeTokenDescriptor {\n collection: string;\n category: string;\n type: string;\n additionalKey: string;\n}\n\n/**\n * Token descriptor with instance (for specific token instances)\n */\nexport interface BridgeTokenInstance extends BridgeTokenDescriptor {\n instance: string;\n}\n\n/**\n * Ethereum token configuration\n */\nexport interface EthereumTokenConfig {\n symbol: string;\n amount: string;\n contractAddress: string;\n bridgeUsesPermit?: boolean;\n decimals?: number;\n}\n\n/**\n * Solana token configuration\n */\nexport interface SolanaTokenConfig {\n symbol: string;\n amount: string;\n mintAddress: string;\n isNative?: boolean;\n decimals?: number;\n}\n\n/**\n * Bridge token configuration from GalaConnect API\n */\nexport interface BridgeConfigurationToken extends BridgeTokenDescriptor {\n symbol: string;\n decimals: number;\n verified?: boolean;\n channel?: string;\n canBridgeTo?: Array<{\n network: string;\n symbol: string;\n destinationChainIds: string[];\n }>;\n otherNetworks?: Array<{\n network: string;\n symbol: string;\n contractAddress: string;\n canBridgeTo?: Array<{\n network: string;\n symbol: string;\n destinationChainIds: string[];\n }>;\n }>;\n}\n\n/**\n * Bridge token metadata for internal use\n *\n * Lightweight metadata for bridging operations,\n * distinct from blockchain metadata or cache entries.\n *\n * @since 6.10.0 - Renamed from TokenMetadata for clarity\n */\nexport interface BridgeTokenMetadata {\n /** Token descriptor (collection, category, type, additionalKey) */\n descriptor: BridgeTokenDescriptor;\n /** Token decimal places */\n decimals: number;\n /** GalaChain channel (optional) */\n channel?: string;\n}\n\n/**\n * External token information (for exchange rates)\n */\nexport interface ExternalTokenInfo {\n name: string;\n symbol: string;\n}\n\n/**\n * GALA exchange rate from oracle\n */\nexport interface GalaExchangeRate {\n identity: string;\n oracle: string;\n source: string;\n sourceUrl: string;\n timestamp: number | string;\n baseToken?: BridgeTokenInstance;\n exchangeRate: string;\n externalQuoteToken?: ExternalTokenInfo;\n}\n\n/**\n * Base token cross rate\n */\nexport interface BaseTokenCrossRate {\n identity: string;\n oracle: string;\n source: string;\n sourceUrl: string;\n timestamp: number | string;\n exchangeRate: string;\n externalBaseToken?: ExternalTokenInfo;\n externalQuoteToken?: ExternalTokenInfo;\n signature: string;\n}\n\n/**\n * Quote token cross rate\n */\nexport interface QuoteTokenCrossRate {\n identity: string;\n oracle: string;\n source: string;\n sourceUrl: string;\n timestamp: number | string;\n baseToken?: BridgeTokenInstance;\n exchangeRate: string;\n externalQuoteToken?: ExternalTokenInfo;\n signature: string;\n}\n\n/**\n * GALA exchange cross rate (for non-GALA tokens)\n */\nexport interface GalaExchangeCrossRate {\n baseTokenCrossRate?: BaseTokenCrossRate;\n crossRate: string;\n externalCrossRateToken?: ExternalTokenInfo;\n identity: string;\n oracle: string;\n quoteTokenCrossRate?: QuoteTokenCrossRate;\n source: string;\n timestamp: number | string;\n}\n\n/**\n * Destination chain transaction fee structure\n */\nexport interface DestinationChainTxFee {\n bridgeToken: BridgeTokenDescriptor;\n bridgeTokenIsNonFungible: boolean;\n estimatedPricePerTxFeeUnit: string;\n estimatedTotalTxFeeInExternalToken: string;\n estimatedTotalTxFeeInGala: string;\n estimatedTxFeeUnitsTotal: string;\n galaDecimals: number | string;\n galaExchangeRate?: GalaExchangeRate;\n galaExchangeCrossRate?: GalaExchangeCrossRate;\n timestamp: number | string;\n signingIdentity: string;\n signature: string;\n}\n\n/**\n * Bridge fee estimate returned to SDK users\n */\nexport interface BridgeFeeEstimate {\n /** Estimated fee in GALA */\n estimatedFeeInGala: string;\n /** Estimated fee in the external chain's native token */\n estimatedFeeInExternalToken: string;\n /** Token used for bridge fees */\n feeToken: BridgeTokenDescriptor;\n /** Gas price per unit */\n pricePerUnit: string;\n /** Total estimated gas units */\n estimatedGasUnits: string;\n /** GALA exchange rate at time of estimate */\n exchangeRate: string;\n /** Timestamp of the estimate */\n timestamp: number;\n /** Raw fee response for advanced usage */\n raw: DestinationChainTxFee;\n}\n\n/**\n * Bridge request DTO for outbound bridges\n */\nexport interface BridgeRequestDto {\n uniqueKey?: string;\n tokenInstance: BridgeTokenInstance;\n destinationChainId: number | string;\n quantity: string;\n recipient: string;\n destinationChainTxFee: DestinationChainTxFee;\n}\n\n/**\n * Bridge status codes\n */\nexport enum BridgeStatusCode {\n PENDING = 0,\n SUBMITTED = 1,\n CONFIRMED = 2,\n PROCESSING = 3,\n FINALIZING = 4,\n COMPLETED = 5,\n FAILED = 6,\n /** Delivery failed - tokens left source chain but failed to arrive on destination */\n DELIVERY_FAILED = 7,\n}\n\n/**\n * Bridge status response (normalized)\n */\nexport interface BridgeStatus {\n /** Numeric status code */\n status: BridgeStatusCode;\n /** Human-readable status description */\n statusDescription: string;\n /** Source chain */\n fromChain: string;\n /** Destination chain */\n toChain: string;\n /** Amount being bridged */\n quantity: string;\n /** Transaction hash on emitter chain */\n transactionHash: string;\n /** Token being bridged */\n tokenInstance?: BridgeTokenInstance;\n /** Whether the bridge is complete */\n isComplete: boolean;\n /** Whether the bridge failed */\n isFailed: boolean;\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Solana transaction status from RPC query\n *\n * Used by `getSolanaTransactionStatus()` to report the confirmation\n * status of Solana transactions (airdrops, bridges, etc.)\n */\nexport interface SolanaTransactionStatus {\n /**\n * Whether the transaction has been successfully processed on-chain.\n * - true: Transaction executed successfully\n * - false: Transaction not found, still pending, or failed\n */\n confirmed: boolean;\n\n /**\n * Detailed status of the transaction:\n * - 'confirmed': Transaction confirmed by supermajority of cluster\n * - 'finalized': Transaction finalized (maximum certainty)\n * - 'processed': Transaction processed by connected node\n * - 'not_found': Transaction not yet visible on-chain\n * - 'failed': Transaction was processed but failed (see error field)\n */\n status: 'confirmed' | 'finalized' | 'processed' | 'not_found' | 'failed';\n\n /**\n * Block slot number where transaction was processed.\n * Present when transaction has been found on-chain.\n */\n slot?: number;\n\n /**\n * Error details if transaction failed.\n * Contains JSON-stringified Solana error object.\n */\n error?: string;\n}\n\n/**\n * Ethereum transaction status from RPC query\n *\n * Used by `getEthereumTransactionStatus()` to report the confirmation\n * status of Ethereum transactions (bridges, transfers, etc.)\n */\nexport interface EthereumTransactionStatus {\n /**\n * Whether the transaction has been successfully processed on-chain.\n * - true: Transaction confirmed and executed successfully\n * - false: Transaction not found, still pending, or failed\n */\n confirmed: boolean;\n\n /**\n * Detailed status of the transaction:\n * - 'pending': Transaction in mempool, not yet mined\n * - 'confirmed': Transaction mined in block\n * - 'finalized': Transaction finalized (12+ confirmations for safety)\n * - 'not_found': Transaction not yet visible on-chain\n * - 'failed': Transaction mined but execution failed (reverted)\n */\n status: 'pending' | 'confirmed' | 'finalized' | 'not_found' | 'failed';\n\n /**\n * Block number where transaction was mined.\n * Present when transaction has been found on-chain.\n */\n blockNumber?: number;\n\n /**\n * Number of confirmations since block inclusion.\n * Calculated as (currentBlockNumber - blockNumber + 1).\n * Higher values indicate stronger finality.\n */\n confirmations?: number;\n\n /**\n * Transaction hash (normalized to lowercase).\n */\n transactionHash: string;\n\n /**\n * Gas used by transaction (if mined).\n */\n gasUsed?: string;\n\n /**\n * Effective gas price in wei (if mined).\n */\n effectiveGasPrice?: string;\n\n /**\n * Error details if transaction failed.\n * Contains the revert reason or execution error.\n */\n error?: string;\n}\n\n/**\n * Bridge transaction result\n */\nexport interface BridgeTransaction {\n /** Direction of the bridge */\n direction: 'outbound' | 'inbound';\n /** Source chain */\n fromChain: string;\n /** Destination chain */\n toChain: string;\n /** Transaction hash */\n transactionHash: string;\n /** Token symbol */\n tokenSymbol: string;\n /** Amount bridged */\n amount: string;\n /** Fee paid (in GALA for outbound, native token for inbound) */\n feePaid?: string;\n /** Timestamp when transaction was submitted */\n timestamp: number;\n /** Bridge status tracking URL */\n statusUrl: string;\n}\n\n/**\n * Bridge leg result (for round-trip tracking)\n */\nexport interface BridgeLegResult {\n direction: 'Outbound' | 'Inbound';\n fromChain: string;\n toChain: string;\n startTimestamp: number;\n endTimestamp?: number;\n durationMs?: number;\n feePaid?: string;\n feeToken?: string;\n transactionHash?: string;\n additionalInfo?: Record<string, unknown>;\n error?: string;\n}\n\n/**\n * Token round-trip result\n */\nexport interface TokenRoundTripResult {\n token: string;\n network: ExternalNetwork;\n amount: string;\n legs: BridgeLegResult[];\n outboundCompleted: boolean;\n inboundCompleted: boolean;\n roundTripDurationMs?: number;\n totalFees?: Array<{ amount: string; token: string; context: string }>;\n failures?: string[];\n}\n\n/**\n * Supported bridge token info for discovery\n */\nexport interface BridgeToken {\n /** Token symbol (e.g., 'GALA', 'GWETH') */\n symbol: string;\n /** Token name */\n name?: string;\n /** Token decimals */\n decimals: number;\n /** Whether verified by Gala */\n verified: boolean;\n /** Supported destination chains */\n supportedChains: ExternalNetwork[];\n /** GalaChain token descriptor */\n galaChainDescriptor: BridgeTokenDescriptor;\n /** External chain addresses */\n externalAddresses: {\n ethereum?: string;\n solana?: string;\n };\n}\n\n/**\n * Bridge SDK configuration\n */\nexport interface BridgeConfig {\n /** GalaConnect API base URL */\n galaConnectBaseUrl: string;\n /** GalaChain API base URL (optional, defaults to galaConnectBaseUrl) */\n galaChainApiBaseUrl?: string;\n /** Ethereum RPC URL (optional, defaults to public endpoint) */\n ethereumRpcUrl?: string;\n /** Solana RPC URL (optional, defaults to public endpoint) */\n solanaRpcUrl?: string;\n /** Ethereum bridge contract address (optional, defaults to mainnet) */\n ethereumBridgeContract?: string;\n /** Solana bridge program ID (optional, defaults to mainnet) */\n solanaBridgeProgram?: string;\n /** Ethereum private key for inbound bridges (optional) */\n ethereumPrivateKey?: string;\n /** Solana private key (base58) for inbound bridges (optional) */\n solanaPrivateKey?: string;\n /** Rate limit for API calls (requests per second) */\n rateLimit?: number;\n /** Status polling interval in milliseconds */\n pollInterval?: number;\n /** Status polling timeout in milliseconds */\n pollTimeout?: number;\n}\n\n/**\n * Parameters for estimating bridge fees\n *\n * @example Using string tokenId (pipe-delimited)\n * ```typescript\n * const fee = await sdk.estimateBridgeFee({\n * tokenId: 'GALA|Unit|none|none',\n * destinationChain: 'Ethereum',\n * });\n * ```\n *\n * @example Using TokenClassKey object\n * ```typescript\n * const fee = await sdk.estimateBridgeFee({\n * tokenId: { collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' },\n * destinationChain: 'Ethereum',\n * });\n * ```\n */\nexport interface EstimateBridgeFeeParams {\n /**\n * Token identifier - accepts pipe-delimited string or TokenClassKey object.\n *\n * Get from `fetchAllBridgeableTokensByNetwork()` result's `stringifiedTokenClassKey` field,\n * or construct manually: `{ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }`\n */\n tokenId: TokenId;\n /** Destination chain (the fee is a per-transfer cost: it does not depend on the amount) */\n destinationChain: ExternalNetwork;\n}\n\n/**\n * Parameters for bridging out (GalaChain -> External)\n *\n * @example Bridge GALA to Ethereum\n * ```typescript\n * const result = await sdk.bridgeOut({\n * tokenId: 'GALA|Unit|none|none',\n * amount: '100',\n * destinationChain: 'Ethereum',\n * recipientAddress: '0x1234...abcd',\n * });\n * ```\n */\nexport interface BridgeOutParams {\n /**\n * Token identifier - accepts pipe-delimited string or TokenClassKey object.\n *\n * Get from `fetchAllBridgeableTokensByNetwork()` result's `stringifiedTokenClassKey` field,\n * or construct manually: `{ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }`\n */\n tokenId: TokenId;\n /** Amount to bridge */\n amount: string;\n /** Destination chain */\n destinationChain: ExternalNetwork;\n /** Recipient address on destination chain */\n recipientAddress: string;\n /** Optional slippage tolerance for fee (0-1, e.g., 0.01 for 1%) */\n feeSlippageTolerance?: number;\n /**\n * @internal Resolved token symbol (set by BridgeService, not user-provided)\n */\n tokenSymbol?: string;\n}\n\n/**\n * Parameters for bridging in (External -> GalaChain)\n *\n * @example Bridge GALA from Ethereum to GalaChain\n * ```typescript\n * const result = await sdk.bridgeIn({\n * tokenId: 'GALA|Unit|none|none',\n * amount: '100',\n * sourceChain: 'Ethereum',\n * sourcePrivateKey: '0xabc...', // Ethereum wallet private key\n * });\n * ```\n */\nexport interface BridgeInParams {\n /**\n * Token identifier - accepts pipe-delimited string or TokenClassKey object.\n *\n * Get from `fetchAllBridgeableTokensByNetwork()` result's `stringifiedTokenClassKey` field,\n * or construct manually: `{ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }`\n */\n tokenId: TokenId;\n /** Amount to bridge */\n amount: string;\n /** Source chain */\n sourceChain: ExternalNetwork;\n /** Private key for source chain wallet (overrides config) */\n sourcePrivateKey?: string;\n /** Recipient GalaChain address (optional, defaults to SDK wallet) */\n recipientAddress?: string;\n /**\n * @internal Resolved token symbol (set by BridgeService, not user-provided)\n */\n tokenSymbol?: string;\n}\n\n/**\n * Options for waiting on bridge completion\n */\nexport interface WaitForBridgeOptions {\n /** Polling interval in milliseconds (default: 15000) */\n pollInterval?: number;\n /** Timeout in milliseconds (default: 45 minutes) */\n timeout?: number;\n /** Callback for status updates */\n onStatusUpdate?: (status: BridgeStatus) => void;\n}\n\n// ============================================================================\n// GalaConnect API Response Types\n// ============================================================================\n\n/**\n * Configuration for GalaConnect client\n */\nexport interface GalaConnectConfig {\n /** GalaConnect API base URL */\n baseUrl?: string;\n /** GalaChain API base URL */\n galachainBaseUrl?: string;\n /**\n * The wallet's GalaChain user reference: an Ethereum account (`eth|...`, `0x...`, bare hex; sent\n * as `eth|<checksummed>`) or a `client|` alias; `''` for a client with no wallet.\n */\n walletAddress: string;\n /** Sends the HTTP requests (default: the global `fetch`) */\n httpRequestor?: HttpRequestor;\n /**\n * How long one request may take, in milliseconds (default 30 000; `Infinity` for no limit). A\n * read that runs out is `REQUEST_TIMEOUT`, a write `BRIDGE_WRITE_OUTCOME_UNKNOWN`.\n */\n requestTimeoutMs?: number;\n /** Requests per second (rate limiting) */\n requestsPerSecond?: number;\n /**\n * Enable automatic retry for transient failures (default: true)\n *\n * When enabled, requests that fail due to network errors or\n * server errors (5xx, 429) will be automatically retried with\n * exponential backoff.\n */\n enableRetry?: boolean;\n /**\n * Maximum number of retry attempts (default: 3)\n *\n * Only used when enableRetry is true.\n */\n maxRetries?: number;\n /**\n * Initial delay in milliseconds before first retry (default: 1000)\n *\n * Subsequent retries use exponential backoff (delay doubles each time).\n */\n retryInitialDelayMs?: number;\n /**\n * Callback invoked before each retry attempt.\n *\n * Useful for logging or monitoring retry behavior.\n *\n * @param error - The error that triggered the retry\n * @param attempt - Current attempt number (1-based)\n * @param delayMs - Delay before next attempt in milliseconds\n */\n onRetry?: (error: unknown, attempt: number, delayMs: number) => void;\n}\n\n/**\n * Bridge fee response from GalaConnect API\n */\nexport interface BridgeFeeResponse {\n bridgeToken: BridgeTokenDescriptor;\n bridgeTokenIsNonFungible: boolean;\n estimatedPricePerTxFeeUnit: string;\n estimatedTotalTxFeeInExternalToken: string;\n estimatedTotalTxFeeInGala: string;\n estimatedTxFeeUnitsTotal: string;\n galaDecimals: number;\n galaExchangeRate: GalaExchangeRate;\n galaExchangeCrossRate?: GalaExchangeCrossRate;\n timestamp: number;\n signingIdentity: string;\n signature: string;\n}\n\n/**\n * Response from RequestTokenBridgeOut API\n *\n * Note: The GalaConnect API may return additional undocumented fields.\n * The index signature ensures compatibility with Record<string, unknown>\n * while preserving type safety for known fields.\n *\n * Known fields may appear in different casings (e.g., Data/data, Hash/hash)\n * due to API response inconsistencies across different endpoints.\n */\nexport interface RequestBridgeOutResponse {\n Data?: string;\n data?: { Data?: string } | string;\n Hash?: string;\n hash?: string;\n Status?: number;\n status?: number;\n message?: string;\n /** Index signature for API compatibility (additional undocumented fields) */\n [key: string]: unknown;\n}\n\n/**\n * Response from BridgeTokenOut API\n */\nexport interface BridgeTokenOutResponse {\n Data?: {\n chainId: number;\n emitter: string;\n nonce: string;\n sequence: string;\n payload: string;\n };\n Hash?: string;\n hash?: string;\n Status?: number;\n status?: number;\n message?: string;\n}\n\n/**\n * Response from bridge status API.\n *\n * Note: The API returns a flat response structure (no data wrapper).\n */\nexport interface BridgeStatusResponse {\n /** Status code (0-6 mapping to BridgeStatusCode) */\n status: number;\n /** Human-readable status description */\n statusDescription: string;\n /** Source chain (e.g., \"GC\" for GalaChain) */\n fromChain: string;\n /** Destination chain (e.g., \"Ethereum\") */\n toChain: string;\n /** Amount being bridged */\n quantity: string;\n /** Transaction hash on the emitter (source) chain */\n emitterTransactionHash: string;\n /** Token instance being bridged */\n tokenInstance: BridgeTokenInstance;\n /** Transaction hash on the receiver (destination) chain, if available */\n receiverTransactionHash?: string;\n}\n\n/**\n * Response from bridge transaction registration API\n */\nexport interface BridgeTransactionRegistrationResponse {\n status: number;\n message: string;\n error: boolean;\n data?: Record<string, unknown>;\n}\n\n/**\n * Token balance entry from FetchBalances\n */\nexport interface TokenBalanceEntry {\n tokenInstance: BridgeTokenInstance;\n balance: string;\n locked?: string;\n}\n\n/**\n * Response from FetchBalances API\n */\nexport interface FetchBalancesResponse {\n status: number;\n message: string;\n error: boolean;\n data?: {\n balances: TokenBalanceEntry[];\n };\n}\n\n// ============================================================================\n// External Chain Wallet Balance Types\n// ============================================================================\n\n/**\n * Balance for a single token on an external chain (Ethereum or Solana)\n *\n * Represents either a native token (ETH/SOL) or a token contract (ERC-20/SPL).\n *\n * @example\n * ```typescript\n * // Native ETH balance\n * const ethBalance: ExternalChainBalance = {\n * symbol: 'ETH',\n * quantity: '1.500000000000000000',\n * decimals: 18,\n * contractAddress: null,\n * isNative: true,\n * };\n *\n * // ERC-20 GALA balance\n * const galaBalance: ExternalChainBalance = {\n * symbol: 'GALA',\n * quantity: '1000.00000000',\n * decimals: 8,\n * contractAddress: '0x15D4c048F83bd7e37d49eA4C83a07267Ec4203dA',\n * isNative: false,\n * };\n * ```\n */\nexport interface ExternalChainBalance {\n /** Token symbol (e.g., \"GALA\", \"GWETH\", \"ETH\", \"SOL\") */\n symbol: string;\n /** Balance as decimal string (e.g., \"123.45678901\") */\n quantity: string;\n /** Token decimals */\n decimals: number;\n /** Contract address (ERC-20) or mint address (SPL), null for native tokens */\n contractAddress: string | null;\n /** Whether this is the native token (ETH/SOL) */\n isNative: boolean;\n}\n\n/**\n * Complete Ethereum wallet balance result\n *\n * Returns native ETH balance plus all supported ERC-20 token balances:\n * GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC\n *\n * @example\n * ```typescript\n * const result = await sdk.fetchEthereumWalletBalance('0x...');\n * console.log(`ETH: ${result.native.quantity}`);\n * console.log(`Tokens: ${result.tokens.map(t => `${t.symbol}: ${t.quantity}`).join(', ')}`);\n * ```\n */\nexport interface EthereumWalletBalanceResult {\n /** Wallet address queried (0x format) */\n address: string;\n /** Native ETH balance */\n native: ExternalChainBalance;\n /** ERC-20 token balances (GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC) */\n tokens: ExternalChainBalance[];\n /** Query timestamp (epoch ms) */\n timestamp: number;\n}\n\n/**\n * Complete Solana wallet balance result\n *\n * Returns native SOL balance plus all supported SPL token balances:\n * GALA, GSOL\n *\n * @example\n * ```typescript\n * const result = await sdk.fetchSolanaWalletBalance('9WzDXw...');\n * console.log(`SOL: ${result.native.quantity}`);\n * console.log(`Tokens: ${result.tokens.map(t => `${t.symbol}: ${t.quantity}`).join(', ')}`);\n * ```\n */\nexport interface SolanaWalletBalanceResult {\n /** Wallet address queried (base58 format) */\n address: string;\n /** Native SOL balance */\n native: ExternalChainBalance;\n /** SPL token balances (GALA, GSOL) */\n tokens: ExternalChainBalance[];\n /** Query timestamp (epoch ms) */\n timestamp: number;\n}\n","/**\n * EIP-712 Typed Data Schemas for GalaChain Bridge\n *\n * These schemas define the structure for typed data signing\n * required by the GalaChain bridge.\n */\n\n/**\n * GalaConnect typed data domain\n */\nexport const GALA_BRIDGE_TYPED_DATA_DOMAIN = {\n name: 'GalaConnect',\n chainId: 1,\n} as const;\n\n/**\n * EIP-712 type definition\n */\nexport interface TypedDataField {\n name: string;\n type: string;\n}\n\n// ============================================================================\n// Common Type Definitions (shared between legacy and cross-rate schemas)\n// ============================================================================\n\n/**\n * Common GalaTransaction fields (identical in both schemas)\n */\nconst GALA_TRANSACTION_TYPE: TypedDataField[] = [\n { name: 'destinationChainId', type: 'uint256' },\n { name: 'destinationChainTxFee', type: 'destinationChainTxFee' },\n { name: 'dtoOperation', type: 'string' },\n { name: 'quantity', type: 'string' },\n { name: 'recipient', type: 'string' },\n { name: 'tokenInstance', type: 'tokenInstance' },\n { name: 'uniqueKey', type: 'string' },\n];\n\n/**\n * Bridge token descriptor (GalaChain token class key)\n */\nconst BRIDGE_TOKEN_TYPE: TypedDataField[] = [\n { name: 'collection', type: 'string' },\n { name: 'category', type: 'string' },\n { name: 'type', type: 'string' },\n { name: 'additionalKey', type: 'string' },\n];\n\n/**\n * Token instance with instance field (for specific token instances)\n */\nconst TOKEN_INSTANCE_TYPE: TypedDataField[] = [\n { name: 'collection', type: 'string' },\n { name: 'category', type: 'string' },\n { name: 'type', type: 'string' },\n { name: 'additionalKey', type: 'string' },\n { name: 'instance', type: 'string' },\n];\n\n/**\n * External token info (name and symbol only)\n */\nconst EXTERNAL_TOKEN_TYPE: TypedDataField[] = [\n { name: 'name', type: 'string' },\n { name: 'symbol', type: 'string' },\n];\n\n// ============================================================================\n// Schema-Specific Type Definitions\n// ============================================================================\n\n/**\n * Legacy typed data types (for tokens with direct GALA exchange rate)\n */\nexport const LEGACY_TYPED_DATA_TYPES: Record<string, TypedDataField[]> = {\n GalaTransaction: GALA_TRANSACTION_TYPE,\n destinationChainTxFee: [\n { name: 'bridgeToken', type: 'bridgeToken' },\n { name: 'bridgeTokenIsNonFungible', type: 'bool' },\n { name: 'estimatedPricePerTxFeeUnit', type: 'string' },\n { name: 'estimatedTotalTxFeeInExternalToken', type: 'string' },\n { name: 'estimatedTotalTxFeeInGala', type: 'string' },\n { name: 'estimatedTxFeeUnitsTotal', type: 'string' },\n { name: 'galaDecimals', type: 'uint256' },\n { name: 'galaExchangeRate', type: 'galaExchangeRate' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'signingIdentity', type: 'string' },\n { name: 'signature', type: 'string' },\n ],\n bridgeToken: BRIDGE_TOKEN_TYPE,\n galaExchangeRate: [\n { name: 'identity', type: 'string' },\n { name: 'oracle', type: 'string' },\n { name: 'source', type: 'string' },\n { name: 'sourceUrl', type: 'string' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'baseToken', type: 'baseToken' },\n { name: 'exchangeRate', type: 'string' },\n { name: 'externalQuoteToken', type: 'externalQuoteToken' },\n ],\n baseToken: TOKEN_INSTANCE_TYPE,\n externalQuoteToken: EXTERNAL_TOKEN_TYPE,\n tokenInstance: TOKEN_INSTANCE_TYPE,\n};\n\n/**\n * Cross-rate typed data types (for tokens requiring cross-rate calculation)\n */\nexport const CROSS_RATE_TYPED_DATA_TYPES: Record<string, TypedDataField[]> = {\n GalaTransaction: GALA_TRANSACTION_TYPE,\n destinationChainTxFee: [\n { name: 'bridgeToken', type: 'bridgeToken' },\n { name: 'bridgeTokenIsNonFungible', type: 'bool' },\n { name: 'estimatedPricePerTxFeeUnit', type: 'string' },\n { name: 'estimatedTotalTxFeeInExternalToken', type: 'string' },\n { name: 'estimatedTotalTxFeeInGala', type: 'string' },\n { name: 'estimatedTxFeeUnitsTotal', type: 'string' },\n { name: 'galaDecimals', type: 'uint256' },\n { name: 'galaExchangeCrossRate', type: 'galaExchangeCrossRate' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'signingIdentity', type: 'string' },\n { name: 'signature', type: 'string' },\n ],\n bridgeToken: BRIDGE_TOKEN_TYPE,\n galaExchangeCrossRate: [\n { name: 'baseTokenCrossRate', type: 'baseTokenCrossRate' },\n { name: 'crossRate', type: 'string' },\n { name: 'externalCrossRateToken', type: 'externalCrossRateToken' },\n { name: 'identity', type: 'string' },\n { name: 'oracle', type: 'string' },\n { name: 'quoteTokenCrossRate', type: 'quoteTokenCrossRate' },\n { name: 'source', type: 'string' },\n { name: 'timestamp', type: 'uint256' },\n ],\n baseTokenCrossRate: [\n { name: 'identity', type: 'string' },\n { name: 'oracle', type: 'string' },\n { name: 'source', type: 'string' },\n { name: 'sourceUrl', type: 'string' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'exchangeRate', type: 'string' },\n { name: 'externalBaseToken', type: 'externalBaseToken' },\n { name: 'externalQuoteToken', type: 'externalQuoteToken' },\n { name: 'signature', type: 'string' },\n ],\n externalBaseToken: EXTERNAL_TOKEN_TYPE,\n externalQuoteToken: EXTERNAL_TOKEN_TYPE,\n externalCrossRateToken: EXTERNAL_TOKEN_TYPE,\n quoteTokenCrossRate: [\n { name: 'identity', type: 'string' },\n { name: 'oracle', type: 'string' },\n { name: 'source', type: 'string' },\n { name: 'sourceUrl', type: 'string' },\n { name: 'timestamp', type: 'uint256' },\n { name: 'baseToken', type: 'baseToken' },\n { name: 'exchangeRate', type: 'string' },\n { name: 'externalQuoteToken', type: 'externalQuoteToken' },\n { name: 'signature', type: 'string' },\n ],\n baseToken: TOKEN_INSTANCE_TYPE,\n tokenInstance: TOKEN_INSTANCE_TYPE,\n};\n\n/**\n * Get the appropriate typed data types based on whether cross-rate is used\n *\n * @param hasCrossRate - Whether the fee uses cross-rate calculation\n * @returns The appropriate typed data types for EIP-712 signing\n */\nexport function getGalaBridgeTypedDataTypes(\n hasCrossRate: boolean,\n): Record<string, TypedDataField[]> {\n return hasCrossRate ? CROSS_RATE_TYPED_DATA_TYPES : LEGACY_TYPED_DATA_TYPES;\n}\n","/**\n * The small value helpers the bridge code used from launchpad-sdk's utils (`safe-parsers`,\n * `primitives`, `error-utils`, `tokenNameNormalizer`, `token-stringification`, `numeric-wrappers`,\n * `bignumber-helpers`), copied with the same behaviour. Internal to `./bridge`: never exported.\n */\nimport BigNumber from 'bignumber.js';\nimport type { GalaChainTokenClassKey } from '../../index.js';\n\n/** `null` or `undefined`. */\nexport function isNullish(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** `null`, `undefined` or `''`. */\nexport function isEmptyValue(value: unknown): value is null | undefined | '' {\n return value === null || value === undefined || value === '';\n}\n\n/** A string with something other than whitespace in it. */\nexport function isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/**\n * The fields of `value` when it is an object, else none: how an answer is read without trusting\n * its shape (an empty answer, `null`, a string all have no fields).\n */\nexport function fieldsOf(value: unknown): Record<string, unknown> {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};\n}\n\n/** A non-null object that is not an array. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Whether `record` has a string at each of `required`, and at each of `optional` either nothing\n * or a value of the type named for it.\n */\nexport function hasFields(\n record: Record<string, unknown>,\n required: readonly string[],\n optional: Readonly<Record<string, 'string' | 'number' | 'boolean' | 'object'>> = {},\n): boolean {\n return (\n required.every((key) => typeof record[key] === 'string') &&\n Object.entries(optional).every(([key, kind]) => {\n const value = record[key];\n return value === undefined || (kind === 'object' ? isRecord(value) : typeof value === kind);\n })\n );\n}\n\n/** A finite number. */\nexport function isValidNumber(value: unknown): value is number {\n if (typeof value !== 'number') return false;\n return !isNaN(value) && isFinite(value);\n}\n\n/**\n * An integer from a number (floored), a bigint or a decimal string (`parseInt`), or `fallback`\n * for nullish, `NaN` and unparseable input.\n */\nexport function safeParseInt(\n value: string | number | bigint | null | undefined,\n fallback: number,\n): number {\n if (isNullish(value)) {\n return fallback;\n }\n if (typeof value === 'bigint') {\n return Number(value);\n }\n if (typeof value === 'number') {\n return isNaN(value) ? fallback : Math.floor(value);\n }\n const parsed = parseInt(String(value), 10);\n return isNaN(parsed) ? fallback : parsed;\n}\n\n/** A finite float (`parseFloat`), or `fallback` for empty, `NaN` and infinite input. */\nexport function safeParseFloat(value: string | number | null | undefined, fallback = 0): number {\n if (isEmptyValue(value)) {\n return fallback;\n }\n if (typeof value === 'number') {\n return isNaN(value) || !isFinite(value) ? fallback : value;\n }\n const parsed = parseFloat(value);\n return isNaN(parsed) || !isFinite(parsed) ? fallback : parsed;\n}\n\n/** `JSON.parse(value)`, or `fallback` for empty or invalid JSON. */\nexport function safeParseJson<T>(value: string | null | undefined, fallback: T): T {\n if (isEmptyValue(value)) {\n return fallback;\n }\n try {\n return JSON.parse(value) as T;\n } catch {\n return fallback;\n }\n}\n\n/** A BigNumber of `value`, or of `fallback` for empty, `NaN` or infinite input. */\nexport function toBigNumber(\n value: string | number | BigNumber | null | undefined,\n fallback: string | number = '0',\n): BigNumber {\n if (isEmptyValue(value)) {\n return new BigNumber(fallback);\n }\n if (BigNumber.isBigNumber(value)) {\n return value.isNaN() ? new BigNumber(fallback) : value;\n }\n try {\n const parsed = new BigNumber(value);\n return parsed.isNaN() || !parsed.isFinite() ? new BigNumber(fallback) : parsed;\n } catch {\n // `BigNumber.DEBUG = true` (an app setting on the shared bignumber.js) makes a non-number throw.\n return new BigNumber(fallback);\n }\n}\n\n/** `true` when an error is an `Error`. */\nexport function isError(error: unknown): error is Error {\n return error instanceof Error;\n}\n\n/** The message of an error, of an object with a string `message`, a string, or `String(error)`. */\nexport function getErrorMessage(error: unknown): string {\n if (isError(error)) {\n return error.message;\n }\n if (\n typeof error === 'object' &&\n error !== null &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n return typeof error === 'string' ? error : String(error);\n}\n\n/** The string or number `code` of an error object, if it has one. */\nexport function getErrorCode(error: unknown): string | number | undefined {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (typeof error.code === 'string' || typeof error.code === 'number')\n ) {\n return error.code;\n }\n return undefined;\n}\n\n/** A token symbol (or a token map key) as compared: trimmed, upper case. */\nexport function normalizeTokenSymbol(symbol: string): string {\n return symbol.trim().toUpperCase();\n}\n\n/** The pipe-delimited form of a class key: `collection|category|type|additionalKey`. */\nexport function stringifyTokenClassKey(token: GalaChainTokenClassKey): string {\n return `${token.collection}|${token.category}|${token.type}|${token.additionalKey}`;\n}\n","/**\n * Bridge Token Constants\n *\n * Static token configurations and chain IDs for bridging.\n */\n\nimport { normalizeTokenSymbol, stringifyTokenClassKey } from '../internal/values.js';\nimport type {\n BridgeTokenDescriptor,\n BridgeTokenMetadata,\n EthereumTokenConfig,\n SolanaTokenConfig,\n} from '../types/bridge.dto.js';\n\n/**\n * Chain IDs used by the external bridge system (Ethereum/Solana)\n */\nexport const CHAIN_IDS = {\n GALA_CHAIN: 1,\n ETHEREUM: 2,\n SOLANA: 1002,\n} as const;\n\n/**\n * Internal GalaChain Channel IDs (for wrap/unwrap operations)\n *\n * Different from external CHAIN_IDS used for Ethereum/Solana bridges.\n * These represent internal GalaChain channels for cross-channel token transfers.\n *\n * @example\n * ```typescript\n * // Wrap: MUSIC (music channel) → GMUSIC (asset channel)\n * destinationChainId: GALACHAIN_CHANNELS.ASSET\n *\n * // Unwrap: GMUSIC (asset channel) → MUSIC (music channel)\n * destinationChainId: GALACHAIN_CHANNELS.MUSIC\n * ```\n */\nexport const GALACHAIN_CHANNELS = {\n /** Asset channel - where wrapped tokens (GMUSIC, GWETH, GALA, etc.) live */\n ASSET: 1,\n /** Music channel - where native MUSIC token lives (legacy) */\n MUSIC: 3,\n} as const;\n\n/** Type for internal GalaChain channel IDs */\nexport type GalaChainChannel = (typeof GALACHAIN_CHANNELS)[keyof typeof GALACHAIN_CHANNELS];\n\n/**\n * Check if a number is a valid GalaChain channel ID\n *\n * @param channel - Channel ID to validate\n * @returns True if valid GalaChain channel\n */\nexport function isValidGalaChainChannel(channel: number): channel is GalaChainChannel {\n return Object.values(GALACHAIN_CHANNELS).includes(channel as GalaChainChannel);\n}\n\n/**\n * Rate limit for GalaConnect API (requests per second)\n */\nexport const DEFAULT_RATE_LIMIT_RPS = 12;\n\n/**\n * Default polling interval for bridge status (15 seconds)\n */\nexport const DEFAULT_POLL_INTERVAL_MS = 15_000;\n\n/**\n * Default polling timeout (45 minutes)\n */\nexport const DEFAULT_POLL_TIMEOUT_MS = 45 * 60 * 1_000;\n\n/**\n * Delay before registering inbound bridge transactions (30 seconds)\n */\nexport const REGISTRATION_DELAY_MS = 30_000;\n\n/**\n * Solana compute budget settings\n */\nexport const SOLANA_COMPUTE = {\n UNIT_LIMIT: 200_000,\n UNIT_PRICE_MICROLAMPORTS: 375_000,\n} as const;\n\n/**\n * Default Ethereum RPC URL (public endpoint)\n *\n * **WARNING: Public RPC Endpoint Limitations**\n *\n * This is a free public endpoint with the following limitations:\n * - **Rate Limits**: Typically 10-25 requests/second (varies by provider load)\n * - **Reliability**: No SLA, may experience downtime during high network activity\n * - **Privacy**: Requests may be logged by the provider\n * - **Features**: May not support all RPC methods (e.g., trace_* calls)\n * - **Monitoring**: No error tracking, request analytics, or debugging tools available\n *\n * **For Production Use**, provide your own RPC URL from:\n * - Infura: https://infura.io (free tier: 100k requests/day)\n * - Alchemy: https://alchemy.com (free tier: 300M compute units/month)\n * - QuickNode: https://quicknode.com\n * - Your own Ethereum node\n *\n * @example\n * ```typescript\n * const bridgeService = new BridgeService({\n * ethereumRpcUrl: 'https://mainnet.infura.io/v3/YOUR_API_KEY',\n * // ... other config\n * });\n * ```\n */\nexport const DEFAULT_ETHEREUM_RPC_URL = 'https://ethereum.publicnode.com';\n\n/**\n * Default Solana RPC URL (public endpoint)\n *\n * **WARNING: Public RPC Endpoint Limitations**\n *\n * This is the official Solana public RPC with the following limitations:\n * - **Rate Limits**: Aggressive rate limiting (may return 429 errors under load)\n * - **Reliability**: Best-effort availability, no SLA\n * - **Performance**: Higher latency than dedicated endpoints\n * - **Features**: Some methods may be disabled or limited\n * - **Monitoring**: No error tracking, request analytics, or debugging tools available\n *\n * **For Production Use**, provide your own RPC URL from:\n * - Helius: https://helius.dev (free tier: 500k credits/month)\n * - QuickNode: https://quicknode.com\n * - Triton: https://triton.one\n * - Your own Solana validator\n *\n * @example\n * ```typescript\n * const bridgeService = new BridgeService({\n * solanaRpcUrl: 'https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY',\n * // ... other config\n * });\n * ```\n */\nexport const DEFAULT_SOLANA_RPC_URL = 'https://api.mainnet-beta.solana.com';\n\n/**\n * Default Ethereum bridge contract address (mainnet)\n */\nexport const DEFAULT_ETHEREUM_BRIDGE_CONTRACT = '0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9';\n\n/**\n * Ethereum bridge contract address for Sepolia testnet\n */\nexport const ETHEREUM_BRIDGE_CONTRACT_SEPOLIA = '0x6a1734E09f3099a3675645D214ce547080ea67e0';\n\n/**\n * Default Solana bridge program ID (mainnet)\n */\nexport const DEFAULT_SOLANA_BRIDGE_PROGRAM = 'AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS';\n\n/**\n * GalaConnect production base URL (DEX API platform)\n */\nexport const GALACONNECT_PRODUCTION_URL = 'https://dex-api-platform-dex-prod-gala.gala.com';\n\n/**\n * Ethereum tokens for bridging - Production (Mainnet)\n */\nexport const ETHEREUM_TOKENS_PROD: (EthereumTokenConfig & { decimals: number })[] = [\n {\n symbol: 'GALA',\n amount: '1',\n contractAddress: '0xd1d2Eb1B1e90B638588728b4130137D262C87cae',\n bridgeUsesPermit: true,\n decimals: 8,\n },\n {\n symbol: 'GWETH',\n amount: '0.0001',\n contractAddress: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n bridgeUsesPermit: false,\n decimals: 18,\n },\n {\n symbol: 'GUSDC',\n amount: '1',\n contractAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GUSDT',\n amount: '1',\n contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GWTRX',\n amount: '1',\n contractAddress: '0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GWBTC',\n amount: '0.00001',\n contractAddress: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599',\n bridgeUsesPermit: false,\n decimals: 8,\n },\n];\n\n/**\n * Ethereum tokens for bridging - Stage (Sepolia testnet)\n *\n * Note: GWTRX is not available on Sepolia\n */\nexport const ETHEREUM_TOKENS_STAGE: (EthereumTokenConfig & { decimals: number })[] = [\n {\n symbol: 'GALA',\n amount: '1',\n contractAddress: '0x9fBFf09325C1967A135AC9b4860b1cf89aca52DA',\n bridgeUsesPermit: true,\n decimals: 8,\n },\n {\n symbol: 'GWETH',\n amount: '0.0001',\n contractAddress: '0xC3F00B9CbC4221D85A66EEbe928551d0d8dD9158',\n bridgeUsesPermit: false,\n decimals: 18,\n },\n {\n symbol: 'GUSDC',\n amount: '1',\n contractAddress: '0x081e78E33bfa612b23A99ef61e7c194649AA318E',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GUSDT',\n amount: '1',\n contractAddress: '0x461e3595f087bfb0E32B6e44BCbF4C74D99B0001',\n bridgeUsesPermit: false,\n decimals: 6,\n },\n {\n symbol: 'GWBTC',\n amount: '0.00001',\n contractAddress: '0x5f69276935EF17e5aF5289b60aFBf6d48B344770',\n bridgeUsesPermit: false,\n decimals: 8,\n },\n];\n\n/** Bridge environment type for token selection */\nexport type BridgeEnvironment = 'prod' | 'stage';\n\n/**\n * Get Ethereum tokens by environment\n *\n * @param environment - Target environment (PROD or STAGE)\n * @returns Token configurations for the specified environment\n */\nexport function getEthereumTokensByEnvironment(\n environment: BridgeEnvironment,\n): (EthereumTokenConfig & { decimals: number })[] {\n return environment === 'prod' ? ETHEREUM_TOKENS_PROD : ETHEREUM_TOKENS_STAGE;\n}\n\n/**\n * Get Ethereum bridge contract address by environment\n *\n * @param environment - Target environment (PROD or STAGE)\n * @returns Bridge contract address for the specified environment\n */\nexport function getEthereumBridgeContractByEnvironment(environment: BridgeEnvironment): string {\n return environment === 'prod'\n ? DEFAULT_ETHEREUM_BRIDGE_CONTRACT\n : ETHEREUM_BRIDGE_CONTRACT_SEPOLIA;\n}\n\n/**\n * Default supported Solana tokens for bridging\n */\nexport const DEFAULT_SOLANA_TOKENS: (SolanaTokenConfig & { decimals: number })[] = [\n {\n symbol: 'GALA',\n amount: '1',\n mintAddress: 'eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6',\n isNative: false,\n decimals: 8,\n },\n {\n symbol: 'GSOL',\n amount: '0.001',\n mintAddress: 'So11111111111111111111111111111111111111111',\n isNative: true,\n decimals: 9,\n },\n];\n\n/**\n * Static token metadata for common bridge tokens\n *\n * This avoids API calls for well-known tokens.\n */\nexport const STATIC_TOKEN_METADATA: Record<string, BridgeTokenMetadata> = {\n GALA: {\n descriptor: { collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 8,\n channel: 'asset',\n },\n GWETH: {\n descriptor: { collection: 'GWETH', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 18,\n channel: 'asset',\n },\n GUSDC: {\n descriptor: { collection: 'GUSDC', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 6,\n channel: 'asset',\n },\n GUSDT: {\n descriptor: { collection: 'GUSDT', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 6,\n channel: 'asset',\n },\n GWTRX: {\n descriptor: { collection: 'GWTRX', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 6,\n channel: 'asset',\n },\n GWBTC: {\n descriptor: { collection: 'GWBTC', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 8,\n channel: 'asset',\n },\n GSOL: {\n descriptor: { collection: 'GSOL', category: 'Unit', type: 'none', additionalKey: 'none' },\n decimals: 9,\n channel: 'asset',\n },\n};\n\n/**\n * Ethereum ERC-20 ABI for bridge operations\n */\nexport const ERC20_ABI = [\n 'function decimals() view returns (uint8)',\n 'function balanceOf(address owner) view returns (uint256)',\n 'function approve(address spender, uint256 value) returns (bool)',\n 'function allowance(address owner, address spender) view returns (uint256)',\n 'function transfer(address to, uint256 value) returns (bool)',\n 'function name() view returns (string)',\n 'function nonces(address owner) view returns (uint256)',\n 'function permit(address owner,address spender,uint256 value,uint256 deadline,uint8 v,bytes32 r,bytes32 s)',\n] as const;\n\n/**\n * Ethereum bridge contract ABI\n */\nexport const BRIDGE_CONTRACT_ABI = [\n 'function bridgeOut(address token,uint256 amount,uint256 tokenId,uint16 destinationChainId,bytes recipient) external',\n 'function bridgeOutWithPermit(address token,uint256 amount,uint16 destinationChainId,bytes recipient,uint256 deadline,uint8 v,bytes32 r,bytes32 s) external',\n] as const;\n\n/**\n * Solana bridge instruction discriminators. Plain bytes: importing `./bridge` touches no `Buffer`\n * (React Native has none at load).\n */\nexport const SOLANA_DISCRIMINATORS = {\n BRIDGE_OUT: Uint8Array.from([27, 194, 57, 119, 215, 165, 247, 150]),\n BRIDGE_OUT_NATIVE: Uint8Array.from([243, 44, 75, 224, 249, 206, 98, 79]),\n} as const;\n\n/**\n * Get token metadata by symbol\n */\nexport function getStaticTokenMetadata(symbol: string): BridgeTokenMetadata | undefined {\n const upperSymbol = normalizeTokenSymbol(symbol);\n\n // Exact symbol only: a symbol is never rewritten (no \"USDC\" -> \"GUSDC\" guessing).\n return STATIC_TOKEN_METADATA[upperSymbol];\n}\n\n/**\n * Get Ethereum token config by symbol (mainnet tokens; see `getEthereumTokensByEnvironment`)\n */\nexport function getEthereumTokenConfig(symbol: string): EthereumTokenConfig | undefined {\n const upperSymbol = normalizeTokenSymbol(symbol);\n return ETHEREUM_TOKENS_PROD.find((t) => normalizeTokenSymbol(t.symbol) === upperSymbol);\n}\n\n/**\n * Get Solana token config by symbol\n */\nexport function getSolanaTokenConfig(symbol: string): SolanaTokenConfig | undefined {\n const upperSymbol = normalizeTokenSymbol(symbol);\n return DEFAULT_SOLANA_TOKENS.find((t) => normalizeTokenSymbol(t.symbol) === upperSymbol);\n}\n\n/**\n * Format a BridgeTokenDescriptor as a pipe-separated string\n * Uses centralized stringification from token-stringification.ts\n */\nexport function formatTokenDescriptor(descriptor: BridgeTokenDescriptor): string {\n return stringifyTokenClassKey(descriptor);\n}\n","/**\n * Bridge validation helpers: each refusal is a `GalaSDKError` with a catalog code (no English\n * message is built here).\n */\n\nimport { PublicKey } from '@solana/web3.js';\nimport { isAddress as isEthereumAddress } from 'ethers';\n\nimport { GalaSDKError } from '../../index.js';\nimport { fieldsOf } from '../internal/values.js';\n\n// ==========================================================================\n// Token Symbol Validation\n// ==========================================================================\n\n/**\n * Validate that a token symbol was resolved (BridgeService resolves `tokenId` to it before it\n * calls a strategy; a strategy called directly needs it set).\n *\n * @param symbol - The resolved token symbol (may be undefined)\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`tokenSymbol`, `missing`) if undefined or empty\n * @returns The validated symbol (type-narrowed to string)\n *\n * @example\n * ```typescript\n * const tokenSymbol = assertTokenSymbolResolved(params.tokenSymbol);\n * ```\n */\nexport function assertTokenSymbolResolved(symbol: string | undefined): string {\n if (symbol === undefined || symbol === '') {\n throw new GalaSDKError('INVALID_TOKEN_REFERENCE', { field: 'tokenSymbol', reason: 'missing' });\n }\n return symbol;\n}\n\n// ==========================================================================\n// Bridge Response Validation\n// ==========================================================================\n\n/**\n * Assert that GalaChain did not refuse a bridge write: an answer with a numeric `Status` other\n * than 1 is its refusal, `BRIDGE_REQUEST_REJECTED` (`chainStatus`, its `ErrorKey` and `Message`;\n * the chain's own `ErrorCode` as `status` when the answer has one, which is what says whether the\n * refusal is definite: a 409 is a uniqueKey already consumed). Any other answer passes.\n *\n * @param method - The write (`RequestTokenBridgeOut`, `BridgeTokenOut`)\n * @param answer - GalaConnect's answer\n * @param uniqueKey - The write's uniqueKey, when it has one\n */\nexport function assertRequestAccepted(method: string, answer: unknown, uniqueKey?: string): void {\n const fields = fieldsOf(answer);\n const chainStatus = fields['Status'];\n if (typeof chainStatus !== 'number' || chainStatus === 1) {\n return;\n }\n const text = (key: string): string => {\n const value = fields[key];\n return typeof value === 'string' ? value : '';\n };\n const errorCode = fields['ErrorCode'];\n throw new GalaSDKError(\n 'BRIDGE_REQUEST_REJECTED',\n { method, chainStatus, errorKey: text('ErrorKey'), serverMessage: text('Message') },\n {\n write: true,\n body: answer,\n ...(typeof errorCode === 'number' && { status: errorCode }),\n ...(uniqueKey !== undefined && { uniqueKey }),\n },\n );\n}\n\n/**\n * Assert that a bridge request ID was returned from RequestTokenBridgeOut.\n *\n * @param bridgeRequestId - The extracted bridge request ID (may be undefined)\n * @throws GalaSDKError `BRIDGE_RESPONSE_INVALID` if undefined or empty (the request may have been\n * registered)\n * @returns The validated bridge request ID\n */\nexport function assertBridgeRequestId(bridgeRequestId: string | undefined): string {\n if (bridgeRequestId === undefined || bridgeRequestId === '') {\n throw new GalaSDKError('BRIDGE_RESPONSE_INVALID', {\n method: 'RequestTokenBridgeOut',\n missing: 'bridge request id',\n });\n }\n return bridgeRequestId;\n}\n\n/**\n * Extract and validate the transaction hash from a BridgeTokenOut response.\n *\n * Handles multiple response formats (Hash vs hash).\n *\n * @param response - The BridgeTokenOut API response (any value: an empty answer is `undefined`)\n * @throws GalaSDKError `BRIDGE_RESPONSE_INVALID` if there is no non-empty string `Hash` or `hash`\n * (the bridge-out may have been submitted)\n * @returns The validated transaction hash\n */\nexport function extractBridgeOutTransactionHash(response: unknown): string {\n const fields = fieldsOf(response);\n const transactionHash = [fields['Hash'], fields['hash']].find(\n (value): value is string => typeof value === 'string' && value !== '',\n );\n if (transactionHash === undefined) {\n throw new GalaSDKError('BRIDGE_RESPONSE_INVALID', {\n method: 'BridgeTokenOut',\n missing: 'transaction hash',\n });\n }\n return transactionHash;\n}\n\n// ==========================================================================\n// Address Validation with Errors\n// ==========================================================================\n\n/**\n * Validate an Ethereum address.\n *\n * @param address - The address to validate\n * @param context - The field it is (default `address`), e.g. `recipient`\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if it is not a valid Ethereum address\n *\n * @example\n * ```typescript\n * validateEthereumAddressOrThrow(recipientAddress, 'recipient');\n * ```\n */\nexport function validateEthereumAddressOrThrow(address: string, context?: string): void {\n if (!isEthereumAddress(address)) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', {\n field: context ?? 'address',\n value: String(address),\n });\n }\n}\n\n/**\n * Validate a Solana address.\n *\n * @param address - The address to validate\n * @param context - The field it is (default `address`), e.g. `recipient`\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if it is not a valid Solana address\n * @returns The validated PublicKey object\n *\n * @example\n * ```typescript\n * const pubkey = validateSolanaAddressOrThrow(recipientAddress, 'recipient');\n * ```\n */\nexport function validateSolanaAddressOrThrow(address: string, context?: string): PublicKey {\n try {\n return new PublicKey(address);\n } catch {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', {\n field: context ?? 'address',\n value: String(address),\n });\n }\n}\n\n/**\n * Parse a Solana address to a PublicKey.\n *\n * @param address - The address to parse\n * @returns The PublicKey object\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if the address is invalid\n */\nexport function parseSolanaAddressOrThrow(address: string): PublicKey {\n return validateSolanaAddressOrThrow(address);\n}\n\n// ==========================================================================\n// Configuration Options\n// ==========================================================================\n\n/**\n * An RPC URL option: an `http:` or `https:` URL.\n *\n * @param value - The option's value\n * @param option - The option's name (for the refusal)\n * @returns The URL as given\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`option`) otherwise\n */\nexport function assertHttpUrlOption(value: string, option: string): string {\n let protocol = '';\n try {\n protocol = new URL(value).protocol;\n } catch {\n // not a URL at all: refused below\n }\n if (protocol !== 'http:' && protocol !== 'https:') {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option });\n }\n return value;\n}\n\n/**\n * An Ethereum address option (a contract or an account).\n *\n * @param value - The option's value\n * @param option - The option's name (for the refusal)\n * @returns The address as given\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`option`) for what is not an Ethereum address\n */\nexport function assertEthereumAddressOption(value: string, option: string): string {\n if (typeof value !== 'string' || !isEthereumAddress(value)) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option });\n }\n return value;\n}\n\n/**\n * A Solana public key option (a program id).\n *\n * @param value - The option's value (base58)\n * @param option - The option's name (for the refusal)\n * @returns The public key\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`option`) for what is not a 32-byte base58 key\n */\nexport function solanaPublicKeyOption(value: string, option: string): PublicKey {\n try {\n if (typeof value === 'string' && value !== '') return new PublicKey(value);\n } catch {\n // not a public key: refused below\n }\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option });\n}\n","/**\n * Rate Limiter\n *\n * Serializes API calls and keeps a minimum interval between their starts, so the backend is\n * never sent more than `requestsPerSecond` requests.\n */\n\nimport { GalaSDKError } from '../../index.js';\n\n/**\n * Rate limiter that ensures a minimum interval between requests. Tasks run one at a time, in the\n * order they were scheduled; the interval is measured between task starts.\n */\nexport class RateLimiter {\n private readonly minIntervalMs: number;\n private lastTimestamp = 0;\n private pendingPromise: Promise<void> = Promise.resolve();\n\n /**\n * Create a new rate limiter\n *\n * @param requestsPerSecond - Maximum requests per second\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`requestsPerSecond`) unless it is a number above\n * zero (`NaN` would silently disable the limit)\n */\n constructor(requestsPerSecond: number) {\n if (!(requestsPerSecond > 0)) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'requestsPerSecond' });\n }\n this.minIntervalMs = 1000 / requestsPerSecond;\n }\n\n /**\n * Schedule a task to run within rate limits. Tasks run serially, inside the chain, so\n * concurrent callers can never exceed the limit.\n *\n * @param task - The async task to execute\n * @returns The result of the task; its failure (whatever it threw) as the rejection\n */\n schedule<T>(task: () => Promise<T>): Promise<T> {\n const run = this.pendingPromise.then(async () => {\n const waitTime = this.minIntervalMs - (Date.now() - this.lastTimestamp);\n if (waitTime > 0) {\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n this.lastTimestamp = Date.now();\n return task();\n });\n // The next task waits for this one to settle, whether it succeeded or not; a settled chain\n // link holds no reference to earlier ones.\n this.pendingPromise = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n","/**\n * Retry Utility\n *\n * Provides exponential backoff retry logic for transient network failures.\n */\n\nimport { getErrorCode, getErrorMessage } from '../internal/values.js';\n\n/**\n * Configuration options for retry behavior.\n */\nexport interface RetryOptions {\n /**\n * Maximum number of retry attempts (default: 3)\n */\n maxRetries?: number;\n\n /**\n * Initial delay in milliseconds before first retry (default: 1000)\n */\n initialDelayMs?: number;\n\n /**\n * Maximum delay in milliseconds between retries (default: 30000)\n */\n maxDelayMs?: number;\n\n /**\n * Multiplier for exponential backoff (default: 2)\n */\n backoffMultiplier?: number;\n\n /**\n * Jitter factor to add randomness to delays (0-1, default: 0.1)\n * Helps prevent thundering herd problems.\n */\n jitterFactor?: number;\n\n /**\n * Custom function to determine if an error should trigger a retry.\n * Default: retries on network errors and 5xx/429 status codes.\n */\n shouldRetry?: (error: unknown, attempt: number) => boolean;\n\n /**\n * Callback invoked before each retry attempt.\n * Useful for logging or metrics.\n */\n onRetry?: (error: unknown, attempt: number, delayMs: number) => void;\n}\n\n/**\n * Default retry options.\n */\nconst DEFAULT_RETRY_OPTIONS: Required<Omit<RetryOptions, 'onRetry' | 'shouldRetry'>> = {\n maxRetries: 3,\n initialDelayMs: 1000,\n maxDelayMs: 30_000,\n backoffMultiplier: 2,\n jitterFactor: 0.1,\n};\n\n/**\n * HTTP status codes that should trigger a retry.\n */\nconst RETRYABLE_STATUS_CODES = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/**\n * Error messages that indicate transient network issues.\n */\nconst RETRYABLE_ERROR_PATTERNS = [\n /ECONNRESET/i,\n /ECONNREFUSED/i,\n /ETIMEDOUT/i,\n /ENOTFOUND/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /network/i,\n /timeout/i,\n /aborted/i,\n];\n\n/**\n * Determines if an error is retryable based on its characteristics.\n *\n * @param error - The error to evaluate\n * @returns True if the error should trigger a retry\n */\nexport function isRetryableError(error: unknown): boolean {\n // Check for HTTP status codes\n if (error !== null && error !== undefined && typeof error === 'object') {\n const errorObj = error as Record<string, unknown>;\n\n // Check status property (common in HTTP errors)\n if (typeof errorObj['status'] === 'number') {\n return RETRYABLE_STATUS_CODES.has(errorObj['status']);\n }\n\n // Check statusCode property (alternative naming)\n if (typeof errorObj['statusCode'] === 'number') {\n return RETRYABLE_STATUS_CODES.has(errorObj['statusCode']);\n }\n\n // Check code property (Node.js errors)\n const code = getErrorCode(error);\n if (typeof code === 'string') {\n if (\n code === 'ECONNRESET' ||\n code === 'ECONNREFUSED' ||\n code === 'ETIMEDOUT' ||\n code === 'ENOTFOUND' ||\n code === 'EAI_AGAIN'\n ) {\n return true;\n }\n }\n }\n\n // Check error message for retryable patterns\n const message = getErrorMessage(error);\n return RETRYABLE_ERROR_PATTERNS.some((pattern) => pattern.test(message));\n}\n\n/**\n * Calculates the delay before the next retry attempt using exponential backoff with jitter.\n *\n * @param attempt - Current attempt number (1-based)\n * @param options - Retry configuration options\n * @returns Delay in milliseconds\n */\nexport function calculateRetryDelay(\n attempt: number,\n options: Required<Omit<RetryOptions, 'onRetry' | 'shouldRetry'>>,\n): number {\n // Calculate base delay with exponential backoff\n const baseDelay = options.initialDelayMs * Math.pow(options.backoffMultiplier, attempt - 1);\n\n // Apply maximum cap\n const cappedDelay = Math.min(baseDelay, options.maxDelayMs);\n\n // Add jitter to prevent thundering herd\n const jitter = cappedDelay * options.jitterFactor * Math.random();\n\n return Math.floor(cappedDelay + jitter);\n}\n\n/**\n * Executes an async function with exponential backoff retry logic.\n *\n * @param fn - The async function to execute\n * @param options - Retry configuration options\n * @returns The result of the function\n * @throws The last error if all retries are exhausted\n *\n * @example\n * ```typescript\n * const result = await withRetry(\n * () => fetch('https://api.example.com/data'),\n * {\n * maxRetries: 3,\n * onRetry: (error, attempt, delay) => {\n * console.log(`Retry ${attempt} after ${delay}ms: ${error}`);\n * },\n * }\n * );\n * ```\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const resolvedOptions = {\n ...DEFAULT_RETRY_OPTIONS,\n ...options,\n };\n\n const shouldRetry = options.shouldRetry ?? ((error: unknown) => isRetryableError(error));\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= resolvedOptions.maxRetries + 1; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n\n // Check if we've exhausted retries\n if (attempt > resolvedOptions.maxRetries) {\n break;\n }\n\n // Check if error is retryable\n if (!shouldRetry(error, attempt)) {\n break;\n }\n\n // Calculate delay for next retry\n const delayMs = calculateRetryDelay(attempt, resolvedOptions);\n\n // Invoke onRetry callback if provided\n if (options.onRetry) {\n options.onRetry(error, attempt, delayMs);\n }\n\n // Wait before retrying\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n\n // All retries exhausted or non-retryable error\n throw lastError;\n}\n\n/**\n * Simple delay utility for async operations.\n *\n * @param ms - Delay duration in milliseconds\n * @returns Promise that resolves after the specified delay\n *\n * @example\n * ```typescript\n * // Wait 1 second before continuing\n * await delay(1000);\n *\n * // Wait before registration\n * await delay(REGISTRATION_DELAY_MS);\n * ```\n */\nexport function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * GalaConnect Bridge Client\n *\n * HTTP client for the GalaConnect bridge API (the DEX API platform) and the gateway balance read\n * the bridge uses: rate limiting, the wallet header, and the retry policy, moved from launchpad-sdk\n * with the same requests on the wire (recorded vectors: tests/fixtures/galaconnect-wire-recorded.json).\n *\n * Failures are `GalaSDKError`s:\n * - an HTTP status other than 2xx: `GALACONNECT_HTTP_ERROR` (`status`, the body as `error.body`);\n * - no answer (the request failed in transit): a read's `TRANSPORT_ERROR` (`write: false`), a\n * write's `BRIDGE_WRITE_OUTCOME_UNKNOWN` (the request may have reached GalaConnect);\n * - no complete answer within `requestTimeoutMs`: a read's `REQUEST_TIMEOUT` (`write: false`), a\n * write's `BRIDGE_WRITE_OUTCOME_UNKNOWN` (that timeout as cause);\n * - an answer that is not the JSON the call needs: a read's `BRIDGE_READ_RESPONSE_INVALID`, a\n * write's `BRIDGE_RESPONSE_INVALID`.\n * The writes are `requestBridgeOut`, `bridgeTokenOut` and `registerBridgeTransaction`; every\n * other call is a read (`error.write === false`). A write's error carries the payload's\n * `uniqueKey` when it has one.\n */\n\nimport { GalaSDKError, galaChainUserRef, validateTimeoutMs, type HttpRequestor } from '../index.js';\nimport { GALACONNECT_PRODUCTION_URL } from './constants/tokens.js';\nimport { safeParseJson } from './internal/values.js';\nimport { assertHttpUrlOption } from './utils/bridgeErrors.js';\nimport type {\n BridgeConfigurationToken,\n BridgeFeeResponse,\n BridgeStatusResponse,\n BridgeTokenDescriptor,\n BridgeTokenOutResponse,\n BridgeTransactionRegistrationResponse,\n FetchBalancesResponse,\n GalaConnectConfig,\n RequestBridgeOutResponse,\n} from './types/index.js';\nimport { RateLimiter } from './utils/RateLimiter.js';\nimport { isRetryableError, withRetry, type RetryOptions } from './utils/retry.js';\n\nconst DEFAULT_CONFIG: Required<\n Omit<GalaConnectConfig, 'walletAddress' | 'onRetry' | 'httpRequestor'>\n> = {\n baseUrl: GALACONNECT_PRODUCTION_URL,\n galachainBaseUrl: 'https://galachain-gateway-chain-platform-galachain-mainnet.gala.com',\n requestsPerSecond: 12,\n requestTimeoutMs: 30_000,\n enableRetry: true,\n maxRetries: 3,\n retryInitialDelayMs: 1000,\n};\n\n/** The longest server text an error keeps (`serverMessage`, a raw body). */\nconst MAX_ERROR_BODY_LENGTH = 500;\n\n/** One call: the path, and whether it is a write (with the payload's uniqueKey, if any). */\ninterface Operation {\n readonly path: string;\n readonly write: boolean;\n readonly uniqueKey?: string | undefined;\n}\n\n/** A response, read once. */\ninterface Answer {\n readonly ok: boolean;\n readonly status: number;\n readonly text: string;\n}\n\n/** The error context of a failure of `op`: read or write, and the write's uniqueKey. */\nfunction contextOf(op: Operation): { write: boolean; uniqueKey?: string } {\n return op.uniqueKey === undefined\n ? { write: op.write }\n : { write: true, uniqueKey: op.uniqueKey };\n}\n\n/** The `uniqueKey` a write payload carries, when it carries one. */\nfunction uniqueKeyOf(payload: Record<string, unknown>): string | undefined {\n const key = payload['uniqueKey'];\n return typeof key === 'string' && key !== '' ? key : undefined;\n}\n\n/** `GALACONNECT_HTTP_ERROR` for an answer of status `status` and body text `text`. */\nfunction httpFailure(op: Operation, url: string, status: number, text: string): GalaSDKError {\n const body: unknown = safeParseJson(text, { rawBody: text.slice(0, MAX_ERROR_BODY_LENGTH) });\n return new GalaSDKError(\n 'GALACONNECT_HTTP_ERROR',\n { method: op.path, status, serverMessage: text.slice(0, MAX_ERROR_BODY_LENGTH) },\n { ...contextOf(op), status, body, url },\n );\n}\n\n/** The failure of a request that got no (complete) answer: a read is transient, a write unknown. */\nfunction transportFailure(op: Operation, url: string, cause: unknown): GalaSDKError {\n return op.write\n ? new GalaSDKError(\n 'BRIDGE_WRITE_OUTCOME_UNKNOWN',\n { method: op.path },\n { ...contextOf(op), url, cause },\n )\n : new GalaSDKError('TRANSPORT_ERROR', { url }, { write: false, url, cause });\n}\n\n/**\n * A request that ran out of time: a read is `REQUEST_TIMEOUT` (`write: false`), a write\n * `BRIDGE_WRITE_OUTCOME_UNKNOWN` (it may have reached GalaConnect) with that timeout as cause.\n */\nfunction timeoutFailure(\n op: Operation,\n url: string,\n timeoutMs: number,\n cause: unknown,\n): GalaSDKError {\n const timeout = new GalaSDKError(\n 'REQUEST_TIMEOUT',\n { url, timeoutMs },\n { ...contextOf(op), url, cause },\n );\n return op.write ? transportFailure(op, url, timeout) : timeout;\n}\n\n/** An answer that is not the JSON `op` needs. */\nfunction invalidAnswer(op: Operation, url: string): GalaSDKError {\n return op.write\n ? new GalaSDKError(\n 'BRIDGE_RESPONSE_INVALID',\n { method: op.path, missing: 'JSON answer' },\n { ...contextOf(op), url },\n )\n : new GalaSDKError('BRIDGE_READ_RESPONSE_INVALID', { method: op.path }, { write: false, url });\n}\n\n/**\n * The JSON of a 2xx answer to `op` (`undefined` for an empty one).\n *\n * @throws GalaSDKError `GALACONNECT_HTTP_ERROR` for another status; for an answer that is not\n * JSON, a read's `BRIDGE_READ_RESPONSE_INVALID` or a write's `BRIDGE_RESPONSE_INVALID`\n */\nfunction readJson(op: Operation, url: string, answer: Answer): unknown {\n if (!answer.ok) {\n throw httpFailure(op, url, answer.status, answer.text);\n }\n if (answer.text === '') {\n return undefined;\n }\n try {\n return JSON.parse(answer.text) as unknown;\n } catch {\n throw invalidAnswer(op, url);\n }\n}\n\n/**\n * Whether a failed attempt of `op` is sent again (with retries on). A 429 was refused before\n * anything was done: sent again, a write too. A read is also sent again after a 5xx or a\n * transport failure whose own error is retryable (a connection reset, a DNS failure, a timeout);\n * a WRITE never is, because it may have been applied (its error says so, with its uniqueKey). An\n * attempt fails only with the `GalaSDKError` of `httpFailure`, `transportFailure` or\n * `timeoutFailure` (`request` wraps every failure).\n */\nfunction shouldRetryAttempt(error: unknown, op: Operation): boolean {\n const failure = error as GalaSDKError;\n if (failure.code === 'GALACONNECT_HTTP_ERROR') {\n return failure.status === 429 || (!op.write && isRetryableError({ status: failure.status }));\n }\n return !op.write && isRetryableError(failure.cause);\n}\n\n/**\n * GalaConnect API client\n *\n * Handles all HTTP communication with the GalaConnect bridge API.\n */\nexport class GalaConnectClient {\n private readonly baseUrl: string;\n private readonly galachainBaseUrl: string;\n private readonly walletAddress: string;\n private readonly rateLimiter: RateLimiter;\n private readonly defaultHeaders: Record<string, string>;\n private readonly retryOptions: RetryOptions | null;\n private readonly requestor: HttpRequestor;\n private readonly requestTimeoutMs: number;\n\n /**\n * Creates a new GalaConnect client.\n *\n * @param config - Client configuration (`httpRequestor` defaults to the global `fetch`).\n * `walletAddress` is sent (the `X-Wallet-Address` header, the gateway balance read's `owner`)\n * in the gateway's spelling: an Ethereum account in any form as `eth|<checksummed>`, a `client|`\n * alias as written; `''` is a client with no wallet (the public token lists).\n * @throws GalaSDKError `INVALID_TIMEOUT` for a `requestTimeoutMs` that is not a positive number\n * of milliseconds or `Infinity`; `INVALID_BRIDGE_OPTION` (`baseUrl`, `galachainBaseUrl`) for a\n * URL that is not http(s); (`requestsPerSecond`) for a rate that is not above zero;\n * `INVALID_WALLET_ADDRESS` (`walletAddress`) for a wallet address that is no user reference\n */\n constructor(config: GalaConnectConfig) {\n this.requestTimeoutMs = validateTimeoutMs(\n config.requestTimeoutMs ?? DEFAULT_CONFIG.requestTimeoutMs,\n 'requestTimeoutMs',\n );\n // A malformed URL is refused here: sent, it would fail as if in transit (a write: outcome unknown)\n this.baseUrl = assertHttpUrlOption(config.baseUrl ?? DEFAULT_CONFIG.baseUrl, 'baseUrl');\n this.galachainBaseUrl = assertHttpUrlOption(\n config.galachainBaseUrl ?? DEFAULT_CONFIG.galachainBaseUrl,\n 'galachainBaseUrl',\n );\n // Sent to the gateway as is, so spelled the one way it accepts ('' = no wallet: public reads).\n this.walletAddress =\n config.walletAddress === '' ? '' : galaChainUserRef(config.walletAddress, 'walletAddress');\n this.rateLimiter = new RateLimiter(\n config.requestsPerSecond ?? DEFAULT_CONFIG.requestsPerSecond,\n );\n this.requestor = config.httpRequestor ?? ((url, init) => globalThis.fetch(url, init));\n this.defaultHeaders = {\n 'Content-Type': 'application/json',\n 'X-Wallet-Address': this.walletAddress,\n };\n\n const enableRetry = config.enableRetry ?? DEFAULT_CONFIG.enableRetry;\n this.retryOptions = enableRetry\n ? {\n maxRetries: config.maxRetries ?? DEFAULT_CONFIG.maxRetries,\n initialDelayMs: config.retryInitialDelayMs ?? DEFAULT_CONFIG.retryInitialDelayMs,\n // Only include onRetry if defined (exactOptionalPropertyTypes compliance)\n ...(config.onRetry && { onRetry: config.onRetry }),\n }\n : null;\n }\n\n /**\n * Get the base URL for constructing status URLs.\n *\n * @returns The GalaConnect API base URL\n */\n public getBaseUrl(): string {\n return this.baseUrl;\n }\n\n /**\n * Get bridge configurations for tokens matching a prefix.\n *\n * Returns detailed token information including:\n * - Token class key (collection, category, type, additionalKey)\n * - Supported bridge routes\n * - External network contract addresses\n *\n * @param searchPrefix - Token symbol prefix to search (e.g., 'GALA', 'GUS')\n * @returns Array of matching token configurations\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` unless the answer has `data.tokens` (an array)\n */\n async getBridgeConfigurations(searchPrefix: string): Promise<BridgeConfigurationToken[]> {\n const op: Operation = { path: '/v1/connect/bridge-configurations', write: false };\n const url = new URL(op.path, this.baseUrl);\n url.searchParams.set('searchprefix', searchPrefix);\n const answer = await this.send(url.toString(), { method: 'GET' }, op);\n if (!answer.ok) {\n throw httpFailure(op, url.toString(), answer.status, answer.text);\n }\n const json = safeParseJson<{ data?: { tokens?: unknown } } | null>(answer.text, null);\n const tokens = json?.data?.tokens;\n if (!Array.isArray(tokens)) {\n throw invalidAnswer(op, url.toString());\n }\n return tokens as BridgeConfigurationToken[];\n }\n\n /**\n * A GET of the DEX API platform (`baseUrl`): `url` with `params` as its query, the JSON answer\n * (a `DexApiReader`, which the token services read the token lists through). A read: a failure\n * is `GALACONNECT_HTTP_ERROR`, `TRANSPORT_ERROR`, `REQUEST_TIMEOUT` or, for an answer that is\n * not JSON, `BRIDGE_READ_RESPONSE_INVALID`, each with `write: false`.\n *\n * @param config - The path and its query\n * @returns The parsed JSON answer (`undefined` for an empty one)\n */\n async request<T>(config: {\n method: 'GET';\n url: string;\n params: Record<string, string | number | boolean>;\n }): Promise<T> {\n const op: Operation = { path: config.url, write: false };\n const url = new URL(config.url, this.baseUrl);\n for (const [name, value] of Object.entries(config.params)) {\n url.searchParams.set(name, String(value));\n }\n return readJson(\n op,\n url.toString(),\n await this.send(url.toString(), { method: 'GET' }, op),\n ) as T;\n }\n\n /**\n * Fetch bridge fee estimate for a token transfer.\n *\n * @param payload - Fee request parameters\n * @returns Fee estimate with breakdown\n */\n async fetchBridgeFee(payload: {\n chainId: string;\n bridgeToken: BridgeTokenDescriptor;\n }): Promise<BridgeFeeResponse> {\n // Fee endpoint is on the DEX API platform (baseUrl), not GalaChain Gateway\n // It's a public endpoint that doesn't require wallet authentication\n return this.postJson<BridgeFeeResponse>({ path: '/v1/bridge/fee', write: false }, payload, {\n skipWalletHeader: true,\n });\n }\n\n /**\n * Request token bridge out (initiate GalaChain → External transfer).\n *\n * This is the first step in the bridge out process:\n * 1. RequestBridgeOut - Lock tokens on GalaChain\n * 2. BridgeTokenOut - Generate wormhole message\n *\n * @param payload - Bridge out request parameters\n * @returns Response with transaction data\n */\n async requestBridgeOut(payload: Record<string, unknown>): Promise<RequestBridgeOutResponse> {\n return this.postJson<RequestBridgeOutResponse>(\n { path: '/v1/RequestTokenBridgeOut', write: true, uniqueKey: uniqueKeyOf(payload) },\n payload,\n );\n }\n\n /**\n * Execute bridge token out (generate wormhole message).\n *\n * This is the second step in the bridge out process.\n * Called after RequestBridgeOut succeeds.\n *\n * @param payload - Bridge token out parameters\n * @returns Response with wormhole message data\n */\n async bridgeTokenOut(payload: Record<string, unknown>): Promise<BridgeTokenOutResponse> {\n return this.postJson<BridgeTokenOutResponse>(\n { path: '/v1/BridgeTokenOut', write: true, uniqueKey: uniqueKeyOf(payload) },\n payload,\n );\n }\n\n /**\n * Get the status of a bridge transaction.\n *\n * @param hash - Transaction hash to check\n * @returns Current status with details\n */\n async getBridgeStatus(hash: string): Promise<BridgeStatusResponse> {\n return this.postJson<BridgeStatusResponse>(\n { path: '/v1/bridge/status', write: false },\n { hash },\n );\n }\n\n /**\n * Register a bridge transaction (for External → GalaChain transfers).\n *\n * Called after depositing tokens to the bridge contract on the external chain.\n * Notifies GalaConnect to process the inbound transfer.\n *\n * @param payload - Transaction registration data\n * @returns Registration response\n */\n async registerBridgeTransaction(\n payload: Record<string, unknown>,\n ): Promise<BridgeTransactionRegistrationResponse> {\n return this.postJson<BridgeTransactionRegistrationResponse>(\n { path: '/v1/bridge/transaction', write: true, uniqueKey: uniqueKeyOf(payload) },\n payload,\n );\n }\n\n /**\n * Fetch token balances for the wallet.\n *\n * @param channel - Token channel (default: 'asset')\n * @returns Balance response with token holdings\n */\n async fetchBalances(channel = 'asset'): Promise<FetchBalancesResponse> {\n return this.postJson<FetchBalancesResponse>(\n { path: '/v1/FetchBalances', write: false },\n { owner: this.walletAddress, channel },\n { baseUrl: this.galachainBaseUrl },\n );\n }\n\n /**\n * POSTs `body` (bigints as decimal strings) as JSON and reads the JSON answer; an empty answer\n * is `undefined`.\n */\n private async postJson<T>(\n op: Operation,\n body: unknown,\n options: { baseUrl?: string; skipWalletHeader?: boolean } = {},\n ): Promise<T> {\n const url = new URL(op.path, options.baseUrl ?? this.baseUrl).toString();\n // Build headers - optionally skip wallet header for public endpoints\n const headers: Record<string, string> = options.skipWalletHeader\n ? { 'Content-Type': 'application/json', 'X-Wallet-Address': '' } // Empty string = skip\n : this.defaultHeaders;\n const answer = await this.send(\n url,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body, (_, value: unknown) =>\n typeof value === 'bigint' ? value.toString() : value,\n ),\n },\n op,\n );\n return readJson(op, url, answer) as T;\n }\n\n /**\n * Sends one request through the rate limiter (and, with retries on, again after a retryable\n * failure) and reads the answer once.\n */\n private async send(url: string, init: RequestInit, op: Operation): Promise<Answer> {\n const attempt = (): Promise<Answer> =>\n this.rateLimiter.schedule(async () => {\n const headers: Record<string, string> = {\n ...this.defaultHeaders,\n ...(init.headers as Record<string, string> | undefined),\n };\n // An empty X-Wallet-Address opts out of the header (public endpoints).\n if (headers['X-Wallet-Address'] === '') {\n delete headers['X-Wallet-Address'];\n }\n let answer: Answer;\n // One limit for the answer AND its body: a body that stalls is aborted too.\n const controller = new AbortController();\n const timer =\n this.requestTimeoutMs === Infinity\n ? undefined\n : setTimeout(() => controller.abort(), this.requestTimeoutMs);\n try {\n const response = await this.requestor(url, {\n ...init,\n headers,\n signal: controller.signal,\n });\n answer = { ok: response.ok, status: response.status, text: await response.text() };\n } catch (error: unknown) {\n throw controller.signal.aborted\n ? timeoutFailure(op, url, this.requestTimeoutMs, error)\n : transportFailure(op, url, error);\n } finally {\n clearTimeout(timer);\n }\n // With retries on, a 429 or 5xx is thrown here so the retry wrapper decides whether to\n // send it again (see shouldRetryAttempt).\n if (this.retryOptions && !answer.ok && (answer.status === 429 || answer.status >= 500)) {\n throw httpFailure(op, url, answer.status, answer.text);\n }\n return answer;\n });\n return this.retryOptions\n ? withRetry(attempt, {\n ...this.retryOptions,\n shouldRetry: (error: unknown) => shouldRetryAttempt(error, op),\n })\n : attempt();\n }\n}\n","/**\n * Address Validation Utilities\n *\n * Shared functions for validating Ethereum addresses, keys and transaction hashes, and the bridge\n * token configuration lookups. A GalaChain user reference is spelled by the root's\n * `galaChainUserRef` (the one implementation the gateway reads, writes and the bridge share).\n */\n\nimport { isAddress as isEthereumAddress } from 'ethers';\n\nimport { GalaSDKError } from '../../index.js';\nimport { normalizeTokenSymbol as normalizeTokenKey } from '../internal/values.js';\n\n/**\n * Validate an Ethereum address format.\n *\n * @param address - Address to validate\n * @returns True if valid Ethereum address\n *\n * @example\n * ```typescript\n * isValidEthereumAddress('0x1234567890123456789012345678901234567890'); // true\n * isValidEthereumAddress('invalid'); // false\n * ```\n */\nexport function isValidEthereumAddress(address: string): boolean {\n return isEthereumAddress(address);\n}\n\n/**\n * Validate Ethereum private key format.\n *\n * Checks for 0x-prefixed 64-character hex string format.\n * Does NOT validate the key on-chain, just format checking.\n *\n * @param privateKey - Private key to validate\n * @returns True if key matches expected format\n *\n * @example\n * ```typescript\n * isValidEthereumPrivateKeyFormat('0x1234...abcd'); // true (if 64 hex chars)\n * isValidEthereumPrivateKeyFormat('1234...abcd'); // false (missing 0x)\n * ```\n */\nexport function isValidEthereumPrivateKeyFormat(privateKey: string): boolean {\n return /^0x[a-fA-F0-9]{64}$/.test(privateKey);\n}\n\n/**\n * Validate Ethereum transaction hash format.\n *\n * Checks for 0x-prefixed 64-character hex string format.\n *\n * @param hash - Transaction hash to validate\n * @returns True if hash matches expected format\n *\n * @example\n * ```typescript\n * isValidEthereumTransactionHash('0x1234...abcd'); // true (if 64 hex chars)\n * isValidEthereumTransactionHash('1234...abcd'); // false (missing 0x)\n * ```\n */\nexport function isValidEthereumTransactionHash(hash: string): boolean {\n return /^0x[a-fA-F0-9]{64}$/.test(hash);\n}\n\n// ==========================================================================\n// Token Configuration Utilities\n// ==========================================================================\n\n/**\n * Generic token configuration type for bridge tokens.\n * Both EthereumTokenConfig and SolanaTokenConfig share these base fields.\n */\nexport interface BaseTokenConfig {\n /** Token symbol (e.g., 'GALA', 'GWETH') */\n symbol: string;\n /** Token decimals */\n decimals?: number;\n}\n\n/**\n * Create a token config lookup map from an array of configs.\n *\n * Normalizes symbols to uppercase for case-insensitive lookup.\n *\n * @param configs - Array of token configurations\n * @returns Map keyed by uppercase symbol\n *\n * @example\n * ```typescript\n * const configs = [{ symbol: 'GALA', decimals: 8 }, { symbol: 'GWETH', decimals: 18 }];\n * const map = createTokenConfigMap(configs);\n * map.get('gala'); // undefined (use uppercase)\n * map.get('GALA'); // { symbol: 'GALA', decimals: 8 }\n * ```\n */\nexport function createTokenConfigMap<T extends BaseTokenConfig>(configs: T[]): Map<string, T> {\n const map = new Map<string, T>();\n for (const config of configs) {\n map.set(normalizeTokenKey(config.symbol), config);\n }\n return map;\n}\n\n/**\n * Get a token config from a map by symbol (case-insensitive).\n *\n * @param configs - Token config map\n * @param symbol - Token symbol to look up\n * @returns Token config or undefined if not found\n */\nexport function getTokenConfig<T extends BaseTokenConfig>(\n configs: Map<string, T>,\n symbol: string,\n): T | undefined {\n return configs.get(normalizeTokenKey(symbol));\n}\n\n/**\n * Validate that a token is supported and return its config.\n *\n * Throws a descriptive error if the token is not found.\n *\n * @param configs - Token config map\n * @param symbol - Token symbol to validate\n * @param network - Network name for error message (e.g., 'Ethereum', 'Solana')\n * @returns Token config\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` if the token is not supported\n *\n * @example\n * ```typescript\n * const config = requireTokenConfig(ethTokens, 'GALA', 'Ethereum');\n * ```\n */\nexport function requireTokenConfig<T extends BaseTokenConfig>(\n configs: Map<string, T>,\n symbol: string,\n network: string,\n): T {\n const config = getTokenConfig(configs, symbol);\n if (!config) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network, symbol });\n }\n return config;\n}\n\n/**\n * Validate Ethereum private key format and throw descriptive error if invalid.\n *\n * Use this for constructor validation where a descriptive error is needed.\n *\n * @param privateKey - Private key to validate\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` (`bad_encoding`) if the format is invalid; the key is\n * never part of the error\n *\n * @example\n * ```typescript\n * validateEthereumPrivateKeyFormat(config.ethereumPrivateKey);\n * ```\n */\nexport function validateEthereumPrivateKeyFormat(\n privateKey: string | undefined,\n): asserts privateKey is string {\n if (privateKey === undefined || !isValidEthereumPrivateKeyFormat(privateKey)) {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n}\n\n/**\n * Validate Ethereum transaction hash format and throw descriptive error if invalid.\n *\n * Use this for parameter validation where a descriptive error is needed.\n *\n * @param hash - Transaction hash to validate\n * @throws GalaSDKError `INVALID_TRANSACTION_HASH` if the format is invalid\n *\n * @example\n * ```typescript\n * validateEthereumTransactionHashFormat(transactionHash);\n * ```\n */\nexport function validateEthereumTransactionHashFormat(hash: string): void {\n if (!isValidEthereumTransactionHash(hash)) {\n throw new GalaSDKError('INVALID_TRANSACTION_HASH', {\n network: 'Ethereum',\n value: String(hash),\n });\n }\n}\n","/**\n * Balance Query Helpers\n *\n * Consolidated utilities for building ExternalChainBalance and BridgeTransaction response objects.\n * Eliminates DRY violations across BridgeService and bridge strategy methods.\n *\n * @module bridge/utils/balanceHelpers\n */\n\nimport { GalaSDKError } from '../../index.js';\nimport type {\n BridgeRequestDto,\n BridgeTransaction,\n DestinationChainTxFee,\n ExternalChainBalance,\n ExternalNetwork,\n} from '../types/index.js';\nimport type { EthereumTokenConfig, SolanaTokenConfig } from '../types/index.js';\n\n// ==========================================================================\n// Balance Response Builders\n// ==========================================================================\n\n/**\n * Build an ExternalChainBalance for a native token (ETH or SOL).\n *\n * @param symbol - Native token symbol ('ETH' or 'SOL')\n * @param quantity - Balance as decimal string\n * @param decimals - Token decimals (18 for ETH, 9 for SOL)\n * @returns ExternalChainBalance with isNative: true, contractAddress: null\n *\n * @example\n * ```typescript\n * const ethBalance = buildNativeBalance('ETH', '1.5', 18);\n * // { symbol: 'ETH', quantity: '1.5', decimals: 18, contractAddress: null, isNative: true }\n * ```\n */\nexport function buildNativeBalance(\n symbol: 'ETH' | 'SOL',\n quantity: string,\n decimals: number,\n): ExternalChainBalance {\n return {\n symbol,\n quantity,\n decimals,\n contractAddress: null,\n isNative: true,\n };\n}\n\n/**\n * Build an ExternalChainBalance for an Ethereum ERC-20 token.\n *\n * @param tokenConfig - Ethereum token configuration\n * @param quantity - Balance as decimal string\n * @returns ExternalChainBalance with contractAddress and isNative: false\n *\n * @example\n * ```typescript\n * const galaBalance = buildEthereumTokenBalance(\n * { symbol: 'GALA', contractAddress: '0x15D4...', decimals: 8 },\n * '1000.00000000'\n * );\n * ```\n */\nexport function buildEthereumTokenBalance(\n tokenConfig: EthereumTokenConfig,\n quantity: string,\n): ExternalChainBalance {\n return {\n symbol: tokenConfig.symbol,\n quantity,\n decimals: tokenConfig.decimals ?? 18,\n contractAddress: tokenConfig.contractAddress,\n isNative: false,\n };\n}\n\n/**\n * Build an ExternalChainBalance for a Solana SPL token.\n *\n * @param tokenConfig - Solana token configuration\n * @param quantity - Balance as decimal string\n * @returns ExternalChainBalance with mintAddress as contractAddress\n *\n * @example\n * ```typescript\n * const galaBalance = buildSolanaTokenBalance(\n * { symbol: 'GALA', mintAddress: 'GALAxw...', decimals: 8 },\n * '500.00000000'\n * );\n * ```\n */\nexport function buildSolanaTokenBalance(\n tokenConfig: SolanaTokenConfig,\n quantity: string,\n): ExternalChainBalance {\n return {\n symbol: tokenConfig.symbol,\n quantity,\n decimals: tokenConfig.decimals ?? 9,\n contractAddress: tokenConfig.mintAddress,\n isNative: tokenConfig.isNative ?? false,\n };\n}\n\n// ==========================================================================\n// Token Config Validation\n// ==========================================================================\n\n/**\n * Find and validate a token config from an array.\n *\n * @param tokens - Array of token configurations\n * @param symbol - Token symbol to find\n * @param network - Network name for error message ('Ethereum' or 'Solana')\n * @returns Token config\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` if not found\n *\n * @example\n * ```typescript\n * const config = findTokenConfigOrThrow(ethereumTokens, 'GALA', 'Ethereum');\n * ```\n */\nexport function findTokenConfigOrThrow<T extends { symbol: string }>(\n tokens: T[],\n symbol: string,\n network: string,\n): T {\n const tokenConfig = tokens.find((t) => t.symbol === symbol);\n if (!tokenConfig) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network, symbol });\n }\n return tokenConfig;\n}\n\n// ==========================================================================\n// Strategy Assertion Helpers\n// ==========================================================================\n\n/**\n * Assert that a strategy exists and return it typed.\n *\n * @param strategy - Strategy from map (may be undefined)\n * @param network - Network type ('Ethereum' or 'Solana')\n * @returns The strategy (type-narrowed to non-undefined)\n * @throws GalaSDKError `BRIDGE_NOT_CONFIGURED` if strategy is undefined\n *\n * @example\n * ```typescript\n * const strategy = this.strategies.get('Ethereum');\n * const ethStrategy = assertStrategyExists(strategy, 'Ethereum') as EthereumBridgeStrategy;\n * ```\n */\nexport function assertStrategyExists<T>(\n strategy: T | undefined,\n network: 'Ethereum' | 'Solana',\n): T {\n if (strategy === undefined) {\n throw new GalaSDKError('BRIDGE_NOT_CONFIGURED', { network });\n }\n return strategy;\n}\n\n// ==========================================================================\n// Bridge Transaction Response Builders\n// ==========================================================================\n\n/**\n * Parameters for building a bridge outbound transaction response.\n */\nexport interface BridgeOutboundTransactionParams {\n /** Destination chain ('Ethereum' | 'Solana') */\n toChain: ExternalNetwork;\n /** Transaction hash */\n transactionHash: string;\n /** Token symbol (e.g., 'GALA', 'GWETH') */\n tokenSymbol: string;\n /** Amount transferred (decimal string) */\n amount: string;\n /** Fee paid in GALA */\n feePaid: string;\n /** Base URL for status endpoint */\n baseUrl: string;\n}\n\n/**\n * Build a BridgeTransaction response for outbound transfers (GalaChain -> External).\n *\n * Eliminates duplicate response construction in EthereumBridgeStrategy and SolanaBridgeStrategy.\n *\n * @param params - Transaction parameters\n * @returns Complete BridgeTransaction object\n *\n * @example\n * ```typescript\n * return buildBridgeOutboundTransaction({\n * toChain: 'Ethereum',\n * transactionHash: '0x123...',\n * tokenSymbol: 'GALA',\n * amount: '100',\n * feePaid: '0.5',\n * baseUrl: 'https://api.gala.com',\n * });\n * ```\n */\nexport function buildBridgeOutboundTransaction(\n params: BridgeOutboundTransactionParams,\n): BridgeTransaction {\n return {\n direction: 'outbound',\n fromChain: 'GalaChain',\n toChain: params.toChain,\n transactionHash: params.transactionHash,\n tokenSymbol: params.tokenSymbol,\n amount: params.amount,\n feePaid: params.feePaid,\n timestamp: Date.now(),\n statusUrl: `${params.baseUrl}/v1/bridge/transaction?hash=${params.transactionHash}`,\n };\n}\n\n/**\n * Parameters for building a bridge inbound transaction response.\n */\nexport interface BridgeInboundTransactionParams {\n /** Source chain ('Ethereum' | 'Solana') */\n fromChain: ExternalNetwork;\n /** Transaction hash */\n transactionHash: string;\n /** Token symbol (e.g., 'GALA', 'GWETH') */\n tokenSymbol: string;\n /** Amount transferred (decimal string) */\n amount: string;\n /** Base URL for status endpoint */\n baseUrl: string;\n}\n\n/**\n * Build a BridgeTransaction response for inbound transfers (External -> GalaChain).\n *\n * Eliminates duplicate response construction in EthereumBridgeStrategy and SolanaBridgeStrategy.\n *\n * @param params - Transaction parameters\n * @returns Complete BridgeTransaction object\n *\n * @example\n * ```typescript\n * return buildBridgeInboundTransaction({\n * fromChain: 'Ethereum',\n * transactionHash: '0x123...',\n * tokenSymbol: 'GALA',\n * amount: '100',\n * baseUrl: 'https://api.gala.com',\n * });\n * ```\n */\nexport function buildBridgeInboundTransaction(\n params: BridgeInboundTransactionParams,\n): BridgeTransaction {\n return {\n direction: 'inbound',\n fromChain: params.fromChain,\n toChain: 'GalaChain',\n transactionHash: params.transactionHash,\n tokenSymbol: params.tokenSymbol,\n amount: params.amount,\n timestamp: Date.now(),\n statusUrl: `${params.baseUrl}/v1/bridge/transaction?hash=${params.transactionHash}`,\n };\n}\n\n// ==========================================================================\n// Bridge Request DTO Builders\n// ==========================================================================\n\n/**\n * Parameters for building a bridge request DTO.\n */\nexport interface BridgeRequestDtoParams {\n /** Destination chain ID (number) */\n destinationChainId: number;\n /** Bridge fee response from GalaConnect (used as destinationChainTxFee) */\n bridgeFee: DestinationChainTxFee;\n /** Amount to bridge (decimal string) */\n amount: string;\n /** Recipient address on destination chain */\n recipientAddress: string;\n /** Token metadata descriptor */\n tokenDescriptor: {\n collection: string;\n category: string;\n type: string;\n additionalKey: string;\n };\n}\n\n/**\n * Build a BridgeRequestDto for the GalaConnect RequestTokenBridgeOut API.\n *\n * Eliminates duplicate DTO construction across strategies (~10 lines each).\n *\n * @param params - Request parameters\n * @returns BridgeRequestDto ready for signing\n *\n * @example\n * ```typescript\n * const dto = buildBridgeRequestDto({\n * destinationChainId: CHAIN_IDS.ETHEREUM,\n * bridgeFee,\n * amount: '100',\n * recipientAddress: '0x1234...',\n * tokenDescriptor: metadata.descriptor,\n * });\n * ```\n */\nexport function buildBridgeRequestDto(params: BridgeRequestDtoParams): BridgeRequestDto {\n return {\n destinationChainId: params.destinationChainId,\n destinationChainTxFee: params.bridgeFee,\n quantity: params.amount,\n recipient: params.recipientAddress,\n tokenInstance: {\n ...params.tokenDescriptor,\n instance: '0',\n },\n };\n}\n","/**\n * Bridge Payload Utilities\n *\n * Shared utility functions for bridge payload construction and normalization.\n * These functions are used by both EthereumBridgeStrategy and SolanaBridgeStrategy\n * to ensure consistent, deterministic payload generation for EIP-712 signing.\n */\n\nimport { GalaSDKError, type GalaChainTokenClassKey } from '../../index.js';\nimport { fieldsOf, isRecord, safeParseFloat, safeParseInt } from '../internal/values.js';\nimport type {\n BridgeFeeEstimate,\n BridgeTokenMetadata,\n DestinationChainTxFee,\n} from '../types/index.js';\n\n/**\n * Normalize a DestinationChainTxFee response for deterministic signing.\n *\n * Converts string timestamps and decimals to numbers to ensure consistent\n * JSON serialization across different API response formats.\n *\n * @param raw - Raw fee response from GalaConnect API\n * @returns Normalized fee object with numeric timestamps\n */\nexport function normalizeDestinationChainTxFee(raw: DestinationChainTxFee): DestinationChainTxFee {\n const normalized: DestinationChainTxFee = {\n ...raw,\n galaDecimals:\n typeof raw.galaDecimals === 'string' ? safeParseInt(raw.galaDecimals, 0) : raw.galaDecimals,\n timestamp: typeof raw.timestamp === 'string' ? safeParseInt(raw.timestamp, 0) : raw.timestamp,\n };\n\n if (raw.galaExchangeRate) {\n normalized.galaExchangeRate = {\n ...raw.galaExchangeRate,\n timestamp:\n typeof raw.galaExchangeRate.timestamp === 'string'\n ? safeParseInt(raw.galaExchangeRate.timestamp, 0)\n : raw.galaExchangeRate.timestamp,\n };\n }\n\n if (raw.galaExchangeCrossRate) {\n const crossRate = raw.galaExchangeCrossRate;\n normalized.galaExchangeCrossRate = {\n ...crossRate,\n timestamp:\n typeof crossRate.timestamp === 'string'\n ? safeParseInt(crossRate.timestamp, 0)\n : crossRate.timestamp,\n };\n\n if (crossRate.baseTokenCrossRate) {\n normalized.galaExchangeCrossRate.baseTokenCrossRate = {\n ...crossRate.baseTokenCrossRate,\n timestamp:\n typeof crossRate.baseTokenCrossRate.timestamp === 'string'\n ? safeParseInt(crossRate.baseTokenCrossRate.timestamp, 0)\n : crossRate.baseTokenCrossRate.timestamp,\n };\n }\n\n if (crossRate.quoteTokenCrossRate) {\n normalized.galaExchangeCrossRate.quoteTokenCrossRate = {\n ...crossRate.quoteTokenCrossRate,\n timestamp:\n typeof crossRate.quoteTokenCrossRate.timestamp === 'string'\n ? safeParseInt(crossRate.quoteTokenCrossRate.timestamp, 0)\n : crossRate.quoteTokenCrossRate.timestamp,\n };\n }\n }\n\n return normalized;\n}\n\n/**\n * Remove undefined values from an object for deterministic JSON serialization.\n *\n * Creates a clean object without undefined properties, which ensures\n * consistent JSON.stringify output for signature verification.\n *\n * @param obj - Object potentially containing undefined values\n * @returns Clean object with undefined values removed\n */\nexport function sanitizeObject<T extends Record<string, unknown>>(obj: T): T {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined) {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = sanitizeObject(value as Record<string, unknown>);\n } else {\n result[key] = value;\n }\n }\n }\n return result as T;\n}\n\n/**\n * Extract the bridge request ID from a RequestTokenBridgeOut response.\n *\n * Handles multiple response formats from the GalaConnect API:\n * - `{ Data: \"...\" }` - Direct data field\n * - `{ data: \"...\" }` - Lowercase data field\n * - `{ data: { Data: \"...\" } }` - Nested data object\n *\n * @param response - Response from RequestTokenBridgeOut API call (any value: an empty answer is\n * `undefined`)\n * @returns Bridge request ID if found, undefined otherwise (also for an answer that is not an object)\n */\nexport function extractBridgeRequestId(response: unknown): string | undefined {\n const answer = fieldsOf(response);\n if (typeof answer['Data'] === 'string') {\n return answer['Data'];\n }\n const data = answer['data'];\n if (typeof data === 'string') {\n return data;\n }\n const nested = fieldsOf(data)['Data'];\n return typeof nested === 'string' ? nested : undefined;\n}\n\n/**\n * Validate a bridge amount for numeric validity and positivity.\n *\n * Prevents wasted gas on zero/negative/invalid amounts.\n *\n * @param amount - Amount string to validate\n * @throws GalaSDKError `INVALID_BRIDGE_AMOUNT` (`not_positive`) if it is not a number above zero\n * @returns Parsed numeric amount (as side effect of successful validation)\n *\n * @example\n * ```typescript\n * validateBridgeAmount('100.5'); // Returns: 100.5\n * validateBridgeAmount('0'); // Throws\n * validateBridgeAmount('abc'); // Throws\n * ```\n */\nexport function validateBridgeAmount(amount: string): number {\n const numericAmount = safeParseFloat(amount, -1);\n if (numericAmount <= 0) {\n throw new GalaSDKError('INVALID_BRIDGE_AMOUNT', {\n value: String(amount),\n reason: 'not_positive',\n });\n }\n return numericAmount;\n}\n\n/**\n * Build a BridgeTokenMetadata object from token descriptor and decimals.\n *\n * Consolidates the pattern of building bridge token metadata from API responses.\n *\n * @param tokenDescriptor - Token descriptor with collection, category, type, additionalKey\n * @param decimals - Token decimals\n * @param channel - Optional channel identifier for multi-channel tokens\n * @returns BridgeTokenMetadata object\n *\n * @example\n * ```typescript\n * const metadata = buildTokenMetadata(\n * { collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' },\n * 8\n * );\n * ```\n */\nexport function buildTokenMetadata(\n tokenDescriptor: GalaChainTokenClassKey,\n decimals: number,\n channel?: string,\n): BridgeTokenMetadata {\n return {\n descriptor: {\n collection: tokenDescriptor.collection,\n category: tokenDescriptor.category,\n type: tokenDescriptor.type,\n additionalKey: tokenDescriptor.additionalKey,\n },\n decimals,\n // Only include channel if defined (exactOptionalPropertyTypes compliance)\n ...(channel !== undefined ? { channel } : {}),\n };\n}\n\n/**\n * The fee GalaConnect answered, if it is one a bridge-out can carry: an object with the GALA fee\n * (a string) and an exchange rate or a cross rate (which picks the typed data). Anything else (an\n * empty answer included) is `BRIDGE_READ_RESPONSE_INVALID` (a read: nothing was signed or sent).\n */\nexport function assertUsableFee<T>(fee: T): T {\n const answer: unknown = fee;\n if (\n !isRecord(answer) ||\n typeof answer['estimatedTotalTxFeeInGala'] !== 'string' ||\n !(isRecord(answer['galaExchangeRate']) || isRecord(answer['galaExchangeCrossRate']))\n ) {\n throw readAnswerInvalid('/v1/bridge/fee');\n }\n return fee;\n}\n\n/**\n * The bridge status GalaConnect answered, if it is an object (an empty answer is not).\n *\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` otherwise\n */\nexport function assertStatusAnswer<T>(status: T): T {\n if (!isRecord(status)) {\n throw readAnswerInvalid('/v1/bridge/status');\n }\n return status;\n}\n\n/** `BRIDGE_READ_RESPONSE_INVALID` for the GalaConnect read `method`. */\nfunction readAnswerInvalid(method: string): GalaSDKError {\n return new GalaSDKError('BRIDGE_READ_RESPONSE_INVALID', { method }, { write: false });\n}\n\n/**\n * Build a fee payload object from a DestinationChainTxFee response.\n *\n * Consolidates the pattern of extracting fee information from API responses.\n * Normalizes timestamp to ensure it is always a number.\n *\n * @param feeResponse - Raw fee response from GalaConnect API\n * @returns Fee payload with all relevant fields\n *\n * @example\n * ```typescript\n * const feePayload = buildFeePayload({\n * estimatedTotalTxFeeInGala: '100',\n * estimatedTotalTxFeeInExternalToken: '0.005',\n * ...\n * });\n * ```\n */\nexport function buildFeePayload(feeResponse: DestinationChainTxFee): BridgeFeeEstimate {\n const timestamp =\n typeof feeResponse.timestamp === 'string'\n ? safeParseInt(feeResponse.timestamp, 0)\n : feeResponse.timestamp;\n\n return {\n estimatedFeeInGala: feeResponse.estimatedTotalTxFeeInGala,\n estimatedFeeInExternalToken: feeResponse.estimatedTotalTxFeeInExternalToken,\n feeToken: feeResponse.bridgeToken,\n pricePerUnit: feeResponse.estimatedPricePerTxFeeUnit,\n estimatedGasUnits: feeResponse.estimatedTxFeeUnitsTotal,\n exchangeRate: feeResponse.galaExchangeRate?.exchangeRate ?? '0',\n timestamp,\n raw: feeResponse,\n };\n}\n","/**\n * EIP-712 Signing Helpers\n *\n * The signed bridge-out payload (`RequestTokenBridgeOut`) both bridge strategies submit. Moved\n * from launchpad-sdk byte for byte: the signature, the `prefix` and the key order are pinned by\n * launchpad's recorded vectors (tests/fixtures/bridge-out-recorded.json).\n *\n * @module bridge/utils/eip712Helpers\n */\n\nimport type { Signer } from 'ethers';\n\nimport {\n createUniqueKey,\n GalaSDKError,\n isGalaError,\n isWalletUserRejection,\n serialize,\n walletDeclineCode,\n dtoOperationOf,\n} from '../../index.js';\nimport { GALA_BRIDGE_TYPED_DATA_DOMAIN, getGalaBridgeTypedDataTypes } from '../types/eip712.js';\nimport type { BridgeRequestDto } from '../types/index.js';\nimport { normalizeDestinationChainTxFee, sanitizeObject } from './bridgePayload.js';\n\n/** What signs the bridge-out typed data: an ethers `Wallet`, or any ethers `Signer`. */\nexport type BridgeTypedDataSigner = Pick<Signer, 'signTypedData'>;\n\n/**\n * Configuration for building bridge out payloads\n */\nexport interface BuildBridgeOutPayloadConfig {\n /** Signs the EIP-712 typed data (the Ethereum wallet) */\n wallet: BridgeTypedDataSigner;\n}\n\n/** The signed `RequestTokenBridgeOut` body; its `uniqueKey` is the bridge-out's handle. */\nexport type SignedBridgeOutPayload = Record<string, unknown> & { readonly uniqueKey: string };\n\n/** The prefix of a generated bridge-out `uniqueKey`. */\nconst BRIDGE_UNIQUE_KEY_PREFIX = 'galaconnect-operation-';\n\n/**\n * The destination chain id as the number the payload signs: a positive safe integer, or a string\n * of decimal digits that is one. Anything else is `INVALID_BRIDGE_OPTION` (`destinationChainId`):\n * a chain id is never guessed, since a wrong one sends the tokens to another chain.\n */\nfunction destinationChainIdOf(value: number | string): number {\n const id = typeof value === 'string' && /^\\d+$/u.test(value) ? Number(value) : value;\n if (typeof id !== 'number' || !Number.isSafeInteger(id) || id <= 0) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'destinationChainId' });\n }\n return id;\n}\n\n/** The method a bridge-out signing failure names. */\nconst BRIDGE_OUT_METHOD = 'RequestTokenBridgeOut';\n\n/**\n * Signs the bridge-out typed data with the app's signer. Whatever the signer throws that is not\n * already an SDK error (a declined or locked wallet, a message ethers cannot encode) is\n * `SIGNING_FAILED` (`user_rejected` or `failed`, the original as `cause`), and so is a signature\n * that is not a string: nothing was sent, so a retry is safe.\n */\nasync function signBridgeOut(\n wallet: BridgeTypedDataSigner,\n types: ReturnType<typeof getGalaBridgeTypedDataTypes>,\n message: Record<string, unknown>,\n): Promise<string> {\n let signature: unknown;\n try {\n signature = await wallet.signTypedData(GALA_BRIDGE_TYPED_DATA_DOMAIN, types, message);\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n {\n method: BRIDGE_OUT_METHOD,\n reason: isWalletUserRejection(cause) ? 'user_rejected' : 'failed',\n },\n { cause, walletCode: walletDeclineCode(cause) },\n );\n }\n if (typeof signature !== 'string') {\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n { method: BRIDGE_OUT_METHOD, reason: 'failed' },\n { cause: signature },\n );\n }\n return signature;\n}\n\n/**\n * Build an EIP-712 signed bridge out payload.\n *\n * The payload is signed using EIP-712 typed data signing and includes:\n * - The message to be signed\n * - The EIP-712 signature\n * - The typed data types and domain for verification\n * - An Ethereum signed message `prefix` over the deterministic JSON of the typed data (its number\n * is the UTF-16 length of that string, as launchpad-sdk always sent it; the typed-data hash does\n * not cover it)\n *\n * @param dto - Bridge request (a `uniqueKey` is generated when it has none)\n * @param config - The signer\n * @returns The payload for `GalaConnectClient.requestBridgeOut`\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`destinationChainId`) for a chain id that is not a\n * positive integer; `CSPRNG_UNAVAILABLE` when a key must be generated and the platform has no\n * `crypto.getRandomValues`; `SIGNING_FAILED` when the signer fails (see `signBridgeOut`)\n */\nexport async function buildBridgeOutPayload(\n dto: BridgeRequestDto,\n config: BuildBridgeOutPayloadConfig,\n): Promise<SignedBridgeOutPayload> {\n const { wallet } = config;\n\n // Normalize destination chain ID to number (refused, never defaulted, when it is not one)\n const destinationChainId = destinationChainIdOf(dto.destinationChainId);\n\n // Generate unique key for idempotency\n const uniqueKey = dto.uniqueKey ?? createUniqueKey(BRIDGE_UNIQUE_KEY_PREFIX);\n\n // Normalize fee object for deterministic signing\n const normalizedFee = normalizeDestinationChainTxFee(dto.destinationChainTxFee);\n const hasCrossRate = Boolean(normalizedFee.galaExchangeCrossRate);\n\n // Remove unused rate object (either galaExchangeRate or galaExchangeCrossRate)\n const sanitizedFeeObj = hasCrossRate\n ? { ...normalizedFee, galaExchangeRate: undefined }\n : { ...normalizedFee, galaExchangeCrossRate: undefined };\n\n // Build the message payload\n const message = {\n destinationChainId,\n destinationChainTxFee: sanitizeObject(sanitizedFeeObj),\n dtoOperation: dtoOperationOf('asset/bridge-contract', BRIDGE_OUT_METHOD),\n quantity: dto.quantity,\n recipient: dto.recipient,\n tokenInstance: dto.tokenInstance,\n uniqueKey,\n };\n\n // Get appropriate typed data types based on fee structure\n const typedDataTypes = getGalaBridgeTypedDataTypes(hasCrossRate);\n\n // Sign with EIP-712\n const signature = await signBridgeOut(wallet, typedDataTypes, message);\n\n // Deterministic JSON (core's serialize: byte-identical to json-stringify-deterministic for JSON)\n const deterministicPayload = serialize({\n domain: GALA_BRIDGE_TYPED_DATA_DOMAIN,\n message,\n primaryType: 'GalaTransaction',\n types: typedDataTypes,\n });\n\n // Create Ethereum signed message prefix\n const prefix = `\\u0019Ethereum Signed Message:\\n${deterministicPayload.length}`;\n\n return {\n ...message,\n signature,\n prefix,\n types: typedDataTypes,\n domain: GALA_BRIDGE_TYPED_DATA_DOMAIN,\n };\n}\n","/**\n * Bridge Out Flow Helpers\n *\n * The bridge-out flow (GalaChain to an external chain) both strategies run: fee, signed\n * `RequestTokenBridgeOut`, then `BridgeTokenOut`.\n *\n * @module bridge/utils/bridgeOutHelpers\n */\n\nimport { GalaSDKError, type BridgeOutStep } from '../../index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport type { BridgeOutParams, BridgeTransaction, ExternalNetwork } from '../types/index.js';\nimport { buildBridgeOutboundTransaction, buildBridgeRequestDto } from './balanceHelpers.js';\nimport {\n assertBridgeRequestId,\n assertRequestAccepted,\n assertTokenSymbolResolved,\n extractBridgeOutTransactionHash,\n} from './bridgeErrors.js';\nimport { assertUsableFee, extractBridgeRequestId, validateBridgeAmount } from './bridgePayload.js';\nimport { buildBridgeOutPayload, type BridgeTypedDataSigner } from './eip712Helpers.js';\nimport type { TokenMetadataResolver } from './tokenMetadataResolver.js';\n\n/**\n * Configuration for executing bridge out flow\n */\nexport interface BridgeOutFlowConfig {\n /** GalaConnect client for API calls */\n galaConnectClient: GalaConnectClient;\n /** Token metadata resolver */\n tokenMetadataResolver: TokenMetadataResolver;\n /** Signs the EIP-712 bridge-out payload (the Ethereum wallet) */\n ethereumWallet: BridgeTypedDataSigner;\n /** Destination chain ID */\n destinationChainId: number;\n /** Destination chain name */\n destinationChain: ExternalNetwork;\n /** Function to validate recipient address for the destination chain */\n validateRecipientAddress: (address: string, label: string) => void;\n}\n\n/**\n * A bridge-out (an external one, or a cross-channel wrap / unwrap) after GalaConnect accepted its\n * `RequestTokenBridgeOut` (the tokens may be locked): the bridge request id from that answer,\n * `BridgeTokenOut` from `bridgeFromChannel` (GalaChain refusing it is `BRIDGE_REQUEST_REJECTED`),\n * and what `readResult` reads from its answer. Any failure here is `BRIDGE_OUT_OUTCOME_UNKNOWN`\n * (`step`, the `bridgeRequestId` once known, the request's `uniqueKey`, the failure as `cause`),\n * whatever the failure itself was: a `BridgeTokenOut` 429 or 4xx must not read as \"not queued\",\n * since bridging again would lock the tokens a second time. With the `bridgeRequestId`,\n * `BridgeTokenOut` can be sent again to finish this bridge-out.\n *\n * @param readResult - Reads the transaction id from the `BridgeTokenOut` answer (throws when the\n * answer is not usable)\n */\nexport async function completeBridgeOut(\n galaConnectClient: GalaConnectClient,\n requestResponse: unknown,\n uniqueKey: string,\n bridgeFromChannel: string,\n readResult: (bridgeOutResponse: unknown, bridgeRequestId: string) => string,\n): Promise<string> {\n let step: BridgeOutStep = 'request_id';\n let bridgeRequestId = '';\n try {\n bridgeRequestId = assertBridgeRequestId(extractBridgeRequestId(requestResponse));\n step = 'bridge_token_out';\n const bridgeOutResponse = await galaConnectClient.bridgeTokenOut({\n bridgeFromChannel,\n bridgeRequestId,\n });\n assertRequestAccepted('BridgeTokenOut', bridgeOutResponse);\n step = 'transaction_hash';\n return readResult(bridgeOutResponse, bridgeRequestId);\n } catch (cause: unknown) {\n throw new GalaSDKError(\n 'BRIDGE_OUT_OUTCOME_UNKNOWN',\n { step, bridgeRequestId },\n { uniqueKey, cause },\n );\n }\n}\n\n/**\n * Execute the bridge out flow (GalaChain → External chain).\n *\n * Every check runs before anything is signed or sent: the symbol, the amount, the recipient.\n * Then: token metadata, the fee, the signed `RequestTokenBridgeOut`, the bridge request id from\n * its answer, `BridgeTokenOut`, and the transaction hash from that answer.\n *\n * @param params - Bridge out parameters\n * @param config - Flow configuration\n * @returns Bridge transaction result\n * @throws GalaSDKError `BRIDGE_OUT_OUTCOME_UNKNOWN` for any failure after `RequestTokenBridgeOut`\n * was accepted (see `completeBridgeOut`); before it, the failing step's own error\n */\nexport async function executeBridgeOutFlow(\n params: BridgeOutParams,\n config: BridgeOutFlowConfig,\n): Promise<BridgeTransaction> {\n const { amount, recipientAddress, tokenSymbol: resolvedSymbol } = params;\n const {\n galaConnectClient,\n tokenMetadataResolver,\n ethereumWallet,\n destinationChainId,\n destinationChain,\n validateRecipientAddress,\n } = config;\n\n // 1. Validate that BridgeService resolved the symbol\n const tokenSymbol = assertTokenSymbolResolved(resolvedSymbol);\n\n // 2. Validate amount (prevents wasted fees on zero/negative amounts)\n validateBridgeAmount(amount);\n\n // 3. Validate recipient address using chain-specific validation\n validateRecipientAddress(recipientAddress, 'recipient');\n\n // 4. Fetch token metadata\n const metadata = await tokenMetadataResolver.getTokenMetadata(tokenSymbol);\n\n // 5. Fetch bridge fee (the oracle-signed fee the payload carries)\n const bridgeFee = assertUsableFee(\n await galaConnectClient.fetchBridgeFee({\n chainId: destinationChain,\n bridgeToken: metadata.descriptor,\n }),\n );\n\n // 6. Build bridge request DTO using shared helper\n const dtoPayload = buildBridgeRequestDto({\n destinationChainId,\n bridgeFee,\n amount,\n recipientAddress,\n tokenDescriptor: metadata.descriptor,\n });\n\n // 7. Sign and build payload using shared EIP-712 helper\n const signedPayload = await buildBridgeOutPayload(dtoPayload, {\n wallet: ethereumWallet,\n });\n\n // 8. Submit RequestTokenBridgeOut (its own errors carry the payload's uniqueKey)\n const requestResponse = await galaConnectClient.requestBridgeOut(signedPayload);\n // GalaChain refusing the request locked nothing: its own refusal, with the key\n assertRequestAccepted('RequestTokenBridgeOut', requestResponse, signedPayload.uniqueKey);\n\n // 9-11. From here the request is accepted and the tokens may be locked: every failure is\n // BRIDGE_OUT_OUTCOME_UNKNOWN (never a retryable refusal, which would lock them twice).\n const transactionHash = await completeBridgeOut(\n galaConnectClient,\n requestResponse,\n signedPayload.uniqueKey,\n 'asset',\n extractBridgeOutTransactionHash,\n );\n\n // 12. Build and return transaction response\n return buildBridgeOutboundTransaction({\n toChain: destinationChain,\n transactionHash,\n tokenSymbol,\n amount,\n feePaid: bridgeFee.estimatedTotalTxFeeInGala,\n baseUrl: galaConnectClient.getBaseUrl(),\n });\n}\n","/**\n * Bridge Status Parser\n *\n * Shared utility for parsing bridge status responses.\n * Consolidates duplicate status parsing logic from both bridge strategies.\n *\n * @module bridge/utils/bridgeStatusParser\n */\n\nimport { safeParseInt } from '../internal/values.js';\nimport { BridgeStatusCode } from '../types/index.js';\nimport type { BridgeStatus, BridgeStatusResponse } from '../types/index.js';\n\n/**\n * Terminal status codes that indicate a bridge operation is complete.\n */\nexport const TERMINAL_STATUS_CODES = {\n COMPLETED: BridgeStatusCode.COMPLETED,\n FAILED: BridgeStatusCode.FAILED,\n DELIVERY_FAILED: BridgeStatusCode.DELIVERY_FAILED,\n} as const;\n\n/**\n * Parse a bridge status response into a BridgeStatus object.\n *\n * This consolidates the duplicate `getStatus()` result parsing from\n * EthereumBridgeStrategy and SolanaBridgeStrategy.\n *\n * Safely parses the numeric status code using {@link safeParseInt} to handle\n * edge cases where the API returns unexpected values (strings, null, undefined).\n *\n * @param response - Raw response from GalaConnect getBridgeStatus API\n * @returns Parsed BridgeStatus object with normalized fields\n *\n * @example\n * ```typescript\n * const response = await galaConnectClient.getBridgeStatus(hash);\n * const status = parseBridgeStatusResponse(response);\n * if (status.isComplete) {\n * console.log('Bridge completed successfully!');\n * }\n * ```\n */\nexport function parseBridgeStatusResponse(response: BridgeStatusResponse): BridgeStatus {\n // Safely parse status code from API response, defaulting to 0 (UNKNOWN) if invalid\n const rawStatus = response.status;\n const statusCode = safeParseInt(rawStatus, 0);\n\n return {\n status: statusCode,\n statusDescription: response.statusDescription,\n fromChain: response.fromChain,\n toChain: response.toChain,\n quantity: response.quantity,\n transactionHash: response.emitterTransactionHash,\n tokenInstance: response.tokenInstance,\n isComplete: statusCode === Number(TERMINAL_STATUS_CODES.COMPLETED),\n isFailed:\n statusCode === Number(TERMINAL_STATUS_CODES.FAILED) ||\n statusCode === Number(TERMINAL_STATUS_CODES.DELIVERY_FAILED),\n };\n}\n","/**\n * Strategy Delegation Utilities\n *\n * The helpers BridgeService and both strategies share: typed strategy lookup, the fee estimate,\n * the status read, and the token-config queries.\n *\n * @module bridge/utils/strategyDelegation\n */\n\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport type { BridgeStrategy } from '../strategies/BridgeStrategy.js';\nimport type { EthereumBridgeStrategy } from '../strategies/EthereumBridgeStrategy.js';\nimport type { SolanaBridgeStrategy } from '../strategies/SolanaBridgeStrategy.js';\nimport { normalizeTokenSymbol } from '../internal/values.js';\nimport type { BridgeFeeEstimate, BridgeStatus, ExternalNetwork } from '../types/index.js';\nimport { assertStrategyExists } from './balanceHelpers.js';\nimport { assertStatusAnswer, assertUsableFee, buildFeePayload } from './bridgePayload.js';\nimport { parseBridgeStatusResponse } from './bridgeStatusParser.js';\nimport type { TokenMetadataResolver } from './tokenMetadataResolver.js';\n\n// ==========================================================================\n// Type-Safe Strategy Access\n// ==========================================================================\n\n/**\n * The Ethereum strategy, typed.\n *\n * @throws GalaSDKError `BRIDGE_NOT_CONFIGURED` (`Ethereum`) when there is none\n */\nexport function getEthereumStrategy(\n strategies: Map<ExternalNetwork, BridgeStrategy>,\n): EthereumBridgeStrategy {\n return assertStrategyExists(strategies.get('Ethereum'), 'Ethereum') as EthereumBridgeStrategy;\n}\n\n/**\n * The Solana strategy, typed.\n *\n * @throws GalaSDKError `BRIDGE_NOT_CONFIGURED` (`Solana`) when there is none\n */\nexport function getSolanaStrategy(\n strategies: Map<ExternalNetwork, BridgeStrategy>,\n): SolanaBridgeStrategy {\n return assertStrategyExists(strategies.get('Solana'), 'Solana') as SolanaBridgeStrategy;\n}\n\n// ==========================================================================\n// Address Resolution Helpers\n// ==========================================================================\n\n/**\n * The address to act on: the one given, else the strategy's own wallet address.\n */\nexport function resolveTargetAddress(\n providedAddress: string | undefined,\n strategy: { getWalletAddress(): string },\n): string {\n return providedAddress ?? strategy.getWalletAddress();\n}\n\n/**\n * The bridge fee estimate for a token (the fee does not depend on the amount).\n *\n * @param client - GalaConnect client\n * @param resolver - Token metadata resolver\n * @param chainId - Destination chain name (`Ethereum`, `Solana`)\n * @param tokenSymbol - Token symbol\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` for a fee answer without the GALA fee and a rate\n */\nexport async function estimateStrategyFee(\n client: GalaConnectClient,\n resolver: TokenMetadataResolver,\n chainId: string,\n tokenSymbol: string,\n): Promise<BridgeFeeEstimate> {\n const metadata = await resolver.getTokenMetadata(tokenSymbol);\n const feeResponse = await client.fetchBridgeFee({\n chainId,\n bridgeToken: metadata.descriptor,\n });\n return buildFeePayload(assertUsableFee(feeResponse));\n}\n\n/**\n * The status of a bridge transaction, from GalaConnect.\n *\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` for an answer that is not an object\n */\nexport async function getStrategyStatus(\n client: GalaConnectClient,\n transactionHash: string,\n): Promise<BridgeStatus> {\n const response = await client.getBridgeStatus(transactionHash);\n return parseBridgeStatusResponse(assertStatusAnswer(response));\n}\n\n/**\n * The configured token symbols (the map's normalized keys).\n */\nexport function getConfiguredTokenSymbols(tokenConfigs: ReadonlyMap<string, unknown>): string[] {\n return Array.from(tokenConfigs.keys());\n}\n\n/**\n * Whether a token symbol is configured (compared normalized: trimmed, upper case).\n */\nexport function isConfiguredToken(\n tokenConfigs: ReadonlyMap<string, unknown>,\n tokenSymbol: string,\n): boolean {\n return tokenConfigs.has(normalizeTokenSymbol(tokenSymbol));\n}\n","/**\n * Token Metadata Resolver\n *\n * Resolves (and caches) the GalaChain class key and decimals of a bridge token by symbol: the\n * static metadata of the well-known tokens first, else GalaConnect's verified bridge\n * configuration. Used by both bridge strategies.\n *\n * @module bridge/utils/tokenMetadataResolver\n */\n\nimport { GalaSDKError } from '../../index.js';\nimport { STATIC_TOKEN_METADATA } from '../constants/index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport { normalizeTokenSymbol } from '../internal/values.js';\nimport type { BridgeConfigurationToken, BridgeTokenMetadata } from '../types/index.js';\nimport { buildTokenMetadata } from './bridgePayload.js';\n\n/** The GalaConnect call a configuration comes from (the `method` of its errors). */\nconst CONFIGURATIONS_PATH = '/v1/connect/bridge-configurations';\n\n/**\n * Configuration for TokenMetadataResolver\n */\nexport interface TokenMetadataResolverConfig {\n /** GalaConnect client for API lookups */\n galaConnectClient: GalaConnectClient;\n}\n\n/** True when `token` has a usable class key (four strings) and decimals (an integer, 0 or more). */\nfunction isUsableConfiguration(token: BridgeConfigurationToken): boolean {\n return (\n [token.collection, token.category, token.type, token.additionalKey].every(\n (part) => typeof part === 'string',\n ) &&\n Number.isSafeInteger(token.decimals) &&\n token.decimals >= 0 &&\n (token.channel === undefined || typeof token.channel === 'string')\n );\n}\n\n/**\n * Token Metadata Resolver\n *\n * Provides cached token metadata resolution with fallback to API lookup.\n */\nexport class TokenMetadataResolver {\n private readonly galaConnectClient: GalaConnectClient;\n private readonly cache = new Map<string, BridgeTokenMetadata>();\n\n /**\n * Creates a new TokenMetadataResolver.\n *\n * @param config - Resolver configuration\n */\n constructor(config: TokenMetadataResolverConfig) {\n this.galaConnectClient = config.galaConnectClient;\n }\n\n /**\n * Get token metadata by symbol.\n *\n * Resolution order:\n * 1. In-memory cache\n * 2. Static metadata (well-known tokens like GALA, GUSDC)\n * 3. GalaConnect API lookup (the verified configuration of exactly this symbol)\n *\n * @param symbol - Token symbol (e.g., 'GALA', 'GUSDC')\n * @returns Token metadata including descriptor and decimals\n * @throws GalaSDKError `BRIDGE_TOKEN_NOT_FOUND` when GalaConnect has no verified configuration\n * for the symbol; `BRIDGE_READ_RESPONSE_INVALID` when the configuration has no usable class key\n * or decimals; the `GalaConnectClient` read errors\n */\n async getTokenMetadata(symbol: string): Promise<BridgeTokenMetadata> {\n const normalizedSymbol = normalizeTokenSymbol(symbol);\n\n // 1. Check in-memory cache\n const cached = this.cache.get(normalizedSymbol);\n if (cached) {\n return cached;\n }\n\n // 2. Check static metadata for well-known tokens\n const staticMetadata = STATIC_TOKEN_METADATA[normalizedSymbol];\n if (staticMetadata !== undefined) {\n this.cache.set(normalizedSymbol, staticMetadata);\n return staticMetadata;\n }\n\n // 3. Fetch from API\n const metadata = await this.fetchFromApi(symbol);\n this.cache.set(normalizedSymbol, metadata);\n return metadata;\n }\n\n /**\n * Fetch token metadata from GalaConnect API.\n */\n private async fetchFromApi(symbol: string): Promise<BridgeTokenMetadata> {\n const tokens = await this.galaConnectClient.getBridgeConfigurations(symbol);\n const token = tokens.find(\n (t) =>\n typeof t.symbol === 'string' &&\n normalizeTokenSymbol(t.symbol) === normalizeTokenSymbol(symbol) &&\n t.verified === true,\n );\n\n if (!token) {\n throw new GalaSDKError('BRIDGE_TOKEN_NOT_FOUND', { symbol }, { write: false });\n }\n if (!isUsableConfiguration(token)) {\n throw new GalaSDKError(\n 'BRIDGE_READ_RESPONSE_INVALID',\n { method: CONFIGURATIONS_PATH },\n { write: false },\n );\n }\n\n return buildTokenMetadata(\n {\n collection: token.collection,\n category: token.category,\n type: token.type,\n additionalKey: token.additionalKey,\n },\n token.decimals,\n token.channel,\n );\n }\n}\n","/**\n * Token Math Utilities\n *\n * Utilities for converting between decimal and base unit representations.\n */\n\nimport BigNumber from 'bignumber.js';\n\nimport { GalaSDKError } from '../../index.js';\nimport { toBigNumber } from '../internal/values.js';\n\n/** The finite number `amount` spells, or `undefined`. */\nfunction finiteDecimal(amount: string): BigNumber | undefined {\n if (typeof amount !== 'string' || amount === '') {\n return undefined;\n }\n try {\n const value = new BigNumber(amount);\n return value.isFinite() ? value : undefined;\n } catch {\n // `BigNumber.DEBUG = true` (an app setting on the shared bignumber.js) makes a non-number throw.\n return undefined;\n }\n}\n\n/**\n * Convert a decimal amount to base units (smallest denomination)\n *\n * @param amount - The decimal amount as a string (e.g., \"1.5\")\n * @param decimals - The number of decimal places\n * @returns The amount in base units as a bigint\n * @throws GalaSDKError `INVALID_BRIDGE_AMOUNT`: `not_a_number`, or `too_many_decimals` when it\n * cannot be represented with the given decimals (it is never rounded)\n */\nexport function toBaseUnits(amount: string, decimals: number): bigint {\n const value = finiteDecimal(amount);\n if (value === undefined) {\n throw new GalaSDKError('INVALID_BRIDGE_AMOUNT', {\n value: String(amount),\n reason: 'not_a_number',\n });\n }\n const scaled = value.multipliedBy(toBigNumber(10).pow(decimals));\n if (!scaled.isInteger()) {\n throw new GalaSDKError('INVALID_BRIDGE_AMOUNT', { value: amount, reason: 'too_many_decimals' });\n }\n return BigInt(scaled.toFixed(0));\n}\n\n/**\n * Convert base units to a decimal string\n *\n * @param amount - The amount in base units\n * @param decimals - The number of decimal places\n * @returns The decimal string representation with the fraction's trailing zeros removed\n */\nexport function fromBaseUnits(amount: bigint, decimals: number): string {\n const value = toBigNumber(amount.toString());\n return trimFraction(value.dividedBy(toBigNumber(10).pow(decimals)).toFixed(decimals));\n}\n\n/**\n * Drops the trailing zeros of a FRACTION (and a point left bare): \"1.500\" is \"1.5\", \"100.00\" is\n * \"100\", and a whole number keeps every digit (\"100\" stays \"100\").\n */\nfunction trimFraction(text: string): string {\n return text.includes('.') ? text.replace(/\\.?0+$/u, '') : text;\n}\n\n/**\n * Threshold below which we use scientific notation (1 millionth).\n * Numbers smaller than this are hard to read in decimal form.\n */\nconst SCIENTIFIC_NOTATION_THRESHOLD = 0.000001;\n\n/**\n * Format a token amount for display\n *\n * @param amount - The decimal amount as a string\n * @param maxDecimals - Maximum decimals to display (default: 6)\n * @returns Formatted string with appropriate precision\n */\nexport function formatTokenAmount(amount: string, maxDecimals = 6): string {\n // An amount that is not a finite number reads as 0 (toBigNumber's fallback).\n const value = toBigNumber(amount);\n\n // For very small numbers (< 0.000001), use scientific notation for clarity\n if (value.abs().lt(SCIENTIFIC_NOTATION_THRESHOLD) && !value.isZero()) {\n return value.toExponential(2);\n }\n\n // Determine appropriate decimal places\n const decimals = Math.min(\n maxDecimals,\n value.abs().lt(1) ? maxDecimals : value.abs().lt(100) ? 4 : 2,\n );\n\n return trimFraction(value.toFixed(decimals));\n}\n\n/**\n * Compare two token amounts\n *\n * @param a - First amount\n * @param b - Second amount\n * @returns -1 if a < b, 0 if a == b, 1 if a > b\n */\nexport function compareAmounts(a: string, b: string): -1 | 0 | 1 {\n const valueA = toBigNumber(a);\n const valueB = toBigNumber(b);\n // BigNumber.comparedTo always returns exactly -1, 0, or 1 (not arbitrary numbers)\n return valueA.comparedTo(valueB) as -1 | 0 | 1;\n}\n","/**\n * Bridge Strategy Interface\n *\n * Defines the contract for chain-specific bridge implementations.\n * Each external chain (Ethereum, Solana) implements this interface\n * to handle its unique signing, transaction, and status tracking logic.\n */\n\nimport { GalaSDKError } from '../../index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport {\n type BridgeFeeEstimate,\n type BridgeInParams,\n type BridgeOutParams,\n type BridgeStatus,\n BridgeStatusCode,\n type BridgeTransaction,\n type ExternalNetwork,\n} from '../types/index.js';\nimport { delay } from '../utils/retry.js';\nimport {\n getConfiguredTokenSymbols,\n getStrategyStatus,\n isConfiguredToken,\n} from '../utils/strategyDelegation.js';\n\n/** How a strategy waits (a poll interval, a wait before a step). Default: a timer. */\nexport type BridgeSleep = (ms: number) => Promise<void>;\n\n/**\n * Strategy interface for chain-specific bridge operations.\n *\n * The Bridge SDK uses the Strategy pattern to abstract chain-specific logic:\n * - EthereumBridgeStrategy: Handles ERC-20 approvals, ethers.js signing\n * - SolanaBridgeStrategy: Handles SPL token accounts, @solana/web3.js signing\n *\n * Each strategy encapsulates:\n * - Fee estimation for the target chain\n * - Outbound transfers (GalaChain → External)\n * - Inbound transfers (External → GalaChain)\n * - Status polling and transaction tracking\n */\nexport interface BridgeStrategy {\n /**\n * The external network this strategy handles.\n */\n readonly network: ExternalNetwork;\n\n /**\n * Estimate bridge fees for a transfer (a per-transfer cost: it does not depend on the amount).\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GUSDC')\n * @returns Fee estimate with breakdown\n */\n estimateFee(tokenSymbol: string): Promise<BridgeFeeEstimate>;\n\n /**\n * Bridge tokens OUT from GalaChain to external chain.\n *\n * Flow:\n * 1. Lock tokens on GalaChain (via GalaConnect)\n * 2. Wait for bridge confirmation\n * 3. Receive wrapped tokens on external chain\n *\n * @param params - Bridge out parameters\n * @returns Transaction details with tracking info\n */\n bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction>;\n\n /**\n * Bridge tokens IN from external chain to GalaChain.\n *\n * Flow:\n * 1. Approve bridge contract (if needed)\n * 2. Deposit tokens to bridge contract\n * 3. Register the deposit with GalaConnect\n * 4. Receive native tokens on GalaChain\n *\n * @param params - Bridge in parameters\n * @returns Transaction details with tracking info\n */\n bridgeIn(params: BridgeInParams): Promise<BridgeTransaction>;\n\n /**\n * Get the current status of a bridge transaction.\n *\n * @param transactionHash - The bridge transaction hash\n * @returns Current status with details\n */\n getStatus(transactionHash: string): Promise<BridgeStatus>;\n\n /**\n * Wait for a bridge transaction to complete.\n *\n * Polls the transaction status until it reaches a terminal state\n * (completed or failed) or the timeout is reached.\n *\n * @param transactionHash - The bridge transaction hash\n * @param options - Polling options\n * @returns Final status when complete\n * @throws GalaSDKError `BRIDGE_STATUS_TIMEOUT` if the timeout is reached first;\n * `INVALID_BRIDGE_OPTION` for a poll interval or timeout that is not a finite number, 0 or more\n */\n waitForCompletion(transactionHash: string, options?: WaitOptions): Promise<BridgeStatus>;\n\n /**\n * Get the list of supported tokens for this chain.\n *\n * @returns Array of token symbols supported by this bridge\n */\n getSupportedTokens(): string[];\n\n /**\n * Check if a specific token is supported for bridging.\n *\n * @param tokenSymbol - Token symbol to check\n * @returns True if token can be bridged\n */\n isTokenSupported(tokenSymbol: string): boolean;\n\n /**\n * Validate a recipient address for the external chain.\n *\n * @param address - Address to validate\n * @returns True if address is valid for this chain\n */\n isValidAddress(address: string): boolean;\n}\n\n/**\n * Options for waiting on bridge completion.\n */\nexport interface WaitOptions {\n /**\n * Polling interval in milliseconds.\n * @default 15000 (15 seconds)\n */\n pollInterval?: number;\n\n /**\n * Maximum time to wait in milliseconds.\n * @default 2700000 (45 minutes)\n */\n timeout?: number;\n\n /**\n * Callback for status updates during polling.\n */\n onStatusUpdate?: (status: BridgeStatus) => void;\n}\n\n/** The statuses after which a bridge transaction changes no more. */\nconst TERMINAL_STATUSES: ReadonlySet<BridgeStatusCode> = new Set([\n BridgeStatusCode.COMPLETED,\n BridgeStatusCode.FAILED,\n BridgeStatusCode.DELIVERY_FAILED,\n]);\n\n/**\n * Base class providing common functionality for bridge strategies.\n *\n * Concrete strategies extend this class and implement chain-specific logic.\n */\nexport abstract class BaseBridgeStrategy implements BridgeStrategy {\n abstract readonly network: ExternalNetwork;\n\n /** How this strategy waits between polls (and before a step it must wait for). */\n protected readonly sleep: BridgeSleep;\n\n /**\n * @param sleep - How the strategy waits (default: a timer)\n */\n protected constructor(sleep: BridgeSleep = delay) {\n this.sleep = sleep;\n }\n\n abstract estimateFee(tokenSymbol: string): Promise<BridgeFeeEstimate>;\n abstract bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction>;\n abstract bridgeIn(params: BridgeInParams): Promise<BridgeTransaction>;\n abstract getStatus(transactionHash: string): Promise<BridgeStatus>;\n abstract getSupportedTokens(): string[];\n abstract isTokenSupported(tokenSymbol: string): boolean;\n abstract isValidAddress(address: string): boolean;\n\n /**\n * Default implementation of waitForCompletion with polling.\n *\n * Strategies can override this if they have chain-specific\n * event subscription capabilities.\n */\n async waitForCompletion(\n transactionHash: string,\n options: WaitOptions = {},\n ): Promise<BridgeStatus> {\n const {\n pollInterval = 15000,\n timeout = 45 * 60 * 1000, // 45 minutes\n onStatusUpdate,\n } = options;\n // A NaN timeout would never be exceeded (an endless poll); refused, like a negative one.\n for (const [option, value] of [\n ['pollInterval', pollInterval],\n ['timeout', timeout],\n ] as const) {\n if (!Number.isFinite(value) || value < 0) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option });\n }\n }\n\n const startTime = Date.now();\n\n while (true) {\n const status = await this.getStatus(transactionHash);\n\n if (onStatusUpdate) {\n onStatusUpdate(status);\n }\n\n // Check for terminal states (COMPLETED, FAILED, or DELIVERY_FAILED)\n if (TERMINAL_STATUSES.has(status.status)) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > timeout) {\n throw new GalaSDKError(\n 'BRIDGE_STATUS_TIMEOUT',\n { transactionHash, timeoutMs: timeout, lastStatus: status.status },\n { write: false },\n );\n }\n\n // Wait before next poll\n await this.sleep(pollInterval);\n }\n }\n}\n\n/**\n * Base implementation for strategies backed by a configured token map.\n *\n * @typeParam TTokenConfig - Chain-specific token configuration type.\n */\nexport abstract class ConfiguredBridgeStrategy<TTokenConfig> extends BaseBridgeStrategy {\n protected readonly galaConnectClient: GalaConnectClient;\n protected readonly tokenConfigs: Map<string, TTokenConfig>;\n\n /**\n * Create a configured strategy base.\n *\n * @param galaConnectClient - Client used for bridge requests.\n * @param tokenConfigs - Normalized token configuration map.\n * @param sleep - How the strategy waits (default: a timer).\n */\n protected constructor(\n galaConnectClient: GalaConnectClient,\n tokenConfigs: Map<string, TTokenConfig>,\n sleep?: BridgeSleep,\n ) {\n super(sleep);\n this.galaConnectClient = galaConnectClient;\n this.tokenConfigs = tokenConfigs;\n }\n\n /**\n * Get the current status of a bridge transaction.\n *\n * @param transactionHash - Transaction hash to check.\n * @returns Current bridge status.\n */\n async getStatus(transactionHash: string): Promise<BridgeStatus> {\n return getStrategyStatus(this.galaConnectClient, transactionHash);\n }\n\n /**\n * Get the configured symbols supported by this strategy.\n *\n * @returns Supported token symbols.\n */\n getSupportedTokens(): string[] {\n return getConfiguredTokenSymbols(this.tokenConfigs);\n }\n\n /**\n * Check whether a token symbol is configured for this strategy.\n *\n * @param tokenSymbol - Token symbol to check.\n * @returns True when the token is configured.\n */\n isTokenSupported(tokenSymbol: string): boolean {\n return isConfiguredToken(this.tokenConfigs, tokenSymbol);\n }\n}\n","/**\n * Ethereum Bridge Strategy\n *\n * Handles bridging between GalaChain and Ethereum:\n * - Outbound (GalaChain → Ethereum): the EIP-712 signed bridge-out through GalaConnect\n * - Inbound (Ethereum → GalaChain): ERC-20 approve or permit, the bridge contract deposit, and the\n * registration with GalaConnect\n *\n * Failures are `GalaSDKError`s. Everything before the deposit transaction is sent is a refusal\n * that left nothing behind (a bad amount, key or token, a read that failed, a balance that is too\n * low); once the deposit is being sent, every failure is `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN` (with the\n * transaction hash when it is known): the funds may have left the wallet, so another deposit must\n * not be sent before this one is checked.\n */\n\nimport {\n Contract,\n type ContractTransactionResponse,\n JsonRpcProvider,\n Signature,\n Wallet as EthersWallet,\n} from 'ethers';\n\nimport { GalaSDKError, galaChainUserRef, type BridgeDepositStep } from '../../index.js';\nimport {\n BRIDGE_CONTRACT_ABI,\n CHAIN_IDS,\n DEFAULT_ETHEREUM_RPC_URL,\n ERC20_ABI,\n} from '../constants/index.js';\nimport { ETHEREUM_TOKENS_PROD } from '../constants/tokens.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport { getErrorMessage } from '../internal/values.js';\nimport type {\n BridgeFeeEstimate,\n BridgeInParams,\n BridgeOutParams,\n BridgeTokenMetadata,\n BridgeTransaction,\n EthereumTokenConfig,\n EthereumTransactionStatus,\n ExternalNetwork,\n} from '../types/index.js';\nimport {\n createTokenConfigMap,\n requireTokenConfig,\n validateEthereumPrivateKeyFormat,\n validateEthereumTransactionHashFormat,\n} from '../utils/addressValidation.js';\nimport { buildBridgeInboundTransaction } from '../utils/balanceHelpers.js';\nimport {\n assertEthereumAddressOption,\n assertHttpUrlOption,\n assertTokenSymbolResolved,\n validateEthereumAddressOrThrow,\n} from '../utils/bridgeErrors.js';\nimport { executeBridgeOutFlow } from '../utils/bridgeOutHelpers.js';\nimport { validateBridgeAmount } from '../utils/bridgePayload.js';\nimport { estimateStrategyFee } from '../utils/strategyDelegation.js';\nimport { TokenMetadataResolver } from '../utils/tokenMetadataResolver.js';\nimport { fromBaseUnits, toBaseUnits } from '../utils/tokenMath.js';\nimport { type BridgeSleep, ConfiguredBridgeStrategy } from './BridgeStrategy.js';\n\n/** A contract runner: the wallet (to send) or the provider (to read). */\ntype Runner = ConstructorParameters<typeof Contract>[2];\n\n/**\n * {@link ERC20_ABI}'s functions as ethers decodes them (every `uint` a `bigint`, `string` a\n * string): an ethers `Contract` has a method per ABI function, typed only as \"any method\".\n */\ninterface Erc20Contract {\n decimals(): Promise<bigint>;\n balanceOf(owner: string): Promise<bigint>;\n allowance(owner: string, spender: string): Promise<bigint>;\n name(): Promise<string>;\n nonces(owner: string): Promise<bigint>;\n approve(spender: string, value: bigint): Promise<ContractTransactionResponse>;\n}\n\n/** {@link BRIDGE_CONTRACT_ABI}'s functions as ethers sends them. */\ninterface BridgeContract {\n bridgeOut(\n token: string,\n amount: bigint,\n tokenId: number,\n destinationChainId: number,\n recipient: Uint8Array,\n ): Promise<ContractTransactionResponse>;\n bridgeOutWithPermit(\n token: string,\n amount: bigint,\n destinationChainId: number,\n recipient: Uint8Array,\n deadline: bigint,\n v: number,\n r: string,\n s: string,\n ): Promise<ContractTransactionResponse>;\n}\n\n/** The ERC-20 token at `address`. */\nfunction erc20At(address: string, runner: Runner): Erc20Contract {\n return new Contract(address, ERC20_ABI, runner) as unknown as Erc20Contract;\n}\n\n/**\n * An Ethereum read before anything is sent: its failure (the node down or refusing, an answer\n * ethers cannot decode) is `BRIDGE_CHAIN_READ_FAILED` (`call`, the failure as `cause`).\n */\nasync function chainRead<T>(call: string, read: () => Promise<T>): Promise<T> {\n try {\n return await read();\n } catch (cause: unknown) {\n throw new GalaSDKError(\n 'BRIDGE_CHAIN_READ_FAILED',\n { network: 'Ethereum', call },\n { write: false, cause },\n );\n }\n}\n\n/** `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN` for an Ethereum deposit that failed at `step`. */\nfunction depositOutcomeUnknown(\n step: BridgeDepositStep,\n transactionHash: string,\n cause: unknown,\n): GalaSDKError {\n return new GalaSDKError(\n 'BRIDGE_DEPOSIT_OUTCOME_UNKNOWN',\n { network: 'Ethereum', step, transactionHash },\n { cause },\n );\n}\n\n/**\n * Configuration for Ethereum bridge strategy.\n */\nexport interface EthereumBridgeConfig {\n /** GalaConnect API client */\n galaConnectClient: GalaConnectClient;\n /** GalaChain wallet address (`eth|<40 hex>`; `eth|0x...` is refused) */\n galaChainWalletAddress: string;\n /** Ethereum private key for signing */\n ethereumPrivateKey: string;\n /** Ethereum RPC URL (default: {@link DEFAULT_ETHEREUM_RPC_URL}) */\n ethereumRpcUrl?: string;\n /**\n * Ethereum bridge contract address: where inbound deposits (and their approvals and permits) go.\n * Required: there is no default (`getEthereumBridgeContractByEnvironment` gives the deployed one).\n */\n ethereumBridgeContract: string;\n /** Ethereum wallet address (derived from private key if not provided) */\n ethereumWalletAddress?: string;\n /** Token configurations (default: {@link ETHEREUM_TOKENS_PROD}) */\n tokenConfigs?: EthereumTokenConfig[];\n /** How the strategy waits (the delay before an inbound registration). Default: a timer. */\n sleep?: BridgeSleep;\n}\n\n/** Registration delay before notifying GalaConnect of inbound bridge */\nconst REGISTRATION_DELAY_MS = 30_000;\n\n/** An Ethereum address as `isValidAddress` accepts it: `0x` and 40 hex digits. */\nconst ETHEREUM_ADDRESS = /^0x[0-9a-fA-F]{40}$/u;\n\n/**\n * Bridge strategy for GalaChain ↔ Ethereum transfers.\n *\n * Supports 6 tokens: GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC\n */\nexport class EthereumBridgeStrategy extends ConfiguredBridgeStrategy<EthereumTokenConfig> {\n readonly network: ExternalNetwork = 'Ethereum';\n\n /**\n * Ethereum finality threshold (number of confirmations).\n * 12+ confirmations is the practical finality threshold for Ethereum mainnet.\n */\n static readonly ETHEREUM_FINALITY_THRESHOLD = 12;\n\n private readonly galaChainWalletAddress: string;\n private readonly ethereumProvider: JsonRpcProvider;\n private readonly ethereumWallet: EthersWallet;\n private readonly ethereumBridgeContract: string;\n private readonly ethereumWalletAddress: string;\n private readonly tokenMetadataResolver: TokenMetadataResolver;\n\n /**\n * Creates a new Ethereum bridge strategy.\n *\n * @param config - Strategy configuration\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` if ethereumPrivateKey is not 0x and 64 hex digits;\n * `INVALID_BRIDGE_OPTION` (the option) for a bridge contract or wallet address that is not an\n * Ethereum address (the contract is required), or an RPC URL that is not http(s)\n */\n constructor(config: EthereumBridgeConfig) {\n const tokens = config.tokenConfigs ?? ETHEREUM_TOKENS_PROD;\n super(config.galaConnectClient, createTokenConfigMap(tokens), config.sleep);\n for (const token of tokens) assertEthereumAddressOption(token.contractAddress, 'tokenConfigs');\n\n this.galaChainWalletAddress = config.galaChainWalletAddress;\n\n // Validate private key format before use (prevents malformed key crashes)\n validateEthereumPrivateKeyFormat(config.ethereumPrivateKey);\n // Every address and URL option is checked here: a malformed one is refused now, by name,\n // never as a library error at the first request (or after an allowance was granted).\n const ethereumBridgeContract = assertEthereumAddressOption(\n config.ethereumBridgeContract,\n 'ethereumBridgeContract',\n );\n const rpcUrl = assertHttpUrlOption(\n config.ethereumRpcUrl ?? DEFAULT_ETHEREUM_RPC_URL,\n 'ethereumRpcUrl',\n );\n if (config.ethereumWalletAddress !== undefined) {\n assertEthereumAddressOption(config.ethereumWalletAddress, 'ethereumWalletAddress');\n }\n\n // Initialize Ethereum provider and wallet\n this.ethereumProvider = new JsonRpcProvider(rpcUrl);\n this.ethereumWallet = new EthersWallet(config.ethereumPrivateKey, this.ethereumProvider);\n\n this.ethereumWalletAddress = config.ethereumWalletAddress ?? this.ethereumWallet.address;\n this.ethereumBridgeContract = ethereumBridgeContract;\n\n this.tokenMetadataResolver = new TokenMetadataResolver({\n galaConnectClient: this.galaConnectClient,\n });\n }\n\n /**\n * Estimate bridge fees for a transfer to Ethereum.\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GWETH')\n * @returns Fee estimate with breakdown (it does not depend on the amount)\n */\n async estimateFee(tokenSymbol: string): Promise<BridgeFeeEstimate> {\n return estimateStrategyFee(\n this.galaConnectClient,\n this.tokenMetadataResolver,\n 'Ethereum',\n tokenSymbol,\n );\n }\n\n /**\n * Bridge tokens from GalaChain to Ethereum.\n *\n * @param params - Bridge out parameters\n * @returns Transaction details\n */\n async bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction> {\n return executeBridgeOutFlow(params, {\n galaConnectClient: this.galaConnectClient,\n tokenMetadataResolver: this.tokenMetadataResolver,\n ethereumWallet: this.ethereumWallet,\n destinationChainId: CHAIN_IDS.ETHEREUM,\n destinationChain: 'Ethereum',\n validateRecipientAddress: validateEthereumAddressOrThrow,\n });\n }\n\n /**\n * Bridge tokens from Ethereum to GalaChain.\n *\n * @param params - Bridge in parameters\n * @returns Transaction details\n * @throws GalaSDKError before the deposit is sent: the input's refusal, `BRIDGE_CHAIN_READ_FAILED`,\n * `INSUFFICIENT_BRIDGE_BALANCE`; once it is being sent: `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`\n */\n async bridgeIn(params: BridgeInParams): Promise<BridgeTransaction> {\n const { amount, sourcePrivateKey, recipientAddress, tokenSymbol: resolvedSymbol } = params;\n\n // Validate that BridgeService resolved the symbol\n const tokenSymbol = assertTokenSymbolResolved(resolvedSymbol);\n\n // Validate amount (prevents wasted gas on zero/negative amounts)\n validateBridgeAmount(amount);\n\n // Validate sourcePrivateKey format if provided\n const hasSourceKey = sourcePrivateKey !== undefined && sourcePrivateKey !== '';\n if (hasSourceKey) {\n validateEthereumPrivateKeyFormat(sourcePrivateKey);\n }\n\n // The GalaChain recipient, normalized (eth|<checksummed> or a client| alias) before anything\n // is read\n const recipient = galaChainUserRef(recipientAddress ?? this.galaChainWalletAddress, 'address');\n\n // Use provided private key or fall back to configured wallet\n const wallet = hasSourceKey\n ? new EthersWallet(sourcePrivateKey, this.ethereumProvider)\n : this.ethereumWallet;\n\n const tokenConfig = requireTokenConfig(this.tokenConfigs, tokenSymbol, 'Ethereum');\n const metadata = await this.tokenMetadataResolver.getTokenMetadata(tokenSymbol);\n\n // Get token contract\n const tokenContract = erc20At(tokenConfig.contractAddress, wallet);\n\n // Get decimals (a uint8, from the token itself) and calculate base units\n const decimals = Number(await chainRead('decimals', () => tokenContract.decimals()));\n const amountBaseUnits = toBaseUnits(amount, decimals);\n\n // Check balance\n const currentBalance = await chainRead('balanceOf', () =>\n tokenContract.balanceOf(wallet.address),\n );\n if (currentBalance < amountBaseUnits) {\n throw new GalaSDKError('INSUFFICIENT_BRIDGE_BALANCE', {\n network: 'Ethereum',\n symbol: tokenSymbol,\n needed: fromBaseUnits(amountBaseUnits, decimals),\n available: fromBaseUnits(currentBalance, decimals),\n });\n }\n\n const txHash = await this.executeBridgeDeposit({\n wallet,\n tokenContract,\n tokenConfig,\n amountBaseUnits,\n decimals,\n recipient,\n metadata,\n });\n\n return buildBridgeInboundTransaction({\n fromChain: 'Ethereum',\n transactionHash: txHash,\n tokenSymbol,\n amount,\n baseUrl: this.galaConnectClient.getBaseUrl(),\n });\n }\n\n /**\n * Validate an Ethereum address.\n *\n * @param address - Address to validate\n * @returns True if `0x` and 40 hex digits\n */\n isValidAddress(address: string): boolean {\n return ETHEREUM_ADDRESS.test(address);\n }\n\n // ==========================================================================\n // Wallet Info Methods\n // ==========================================================================\n\n /**\n * Get the configured Ethereum wallet address.\n *\n * @returns Ethereum wallet address (0x format)\n */\n getWalletAddress(): string {\n return this.ethereumWalletAddress;\n }\n\n // ==========================================================================\n // Balance Checking Methods\n // ==========================================================================\n\n /**\n * Get ERC-20 token balance for an Ethereum address.\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GWETH', 'GUSDC')\n * @param address - Optional Ethereum address (defaults to configured wallet)\n * @returns Token balance as decimal string (e.g., \"123.45678901\")\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN`, `INVALID_WALLET_ADDRESS`,\n * `BRIDGE_CHAIN_READ_FAILED`\n */\n async getEthereumTokenBalance(tokenSymbol: string, address?: string): Promise<string> {\n const tokenConfig = requireTokenConfig(this.tokenConfigs, tokenSymbol, 'Ethereum');\n const targetAddress = address ?? this.ethereumWalletAddress;\n validateEthereumAddressOrThrow(targetAddress);\n\n const tokenContract = erc20At(tokenConfig.contractAddress, this.ethereumProvider);\n const balanceBaseUnits = await chainRead('balanceOf', () =>\n tokenContract.balanceOf(targetAddress),\n );\n\n // The configured decimals, else the token's own (never an assumed 18).\n const decimals =\n tokenConfig.decimals ?? Number(await chainRead('decimals', () => tokenContract.decimals()));\n return fromBaseUnits(balanceBaseUnits, decimals);\n }\n\n /**\n * Get native ETH balance for an Ethereum address.\n *\n * @param address - Optional Ethereum address (defaults to configured wallet)\n * @returns ETH balance as decimal string (18 decimals)\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if address invalid\n */\n async getEthereumNativeBalance(address?: string): Promise<string> {\n const targetAddress = address ?? this.ethereumWalletAddress;\n validateEthereumAddressOrThrow(targetAddress);\n const balanceWei: bigint = await this.ethereumProvider.getBalance(targetAddress);\n return fromBaseUnits(balanceWei, 18);\n }\n\n // ==========================================================================\n // Transaction Status Methods\n // ==========================================================================\n\n /**\n * Get the status of an Ethereum transaction by hash.\n *\n * Queries Ethereum RPC directly using `getTransactionReceipt()` and `getTransaction()`. An RPC\n * failure is answered as `not_found` with the failure in `error`.\n *\n * @param transactionHash - Ethereum transaction hash (0x-prefixed, 64 hex characters)\n * @returns Transaction status with confirmation details\n * @throws GalaSDKError `INVALID_TRANSACTION_HASH` if hash format is invalid\n */\n async getEthereumTransactionStatus(transactionHash: string): Promise<EthereumTransactionStatus> {\n validateEthereumTransactionHashFormat(transactionHash);\n\n // Normalize hash to lowercase for consistency\n const normalizedHash = transactionHash.toLowerCase();\n\n try {\n // Try to get transaction receipt (only exists if mined)\n const receipt = await this.ethereumProvider.getTransactionReceipt(normalizedHash);\n\n if (receipt) {\n const currentBlock = await this.ethereumProvider.getBlockNumber();\n const confirmations = currentBlock - receipt.blockNumber + 1;\n\n if (receipt.status !== 1) {\n // Transaction was mined but reverted\n return {\n confirmed: false,\n status: 'failed',\n blockNumber: receipt.blockNumber,\n confirmations,\n transactionHash: normalizedHash,\n gasUsed: receipt.gasUsed.toString(),\n effectiveGasPrice: receipt.gasPrice.toString(),\n error: 'Transaction reverted during execution',\n };\n }\n\n const isFinalized = confirmations >= EthereumBridgeStrategy.ETHEREUM_FINALITY_THRESHOLD;\n return {\n confirmed: true,\n status: isFinalized ? 'finalized' : 'confirmed',\n blockNumber: receipt.blockNumber,\n confirmations,\n transactionHash: normalizedHash,\n gasUsed: receipt.gasUsed.toString(),\n effectiveGasPrice: receipt.gasPrice.toString(),\n };\n }\n\n // No receipt - check if transaction exists in mempool (pending)\n const transaction = await this.ethereumProvider.getTransaction(normalizedHash);\n if (transaction) {\n return {\n confirmed: false,\n status: 'pending',\n transactionHash: normalizedHash,\n };\n }\n\n return {\n confirmed: false,\n status: 'not_found',\n transactionHash: normalizedHash,\n error: 'Transaction not found on Ethereum network',\n };\n } catch (error: unknown) {\n return {\n confirmed: false,\n status: 'not_found',\n transactionHash: normalizedHash,\n error: `Failed to query transaction status: ${getErrorMessage(error)}`,\n };\n }\n }\n\n // ==========================================================================\n // Private Methods\n // ==========================================================================\n\n /**\n * Execute bridge deposit on Ethereum: prepare it (reads, an approval or a permit), send it, wait\n * for its receipt, wait {@link REGISTRATION_DELAY_MS}, register it with GalaConnect. From the\n * send on, every failure is `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`.\n */\n private async executeBridgeDeposit(params: {\n wallet: EthersWallet;\n tokenContract: Erc20Contract;\n tokenConfig: EthereumTokenConfig;\n amountBaseUnits: bigint;\n decimals: number;\n recipient: string;\n metadata: BridgeTokenMetadata;\n }): Promise<string> {\n const bridgeContract = new Contract(\n this.ethereumBridgeContract,\n BRIDGE_CONTRACT_ABI,\n params.wallet,\n ) as unknown as BridgeContract;\n\n const recipientBytes = new TextEncoder().encode(params.recipient);\n\n const sendDeposit = params.tokenConfig.bridgeUsesPermit\n ? await this.prepareBridgeWithPermit(\n params.wallet,\n params.tokenContract,\n params.tokenConfig,\n bridgeContract,\n params.amountBaseUnits,\n recipientBytes,\n )\n : await this.prepareBridgeWithApproval(\n params.wallet,\n params.tokenContract,\n bridgeContract,\n params.tokenConfig,\n params.amountBaseUnits,\n recipientBytes,\n );\n\n let tx: ContractTransactionResponse;\n try {\n tx = await sendDeposit();\n } catch (cause: unknown) {\n throw depositOutcomeUnknown('send', '', cause);\n }\n\n // wait() (one confirmation) resolves once the deposit is mined and throws when it reverted.\n try {\n await tx.wait();\n } catch (cause: unknown) {\n throw depositOutcomeUnknown('confirmation', tx.hash, cause);\n }\n\n try {\n await this.sleep(REGISTRATION_DELAY_MS);\n await this.galaConnectClient.registerBridgeTransaction({\n quantity: fromBaseUnits(params.amountBaseUnits, params.decimals),\n tokenInstance: {\n collection: params.metadata.descriptor.collection,\n category: params.metadata.descriptor.category,\n type: params.metadata.descriptor.type,\n additionalKey: params.metadata.descriptor.additionalKey,\n instance: '0',\n },\n fromChain: 'Ethereum',\n toChain: 'GC',\n hash: tx.hash,\n });\n } catch (cause: unknown) {\n throw depositOutcomeUnknown('registration', tx.hash, cause);\n }\n\n return tx.hash;\n }\n\n /**\n * Bridge using ERC-20 Permit for gas-less approval: reads the chain id, the token name and the\n * permit nonce, signs the permit, and returns the deposit send (not yet sent).\n */\n private async prepareBridgeWithPermit(\n wallet: EthersWallet,\n tokenContract: Erc20Contract,\n tokenConfig: EthereumTokenConfig,\n bridgeContract: BridgeContract,\n amountBaseUnits: bigint,\n recipientBytes: Uint8Array,\n ): Promise<() => Promise<ContractTransactionResponse>> {\n const network = await chainRead('chainId', () => this.ethereumProvider.getNetwork());\n const name = await chainRead('name', () => tokenContract.name());\n const nonce = await chainRead('nonces', () => tokenContract.nonces(wallet.address));\n const deadline = BigInt(Math.floor(Date.now() / 1000) + 60 * 60);\n\n // Sign permit\n const signature = await wallet.signTypedData(\n {\n name,\n version: '1',\n chainId: Number(network.chainId),\n verifyingContract: tokenConfig.contractAddress,\n },\n {\n Permit: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n ],\n },\n {\n owner: wallet.address,\n spender: this.ethereumBridgeContract,\n value: amountBaseUnits,\n nonce,\n deadline,\n },\n );\n\n const splitSig = Signature.from(signature);\n\n return () =>\n bridgeContract.bridgeOutWithPermit(\n tokenConfig.contractAddress,\n amountBaseUnits,\n CHAIN_IDS.GALA_CHAIN,\n recipientBytes,\n deadline,\n splitSig.v,\n splitSig.r,\n splitSig.s,\n );\n }\n\n /**\n * Bridge using traditional ERC-20 approval: reads the allowance, sends (and waits for) an\n * approval when it is too low, and returns the deposit send (not yet sent).\n */\n private async prepareBridgeWithApproval(\n wallet: EthersWallet,\n tokenContract: Erc20Contract,\n bridgeContract: BridgeContract,\n tokenConfig: EthereumTokenConfig,\n amountBaseUnits: bigint,\n recipientBytes: Uint8Array,\n ): Promise<() => Promise<ContractTransactionResponse>> {\n const allowance = await chainRead('allowance', () =>\n tokenContract.allowance(wallet.address, this.ethereumBridgeContract),\n );\n\n // An approval moves no funds: if it fails, a retry of the whole bridge-in is safe.\n if (allowance < amountBaseUnits) {\n const approveTx = await tokenContract.approve(this.ethereumBridgeContract, amountBaseUnits);\n await approveTx.wait();\n }\n\n return () =>\n bridgeContract.bridgeOut(\n tokenConfig.contractAddress,\n amountBaseUnits,\n 0, // tokenId (0 for fungible)\n CHAIN_IDS.GALA_CHAIN,\n recipientBytes,\n );\n }\n}\n","/**\n * Solana Bridge Strategy\n *\n * Handles bridging between GalaChain and Solana:\n * - Outbound (GalaChain → Solana): the EIP-712 signed bridge-out through GalaConnect\n * - Inbound (Solana → GalaChain): the bridge program deposit (SPL or native SOL) and the\n * registration with GalaConnect\n *\n * Failures are `GalaSDKError`s. Everything before the deposit transaction is sent is a refusal\n * that left nothing behind; once it is being sent, every failure is\n * `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN` (with the transaction signature): the funds may have left the\n * wallet, so another deposit must not be sent before this one is checked.\n *\n * React Native: nothing here needs a `Buffer` global (instruction data and seeds are\n * `Uint8Array`s); `@solana/web3.js` brings its own `buffer` package.\n */\n\nimport {\n AccountLayout,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n MintLayout,\n TOKEN_PROGRAM_ID,\n} from '@solana/spl-token';\nimport {\n ComputeBudgetProgram,\n Connection,\n Keypair,\n LAMPORTS_PER_SOL,\n PublicKey,\n SystemProgram,\n Transaction,\n TransactionExpiredBlockheightExceededError,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { base58 } from '@scure/base';\nimport { Wallet as EthersWallet } from 'ethers';\n\nimport { GalaSDKError, galaChainUserRef, type BridgeDepositStep } from '../../index.js';\nimport {\n CHAIN_IDS,\n DEFAULT_SOLANA_BRIDGE_PROGRAM,\n DEFAULT_SOLANA_RPC_URL,\n DEFAULT_SOLANA_TOKENS,\n SOLANA_COMPUTE,\n SOLANA_DISCRIMINATORS,\n} from '../constants/index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport type {\n BridgeFeeEstimate,\n BridgeInParams,\n BridgeOutParams,\n BridgeTokenMetadata,\n BridgeTransaction,\n ExternalNetwork,\n SolanaTokenConfig,\n SolanaTransactionStatus,\n} from '../types/index.js';\nimport {\n createTokenConfigMap,\n requireTokenConfig,\n validateEthereumPrivateKeyFormat,\n} from '../utils/addressValidation.js';\nimport { buildBridgeInboundTransaction } from '../utils/balanceHelpers.js';\nimport {\n assertHttpUrlOption,\n assertTokenSymbolResolved,\n parseSolanaAddressOrThrow,\n solanaPublicKeyOption,\n validateSolanaAddressOrThrow,\n} from '../utils/bridgeErrors.js';\nimport { executeBridgeOutFlow } from '../utils/bridgeOutHelpers.js';\nimport { validateBridgeAmount } from '../utils/bridgePayload.js';\nimport { estimateStrategyFee } from '../utils/strategyDelegation.js';\nimport { TokenMetadataResolver } from '../utils/tokenMetadataResolver.js';\nimport { fromBaseUnits, toBaseUnits } from '../utils/tokenMath.js';\nimport { type BridgeSleep, ConfiguredBridgeStrategy } from './BridgeStrategy.js';\n\n/**\n * Configuration for Solana bridge strategy.\n */\nexport interface SolanaBridgeConfig {\n /** GalaConnect API client */\n galaConnectClient: GalaConnectClient;\n /** GalaChain wallet address (`eth|<40 hex>`; `eth|0x...` is refused) */\n galaChainWalletAddress: string;\n /** Ethereum private key for EIP-712 signing (GalaChain uses Ethereum signatures) */\n ethereumPrivateKey: string;\n /** Solana private key in base58 format */\n solanaPrivateKeyBase58: string;\n /** Solana RPC URL (default: {@link DEFAULT_SOLANA_RPC_URL}); unused when `solanaConnection` is given */\n solanaRpcUrl?: string;\n /** The Solana connection to use (default: one to `solanaRpcUrl`, commitment `confirmed`) */\n solanaConnection?: Connection;\n /** Solana bridge program ID (default: {@link DEFAULT_SOLANA_BRIDGE_PROGRAM}) */\n solanaBridgeProgram?: string;\n /** Token configurations (default: {@link DEFAULT_SOLANA_TOKENS}) */\n tokenConfigs?: SolanaTokenConfig[];\n /** How the strategy waits (the backoff before a resend). Default: a timer. */\n sleep?: BridgeSleep;\n}\n\n/** The type `@solana/web3.js` gives instruction data (a Node `Buffer`). */\ntype InstructionData = NonNullable<ConstructorParameters<typeof TransactionInstruction>[0]['data']>;\n\n/**\n * Instruction data as the bytes `@solana/web3.js` reads: it types the field as a `Buffer` but only\n * ever reads it as bytes (it base58-encodes it when it compiles the message), so a `Uint8Array`\n * goes in as it is and no `Buffer` global is needed. The recorded Solana vectors pin the signed\n * transactions byte for byte.\n */\nfunction instructionData(...parts: readonly Uint8Array[]): InstructionData {\n const length = parts.reduce((total, part) => total + part.length, 0);\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) {\n bytes.set(part, offset);\n offset += part.length;\n }\n return bytes as unknown as InstructionData;\n}\n\n/** `value` as 8 little-endian bytes (a u64). */\nfunction u64LittleEndian(value: bigint): Uint8Array {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setBigUint64(0, value, true);\n return bytes;\n}\n\n/** `value` as 4 little-endian bytes (a u32). */\nfunction u32LittleEndian(value: number): Uint8Array {\n const bytes = new Uint8Array(4);\n new DataView(bytes.buffer).setUint32(0, value, true);\n return bytes;\n}\n\n/** The UTF-8 bytes of `text` (a PDA seed, a recipient). */\nfunction utf8(text: string): Uint8Array {\n return new TextEncoder().encode(text);\n}\n\n/**\n * Derive Associated Token Account address synchronously using PDA derivation.\n */\nfunction getAssociatedTokenAddressSync(\n mint: PublicKey,\n owner: PublicKey,\n tokenProgramId: PublicKey,\n associatedTokenProgramId: PublicKey,\n): PublicKey {\n const [address] = PublicKey.findProgramAddressSync(\n [owner.toBytes(), tokenProgramId.toBytes(), mint.toBytes()],\n associatedTokenProgramId,\n );\n return address;\n}\n\n/** `BRIDGE_CHAIN_READ_FAILED` for a Solana read `call` that failed or answered something unusable. */\nfunction readFailed(call: string, cause?: unknown): GalaSDKError {\n return new GalaSDKError(\n 'BRIDGE_CHAIN_READ_FAILED',\n { network: 'Solana', call },\n { write: false, cause },\n );\n}\n\n/**\n * The amount of the token account at `address`, or `undefined` when there is no such account.\n *\n * @throws GalaSDKError `BRIDGE_CHAIN_READ_FAILED` when the account is not a token account of\n * `tokenProgramId`\n */\nasync function getTokenAccountAmount(\n connection: Connection,\n address: PublicKey,\n tokenProgramId: PublicKey,\n): Promise<bigint | undefined> {\n const accountInfo = await connection.getAccountInfo(address);\n if (!accountInfo) {\n return undefined;\n }\n if (!accountInfo.owner.equals(tokenProgramId)) {\n throw readFailed('token account');\n }\n return AccountLayout.decode(accountInfo.data).amount;\n}\n\n/** A Solana keypair from a base58 secret key, or `INVALID_PRIVATE_KEY` (nothing of the key shown). */\nfunction keypairFromBase58(secretKeyBase58: string): Keypair {\n let secretKey: Uint8Array;\n try {\n secretKey = base58.decode(secretKeyBase58);\n } catch {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n // Solana keypairs are 64 bytes (secret and public half)\n if (secretKey.length !== 64) {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'wrong_length' });\n }\n try {\n return Keypair.fromSecretKey(secretKey);\n } catch {\n // The public half does not match the secret half.\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n}\n\n/**\n * Where a Solana deposit is: whether a deposit was sent at all, the step it reached, and the\n * signature of the last one signed.\n */\ninterface DepositProgress {\n sent: boolean;\n step: BridgeDepositStep;\n signature: string;\n}\n\n/**\n * Cached Solana bridge account addresses.\n */\ninterface SolanaBridgeAccounts {\n mintLookup: PublicKey;\n tokenBridge: PublicKey;\n bridgeTokenAccount: PublicKey;\n}\n\n/** The most sends of one deposit (each after the previous provably expired unlanded). */\nconst MAX_DEPOSIT_SENDS = 3;\n\n/** A Solana signature as `getSolanaTransactionStatus` accepts it: 80 to 90 base58 characters. */\nconst SOLANA_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{80,90}$/u;\n\n/**\n * Bridge strategy for GalaChain ↔ Solana transfers.\n *\n * Supports 2 tokens: GALA, GSOL\n */\nexport class SolanaBridgeStrategy extends ConfiguredBridgeStrategy<SolanaTokenConfig> {\n readonly network: ExternalNetwork = 'Solana';\n\n private readonly galaChainWalletAddress: string;\n private readonly ethereumWallet: EthersWallet;\n private readonly solanaConnection: Connection;\n private readonly solanaKeypair: Keypair;\n private readonly solanaBridgeProgramId: PublicKey;\n private readonly solanaBridgeTokenAuthority: PublicKey;\n private readonly solanaBridgeConfigPda: PublicKey;\n private readonly solanaNativeBridgePda: PublicKey;\n private readonly solanaBridgeAccountCache = new Map<string, SolanaBridgeAccounts>();\n private readonly tokenMetadataResolver: TokenMetadataResolver;\n\n /**\n * Creates a new Solana bridge strategy.\n *\n * @param config - Strategy configuration\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` if a key is invalid (nothing of it is shown);\n * `INVALID_BRIDGE_OPTION` (the option) for an RPC URL that is not http(s) or a bridge program\n * that is not a Solana public key\n */\n constructor(config: SolanaBridgeConfig) {\n const tokens = config.tokenConfigs ?? DEFAULT_SOLANA_TOKENS;\n super(config.galaConnectClient, createTokenConfigMap(tokens), config.sleep);\n for (const token of tokens) solanaPublicKeyOption(token.mintAddress, 'tokenConfigs');\n\n this.galaChainWalletAddress = config.galaChainWalletAddress;\n\n // The Ethereum wallet only signs the EIP-712 bridge-out: it needs no provider.\n validateEthereumPrivateKeyFormat(config.ethereumPrivateKey);\n this.ethereumWallet = new EthersWallet(config.ethereumPrivateKey);\n\n // Every URL and program id option is checked here: a malformed one is refused now, by name,\n // never as a library error.\n const rpcUrl = assertHttpUrlOption(\n config.solanaRpcUrl ?? DEFAULT_SOLANA_RPC_URL,\n 'solanaRpcUrl',\n );\n this.solanaConnection = config.solanaConnection ?? new Connection(rpcUrl, 'confirmed');\n this.solanaKeypair = keypairFromBase58(config.solanaPrivateKeyBase58);\n\n // Initialize bridge program PDAs\n this.solanaBridgeProgramId = solanaPublicKeyOption(\n config.solanaBridgeProgram ?? DEFAULT_SOLANA_BRIDGE_PROGRAM,\n 'solanaBridgeProgram',\n );\n [this.solanaBridgeTokenAuthority] = PublicKey.findProgramAddressSync(\n [utf8('bridge_token_authority')],\n this.solanaBridgeProgramId,\n );\n [this.solanaBridgeConfigPda] = PublicKey.findProgramAddressSync(\n [utf8('configv1')],\n this.solanaBridgeProgramId,\n );\n [this.solanaNativeBridgePda] = PublicKey.findProgramAddressSync(\n [utf8('native_sol_bridge')],\n this.solanaBridgeProgramId,\n );\n\n this.tokenMetadataResolver = new TokenMetadataResolver({\n galaConnectClient: this.galaConnectClient,\n });\n }\n\n /**\n * Estimate bridge fees for a transfer to Solana.\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GSOL')\n * @returns Fee estimate with breakdown (it does not depend on the amount)\n */\n async estimateFee(tokenSymbol: string): Promise<BridgeFeeEstimate> {\n return estimateStrategyFee(\n this.galaConnectClient,\n this.tokenMetadataResolver,\n 'Solana',\n tokenSymbol,\n );\n }\n\n /**\n * Bridge tokens from GalaChain to Solana.\n *\n * @param params - Bridge out parameters\n * @returns Transaction details\n */\n async bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction> {\n return executeBridgeOutFlow(params, {\n galaConnectClient: this.galaConnectClient,\n tokenMetadataResolver: this.tokenMetadataResolver,\n ethereumWallet: this.ethereumWallet,\n destinationChainId: CHAIN_IDS.SOLANA,\n destinationChain: 'Solana',\n validateRecipientAddress: validateSolanaAddressOrThrow,\n });\n }\n\n /**\n * Bridge tokens from Solana to GalaChain.\n *\n * @param params - Bridge in parameters\n * @returns Transaction details\n * @throws GalaSDKError before the deposit is sent: the input's refusal (`INVALID_PRIVATE_KEY` for\n * a bad `sourcePrivateKey`), `UNSUPPORTED_BRIDGE_TOKEN`, `BRIDGE_CHAIN_READ_FAILED`; once it is\n * being sent: `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`\n */\n async bridgeIn(params: BridgeInParams): Promise<BridgeTransaction> {\n const { amount, sourcePrivateKey, recipientAddress, tokenSymbol: resolvedSymbol } = params;\n\n // Validate that BridgeService resolved the symbol\n const tokenSymbol = assertTokenSymbolResolved(resolvedSymbol);\n\n // Validate amount (prevents wasted fees on zero/negative amounts)\n validateBridgeAmount(amount);\n\n // Use provided private key or fall back to configured keypair\n const keypair =\n sourcePrivateKey !== undefined && sourcePrivateKey !== ''\n ? keypairFromBase58(sourcePrivateKey)\n : this.solanaKeypair;\n\n // The GalaChain recipient, normalized (eth|<checksummed> or a client| alias) before anything\n // is read or sent\n const recipient = galaChainUserRef(recipientAddress ?? this.galaChainWalletAddress, 'address');\n\n const tokenConfig = requireTokenConfig(this.tokenConfigs, tokenSymbol, 'Solana');\n const metadata = await this.tokenMetadataResolver.getTokenMetadata(tokenSymbol);\n const amountBaseUnits = toBaseUnits(amount, metadata.decimals);\n\n const signature = await this.executeSolanaBridgeOut({\n keypair,\n tokenConfig,\n metadata,\n amountBaseUnits,\n recipient,\n amount,\n });\n\n return buildBridgeInboundTransaction({\n fromChain: 'Solana',\n transactionHash: signature,\n tokenSymbol,\n amount,\n baseUrl: this.galaConnectClient.getBaseUrl(),\n });\n }\n\n /**\n * Validate a Solana address.\n *\n * @param address - Address to validate\n * @returns True if a valid Solana public key\n */\n isValidAddress(address: string): boolean {\n try {\n new PublicKey(address);\n return true;\n } catch {\n return false;\n }\n }\n\n // ==========================================================================\n // Wallet Info Methods\n // ==========================================================================\n\n /**\n * Get the configured Solana wallet address.\n *\n * @returns Solana wallet address (base58)\n */\n getWalletAddress(): string {\n return this.solanaKeypair.publicKey.toBase58();\n }\n\n // ==========================================================================\n // Balance Checking Methods\n // ==========================================================================\n\n /**\n * Get SPL token balance for a Solana address (native SOL for a native token).\n *\n * @param tokenSymbol - Token symbol (e.g., 'GALA', 'GSOL')\n * @param address - Optional Solana address (defaults to configured wallet)\n * @returns Token balance as decimal string (\"0\" when the address has no token account)\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN`, `INVALID_WALLET_ADDRESS`,\n * `BRIDGE_CHAIN_READ_FAILED` (the failure as `cause`)\n */\n async getSolanaTokenBalance(tokenSymbol: string, address?: string): Promise<string> {\n const tokenConfig = requireTokenConfig(this.tokenConfigs, tokenSymbol, 'Solana');\n\n if (tokenConfig.isNative) {\n return this.getSolanaNativeBalance(address);\n }\n\n const targetAddress = address ?? this.solanaKeypair.publicKey.toBase58();\n const ownerPublicKey = parseSolanaAddressOrThrow(targetAddress);\n\n const ataAddress = getAssociatedTokenAddressSync(\n new PublicKey(tokenConfig.mintAddress),\n ownerPublicKey,\n TOKEN_PROGRAM_ID,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n );\n\n let amount: bigint | undefined;\n try {\n amount = await getTokenAccountAmount(this.solanaConnection, ataAddress, TOKEN_PROGRAM_ID);\n } catch (error: unknown) {\n throw error instanceof GalaSDKError ? error : readFailed('token account', error);\n }\n\n // No token account = zero balance; the configured decimals, else the mint's own (never an\n // assumed 8).\n const decimals =\n tokenConfig.decimals ?? (await this.mintDecimals(new PublicKey(tokenConfig.mintAddress)));\n return fromBaseUnits(amount ?? 0n, decimals);\n }\n\n /**\n * The decimals of an SPL mint, from its account.\n *\n * @throws GalaSDKError `BRIDGE_CHAIN_READ_FAILED` (`mint`) when there is no such mint of the token\n * program, or it cannot be read\n */\n private async mintDecimals(mint: PublicKey): Promise<number> {\n let mintAccount: Awaited<ReturnType<Connection['getAccountInfo']>>;\n try {\n mintAccount = await this.solanaConnection.getAccountInfo(mint);\n } catch (error: unknown) {\n throw readFailed('mint', error);\n }\n if (!mintAccount?.owner.equals(TOKEN_PROGRAM_ID)) {\n throw readFailed('mint');\n }\n return MintLayout.decode(mintAccount.data).decimals;\n }\n\n /**\n * Get native SOL balance for a Solana address.\n *\n * @param address - Optional Solana address (defaults to configured wallet)\n * @returns SOL balance as decimal string (9 decimals)\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` if address invalid\n */\n async getSolanaNativeBalance(address?: string): Promise<string> {\n const targetAddress = address ?? this.solanaKeypair.publicKey.toBase58();\n const publicKey = parseSolanaAddressOrThrow(targetAddress);\n const balanceLamports = await this.solanaConnection.getBalance(publicKey, 'confirmed');\n return fromBaseUnits(BigInt(balanceLamports), 9);\n }\n\n /**\n * Request a devnet SOL airdrop (devnet RPC only).\n *\n * Does not wait for confirmation; returns the airdrop signature.\n *\n * @param amount - SOL to request (0.00001 to 2)\n * @param address - Optional recipient (defaults to configured wallet)\n * @returns Airdrop transaction signature\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`airdropAmount` out of range, `solanaRpcUrl` not\n * devnet), `INVALID_WALLET_ADDRESS`\n */\n async requestDevnetAirdrop(amount: number = 1, address?: string): Promise<string> {\n // 1. Validate amount FIRST (cheap, common error)\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount < 0.00001 || amount > 2) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'airdropAmount' });\n }\n\n // 2. Validate address format SECOND (cheap, fails early for typos)\n const publicKey =\n address !== undefined && address !== ''\n ? parseSolanaAddressOrThrow(address)\n : this.solanaKeypair.publicKey;\n\n // 3. Validate environment LAST (before the RPC call)\n if (!this.solanaConnection.rpcEndpoint.includes('devnet')) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'solanaRpcUrl' });\n }\n\n const lamports = Math.floor(amount * LAMPORTS_PER_SOL);\n return this.solanaConnection.requestAirdrop(publicKey, lamports);\n }\n\n /**\n * Get the status of a Solana transaction by signature.\n *\n * @param signature - Transaction signature (base58)\n * @returns Transaction status\n * @throws GalaSDKError `INVALID_TRANSACTION_HASH` if the signature is not 80 to 90 base58 characters\n */\n async getSolanaTransactionStatus(signature: string): Promise<SolanaTransactionStatus> {\n if (typeof signature !== 'string' || !SOLANA_SIGNATURE.test(signature)) {\n throw new GalaSDKError('INVALID_TRANSACTION_HASH', {\n network: 'Solana',\n value: String(signature),\n });\n }\n\n const result = await this.solanaConnection.getSignatureStatuses([signature]);\n const status = result.value[0];\n\n // Transaction not yet visible on-chain (still propagating or invalid)\n if (!status) {\n return { confirmed: false, status: 'not_found' };\n }\n\n // Transaction was processed but failed: on-chain, but it did not succeed\n if (status.err !== null && status.err !== undefined) {\n return {\n confirmed: false,\n status: 'failed',\n slot: status.slot,\n error: JSON.stringify(status.err),\n };\n }\n\n return {\n confirmed: true,\n status: status.confirmationStatus ?? 'processed',\n slot: status.slot,\n };\n }\n\n // ==========================================================================\n // Private Methods\n // ==========================================================================\n\n /**\n * Execute the Solana deposit (the bridge program's bridge-out instruction) and register it with\n * GalaConnect. From the send on, every failure is `BRIDGE_DEPOSIT_OUTCOME_UNKNOWN`.\n */\n private async executeSolanaBridgeOut(params: {\n keypair: Keypair;\n tokenConfig: SolanaTokenConfig;\n metadata: BridgeTokenMetadata;\n amountBaseUnits: bigint;\n recipient: string;\n amount: string;\n }): Promise<string> {\n const mint = new PublicKey(params.tokenConfig.mintAddress);\n const recipientBytes = utf8(params.recipient);\n const instructionArguments = [\n u64LittleEndian(params.amountBaseUnits),\n u32LittleEndian(recipientBytes.length),\n recipientBytes,\n ] as const;\n\n const bridgeInstruction = params.tokenConfig.isNative\n ? this.buildNativeBridgeInstruction(params.keypair.publicKey, instructionArguments)\n : this.buildTokenBridgeInstruction(\n params.keypair.publicKey,\n getAssociatedTokenAddressSync(\n mint,\n params.keypair.publicKey,\n TOKEN_PROGRAM_ID,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n ),\n mint,\n await this.getSolanaBridgeAccounts(mint, params.tokenConfig.symbol),\n instructionArguments,\n );\n\n const transaction = new Transaction();\n transaction.add(\n ComputeBudgetProgram.setComputeUnitPrice({\n microLamports: SOLANA_COMPUTE.UNIT_PRICE_MICROLAMPORTS,\n }),\n ComputeBudgetProgram.setComputeUnitLimit({\n units: SOLANA_COMPUTE.UNIT_LIMIT,\n }),\n bridgeInstruction,\n );\n transaction.feePayer = params.keypair.publicKey;\n\n const progress: DepositProgress = { sent: false, step: 'send', signature: '' };\n try {\n const signature = await this.sendAndConfirm(transaction, params.keypair, progress);\n\n progress.step = 'registration';\n await this.galaConnectClient.registerBridgeTransaction({\n quantity: params.amount,\n tokenInstance: {\n collection: params.metadata.descriptor.collection,\n category: params.metadata.descriptor.category,\n type: params.metadata.descriptor.type,\n additionalKey: params.metadata.descriptor.additionalKey,\n instance: '0',\n },\n fromChain: 'Solana',\n toChain: 'GC',\n hash: signature,\n });\n return signature;\n } catch (cause: unknown) {\n // Nothing sent yet: the failure is the read's own (nothing is pending).\n if (!progress.sent) {\n throw cause;\n }\n throw new GalaSDKError(\n 'BRIDGE_DEPOSIT_OUTCOME_UNKNOWN',\n { network: 'Solana', step: progress.step, transactionHash: progress.signature },\n { cause },\n );\n }\n }\n\n /**\n * Sign, send and confirm the deposit. It is sent AGAIN (re-signed under a fresh blockhash, up to\n * {@link MAX_DEPOSIT_SENDS} sends; `attempt` counts them) only when the previous one provably can never land: its confirmation\n * failed with web3.js's `TransactionExpiredBlockheightExceededError` (the chain is past the\n * blockhash's last valid block height) AND a status read that searches the history finds no\n * trace of it. A send or confirmation that fails any other way (a timeout, a dropped connection,\n * a preflight refusal, a status read that fails) is never sent again: with its blockhash still\n * valid it may land, and a second deposit would land too.\n *\n * `progress` follows it: whether anything was sent, the step reached, and the signature of the\n * deposit last signed. A failure before the first send (the blockhash read) is\n * `BRIDGE_CHAIN_READ_FAILED`.\n */\n private async sendAndConfirm(\n transaction: Transaction,\n keypair: Keypair,\n progress: DepositProgress,\n attempt = 1,\n ): Promise<string> {\n let latestBlockhash: Awaited<ReturnType<Connection['getLatestBlockhash']>>;\n try {\n latestBlockhash = await this.solanaConnection.getLatestBlockhash('confirmed');\n } catch (cause: unknown) {\n throw readFailed('latest blockhash', cause);\n }\n\n // Set the blockhash and sign (a fresh signature: a different transaction)\n transaction.recentBlockhash = latestBlockhash.blockhash;\n transaction.feePayer = keypair.publicKey;\n transaction.signatures = [];\n transaction.sign(keypair);\n // sign() has just set the fee payer's signature.\n progress.signature = base58.encode(transaction.signature as Uint8Array);\n progress.step = 'send';\n progress.sent = true;\n\n const signature = await this.solanaConnection.sendRawTransaction(transaction.serialize(), {\n skipPreflight: false,\n preflightCommitment: 'confirmed',\n });\n progress.step = 'confirmation';\n\n try {\n await this.solanaConnection.confirmTransaction(\n {\n signature,\n blockhash: latestBlockhash.blockhash,\n lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,\n },\n 'confirmed',\n );\n return signature;\n } catch (error: unknown) {\n if (!(error instanceof TransactionExpiredBlockheightExceededError)) {\n throw error;\n }\n // Expired: it can no longer land. Done if it did; sent again only if it never did.\n const {\n value: [status],\n } = await this.solanaConnection.getSignatureStatuses([signature], {\n searchTransactionHistory: true,\n });\n if (status) {\n const landed =\n status.err === null &&\n (status.confirmationStatus === 'confirmed' || status.confirmationStatus === 'finalized');\n if (landed) {\n return signature;\n }\n throw error;\n }\n if (attempt >= MAX_DEPOSIT_SENDS) {\n throw error;\n }\n }\n\n // Wait before sending again, with exponential backoff\n await this.sleep(Math.min(1000 * Math.pow(2, attempt - 1), 5000));\n return this.sendAndConfirm(transaction, keypair, progress, attempt + 1);\n }\n\n /**\n * Build native SOL bridge instruction.\n */\n private buildNativeBridgeInstruction(\n payer: PublicKey,\n instructionArguments: readonly Uint8Array[],\n ): TransactionInstruction {\n return new TransactionInstruction({\n programId: this.solanaBridgeProgramId,\n keys: [\n { pubkey: payer, isSigner: true, isWritable: true },\n { pubkey: this.solanaBridgeTokenAuthority, isSigner: false, isWritable: true },\n { pubkey: this.solanaNativeBridgePda, isSigner: false, isWritable: false },\n { pubkey: this.solanaBridgeConfigPda, isSigner: false, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data: instructionData(SOLANA_DISCRIMINATORS.BRIDGE_OUT_NATIVE, ...instructionArguments),\n });\n }\n\n /**\n * Build SPL token bridge instruction.\n */\n private buildTokenBridgeInstruction(\n payer: PublicKey,\n userTokenAccount: PublicKey,\n mint: PublicKey,\n accounts: SolanaBridgeAccounts,\n instructionArguments: readonly Uint8Array[],\n ): TransactionInstruction {\n return new TransactionInstruction({\n programId: this.solanaBridgeProgramId,\n keys: [\n { pubkey: payer, isSigner: true, isWritable: true },\n { pubkey: userTokenAccount, isSigner: false, isWritable: true },\n { pubkey: mint, isSigner: false, isWritable: true },\n { pubkey: accounts.mintLookup, isSigner: false, isWritable: false },\n { pubkey: accounts.tokenBridge, isSigner: false, isWritable: false },\n { pubkey: accounts.bridgeTokenAccount, isSigner: false, isWritable: true },\n { pubkey: this.solanaBridgeTokenAuthority, isSigner: false, isWritable: false },\n { pubkey: this.solanaBridgeConfigPda, isSigner: false, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n ],\n data: instructionData(SOLANA_DISCRIMINATORS.BRIDGE_OUT, ...instructionArguments),\n });\n }\n\n /**\n * The bridge program accounts of a mint (cached per mint): its mint lookup PDA, the token bridge\n * the lookup names, and the bridge's token account.\n *\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` when the program has no lookup for the mint;\n * `BRIDGE_CHAIN_READ_FAILED` when the lookup is not the program's or is too short\n */\n private async getSolanaBridgeAccounts(\n mint: PublicKey,\n symbol: string,\n ): Promise<SolanaBridgeAccounts> {\n const cacheKey = mint.toBase58();\n const cached = this.solanaBridgeAccountCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const [mintLookup] = PublicKey.findProgramAddressSync(\n [utf8('mint_lookup_v1'), mint.toBytes()],\n this.solanaBridgeProgramId,\n );\n\n const lookupAccount = await this.solanaConnection.getAccountInfo(mintLookup, 'confirmed');\n if (!lookupAccount) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network: 'Solana', symbol });\n }\n if (!lookupAccount.owner.equals(this.solanaBridgeProgramId) || lookupAccount.data.length < 40) {\n throw readFailed('mint lookup');\n }\n\n // Extract token bridge address (bytes 8-40)\n const tokenBridge = new PublicKey(lookupAccount.data.subarray(8, 40));\n\n const bridgeTokenAccount = getAssociatedTokenAddressSync(\n mint,\n this.solanaBridgeTokenAuthority,\n TOKEN_PROGRAM_ID,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n );\n\n const result: SolanaBridgeAccounts = { mintLookup, tokenBridge, bridgeTokenAccount };\n this.solanaBridgeAccountCache.set(cacheKey, result);\n return result;\n }\n}\n","/**\n * Token ID Utilities\n *\n * Parsing a token reference (a pipe-delimited string or a class key object) to its class key, with\n * core's one class-key splitter (`splitClassKey`) and object guard (`isTokenClassKey`).\n */\n\nimport {\n GalaSDKError,\n isTokenClassKey,\n splitClassKey,\n type GalaChainTokenClassKey,\n type TokenClassKeyInput as TokenId,\n} from '../../index.js';\nimport { stringifyTokenClassKey as centralStringify } from '../internal/values.js';\n\n/**\n * Result of parsing a TokenId\n */\nexport interface ParsedTokenId {\n /** Full TokenClassKey structure */\n tokenClassKey: GalaChainTokenClassKey;\n /** Pipe-delimited string format (e.g., \"GALA|Unit|none|none\") */\n stringified: string;\n}\n\n/**\n * Parse a pipe-delimited token string to TokenClassKey. The last three segments are the category,\n * type and additional key; everything before them is the collection (core's `splitClassKey`).\n *\n * @param tokenString - Pipe-delimited string (e.g., \"GALA|Unit|none|none\")\n * @returns TokenClassKey object\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`tokenId`, `bad_class_key`) for anything else\n *\n * @example\n * ```typescript\n * const key = parseTokenString('GALA|Unit|none|none');\n * // { collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }\n * ```\n */\nexport function parseTokenString(tokenString: string): GalaChainTokenClassKey {\n const key = typeof tokenString === 'string' ? splitClassKey(tokenString, '|') : undefined;\n if (key === undefined) {\n throw new GalaSDKError('INVALID_TOKEN_REFERENCE', {\n field: 'tokenId',\n reason: 'bad_class_key',\n });\n }\n return key;\n}\n\n/**\n * Stringify TokenClassKey to pipe-delimited format\n *\n * @param key - TokenClassKey object\n * @returns Pipe-delimited string\n *\n * @example\n * ```typescript\n * stringifyTokenClassKey({ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' });\n * // 'GALA|Unit|none|none'\n * ```\n */\nexport function stringifyTokenClassKey(key: GalaChainTokenClassKey): string {\n return centralStringify(key);\n}\n\n/**\n * Parse a TokenId (string or object) to TokenClassKey and stringified form.\n *\n * @param tokenId - Token identifier (pipe-delimited string or TokenClassKey object)\n * @returns Parsed token with TokenClassKey and stringified form\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`tokenId`, `bad_class_key`) if it is neither\n *\n * @example\n * ```typescript\n * parseTokenId('GALA|Unit|none|none');\n * parseTokenId({ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' });\n * ```\n */\nexport function parseTokenId(tokenId: TokenId): ParsedTokenId {\n let tokenClassKey: GalaChainTokenClassKey;\n\n if (typeof tokenId === 'string') {\n tokenClassKey = parseTokenString(tokenId);\n } else if (isTokenClassKey(tokenId)) {\n tokenClassKey = tokenId;\n } else {\n throw new GalaSDKError('INVALID_TOKEN_REFERENCE', {\n field: 'tokenId',\n reason: 'bad_class_key',\n });\n }\n\n const stringified = stringifyTokenClassKey(tokenClassKey);\n\n return { tokenClassKey, stringified };\n}\n","/**\n * Bridge Service\n *\n * Main orchestrator for cross-chain bridging operations: a unified API for bridging tokens between\n * GalaChain and Ethereum or Solana, over the two strategies.\n *\n * Failures are `GalaSDKError`s (the strategies' and GalaConnect's, passed through as they are).\n */\n\nimport type { Connection } from '@solana/web3.js';\n\nimport {\n GALA_CHAIN_ENVIRONMENTS,\n GalaSDKError,\n galaChainUserRef,\n type HttpRequestor,\n} from '../index.js';\nimport {\n type BridgeEnvironment,\n DEFAULT_SOLANA_BRIDGE_PROGRAM,\n DEFAULT_SOLANA_TOKENS,\n getEthereumBridgeContractByEnvironment,\n getEthereumTokensByEnvironment,\n STATIC_TOKEN_METADATA,\n} from './constants/index.js';\nimport { GalaConnectClient } from './GalaConnectClient.js';\nimport type { BridgeSleep, BridgeStrategy, WaitOptions } from './strategies/BridgeStrategy.js';\nimport { EthereumBridgeStrategy } from './strategies/EthereumBridgeStrategy.js';\nimport { SolanaBridgeStrategy } from './strategies/SolanaBridgeStrategy.js';\nimport type { BridgeableNetwork } from './types/bridgeable-token.dto.js';\nimport type {\n BridgeConfig,\n BridgeFeeEstimate,\n BridgeInParams,\n BridgeOutParams,\n BridgeStatus,\n BridgeToken,\n BridgeTransaction,\n EstimateBridgeFeeParams,\n EthereumTransactionStatus,\n EthereumWalletBalanceResult,\n ExternalChainBalance,\n ExternalNetwork,\n SolanaTransactionStatus,\n SolanaWalletBalanceResult,\n WaitForBridgeOptions,\n} from './types/index.js';\nimport { validateBridgeAmount } from './utils/bridgePayload.js';\nimport {\n buildEthereumTokenBalance,\n buildNativeBalance,\n buildSolanaTokenBalance,\n findTokenConfigOrThrow,\n} from './utils/balanceHelpers.js';\nimport {\n getEthereumStrategy,\n getSolanaStrategy,\n getStrategyStatus,\n resolveTargetAddress,\n} from './utils/strategyDelegation.js';\nimport { parseTokenId } from './utils/tokenIdUtils.js';\n\n/**\n * What resolves a token id to the token bridgeable to a network (its symbol): the\n * `BridgeableTokenService`, or anything with its `getTokenByTokenId`.\n */\nexport interface BridgeTokenLookup {\n getTokenByTokenId(\n tokenId: string,\n network: BridgeableNetwork,\n ): Promise<{ readonly symbol: string } | undefined>;\n}\n\n/**\n * Extended bridge configuration with wallet keys.\n */\nexport interface BridgeServiceConfig extends Omit<BridgeConfig, 'galaConnectBaseUrl'> {\n /** GalaConnect (DEX API platform) base URL (default: the environment's `dexApiBaseUrl`) */\n galaConnectBaseUrl?: string;\n /** GalaChain wallet address (eth|..., 0x..., or a client| alias) */\n galaChainWalletAddress: string;\n /** Ethereum private key for signing (required for all operations) */\n ethereumPrivateKey: string;\n /** Environment - affects default URLs (stage: Sepolia and devnet, prod: mainnet). Default prod. */\n environment?: BridgeEnvironment;\n /**\n * Resolves a `tokenId` to the token bridgeable to a network (the `BridgeableTokenService`).\n * Every method that takes a `tokenId` goes through it, so it is required: a missing lookup is\n * refused at construction (`INVALID_BRIDGE_OPTION`), not at the first call.\n */\n bridgeableTokenService: BridgeTokenLookup;\n /** Sends the GalaConnect requests (default: the global `fetch`) */\n httpRequestor?: HttpRequestor;\n /** The Solana connection the Solana strategy uses (default: one to `solanaRpcUrl`) */\n solanaConnection?: Connection;\n /** How the strategies wait (a poll interval, the wait before an inbound registration) */\n sleep?: BridgeSleep;\n}\n\n/**\n * Bridge-specific RPC URLs by environment (the GalaConnect and gateway URLs are the environment's\n * `GALA_CHAIN_ENVIRONMENTS` ones).\n */\nconst BRIDGE_RPC_URLS: Readonly<Record<BridgeEnvironment, { ethereum: string; solana: string }>> = {\n prod: {\n ethereum: 'https://eth.gala.games', // Gala-hosted Ethereum mainnet RPC\n solana: 'https://api.mainnet-beta.solana.com',\n },\n stage: {\n ethereum: 'https://dev.eth.gala.games', // Gala-hosted Ethereum Sepolia RPC\n solana: 'https://api.devnet.solana.com',\n },\n};\n\n/**\n * Default configuration values for bridge-specific settings.\n */\nconst DEFAULTS = {\n rateLimit: 12,\n pollInterval: 15000,\n pollTimeout: 45 * 60 * 1000,\n};\n\n/**\n * The explicit GalaChain class key of a supported bridge token, read from the curated\n * STATIC_TOKEN_METADATA table. A class key is never built from a symbol (collection and symbol\n * disagree for many tokens), so a supported token without a table row fails loudly.\n *\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` without a table row\n */\nfunction requireBridgeTokenDescriptor(\n symbol: string,\n network: ExternalNetwork,\n): BridgeToken['galaChainDescriptor'] {\n const metadata = STATIC_TOKEN_METADATA[symbol];\n if (metadata === undefined) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network, symbol });\n }\n return { ...metadata.descriptor };\n}\n\n/**\n * Bridge Service - Main entry point for cross-chain operations.\n *\n * Supports bridging between:\n * - GalaChain ↔ Ethereum (6 tokens: GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC)\n * - GalaChain ↔ Solana (2 tokens: GALA, GSOL)\n *\n * @example\n * ```typescript\n * const bridgeService = new BridgeService({\n * galaChainWalletAddress: 'eth|1234...',\n * ethereumPrivateKey: '0xabcd...',\n * solanaPrivateKey: 'base58EncodedKey...',\n * bridgeableTokenService,\n * });\n *\n * const fee = await bridgeService.estimateBridgeFee({\n * tokenId: 'GALA|Unit|none|none',\n * destinationChain: 'Ethereum',\n * });\n * ```\n */\nexport class BridgeService {\n private readonly environment: BridgeEnvironment;\n private readonly pollInterval: number;\n private readonly pollTimeout: number;\n private readonly galaConnectClient: GalaConnectClient;\n private readonly strategies: Map<ExternalNetwork, BridgeStrategy>;\n private readonly bridgeableTokenService: BridgeTokenLookup;\n\n /**\n * @param config - Bridge service configuration\n * @throws GalaSDKError `INVALID_BRIDGE_OPTION` (`bridgeableTokenService`) without a token lookup;\n * `INVALID_WALLET_ADDRESS` (`galaChainWalletAddress`) for a wallet address that is not a\n * GalaChain one; the strategies' refusals of a bad key\n */\n constructor(config: BridgeServiceConfig) {\n // The type requires it; a plain-JavaScript caller (or a cast) that leaves it out fails here,\n // not at the first tokenId call.\n if (\n typeof (config.bridgeableTokenService as BridgeTokenLookup | undefined)?.getTokenByTokenId !==\n 'function'\n ) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'bridgeableTokenService' });\n }\n const galaChainWalletAddress = galaChainUserRef(\n config.galaChainWalletAddress,\n 'galaChainWalletAddress',\n );\n\n this.environment = config.environment ?? 'prod';\n const urls = GALA_CHAIN_ENVIRONMENTS[this.environment];\n const rpcUrls = BRIDGE_RPC_URLS[this.environment];\n this.pollInterval = config.pollInterval ?? DEFAULTS.pollInterval;\n this.pollTimeout = config.pollTimeout ?? DEFAULTS.pollTimeout;\n\n // GalaConnect Bridge API is served from the DEX API platform (the environment's dexApiBaseUrl)\n this.galaConnectClient = new GalaConnectClient({\n baseUrl: config.galaConnectBaseUrl ?? urls.dexApiBaseUrl,\n galachainBaseUrl: config.galaChainApiBaseUrl ?? urls.gatewayBaseUrl,\n walletAddress: galaChainWalletAddress,\n requestsPerSecond: config.rateLimit ?? DEFAULTS.rateLimit,\n ...(config.httpRequestor !== undefined && { httpRequestor: config.httpRequestor }),\n });\n this.bridgeableTokenService = config.bridgeableTokenService;\n\n const sleep = config.sleep !== undefined ? { sleep: config.sleep } : {};\n this.strategies = new Map<ExternalNetwork, BridgeStrategy>([\n [\n 'Ethereum',\n new EthereumBridgeStrategy({\n galaConnectClient: this.galaConnectClient,\n galaChainWalletAddress,\n ethereumPrivateKey: config.ethereumPrivateKey,\n ethereumRpcUrl: config.ethereumRpcUrl ?? rpcUrls.ethereum,\n ethereumBridgeContract:\n config.ethereumBridgeContract ??\n getEthereumBridgeContractByEnvironment(this.environment),\n tokenConfigs: getEthereumTokensByEnvironment(this.environment),\n ...sleep,\n }),\n ],\n ]);\n\n // The Solana strategy only with a Solana key\n if (config.solanaPrivateKey !== undefined && config.solanaPrivateKey !== '') {\n this.strategies.set(\n 'Solana',\n new SolanaBridgeStrategy({\n galaConnectClient: this.galaConnectClient,\n galaChainWalletAddress,\n ethereumPrivateKey: config.ethereumPrivateKey,\n solanaPrivateKeyBase58: config.solanaPrivateKey,\n solanaRpcUrl: config.solanaRpcUrl ?? rpcUrls.solana,\n solanaBridgeProgram: config.solanaBridgeProgram ?? DEFAULT_SOLANA_BRIDGE_PROGRAM,\n tokenConfigs: DEFAULT_SOLANA_TOKENS,\n ...(config.solanaConnection !== undefined && {\n solanaConnection: config.solanaConnection,\n }),\n ...sleep,\n }),\n );\n }\n }\n\n /**\n * Resolve a tokenId to its symbol through the bridgeable token lookup (which also proves the\n * token is bridgeable to the network).\n *\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` when the token is not bridgeable to the\n * network; the token id's own refusal\n */\n private async resolveTokenSymbol(\n tokenId: Parameters<typeof parseTokenId>[0],\n network: ExternalNetwork,\n ): Promise<string> {\n const stringifiedTokenId = parseTokenId(tokenId).stringified;\n const bridgeableNetwork: BridgeableNetwork = network === 'Ethereum' ? 'ETHEREUM' : 'SOLANA';\n const token = await this.bridgeableTokenService.getTokenByTokenId(\n stringifiedTokenId,\n bridgeableNetwork,\n );\n if (!token) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network, symbol: stringifiedTokenId });\n }\n return token.symbol;\n }\n\n /**\n * Estimate the fee of a bridge-out (a per-transfer cost: it does not depend on the amount).\n *\n * @param params - Token and destination chain\n * @returns Fee estimate\n */\n async estimateBridgeFee(params: EstimateBridgeFeeParams): Promise<BridgeFeeEstimate> {\n const strategy = this.getStrategy(params.destinationChain);\n const symbol = await this.resolveTokenSymbol(params.tokenId, params.destinationChain);\n return strategy.estimateFee(symbol);\n }\n\n /**\n * Bridge tokens out from GalaChain to an external chain.\n *\n * @param params - Bridge out parameters\n * @returns Transaction details\n * @throws GalaSDKError `INVALID_WALLET_ADDRESS` (`recipientAddress`) for a recipient that is not\n * an address of the destination chain; `UNSUPPORTED_BRIDGE_TOKEN` for a token the chain's\n * strategy does not bridge; the strategy's failures\n */\n async bridgeOut(params: BridgeOutParams): Promise<BridgeTransaction> {\n // Every refusal of the caller's own input comes before the token-list read\n const strategy = this.getStrategy(params.destinationChain);\n if (!strategy.isValidAddress(params.recipientAddress)) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', {\n field: 'recipientAddress',\n value: String(params.recipientAddress),\n });\n }\n validateBridgeAmount(params.amount);\n const symbol = await this.resolveTokenSymbol(params.tokenId, params.destinationChain);\n this.assertTokenSupported(strategy, symbol);\n return strategy.bridgeOut({ ...params, tokenSymbol: symbol });\n }\n\n /**\n * Bridge tokens in from an external chain to GalaChain.\n *\n * @param params - Bridge in parameters\n * @returns Transaction details\n * @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` for a token the chain's strategy does not\n * bridge; the strategy's failures\n */\n async bridgeIn(params: BridgeInParams): Promise<BridgeTransaction> {\n // Every refusal of the caller's own input comes before the token-list read\n const strategy = this.getStrategy(params.sourceChain);\n validateBridgeAmount(params.amount);\n const symbol = await this.resolveTokenSymbol(params.tokenId, params.sourceChain);\n this.assertTokenSupported(strategy, symbol);\n return strategy.bridgeIn({ ...params, tokenSymbol: symbol });\n }\n\n /**\n * Get the status of a bridge transaction (GalaConnect tracks both chains: one read).\n *\n * @param transactionHash - Transaction hash\n * @returns Current status\n */\n async getBridgeStatus(transactionHash: string): Promise<BridgeStatus> {\n return getStrategyStatus(this.galaConnectClient, transactionHash);\n }\n\n /**\n * Wait for a bridge transaction to reach a final status (completed, failed, delivery failed).\n *\n * @param transactionHash - Transaction hash\n * @param options - Polling options (defaults: the service's pollInterval and pollTimeout)\n * @returns Final status\n * @throws GalaSDKError `BRIDGE_STATUS_TIMEOUT` when the timeout comes first\n */\n async waitForBridgeCompletion(\n transactionHash: string,\n options?: WaitForBridgeOptions,\n ): Promise<BridgeStatus> {\n const waitOptions: WaitOptions = {\n pollInterval: options?.pollInterval ?? this.pollInterval,\n timeout: options?.timeout ?? this.pollTimeout,\n ...(options?.onStatusUpdate && { onStatusUpdate: options.onStatusUpdate }),\n };\n return this.getStrategy('Ethereum').waitForCompletion(transactionHash, waitOptions);\n }\n\n /**\n * Get the bridge tokens (for one chain, or all).\n *\n * @param chain - Optional chain filter\n * @returns Supported tokens with their chains and addresses\n */\n getSupportedBridgeTokens(chain?: ExternalNetwork): BridgeToken[] {\n const tokens: BridgeToken[] = [];\n\n if (chain === undefined || chain === 'Ethereum') {\n for (const config of getEthereumTokensByEnvironment(this.environment)) {\n tokens.push({\n symbol: config.symbol,\n decimals: config.decimals,\n verified: true,\n supportedChains: ['Ethereum'],\n galaChainDescriptor: requireBridgeTokenDescriptor(config.symbol, 'Ethereum'),\n externalAddresses: { ethereum: config.contractAddress },\n });\n }\n }\n\n if (chain === undefined || chain === 'Solana') {\n for (const config of DEFAULT_SOLANA_TOKENS) {\n const existing = tokens.find((token) => token.symbol === config.symbol);\n if (existing) {\n existing.supportedChains.push('Solana');\n existing.externalAddresses.solana = config.mintAddress;\n } else {\n tokens.push({\n symbol: config.symbol,\n decimals: config.decimals,\n verified: true,\n supportedChains: ['Solana'],\n galaChainDescriptor: requireBridgeTokenDescriptor(config.symbol, 'Solana'),\n externalAddresses: { solana: config.mintAddress },\n });\n }\n }\n }\n\n return tokens;\n }\n\n /**\n * Get the chains this service can bridge with (Solana only with a Solana key).\n */\n getSupportedBridgeChains(): ExternalNetwork[] {\n return Array.from(this.strategies.keys());\n }\n\n /**\n * Whether a token symbol is bridgeable (with `chain`, or with any configured chain).\n */\n isTokenSupported(tokenSymbol: string, chain?: ExternalNetwork): boolean {\n const strategies =\n chain === undefined ? [...this.strategies.values()] : [this.strategies.get(chain)];\n return strategies.some((strategy) => strategy?.isTokenSupported(tokenSymbol) === true);\n }\n\n /**\n * Whether an address is valid for a chain (false for a chain that is not configured).\n */\n isValidAddress(address: string, chain: ExternalNetwork): boolean {\n return this.strategies.get(chain)?.isValidAddress(address) ?? false;\n }\n\n // ==========================================================================\n // Balance and status reads of the external chains\n // ==========================================================================\n\n /** An ERC-20 balance (decimal string) of the Ethereum wallet or `address`. */\n async getEthereumTokenBalance(tokenSymbol: string, address?: string): Promise<string> {\n return getEthereumStrategy(this.strategies).getEthereumTokenBalance(tokenSymbol, address);\n }\n\n /** The ETH balance (decimal string) of the Ethereum wallet or `address`. */\n async getEthereumNativeBalance(address?: string): Promise<string> {\n return getEthereumStrategy(this.strategies).getEthereumNativeBalance(address);\n }\n\n /** An SPL balance (decimal string) of the Solana wallet or `address`. */\n async getSolanaTokenBalance(tokenSymbol: string, address?: string): Promise<string> {\n return getSolanaStrategy(this.strategies).getSolanaTokenBalance(tokenSymbol, address);\n }\n\n /** The SOL balance (decimal string) of the Solana wallet or `address`. */\n async getSolanaNativeBalance(address?: string): Promise<string> {\n return getSolanaStrategy(this.strategies).getSolanaNativeBalance(address);\n }\n\n /** One ERC-20 balance of the Ethereum wallet or `address`, with its token's details. */\n async fetchEthereumWalletTokenBalance(\n symbol: string,\n address?: string,\n ): Promise<ExternalChainBalance> {\n const ethStrategy = getEthereumStrategy(this.strategies);\n const tokenConfig = findTokenConfigOrThrow(\n getEthereumTokensByEnvironment(this.environment),\n symbol,\n 'Ethereum',\n );\n const targetAddress = resolveTargetAddress(address, ethStrategy);\n const balance = await ethStrategy.getEthereumTokenBalance(symbol, targetAddress);\n return buildEthereumTokenBalance(tokenConfig, balance);\n }\n\n /** The ETH balance of the Ethereum wallet or `address`. */\n async fetchEthereumWalletNativeBalance(address?: string): Promise<ExternalChainBalance> {\n const ethStrategy = getEthereumStrategy(this.strategies);\n const targetAddress = resolveTargetAddress(address, ethStrategy);\n const balance = await ethStrategy.getEthereumNativeBalance(targetAddress);\n return buildNativeBalance('ETH', balance, 18);\n }\n\n /** One SPL balance of the Solana wallet or `address`, with its token's details. */\n async fetchSolanaWalletTokenBalance(\n symbol: string,\n address?: string,\n ): Promise<ExternalChainBalance> {\n const solStrategy = getSolanaStrategy(this.strategies);\n const tokenConfig = findTokenConfigOrThrow(DEFAULT_SOLANA_TOKENS, symbol, 'Solana');\n const targetAddress = resolveTargetAddress(address, solStrategy);\n const balance = await solStrategy.getSolanaTokenBalance(symbol, targetAddress);\n return buildSolanaTokenBalance(tokenConfig, balance);\n }\n\n /** The SOL balance of the Solana wallet or `address`. */\n async fetchSolanaWalletNativeBalance(address?: string): Promise<ExternalChainBalance> {\n const solStrategy = getSolanaStrategy(this.strategies);\n const targetAddress = resolveTargetAddress(address, solStrategy);\n const balance = await solStrategy.getSolanaNativeBalance(targetAddress);\n return buildNativeBalance('SOL', balance, 9);\n }\n\n /** Request a devnet SOL airdrop (devnet only). */\n async requestSolanaDevnetAirdrop(amount?: number, address?: string): Promise<string> {\n return getSolanaStrategy(this.strategies).requestDevnetAirdrop(amount, address);\n }\n\n /** The status of a Solana transaction, from the Solana RPC. */\n async getSolanaTransactionStatus(signature: string): Promise<SolanaTransactionStatus> {\n return getSolanaStrategy(this.strategies).getSolanaTransactionStatus(signature);\n }\n\n /** The status of an Ethereum transaction, from the Ethereum RPC. */\n async getEthereumTransactionStatus(transactionHash: string): Promise<EthereumTransactionStatus> {\n return getEthereumStrategy(this.strategies).getEthereumTransactionStatus(transactionHash);\n }\n\n /** Every bridge-token balance and the ETH balance of the Ethereum wallet or `address`. */\n async fetchEthereumWalletAllBalances(address?: string): Promise<EthereumWalletBalanceResult> {\n const ethStrategy = getEthereumStrategy(this.strategies);\n const targetAddress = resolveTargetAddress(address, ethStrategy);\n const [nativeBalance, tokenBalances] = await Promise.all([\n ethStrategy.getEthereumNativeBalance(targetAddress),\n Promise.all(\n getEthereumTokensByEnvironment(this.environment).map(\n async (token): Promise<ExternalChainBalance> =>\n buildEthereumTokenBalance(\n token,\n await ethStrategy.getEthereumTokenBalance(token.symbol, targetAddress),\n ),\n ),\n ),\n ]);\n return {\n address: targetAddress,\n native: buildNativeBalance('ETH', nativeBalance, 18),\n tokens: tokenBalances,\n timestamp: Date.now(),\n };\n }\n\n /** Every bridge-token balance and the SOL balance of the Solana wallet or `address`. */\n async fetchSolanaWalletAllBalances(address?: string): Promise<SolanaWalletBalanceResult> {\n const solStrategy = getSolanaStrategy(this.strategies);\n const targetAddress = resolveTargetAddress(address, solStrategy);\n const [nativeBalance, tokenBalances] = await Promise.all([\n solStrategy.getSolanaNativeBalance(targetAddress),\n Promise.all(\n DEFAULT_SOLANA_TOKENS.map(async (token): Promise<ExternalChainBalance> =>\n buildSolanaTokenBalance(\n token,\n await solStrategy.getSolanaTokenBalance(token.symbol, targetAddress),\n ),\n ),\n ),\n ]);\n return {\n address: targetAddress,\n native: buildNativeBalance('SOL', nativeBalance, 9),\n tokens: tokenBalances,\n timestamp: Date.now(),\n };\n }\n\n /**\n * The strategy of `chain`.\n *\n * @throws GalaSDKError `BRIDGE_NOT_CONFIGURED` (Solana without a Solana key)\n */\n private getStrategy(chain: ExternalNetwork): BridgeStrategy {\n const strategy = this.strategies.get(chain);\n if (!strategy) {\n throw new GalaSDKError('BRIDGE_NOT_CONFIGURED', { network: chain });\n }\n return strategy;\n }\n\n /** @throws GalaSDKError `UNSUPPORTED_BRIDGE_TOKEN` unless `strategy` bridges `symbol` */\n private assertTokenSupported(strategy: BridgeStrategy, symbol: string): void {\n if (!strategy.isTokenSupported(symbol)) {\n throw new GalaSDKError('UNSUPPORTED_BRIDGE_TOKEN', { network: strategy.network, symbol });\n }\n }\n}\n","/**\n * The token lists of the DEX API platform (GalaConnect's `/v1/tokens`): one page, and every page\n * (offset pagination). What `BridgeableTokenService` and `WrappableTokenService` read through.\n *\n * @module bridge/tokens/tokenPages\n */\n\nimport { GalaSDKError, isGalaError } from '../../index.js';\nimport { fieldsOf, hasFields, isRecord } from '../internal/values.js';\n\n/** The DEX API platform path the token lists are read from. */\nexport const TOKENS_PATH = '/v1/tokens';\n\n/** The most tokens one page holds (the API's maximum page size); also the default page size. */\nexport const TOKEN_PAGE_MAX = 1000;\n\n/** The most pages one full read takes. */\nconst MAX_TOKEN_PAGES = 10_000;\n\n/** The query of a token list read. */\nexport type TokenListParams = Record<string, string | number | boolean>;\n\n/**\n * Sends a DEX API GET and resolves with its parsed JSON body: a `GalaConnectClient`, or any client\n * with this `request` (launchpad-sdk's `HttpClient`). A failure that is not a `GalaSDKError` is\n * read for an HTTP status (`status` or `statusCode`) to say what it was.\n */\nexport interface DexApiReader {\n request<T>(config: { method: 'GET'; url: string; params: TokenListParams }): Promise<T>;\n}\n\n/** One page: its tokens, and how many entries the API answered (the page is full or not). */\nexport interface TokenPage<T> {\n items: T[];\n rawCount: number;\n}\n\n/**\n * Whether an entry of the token list is a usable token: an object with the token strings (symbol,\n * name, class key and its four parts), integer decimals (0 or more), a boolean `verified`, and\n * `image` / `description` strings when present.\n */\nexport function isTokenEntry(entry: unknown): entry is Record<string, unknown> {\n return (\n isRecord(entry) &&\n hasFields(\n entry,\n [\n 'symbol',\n 'name',\n 'stringifiedTokenClassKey',\n 'collection',\n 'category',\n 'type',\n 'additionalKey',\n ],\n { image: 'string', description: 'string' },\n ) &&\n Number.isSafeInteger(entry['decimals']) &&\n (entry['decimals'] as number) >= 0 &&\n typeof entry['verified'] === 'boolean'\n );\n}\n\n/** The HTTP status a reader's failure carries (`status`, else `statusCode`), if any. */\nfunction statusOf(failure: unknown): number | undefined {\n const fields = fieldsOf(failure);\n const status = fields['status'] ?? fields['statusCode'];\n return typeof status === 'number' ? status : undefined;\n}\n\n/**\n * A failed token list read: a `GalaSDKError` as it is; a failure with an HTTP status\n * `GALACONNECT_HTTP_ERROR`; any other `TRANSPORT_ERROR`. All are reads (`write: false`), the\n * original as cause.\n */\nfunction readFailure(cause: unknown): Error {\n if (isGalaError(cause)) {\n return cause;\n }\n const status = statusOf(cause);\n return status === undefined\n ? new GalaSDKError('TRANSPORT_ERROR', { url: TOKENS_PATH }, { write: false, cause })\n : new GalaSDKError(\n 'GALACONNECT_HTTP_ERROR',\n { method: TOKENS_PATH, status, serverMessage: '' },\n { write: false, status, cause },\n );\n}\n\n/**\n * Reads one page of the token list: `params` plus `pageSize` (at most {@link TOKEN_PAGE_MAX}) and\n * `offset`, the API entries turned into tokens by `transform` (which leaves out an entry that is\n * not a usable token). `rawCount` counts every entry, so paging never depends on how many were\n * usable.\n *\n * @throws GalaSDKError `BRIDGE_READ_RESPONSE_INVALID` for an answer without a `tokens` array; the\n * reader's failure (see `readFailure`)\n */\nexport async function fetchTokenPage<T>(\n reader: DexApiReader,\n params: TokenListParams,\n offset: number,\n limit: number,\n transform: (apiTokens: unknown[]) => T[],\n): Promise<TokenPage<T>> {\n let response: unknown;\n try {\n response = await reader.request<unknown>({\n method: 'GET',\n url: TOKENS_PATH,\n params: { ...params, pageSize: Math.min(limit, TOKEN_PAGE_MAX), offset },\n });\n } catch (cause: unknown) {\n throw readFailure(cause);\n }\n const tokens = fieldsOf(response)['tokens'];\n if (!Array.isArray(tokens)) {\n throw new GalaSDKError(\n 'BRIDGE_READ_RESPONSE_INVALID',\n { method: TOKENS_PATH },\n { write: false },\n );\n }\n return { items: transform(tokens as unknown[]), rawCount: tokens.length };\n}\n\n/**\n * Reads every page: full pages of {@link TOKEN_PAGE_MAX} from offset 0 until a page that is not\n * full.\n *\n * @throws GalaSDKError `PAGINATION_LIMIT_EXCEEDED` when {@link MAX_TOKEN_PAGES} pages are all full\n * (the list is longer than the cap): never a list cut short in silence\n */\nexport async function fetchAllTokenPages<T>(\n fetchPage: (offset: number, limit: number) => Promise<TokenPage<T>>,\n): Promise<T[]> {\n const all: T[] = [];\n for (let page = 0; page < MAX_TOKEN_PAGES; page++) {\n const result = await fetchPage(page * TOKEN_PAGE_MAX, TOKEN_PAGE_MAX);\n all.push(...result.items);\n if (result.rawCount !== TOKEN_PAGE_MAX) {\n return all;\n }\n }\n throw new GalaSDKError(\n 'PAGINATION_LIMIT_EXCEEDED',\n { method: TOKENS_PATH, maxPages: MAX_TOKEN_PAGES },\n { write: false },\n );\n}\n","/**\n * Bridgeable Token Service\n *\n * The tokens bridgeable to Ethereum or Solana, from the DEX API platform's token list\n * (`/v1/tokens?canBridgeTo=<network>`), cached per network, with lookups by symbol and token id.\n *\n * @module bridge/tokens/BridgeableTokenService\n */\n\nimport type { TokenClassKeyInput as TokenId } from '../../index.js';\nimport { hasFields, isRecord, normalizeTokenSymbol } from '../internal/values.js';\nimport type {\n BridgeableNetwork,\n BridgeableToken,\n BridgeableTokenApiResponse,\n FetchBridgeableTokensOptions,\n FetchBridgeableTokensResult,\n IsTokenBridgeableOptions,\n IsTokenBridgeableResult,\n} from '../types/bridgeable-token.dto.js';\nimport { parseTokenId, stringifyTokenClassKey } from '../utils/tokenIdUtils.js';\nimport {\n type DexApiReader,\n fetchAllTokenPages,\n fetchTokenPage,\n isTokenEntry,\n TOKEN_PAGE_MAX,\n type TokenPage,\n} from './tokenPages.js';\n\n/** What the bridgeable token cache holds, per network. */\nexport interface BridgeableTokenCacheStats {\n /** The networks with cached tokens */\n networks: BridgeableNetwork[];\n /** Cached tokens, all networks */\n totalItems: number;\n /** Cached tokens per network (0 for a network not read) */\n itemsByNetwork: Record<BridgeableNetwork, number>;\n /** When each cached network was read */\n fetchTimestamps: Partial<Record<BridgeableNetwork, number>>;\n /** `totalItems` */\n totalTokens: number;\n /** `itemsByNetwork` */\n tokensByNetwork: Record<BridgeableNetwork, number>;\n}\n\n/** One network's cached tokens. */\ninterface NetworkTokens {\n /** Every token, in the API's order */\n readonly tokens: readonly BridgeableToken[];\n /** By symbol (trimmed, upper case): the first token listed with it */\n readonly bySymbol: Map<string, BridgeableToken>;\n /** By token id, exactly (GalaChain class keys are case-sensitive) */\n readonly byTokenId: Map<string, BridgeableToken>;\n readonly fetchedAt: number;\n}\n\n/** The networks a token list is read for. */\nconst NETWORKS: readonly BridgeableNetwork[] = ['ETHEREUM', 'SOLANA'];\n\n/**\n * Whether a list entry is a usable bridgeable token: a token entry with `canBridgeTo` (objects with\n * a string `network`) and `otherNetworks` (objects with a string `network`, and a string\n * `contractAddress` and `symbol` and a number `allowanceStorageSlot` when present).\n */\nfunction isBridgeableEntry(entry: unknown): entry is BridgeableTokenApiResponse {\n if (!isTokenEntry(entry)) {\n return false;\n }\n const { canBridgeTo, otherNetworks } = entry;\n return (\n Array.isArray(canBridgeTo) &&\n canBridgeTo.every(\n (destination) => isRecord(destination) && hasFields(destination, ['network']),\n ) &&\n Array.isArray(otherNetworks) &&\n otherNetworks.every(\n (network) =>\n isRecord(network) &&\n hasFields(network, ['network'], {\n contractAddress: 'string',\n symbol: 'string',\n allowanceStorageSlot: 'number',\n }),\n )\n );\n}\n\n/** A bridgeable token from its API entry. */\nfunction toBridgeableToken(t: BridgeableTokenApiResponse): BridgeableToken {\n const ethereumNetwork = t.otherNetworks.find((n) => n.network === 'Ethereum');\n const solanaNetwork = t.otherNetworks.find((n) => n.network === 'Solana');\n\n // Supported chains from the canBridgeTo array (Ethereum and Solana only)\n const supportedChains = t.canBridgeTo\n .map((d) => d.network)\n .filter((n): n is 'Ethereum' | 'Solana' => n === 'Ethereum' || n === 'Solana');\n\n const token: BridgeableToken = {\n symbol: t.symbol,\n name: t.name,\n decimals: t.decimals,\n galaChainDescriptor: {\n collection: t.collection,\n category: t.category,\n type: t.type,\n additionalKey: t.additionalKey,\n },\n stringifiedTokenClassKey: t.stringifiedTokenClassKey,\n verified: t.verified,\n supportedChains,\n };\n\n // Optional fields only when defined (exactOptionalPropertyTypes)\n if (ethereumNetwork?.contractAddress !== undefined) {\n token.ethereumContractAddress = ethereumNetwork.contractAddress;\n }\n if (ethereumNetwork?.symbol !== undefined) {\n token.ethereumSymbol = ethereumNetwork.symbol;\n }\n if (ethereumNetwork?.allowanceStorageSlot !== undefined) {\n token.ethereumAllowanceSlot = ethereumNetwork.allowanceStorageSlot;\n }\n if (solanaNetwork?.contractAddress !== undefined) {\n token.solanaContractAddress = solanaNetwork.contractAddress;\n }\n if (solanaNetwork?.symbol !== undefined) {\n token.solanaSymbol = solanaNetwork.symbol;\n }\n if (t.image !== undefined) {\n token.image = t.image;\n }\n if (t.description !== undefined) {\n token.description = t.description;\n }\n return token;\n}\n\n/**\n * Service for the tokens bridgeable to Ethereum and Solana.\n *\n * Reads go through a {@link DexApiReader} (a `GalaConnectClient`, or launchpad-sdk's DEX API\n * `HttpClient`). Failures are `GalaSDKError`s: `BRIDGE_READ_RESPONSE_INVALID` for an answer\n * without a token list, `INVALID_TOKEN_REFERENCE` for a token id that is not one, and the read's\n * own (`GALACONNECT_HTTP_ERROR`, `TRANSPORT_ERROR`, ...).\n */\nexport class BridgeableTokenService {\n private readonly cache = new Map<BridgeableNetwork, NetworkTokens>();\n\n /**\n * @param dexApi - Reads the DEX API platform's token list\n */\n constructor(private readonly dexApi: DexApiReader) {}\n\n /** One page of the token list of `network`. */\n private fetchPage(\n network: BridgeableNetwork,\n offset: number,\n limit: number,\n ): Promise<TokenPage<BridgeableToken>> {\n return fetchTokenPage(\n this.dexApi,\n { canBridgeTo: network.toLowerCase() },\n offset,\n limit,\n (apiTokens) => apiTokens.filter(isBridgeableEntry).map(toBridgeableToken),\n );\n }\n\n /**\n * Caches the FULL token list of `network`, replacing what it held: every token (none is dropped\n * for sharing a symbol), by symbol (the first token listed with it), and by token id exactly\n * (the class key of its four parts: GalaChain class keys are case-sensitive).\n */\n private store(network: BridgeableNetwork, tokens: BridgeableToken[]): void {\n const bySymbol = new Map<string, BridgeableToken>();\n const byTokenId = new Map<string, BridgeableToken>();\n for (const token of tokens) {\n const symbol = normalizeTokenSymbol(token.symbol);\n if (!bySymbol.has(symbol)) {\n bySymbol.set(symbol, token);\n }\n byTokenId.set(stringifyTokenClassKey(token.galaChainDescriptor), token);\n }\n this.cache.set(network, { tokens, bySymbol, byTokenId, fetchedAt: Date.now() });\n }\n\n /** The cached tokens of `network`, read first when it has none. */\n private async tokensOf(network: BridgeableNetwork): Promise<NetworkTokens> {\n const cached = this.cache.get(network);\n if (cached !== undefined && cached.tokens.length > 0) {\n return cached;\n }\n await this.fetchAllBridgeableTokensByNetwork(network);\n return this.cache.get(network) as NetworkTokens;\n }\n\n /**\n * Fetch one page of the tokens bridgeable to a network. Not cached: the cache holds only the\n * full list (a page standing in for it would hide every token on the other pages).\n *\n * @param options - Network, offset (default 0) and limit (default and at most 1000)\n */\n async fetchBridgeableTokensByNetwork(\n options: FetchBridgeableTokensOptions,\n ): Promise<FetchBridgeableTokensResult> {\n const { network, offset = 0, limit = TOKEN_PAGE_MAX } = options;\n const { items: tokens } = await this.fetchPage(network, offset, limit);\n return { tokens, network, fetchedAt: Date.now(), tokenCount: tokens.length };\n }\n\n /**\n * Fetch every token bridgeable to a network (every page), or the cached ones.\n *\n * @param network - ETHEREUM or SOLANA\n */\n async fetchAllBridgeableTokensByNetwork(\n network: BridgeableNetwork,\n ): Promise<FetchBridgeableTokensResult> {\n const cached = this.cache.get(network);\n if (cached !== undefined && cached.tokens.length > 0) {\n const tokens = [...cached.tokens];\n return { tokens, network, fetchedAt: cached.fetchedAt, tokenCount: tokens.length };\n }\n const tokens = await fetchAllTokenPages((offset, limit) =>\n this.fetchPage(network, offset, limit),\n );\n this.store(network, tokens);\n return { tokens, network, fetchedAt: Date.now(), tokenCount: tokens.length };\n }\n\n /** Every token bridgeable to Ethereum. */\n async fetchAllTokensBridgeableToEthereum(): Promise<FetchBridgeableTokensResult> {\n return this.fetchAllBridgeableTokensByNetwork('ETHEREUM');\n }\n\n /** Every token bridgeable to Solana. */\n async fetchAllTokensBridgeableToSolana(): Promise<FetchBridgeableTokensResult> {\n return this.fetchAllBridgeableTokensByNetwork('SOLANA');\n }\n\n /**\n * Whether a token (by token id) is bridgeable to a network, with its symbol and contract\n * address there. The symbol is the cached token's, never derived from the token id.\n */\n async isTokenBridgeableToNetwork(\n options: IsTokenBridgeableOptions,\n ): Promise<IsTokenBridgeableResult> {\n const { tokenId, network } = options;\n // The id is checked before the list is read: a refused id costs no read, whatever the read does\n const key = parseTokenId(tokenId).stringified;\n const token = (await this.tokensOf(network)).byTokenId.get(key);\n\n const result: IsTokenBridgeableResult = { isBridgeable: token !== undefined, network };\n if (token !== undefined) {\n result.tokenSymbol = token.symbol;\n const contractAddress =\n network === 'ETHEREUM' ? token.ethereumContractAddress : token.solanaContractAddress;\n if (contractAddress !== undefined) {\n result.contractAddress = contractAddress;\n }\n }\n return result;\n }\n\n /** Whether a token is bridgeable to Ethereum. */\n async isTokenBridgeableToEthereum(tokenId: TokenId): Promise<IsTokenBridgeableResult> {\n return this.isTokenBridgeableToNetwork({ tokenId, network: 'ETHEREUM' });\n }\n\n /** Whether a token is bridgeable to Solana. */\n async isTokenBridgeableToSolana(tokenId: TokenId): Promise<IsTokenBridgeableResult> {\n return this.isTokenBridgeableToNetwork({ tokenId, network: 'SOLANA' });\n }\n\n /** The token bridgeable to `network` with `symbol` (any case; the first listed), if any. */\n async getTokenBySymbol(\n symbol: string,\n network: BridgeableNetwork,\n ): Promise<BridgeableToken | undefined> {\n return (await this.tokensOf(network)).bySymbol.get(normalizeTokenSymbol(symbol));\n }\n\n /**\n * The token bridgeable to `network` with the token id `tokenId` (a pipe class key, matched\n * exactly: class keys are case-sensitive), if any.\n */\n async getTokenByTokenId(\n tokenId: string,\n network: BridgeableNetwork,\n ): Promise<BridgeableToken | undefined> {\n return (await this.tokensOf(network)).byTokenId.get(tokenId);\n }\n\n /** The contract address on `network` of the token with `symbol`, if any. */\n async getContractAddress(\n symbol: string,\n network: BridgeableNetwork,\n ): Promise<string | undefined> {\n const token = await this.getTokenBySymbol(symbol, network);\n return network === 'ETHEREUM' ? token?.ethereumContractAddress : token?.solanaContractAddress;\n }\n\n /** The symbols of the tokens bridgeable to `network`. */\n async getSupportedTokenSymbols(network: BridgeableNetwork): Promise<string[]> {\n return (await this.tokensOf(network)).tokens.map((token) => token.symbol);\n }\n\n /** Read both networks' token lists. */\n async preload(): Promise<void> {\n await Promise.all(NETWORKS.map((network) => this.fetchAllBridgeableTokensByNetwork(network)));\n }\n\n /** What the cache holds. */\n getCacheStats(): BridgeableTokenCacheStats {\n const itemsByNetwork: Record<BridgeableNetwork, number> = { ETHEREUM: 0, SOLANA: 0 };\n const fetchTimestamps: Partial<Record<BridgeableNetwork, number>> = {};\n for (const [network, entry] of this.cache) {\n itemsByNetwork[network] = entry.tokens.length;\n fetchTimestamps[network] = entry.fetchedAt;\n }\n const totalItems = itemsByNetwork.ETHEREUM + itemsByNetwork.SOLANA;\n return {\n networks: [...this.cache.keys()],\n totalItems,\n itemsByNetwork,\n fetchTimestamps,\n totalTokens: totalItems,\n tokensByNetwork: itemsByNetwork,\n };\n }\n\n /** Forget the cached tokens of `network`, or of every network. */\n clearCache(network?: BridgeableNetwork): void {\n if (network === undefined) {\n this.cache.clear();\n } else {\n this.cache.delete(network);\n }\n }\n}\n","/**\n * Wrappable Token Service\n *\n * The tokens that can be wrapped or unwrapped (moved between the asset channel and their own\n * channel), from the DEX API platform's token list (`/v1/tokens?wrappable=true`), cached, with\n * lookups by token id.\n *\n * @module bridge/tokens/WrappableTokenService\n */\n\nimport type { TokenClassKeyInput as TokenId } from '../../index.js';\nimport { hasFields } from '../internal/values.js';\nimport type {\n FetchWrappableTokensOptions,\n FetchWrappableTokensResult,\n IsTokenWrappableResult,\n WrappableToken,\n WrappableTokenApiResponse,\n WrappableTokenCacheStats,\n} from '../types/wrappable-token.dto.js';\nimport { parseTokenId, stringifyTokenClassKey } from '../utils/tokenIdUtils.js';\nimport {\n type DexApiReader,\n fetchAllTokenPages,\n fetchTokenPage,\n isTokenEntry,\n TOKEN_PAGE_MAX,\n type TokenPage,\n} from './tokenPages.js';\n\n/**\n * Whether a list entry is a usable wrappable token: a token entry with the `wrap` counterpart (a\n * string) and a boolean `swappable`, and a string `channel`, a boolean `trending` and an object\n * `currentPrices` when present.\n */\nfunction isWrappableEntry(entry: unknown): entry is WrappableTokenApiResponse {\n return (\n isTokenEntry(entry) &&\n hasFields(entry, ['wrap'], {\n channel: 'string',\n trending: 'boolean',\n currentPrices: 'object',\n }) &&\n typeof entry['swappable'] === 'boolean'\n );\n}\n\n/** A wrappable token from its API entry. */\nfunction toWrappableToken(t: WrappableTokenApiResponse): WrappableToken {\n const token: WrappableToken = {\n symbol: t.symbol,\n name: t.name,\n decimals: t.decimals,\n galaChainDescriptor: {\n collection: t.collection,\n category: t.category,\n type: t.type,\n additionalKey: t.additionalKey,\n },\n stringifiedTokenClassKey: t.stringifiedTokenClassKey,\n wrapCounterpart: t.wrap,\n swappable: t.swappable,\n verified: t.verified,\n };\n\n // Optional fields only when defined (exactOptionalPropertyTypes)\n if (t.channel !== undefined && t.channel !== '') {\n token.channel = t.channel;\n }\n if (t.trending !== undefined) {\n token.trending = t.trending;\n }\n if (t.image !== undefined && t.image !== '') {\n token.image = t.image;\n }\n if (t.description !== undefined && t.description !== '') {\n token.description = t.description;\n }\n if (t.currentPrices !== undefined) {\n token.currentPrices = t.currentPrices;\n }\n return token;\n}\n\n/**\n * Service for the wrappable tokens.\n *\n * Reads go through a {@link DexApiReader} (a `GalaConnectClient`, or launchpad-sdk's DEX API\n * `HttpClient`). Failures are `GalaSDKError`s: `BRIDGE_READ_RESPONSE_INVALID` for an answer\n * without a token list, `INVALID_TOKEN_REFERENCE` for a token id that is not one, and the read's\n * own (`GALACONNECT_HTTP_ERROR`, `TRANSPORT_ERROR`, ...).\n */\nexport class WrappableTokenService {\n /** The cached tokens by token id: the class key of its four parts, exactly (case-sensitive). */\n private readonly byTokenId = new Map<string, WrappableToken>();\n private fetchedAt: number | null = null;\n\n /**\n * @param dexApi - Reads the DEX API platform's token list\n */\n constructor(private readonly dexApi: DexApiReader) {}\n\n /** One page of the wrappable token list. */\n private fetchPage(offset: number, limit: number): Promise<TokenPage<WrappableToken>> {\n return fetchTokenPage(this.dexApi, { wrappable: true }, offset, limit, (apiTokens) =>\n apiTokens.filter(isWrappableEntry).map(toWrappableToken),\n );\n }\n\n /** Caches the FULL token list, replacing what the cache held. */\n private store(tokens: WrappableToken[]): void {\n this.byTokenId.clear();\n for (const token of tokens) {\n this.byTokenId.set(stringifyTokenClassKey(token.galaChainDescriptor), token);\n }\n this.fetchedAt = Date.now();\n }\n\n /** The cached token with `tokenId` (any token id form), reading the list first when empty. */\n private async lookup(tokenId: TokenId): Promise<{ key: string; token?: WrappableToken }> {\n const key = parseTokenId(tokenId).stringified;\n if (this.byTokenId.size === 0) {\n await this.fetchAllWrappableTokens();\n }\n const token = this.byTokenId.get(key);\n return token === undefined ? { key } : { key, token };\n }\n\n /**\n * Fetch one page of the wrappable tokens. Not cached: the cache holds only the full list (a page\n * standing in for it would hide every token on the other pages).\n *\n * @param options - Offset (default 0) and limit (default and at most 1000)\n */\n async fetchWrappableTokens(\n options: FetchWrappableTokensOptions = {},\n ): Promise<FetchWrappableTokensResult> {\n const { offset = 0, limit = TOKEN_PAGE_MAX } = options;\n const { items: tokens } = await this.fetchPage(offset, limit);\n return { tokens, fetchedAt: Date.now(), tokenCount: tokens.length };\n }\n\n /** Fetch every wrappable token (every page), or the cached ones. */\n async fetchAllWrappableTokens(): Promise<FetchWrappableTokensResult> {\n if (this.byTokenId.size > 0) {\n const tokens = [...this.byTokenId.values()];\n return { tokens, fetchedAt: this.fetchedAt as number, tokenCount: tokens.length };\n }\n const tokens = await fetchAllTokenPages((offset, limit) => this.fetchPage(offset, limit));\n this.store(tokens);\n return { tokens, fetchedAt: Date.now(), tokenCount: tokens.length };\n }\n\n /** The wrappable token with `tokenId`, if any. */\n async getWrappableToken(tokenId: TokenId): Promise<WrappableToken | undefined> {\n return (await this.lookup(tokenId)).token;\n }\n\n /** The token a wrappable token wraps to or unwraps from, if both are wrappable. */\n async getWrapCounterpart(tokenId: TokenId): Promise<WrappableToken | undefined> {\n const token = await this.getWrappableToken(tokenId);\n return token === undefined ? undefined : this.getWrappableToken(token.wrapCounterpart);\n }\n\n /** Whether a token is wrappable, with its counterpart. */\n async isTokenWrappable(tokenId: TokenId): Promise<IsTokenWrappableResult> {\n const { key, token } = await this.lookup(tokenId);\n const result: IsTokenWrappableResult = { isWrappable: token !== undefined, tokenId: key };\n if (token !== undefined) {\n result.wrapCounterpart = token.wrapCounterpart;\n }\n return result;\n }\n\n /** What the cache holds. */\n getCacheStats(): WrappableTokenCacheStats {\n return {\n totalItems: this.byTokenId.size,\n tokenCount: this.byTokenId.size,\n isPopulated: this.byTokenId.size > 0,\n lastFetchedAt: this.fetchedAt,\n };\n }\n\n /** Forget the cached tokens. */\n clearCache(): void {\n this.byTokenId.clear();\n this.fetchedAt = null;\n }\n}\n","/**\n * Wrap Service\n *\n * Cross-channel wrap (a token from its own channel to the asset channel, e.g. MUSIC → GMUSIC) and\n * unwrap (back), through GalaConnect: the natively signed `RequestTokenBridgeOut`, then\n * `BridgeTokenOut` from the source channel.\n *\n * A wrap or unwrap that does not complete throws (nothing is returned as a \"failed\" result):\n * before anything is sent, the refusal of the input (`TOKEN_NOT_WRAPPABLE`,\n * `INVALID_WRAP_DIRECTION`, `INVALID_BRIDGE_AMOUNT`, `INVALID_WALLET_ADDRESS`,\n * `INVALID_BRIDGE_OPTION` without a signer, `SIGNING_FAILED`); GalaConnect's or GalaChain's refusal\n * of the request (`GALACONNECT_HTTP_ERROR`, `BRIDGE_REQUEST_REJECTED`, ...: nothing was locked);\n * and, once the request was accepted, `BRIDGE_OUT_OUTCOME_UNKNOWN` (the tokens may be locked: never\n * wrap again, finish or check this one).\n *\n * @module bridge/tokens/WrapService\n */\n\nimport {\n createUniqueKey,\n GalaSDKError,\n galaChainUserRef,\n signPreSend,\n type GalaChainSigner,\n type TokenClassKeyInput as TokenId,\n} from '../../index.js';\nimport { GALACHAIN_CHANNELS } from '../constants/index.js';\nimport type { GalaConnectClient } from '../GalaConnectClient.js';\nimport { fieldsOf, stringifyTokenClassKey } from '../internal/values.js';\nimport type {\n UnwrapTokenOptions,\n WrappableToken,\n WrapTokenOptions,\n WrapUnwrapFeeEstimate,\n WrapUnwrapResult,\n} from '../types/wrappable-token.dto.js';\nimport { assertRequestAccepted } from '../utils/bridgeErrors.js';\nimport { completeBridgeOut } from '../utils/bridgeOutHelpers.js';\nimport { validateBridgeAmount } from '../utils/bridgePayload.js';\nimport type { WrappableTokenService } from './WrappableTokenService.js';\n\n/** The asset channel's name. */\nconst ASSET_CHANNEL = 'asset';\n\n/** The channels a wrap moves between, by name: their GalaChain channel ids. */\nconst CHANNEL_IDS: Readonly<Record<string, number>> = {\n [ASSET_CHANNEL]: GALACHAIN_CHANNELS.ASSET,\n music: GALACHAIN_CHANNELS.MUSIC,\n};\n\n/** The prefix of a wrap or unwrap uniqueKey. */\nconst WRAP_UNIQUE_KEY_PREFIX = 'galaswap-operation-';\n\n/** Where a wrap or unwrap goes: the channel it leaves, and the channel (and its id) it goes to. */\ninterface ChannelRouting {\n sourceChannel: string;\n destinationChannel: string;\n destinationChannelId: number;\n}\n\n/**\n * The channel of a token, when it is one a wrap moves between.\n *\n * @throws GalaSDKError `TOKEN_NOT_WRAPPABLE` (`unknown_channel`) otherwise\n */\nfunction channelOf(token: WrappableToken): string {\n if (token.channel === undefined || CHANNEL_IDS[token.channel] === undefined) {\n throw new GalaSDKError('TOKEN_NOT_WRAPPABLE', {\n tokenId: token.stringifiedTokenClassKey,\n reason: 'unknown_channel',\n });\n }\n return token.channel;\n}\n\n/**\n * Configuration for the wrap service.\n */\nexport interface WrapServiceConfig {\n /** GalaConnect client (`RequestTokenBridgeOut` and `BridgeTokenOut`) */\n galaConnectClient: GalaConnectClient;\n /** Resolves the wrappable tokens (a WrappableTokenService) */\n wrappableTokenService: Pick<WrappableTokenService, 'getWrappableToken' | 'getWrapCounterpart'>;\n /** Signs the `RequestTokenBridgeOut` (a native GalaChain signature); required to wrap */\n signer?: GalaChainSigner | undefined;\n /** The GalaChain address the signer signs for (the default recipient); required to wrap */\n walletAddress?: string | undefined;\n}\n\n/**\n * Service for cross-channel wrap and unwrap.\n */\nexport class WrapService {\n private readonly galaConnectClient: GalaConnectClient;\n private readonly wrappableTokenService: WrapServiceConfig['wrappableTokenService'];\n private readonly signer: GalaChainSigner | undefined;\n private readonly walletAddress: string | undefined;\n\n /**\n * @param config - Wrap service configuration\n */\n constructor(config: WrapServiceConfig) {\n this.galaConnectClient = config.galaConnectClient;\n this.wrappableTokenService = config.wrappableTokenService;\n this.signer = config.signer;\n this.walletAddress = config.walletAddress;\n }\n\n /**\n * Wrap a token: from its own channel to the asset channel (e.g. MUSIC → GMUSIC).\n *\n * @param options - The token, the amount, an optional recipient\n * @returns The completed wrap\n */\n async wrapToken(options: WrapTokenOptions): Promise<WrapUnwrapResult> {\n return this.execute(options, 'wrap');\n }\n\n /**\n * Unwrap a token: from the asset channel back to its own channel (e.g. GMUSIC → MUSIC).\n *\n * @param options - The token, the amount, an optional recipient\n * @returns The completed unwrap\n */\n async unwrapToken(options: UnwrapTokenOptions): Promise<WrapUnwrapResult> {\n return this.execute(options, 'unwrap');\n }\n\n /**\n * The fee and authorization of a wrap. The fee is the constant \"0\" GALA launchpad-sdk reported\n * (the channel bridge charges no fee the SDK can see).\n *\n * @param tokenId - The token to wrap\n * @param amount - The amount (checked like a wrap's)\n */\n async estimateWrapFee(tokenId: TokenId, amount: string): Promise<WrapUnwrapFeeEstimate> {\n return this.estimate(tokenId, amount, 'wrap');\n }\n\n /**\n * The fee and authorization of an unwrap (see {@link estimateWrapFee}).\n *\n * @param tokenId - The token to unwrap\n * @param amount - The amount (checked like an unwrap's)\n */\n async estimateUnwrapFee(tokenId: TokenId, amount: string): Promise<WrapUnwrapFeeEstimate> {\n return this.estimate(tokenId, amount, 'unwrap');\n }\n\n /** The source token, on the right channel for `direction`. */\n private async sourceToken(\n tokenId: TokenId,\n direction: 'wrap' | 'unwrap',\n ): Promise<WrappableToken> {\n const token = await this.wrappableTokenService.getWrappableToken(tokenId);\n if (token === undefined) {\n throw new GalaSDKError('TOKEN_NOT_WRAPPABLE', {\n // an object id by its class key: the form the list is keyed by\n tokenId: typeof tokenId === 'string' ? tokenId : stringifyTokenClassKey(tokenId),\n reason: 'not_listed',\n });\n }\n const onAsset = token.channel === ASSET_CHANNEL;\n if (direction === 'wrap' ? onAsset : !onAsset) {\n throw new GalaSDKError('INVALID_WRAP_DIRECTION', { symbol: token.symbol, direction });\n }\n return token;\n }\n\n /** The fee estimate of a wrap or unwrap. */\n private async estimate(\n tokenId: TokenId,\n amount: string,\n direction: 'wrap' | 'unwrap',\n ): Promise<WrapUnwrapFeeEstimate> {\n validateBridgeAmount(amount);\n const source = await this.sourceToken(tokenId, direction);\n return {\n fee: '0',\n feeToken: 'GALA',\n authorizationType: direction === 'wrap' ? 'cross_channel_authorization' : 'automatic',\n feeChannel: direction === 'wrap' ? channelOf(source) : ASSET_CHANNEL,\n };\n }\n\n /** A wrap or unwrap: every check, the signed request, then BridgeTokenOut. */\n private async execute(\n options: WrapTokenOptions | UnwrapTokenOptions,\n direction: 'wrap' | 'unwrap',\n ): Promise<WrapUnwrapResult> {\n const { amount } = options;\n validateBridgeAmount(amount);\n if (this.signer === undefined) {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'signer' });\n }\n if (this.walletAddress === undefined || this.walletAddress === '') {\n throw new GalaSDKError('INVALID_BRIDGE_OPTION', { option: 'walletAddress' });\n }\n const senderAddress = galaChainUserRef(this.walletAddress, 'walletAddress');\n const recipient =\n options.recipient === undefined || options.recipient === ''\n ? senderAddress\n : galaChainUserRef(options.recipient, 'recipient');\n\n const source = await this.sourceToken(options.tokenId, direction);\n const destination = await this.wrappableTokenService.getWrapCounterpart(options.tokenId);\n if (destination === undefined) {\n throw new GalaSDKError('TOKEN_NOT_WRAPPABLE', {\n tokenId: source.wrapCounterpart,\n reason: 'no_counterpart',\n });\n }\n // Wrap: the source token's channel → asset; unwrap: asset → the destination token's channel\n // (each a channel a wrap moves between: never guessed).\n const routing: ChannelRouting =\n direction === 'wrap'\n ? {\n sourceChannel: channelOf(source),\n destinationChannel: ASSET_CHANNEL,\n destinationChannelId: GALACHAIN_CHANNELS.ASSET,\n }\n : {\n sourceChannel: ASSET_CHANNEL,\n destinationChannel: channelOf(destination),\n destinationChannelId: CHANNEL_IDS[channelOf(destination)] as number,\n };\n\n // The native GalaChain message: quantity is the decimal amount; `wrap` is always true (the\n // direction is the destination channel id).\n const uniqueKey = createUniqueKey(WRAP_UNIQUE_KEY_PREFIX);\n const message = {\n quantity: amount,\n tokenInstance: {\n collection: source.galaChainDescriptor.collection,\n category: source.galaChainDescriptor.category,\n type: source.galaChainDescriptor.type,\n additionalKey: source.galaChainDescriptor.additionalKey,\n instance: '0',\n },\n destinationChainId: routing.destinationChannelId,\n recipient,\n wrap: true,\n uniqueKey,\n };\n const requestBody = await signPreSend(\n this.signer,\n 'asset/bridge-contract',\n 'RequestTokenBridgeOut',\n message,\n );\n\n const response = await this.galaConnectClient.requestBridgeOut(requestBody);\n // GalaChain refusing the request locked nothing: its own refusal, with the key\n assertRequestAccepted('RequestTokenBridgeOut', response, uniqueKey);\n\n const transactionId = await completeBridgeOut(\n this.galaConnectClient,\n response,\n uniqueKey,\n routing.sourceChannel,\n readWrapResult,\n );\n\n return {\n success: true,\n transactionId,\n fromToken: source.symbol,\n toToken: destination.symbol,\n amount,\n fromChannel: routing.sourceChannel,\n toChannel: routing.destinationChannel,\n completedAt: Date.now(),\n };\n }\n}\n\n/**\n * A wrap's `BridgeTokenOut` answer: it must say `Status` 1; its transaction id is its `Hash`, else\n * the bridge request id.\n *\n * @throws GalaSDKError `BRIDGE_RESPONSE_INVALID` without `Status` 1\n */\nfunction readWrapResult(bridgeOutResponse: unknown, bridgeRequestId: string): string {\n const fields = fieldsOf(bridgeOutResponse);\n if (fields['Status'] !== 1) {\n throw new GalaSDKError('BRIDGE_RESPONSE_INVALID', {\n method: 'BridgeTokenOut',\n missing: 'Status 1',\n });\n }\n const hash = fields['Hash'];\n return typeof hash === 'string' && hash !== '' ? hash : bridgeRequestId;\n}\n","/**\n * Solana wallet creation (for bridging to and from Solana).\n *\n * The Ethereum wallet helpers (`createWallet`, `validateWalletInput`, `getPublicKeyFromPrivateKey`,\n * `getEthereumAddressFromPrivateKey`) are the core root's: they need no Solana library.\n *\n * @module bridge/solanaWallet\n */\n\nimport { base58 } from '@scure/base';\nimport { Keypair } from '@solana/web3.js';\n\n/**\n * A generated Solana wallet.\n */\nexport interface GeneratedSolanaWallet {\n /** Base58-encoded 64-byte secret key (used for signing) */\n privateKey: string;\n /** Base58-encoded 32-byte public key */\n publicKey: string;\n /** Solana address (the public key: Solana addresses ARE public keys) */\n address: string;\n}\n\n/**\n * Creates a new random Solana wallet: an Ed25519 keypair, its secret key in base58 (the form the\n * Solana bridge strategy's `solanaPrivateKey` takes).\n *\n * @returns The generated wallet: secret key, public key, address\n *\n * @example\n * ```typescript\n * import { createSolanaWallet } from '@gala-chain/gala-core-sdk/bridge';\n *\n * const wallet = createSolanaWallet();\n * console.log(wallet.address); // base58 public key\n * ```\n */\nexport function createSolanaWallet(): GeneratedSolanaWallet {\n const keypair = Keypair.generate();\n const publicKey = keypair.publicKey.toBase58();\n return {\n privateKey: base58.encode(keypair.secretKey),\n publicKey,\n address: publicKey,\n };\n}\n","/**\n * Address Formatter - Utilities for converting between Ethereum and GalaChain address formats\n *\n * Consolidates scattered address format conversion patterns across the SDK.\n * Provides consistent address normalization for blockchain interoperability.\n *\n * @category Bridge Utilities\n * @since 6.15.0\n */\n\n/**\n * Removes \"0x\" prefix from Ethereum address hex values\n *\n * Consolidates 13 scattered instances of manual 0x removal patterns:\n * - .replace('0x', '')\n * - .slice(2)\n * - .substring(2) with startsWith check\n *\n * @param hex Hex value potentially with 0x prefix\n * @returns Hex value without 0x prefix\n * @example\n * stripHexPrefix('0x123abc') // '123abc'\n * stripHexPrefix('123abc') // '123abc'\n */\nexport function stripHexPrefix(hex: string): string {\n if (hex === '') return '';\n return hex.startsWith('0x') ? hex.slice(2) : hex;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwNA,IAAY,mBAAL;CACL;CACA;CACA;CACA;CACA;CACA;CACA;;CAEA;;AACF;;;;;;;;;;;;;ACxNA,MAAa,gCAAgC;CAC3C,MAAM;CACN,SAAS;AACX;;;;AAiBA,MAAM,wBAA0C;CAC9C;EAAE,MAAM;EAAsB,MAAM;CAAU;CAC9C;EAAE,MAAM;EAAyB,MAAM;CAAwB;CAC/D;EAAE,MAAM;EAAgB,M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