@avalabs/fusion-sdk 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mod.d.cts +2 -2
- package/dist/mod.d.ts +2 -2
- package/dist/transfer-manager.cjs +1 -1
- package/dist/transfer-manager.cjs.map +1 -1
- package/dist/transfer-manager.js +1 -1
- package/dist/transfer-manager.js.map +1 -1
- package/dist/transfer-service/markr/_api.cjs +1 -1
- package/dist/transfer-service/markr/_api.cjs.map +1 -1
- package/dist/transfer-service/markr/_api.js +1 -1
- package/dist/transfer-service/markr/_api.js.map +1 -1
- package/dist/transfer-service/markr/_handlers/estimate-native-fee.cjs +1 -1
- package/dist/transfer-service/markr/_handlers/estimate-native-fee.cjs.map +1 -1
- package/dist/transfer-service/markr/_handlers/estimate-native-fee.js +1 -1
- package/dist/transfer-service/markr/_handlers/estimate-native-fee.js.map +1 -1
- package/dist/transfer-service/markr/_handlers/stream-quotes.cjs +1 -1
- package/dist/transfer-service/markr/_handlers/stream-quotes.cjs.map +1 -1
- package/dist/transfer-service/markr/_handlers/stream-quotes.js +1 -1
- package/dist/transfer-service/markr/_handlers/stream-quotes.js.map +1 -1
- package/dist/transfer-service/markr/_handlers/track-transfer.cjs +1 -1
- package/dist/transfer-service/markr/_handlers/track-transfer.cjs.map +1 -1
- package/dist/transfer-service/markr/_handlers/track-transfer.js +1 -1
- package/dist/transfer-service/markr/_handlers/track-transfer.js.map +1 -1
- package/dist/transfer-service/markr/_handlers/transfer-asset.cjs +1 -1
- package/dist/transfer-service/markr/_handlers/transfer-asset.cjs.map +1 -1
- package/dist/transfer-service/markr/_handlers/transfer-asset.js +1 -1
- package/dist/transfer-service/markr/_handlers/transfer-asset.js.map +1 -1
- package/dist/transfer-service/markr/_schema.cjs +1 -1
- package/dist/transfer-service/markr/_schema.cjs.map +1 -1
- package/dist/transfer-service/markr/_schema.js +1 -1
- package/dist/transfer-service/markr/_schema.js.map +1 -1
- package/dist/transfer-service/markr/_utils.cjs +1 -1
- package/dist/transfer-service/markr/_utils.cjs.map +1 -1
- package/dist/transfer-service/markr/_utils.js +1 -1
- package/dist/transfer-service/markr/_utils.js.map +1 -1
- package/dist/transfer-service/markr/markr-service.cjs +1 -1
- package/dist/transfer-service/markr/markr-service.cjs.map +1 -1
- package/dist/transfer-service/markr/markr-service.js +1 -1
- package/dist/transfer-service/markr/markr-service.js.map +1 -1
- package/dist/types/service.d.cts +6 -0
- package/dist/types/service.d.ts +6 -0
- package/dist/types/signer.d.cts +3 -1
- package/dist/types/signer.d.ts +3 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"estimate-native-fee.cjs","names":["isEvmNamespace","isSolanaNamespace","InvalidParamsError","ErrorReason","getEvmClientForChain","assetToAddressString","SdkError","ErrorCode","isTokenAddressNative","markrGetSpenderAddress","caip2ToEip155ChainId","erc20Abi","calculateMarkrMinimumAmountOut","markrSwap","isEvmSwapResponse","applyFeeUnitsBpsMargin","estimateEvmFeesPerGas","isSolanaSwapResponse","getSolanaRpcForChain","decodeMarkrRevertError","getMarkrSwapWrapperAbi"],"sources":["../../../../src/transfer-service/markr/_handlers/estimate-native-fee.ts"],"sourcesContent":["import {\n type CompiledTransactionMessage,\n getCompiledTransactionMessageDecoder,\n getTransactionDecoder,\n isAddress as isSolanaAddress,\n type Base64EncodedWireTransaction,\n type Rpc,\n type SolanaRpcApi,\n type TransactionMessageBytes,\n type TransactionMessageBytesBase64,\n} from '@solana/kit';\nimport { encodeFunctionData, erc20Abi, type Address as EvmAddress, isAddress as isEvmAddress } from 'viem';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { EstimateNativeFeeOptions, NativeFeeEstimate, TransferService } from '../../../types/service';\nimport { applyFeeUnitsBpsMargin, getEvmClientForChain, getSolanaRpcForChain } from '../../_utils';\nimport { estimateEvmFeesPerGas } from '../../_evm-gas';\nimport { markrGetSpenderAddress, markrSwap, type ApiOptions } from '../_api';\nimport {\n assetToAddressString,\n calculateMarkrMinimumAmountOut,\n decodeMarkrRevertError,\n getMarkrSwapWrapperAbi,\n isTokenAddressNative,\n} from '../_utils';\nimport type { WrappedSwapTransactionResponse } from '../_schema';\nimport { isEvmSwapResponse, isSolanaSwapResponse } from '../_type-guards';\nimport { caip2ToEip155ChainId } from '../../../utils/caip';\nimport type { Quote } from '../../../types/quote';\nimport { isEvmNamespace, isSolanaNamespace } from '../../../_utils/chain';\n\n/**\n * This is just a fallback value used in the case that an\n * allowance approval is needed, and Markr didn't return us any gas estimate data.\n *\n * Just based on my review of some quotes, I think this is a reasonable estimate\n * left on the higher end.\n *\n * Assume this could need to change.\n */\nconst EVM_SWAP_FALLBACK_GAS_ESTIMATE = 700_000n;\n\n/**\n * Compute Budget program address.\n *\n * Used to detect `SetComputeUnitPrice` instructions when deriving\n * the Solana priority fee component from transaction message bytes.\n */\nconst SOLANA_COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';\n\n/**\n * System Program address.\n *\n * Used to detect account-creation instructions and extract lamports\n * funded upfront for newly created system accounts.\n */\nconst SOLANA_SYSTEM_PROGRAM = '11111111111111111111111111111111';\n\n/**\n * Associated Token Account (ATA) program address.\n *\n * Used to detect ATA create instructions so the estimator can include\n * rent-exempt funding when the ATA does not already exist on-chain.\n */\nconst SOLANA_ASSOCIATED_TOKEN_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n\n/**\n * Legacy SPL Token program address.\n *\n * Used to detect close-account instructions that may refund lamports\n * from temporary token accounts back to the sender.\n */\nconst SOLANA_SPL_TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\n\n/**\n * SPL Token-2022 program address.\n *\n * Used alongside the legacy token program for close-account detection\n * when computing expected refundable lamports.\n */\nconst SOLANA_SPL_TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';\n\n/**\n * SPL token account size for rent-exemption calculations.\n *\n * Used with `getMinimumBalanceForRentExemption` to estimate ATA\n * creation funding requirements.\n */\nconst SPL_TOKEN_ACCOUNT_SIZE_BYTES = 165n;\n\nexport interface EstimateNativeFeeFactoryConfig {\n apiOptions: ApiOptions;\n appId: string;\n}\n\ninterface CreatedRentAccount {\n address: string;\n kind: 'ata' | 'system';\n lamports: bigint;\n refunded: boolean;\n}\n\ninterface SolanaRentEstimate {\n createdAccounts: CreatedRentAccount[];\n rentFee: bigint;\n rentFeeNet: bigint;\n refundable: bigint;\n}\n\nexport function estimateNativeFeeFactory(config: EstimateNativeFeeFactoryConfig): TransferService['estimateNativeFee'] {\n return async (quote, options) => {\n // Either the source chain is EVM or Solana, we need to call different functions that\n // calculate the native fee depending on the chain kind.\n\n if (isEvmNamespace(quote.sourceChain.chainId)) {\n return await _estimateNativeFeeEvm(quote, options, config);\n }\n\n if (isSolanaNamespace(quote.sourceChain.chainId)) {\n return await _estimateNativeFeeSolana(quote, options, config);\n }\n\n throw new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n `Unsupported source chain namespace for estimateNativeFee: ${quote.sourceChain.chainId}`,\n );\n };\n}\n\n/** @internal */\nexport async function _estimateNativeFeeEvm(\n quote: Quote,\n options: EstimateNativeFeeOptions | undefined,\n { apiOptions, appId }: EstimateNativeFeeFactoryConfig,\n): Promise<NativeFeeEstimate> {\n if (!isEvmAddress(quote.fromAddress)) {\n throw new InvalidParamsError(ErrorReason.INVALID_PARAMS, `Invalid fromAddress: ${quote.fromAddress}`);\n }\n\n const sourceClient = getEvmClientForChain({ chain: quote.sourceChain });\n\n const assetInAddressString = assetToAddressString(quote.assetIn, quote.sourceChain.chainId);\n\n if (!isEvmAddress(assetInAddressString)) {\n throw new SdkError(ErrorReason.INVALID_PARAMS, ErrorCode.INVALID_PARAMS, {\n details: `assetIn address is not a valid EVM address. Can not call estimateGas.`,\n });\n }\n\n const isAssetInNative = isTokenAddressNative(assetInAddressString);\n const isCrossChainSwap = quote.sourceChain.chainId.toLowerCase() !== quote.targetChain.chainId.toLowerCase();\n\n let allowanceApprovalGas = 0n;\n if (!isAssetInNative) {\n // Check if approval is needed, and if so, calculate the gas cost for the approval.\n let allowance: bigint;\n\n const { address: spenderAddress } = await markrGetSpenderAddress(\n apiOptions,\n caip2ToEip155ChainId(quote.sourceChain.chainId),\n isCrossChainSwap,\n );\n\n try {\n allowance = await sourceClient.readContract({\n address: assetInAddressString,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [quote.fromAddress, spenderAddress],\n });\n } catch (error) {\n throw new SdkError('Error during allowance check', ErrorCode.VIEM_ERROR, {\n cause: error,\n details: 'Failed to read ERC20 allowance for Markr spender.',\n });\n }\n\n const approvalNeeded = allowance < quote.amountIn;\n\n if (approvalNeeded) {\n try {\n allowanceApprovalGas = await sourceClient.estimateGas({\n account: quote.fromAddress,\n to: assetInAddressString,\n data: encodeFunctionData({\n abi: erc20Abi,\n functionName: 'approve',\n args: [spenderAddress, quote.amountIn],\n }),\n value: 0n,\n });\n } catch (error) {\n throw new SdkError('Error during gas estimation', ErrorCode.VIEM_ERROR, {\n cause: error,\n details: 'Failed to estimate gas for ERC20 approval transaction.',\n });\n }\n }\n }\n\n const allowanceApprovalIsNeeded = allowanceApprovalGas > 0n;\n\n const minAmountOut = calculateMarkrMinimumAmountOut({\n amountOut: quote.amountOut,\n assetOut: quote.assetOut,\n slippageBps: quote.slippageBps,\n });\n\n const swap = await markrSwap(apiOptions, {\n amountIn: quote.amountIn.toString(),\n appId,\n minAmountOut: minAmountOut.toString(),\n tokenIn: assetInAddressString,\n tokenOut: assetToAddressString(quote.assetOut, quote.targetChain.chainId),\n uuid: quote.id,\n });\n\n if (!isEvmSwapResponse(swap)) {\n // Should hopefully never happen.\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: `Received non-EVM swap response from Markr. Expected EVM transaction data for gas estimation, but got response with chainType ${swap.chainType}.`,\n });\n }\n\n let gasWithMargin = 0n;\n\n // If an approval is needed, we can't call `eth_estimateGas` on the\n // swap transaction because no actual allowance approval was performed yet,\n // so a gas estimation would fail due to needing allowance.\n //\n // So if an allowance approval is needed, we fall back to some other logic for\n // estimating the swap tx gas.\n if (allowanceApprovalIsNeeded) {\n // Attempt to use the Markr provided `gasEstimate` first if available.\n // Otherwise we attempt to get the gas from the `fees` component that are applicable\n // to the source chain. If neither of those are available, we fall back to a hardcoded value.\n if (quote.gasEstimate) {\n gasWithMargin = applyFeeUnitsBpsMargin(quote.gasEstimate, options?.feeUnitsMarginBps);\n } else {\n const sourceGasFee = quote.fees\n .filter((fee) => fee.type === 'gas' && fee.chainId === quote.sourceChain.chainId)\n .reduce((acc, fee) => acc + fee.amount, 0n);\n\n gasWithMargin = applyFeeUnitsBpsMargin(\n sourceGasFee || EVM_SWAP_FALLBACK_GAS_ESTIMATE,\n options?.feeUnitsMarginBps,\n );\n }\n } else {\n gasWithMargin = await _estimateGasFromSwapResponse({\n crossChain: isCrossChainSwap,\n feeUnitsMarginBps: options?.feeUnitsMarginBps,\n fromAddress: quote.fromAddress,\n sourceClient,\n swap,\n });\n }\n\n const fees = await estimateEvmFeesPerGas(sourceClient, quote.sourceChain, options?.overrides?.feeRateTier);\n\n const maxFeePerGas = options?.overrides?.maxFeePerGas ?? fees.maxFeePerGas;\n const maxPriorityFeePerGas = options?.overrides?.maxPriorityFeePerGas ?? fees.maxPriorityFeePerGas;\n\n const totalFee =\n (gasWithMargin + applyFeeUnitsBpsMargin(allowanceApprovalGas, options?.feeUnitsMarginBps)) * maxFeePerGas;\n\n return {\n asset: quote.sourceChain.networkToken,\n totalFee,\n meta: {\n approvalFee: allowanceApprovalIsNeeded\n ? applyFeeUnitsBpsMargin(allowanceApprovalGas, options?.feeUnitsMarginBps) * maxFeePerGas\n : undefined,\n maxFeePerGas,\n maxPriorityFeePerGas,\n },\n };\n}\n\n/** @internal */\nexport async function _estimateNativeFeeSolana(\n quote: Quote,\n options: EstimateNativeFeeOptions | undefined,\n { apiOptions, appId }: EstimateNativeFeeFactoryConfig,\n): Promise<NativeFeeEstimate> {\n const assetInAddressString = assetToAddressString(quote.assetIn, quote.sourceChain.chainId);\n\n if (!isSolanaAddress(assetInAddressString)) {\n throw new SdkError(ErrorReason.INVALID_PARAMS, ErrorCode.INVALID_PARAMS, {\n details: `assetIn address is not a valid Solana address. Can not call estimateGas.`,\n });\n }\n\n const minAmountOut = calculateMarkrMinimumAmountOut({\n amountOut: quote.amountOut,\n assetOut: quote.assetOut,\n slippageBps: quote.slippageBps,\n });\n\n const swap = await markrSwap(apiOptions, {\n amountIn: quote.amountIn.toString(),\n appId,\n minAmountOut: minAmountOut.toString(),\n tokenIn: assetInAddressString,\n tokenOut: assetToAddressString(quote.assetOut, quote.targetChain.chainId),\n userPublicKey: quote.fromAddress,\n uuid: quote.id,\n });\n\n if (!isSolanaSwapResponse(swap)) {\n // Should hopefully never happen.\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: 'Received non-Solana swap response from Markr. Expected Solana transaction data for fee estimation.',\n });\n }\n\n const rpc = getSolanaRpcForChain({ chain: quote.sourceChain });\n\n const txBytes = base64ToBytes(swap.swapTransaction);\n const tx = getTransactionDecoder().decode(txBytes);\n\n const messageBase64: TransactionMessageBytesBase64 = _transactionMessageBytesToBase64(tx.messageBytes);\n\n // Base fee (signature fee etc.) in lamports.\n const feeForMessageResponse = await rpc.getFeeForMessage(messageBase64).send();\n\n if (!feeForMessageResponse.value) {\n // This can happen if the block hash is expired or invalid.\n // Most likely expired. Use a new \"swapTxBase64\" with a recent block hash and try again.\n throw new SdkError(\n 'Failed to get fee for message. Most likely the block hash in the transaction is expired.',\n ErrorCode.TIMEOUT,\n {\n details: 'Please use a new quote with a recent block hash and try again.',\n },\n );\n }\n\n const baseFeeLamports = feeForMessageResponse.value;\n\n const sim = await rpc\n .simulateTransaction(swap.swapTransaction as Base64EncodedWireTransaction, {\n encoding: 'base64',\n sigVerify: false,\n })\n .send();\n\n if (sim.value.err) {\n throw new SdkError('Failed to simulate transaction for estimating fee.', ErrorCode.SOLANA_ERROR, {\n cause: sim.value.err,\n });\n }\n\n const unitsConsumed = applyFeeUnitsBpsMargin(sim.value.unitsConsumed ?? 0n, options?.feeUnitsMarginBps);\n // Lamports\n const computeUnitPriceMicroLamports = _getComputeUnitPriceMicroLamports(tx.messageBytes);\n const priorityFee = (unitsConsumed * computeUnitPriceMicroLamports) / 1_000_000n;\n const rentEstimate = await _estimateRentFeesFromTransactionMessage({\n fromAddress: quote.fromAddress,\n rpc,\n transactionMessageBytes: tx.messageBytes,\n });\n const totalLamports = baseFeeLamports + priorityFee + rentEstimate.rentFee;\n\n return {\n asset: quote.sourceChain.networkToken,\n totalFee: totalLamports,\n refundable: rentEstimate.refundable,\n meta: {\n baseFee: baseFeeLamports,\n priorityFee,\n computeUnitPriceMicroLamports,\n unitsConsumed,\n createdAccounts: rentEstimate.createdAccounts,\n rentFee: rentEstimate.rentFee,\n rentFeeNet: rentEstimate.rentFeeNet,\n },\n };\n}\n\n/** @internal */\nexport async function _estimateGasFromSwapResponse({\n crossChain,\n feeUnitsMarginBps,\n fromAddress,\n sourceClient,\n swap,\n}: {\n crossChain: boolean;\n feeUnitsMarginBps?: number;\n fromAddress: EvmAddress;\n sourceClient: ReturnType<typeof getEvmClientForChain>;\n swap: WrappedSwapTransactionResponse;\n}): Promise<bigint> {\n try {\n const gasEstimate = await sourceClient.estimateGas({\n account: fromAddress,\n to: swap.to,\n data: swap.data,\n value: swap.value,\n });\n\n return applyFeeUnitsBpsMargin(gasEstimate, feeUnitsMarginBps);\n } catch (err) {\n let details = 'Failed to estimate gas for Markr swap transaction.';\n\n try {\n const markrSwapWrapperAbi = await getMarkrSwapWrapperAbi(crossChain);\n const decodedRevert = decodeMarkrRevertError(markrSwapWrapperAbi, err);\n\n if (decodedRevert) {\n details = `${details} Markr revert: ${decodedRevert}.`;\n }\n } catch {\n // Keep the base details message if revert decoding fails.\n }\n\n throw new SdkError('Error during gas estimation', ErrorCode.VIEM_ERROR, {\n cause: err,\n details,\n });\n }\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n}\n\nfunction _transactionMessageBytesToBase64(bytes: TransactionMessageBytes): TransactionMessageBytesBase64 {\n let binary = '';\n for (const b of bytes) {\n binary += String.fromCharCode(b);\n }\n return btoa(binary) as TransactionMessageBytesBase64;\n}\n\nfunction _getComputeUnitPriceMicroLamports(transactionMessageBytes: TransactionMessageBytes): bigint {\n const compiledTxMessage = getCompiledTransactionMessageDecoder().decode(transactionMessageBytes);\n\n for (const instruction of compiledTxMessage.instructions) {\n const programAddress = compiledTxMessage.staticAccounts[instruction.programAddressIndex];\n if (programAddress !== SOLANA_COMPUTE_BUDGET_PROGRAM) {\n continue;\n }\n\n const data = instruction.data;\n\n if (!data || data.length < 1 + 8) {\n continue;\n }\n\n // ComputeBudget: u8 discriminator, then args\n // discriminator 3 = SetComputeUnitPrice, args = u64 microLamports\n const discriminator = data[0];\n if (discriminator !== 3) {\n continue;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n return view.getBigUint64(1, true);\n }\n\n return 0n;\n}\n\nasync function _estimateRentFeesFromTransactionMessage({\n fromAddress,\n rpc,\n transactionMessageBytes,\n}: {\n fromAddress: string;\n rpc: Rpc<SolanaRpcApi>;\n transactionMessageBytes: TransactionMessageBytes;\n}): Promise<SolanaRentEstimate> {\n const compiledMessage: CompiledTransactionMessage =\n getCompiledTransactionMessageDecoder().decode(transactionMessageBytes);\n\n const createdAccounts = new Map<string, Omit<CreatedRentAccount, 'refunded'>>();\n const closedAccountDestinationByAddress = new Map<string, string>();\n\n let ataRentLamports: bigint | undefined;\n\n for (const instruction of compiledMessage.instructions) {\n const programAddress = compiledMessage.staticAccounts[instruction.programAddressIndex];\n\n if (programAddress === SOLANA_SYSTEM_PROGRAM) {\n const createdAccountAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n const lamports = _getSystemCreateAccountLamports(instruction.data);\n if (createdAccountAddress && lamports > 0n) {\n createdAccounts.set(createdAccountAddress, {\n address: createdAccountAddress,\n kind: 'system',\n lamports,\n });\n }\n continue;\n }\n\n if (programAddress === SOLANA_ASSOCIATED_TOKEN_PROGRAM) {\n const discriminator = instruction.data?.[0];\n const isAssociatedTokenCreateInstruction =\n discriminator === undefined || discriminator === 0 || discriminator === 1;\n\n if (!isAssociatedTokenCreateInstruction) {\n continue;\n }\n\n const associatedTokenAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n if (!associatedTokenAddress) {\n continue;\n }\n\n const accountInfo = await rpc.getAccountInfo(associatedTokenAddress).send();\n if (accountInfo.value) {\n continue;\n }\n\n if (ataRentLamports === undefined) {\n ataRentLamports = await rpc.getMinimumBalanceForRentExemption(SPL_TOKEN_ACCOUNT_SIZE_BYTES).send();\n }\n\n createdAccounts.set(associatedTokenAddress, {\n address: associatedTokenAddress,\n kind: 'ata',\n lamports: ataRentLamports,\n });\n\n continue;\n }\n\n const isSplTokenProgram =\n programAddress === SOLANA_SPL_TOKEN_PROGRAM || programAddress === SOLANA_SPL_TOKEN_2022_PROGRAM;\n if (!isSplTokenProgram) {\n continue;\n }\n\n const discriminator = instruction.data?.[0];\n if (discriminator !== 9) {\n continue;\n }\n\n const closedAccountAddress = _getInstructionAccountAddress(compiledMessage, instruction, 0);\n const refundDestinationAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n\n if (closedAccountAddress && refundDestinationAddress) {\n closedAccountDestinationByAddress.set(closedAccountAddress, refundDestinationAddress);\n }\n }\n\n const normalizedFromAddress = isSolanaAddress(fromAddress) ? fromAddress : undefined;\n const createdAccountEntries = Array.from(createdAccounts.values()).map((createdAccount) => {\n const refundDestinationAddress = closedAccountDestinationByAddress.get(createdAccount.address);\n const refunded = normalizedFromAddress !== undefined && refundDestinationAddress === normalizedFromAddress;\n\n return {\n ...createdAccount,\n refunded,\n } satisfies CreatedRentAccount;\n });\n\n const rentLamportsUpfront = createdAccountEntries.reduce((acc, account) => acc + account.lamports, 0n);\n const refundedLamports = createdAccountEntries.reduce(\n (acc, account) => acc + (account.refunded ? account.lamports : 0n),\n 0n,\n );\n const rentFeeNet = rentLamportsUpfront - refundedLamports;\n\n return {\n createdAccounts: createdAccountEntries,\n rentFee: rentLamportsUpfront,\n rentFeeNet,\n refundable: refundedLamports,\n };\n}\n\n/**\n * Resolves an account address used by a compiled instruction.\n *\n * Compiled instructions reference accounts by index into the transaction\n * message's `staticAccounts` list. This helper converts an instruction-local\n * `accountIndex` into the corresponding static account address.\n *\n * Returns `undefined` when the instruction does not provide an account at the\n * requested index.\n */\nfunction _getInstructionAccountAddress(\n message: CompiledTransactionMessage,\n instruction: CompiledTransactionMessage['instructions'][number],\n accountIndex: number,\n): CompiledTransactionMessage['staticAccounts'][number] | undefined {\n const messageAccountIndex = instruction.accountIndices?.[accountIndex];\n\n if (messageAccountIndex === undefined) {\n return undefined;\n }\n\n return message.staticAccounts[messageAccountIndex];\n}\n\n/**\n * Extracts lamports from System Program account-creation instruction data.\n *\n * Supported instruction layouts:\n * - `CreateAccount` (`u32 discriminator = 0`): lamports at byte offset `4`.\n * - `CreateAccountWithSeed` (`u32 discriminator = 3`): lamports are located\n * after the variable-length seed field.\n *\n * Returns `0n` when data is missing, malformed, or not one of the supported\n * System Program create-account variants.\n */\nfunction _getSystemCreateAccountLamports(data: CompiledTransactionMessage['instructions'][number]['data']): bigint {\n if (!data || data.length < 12) {\n return 0n;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const instructionDiscriminator = view.getUint32(0, true);\n\n if (instructionDiscriminator === 0 && data.length >= 12) {\n return view.getBigUint64(4, true);\n }\n\n if (instructionDiscriminator === 3 && data.length >= 44) {\n const seedLenOffset = 36;\n const seedLength = Number(view.getBigUint64(seedLenOffset, true));\n if (!Number.isSafeInteger(seedLength) || seedLength < 0) {\n return 0n;\n }\n\n const lamportsOffset = seedLenOffset + 8 + seedLength;\n if (lamportsOffset + 8 > data.length) {\n return 0n;\n }\n\n return new DataView(data.buffer, data.byteOffset + lamportsOffset, 8).getBigUint64(0, true);\n }\n\n return 0n;\n}\n"],"mappings":"wWA4GA,SAAgB,EAAyB,EAA8E,CACrH,OAAO,MAAO,EAAO,IAAY,CAI/B,GAAIA,EAAAA,eAAe,EAAM,YAAY,QAAQ,CAC3C,OAAO,MAAM,EAAsB,EAAO,EAAS,EAAO,CAG5D,GAAIC,EAAAA,kBAAkB,EAAM,YAAY,QAAQ,CAC9C,OAAO,MAAM,EAAyB,EAAO,EAAS,EAAO,CAG/D,MAAM,IAAIC,EAAAA,mBACRC,EAAAA,YAAY,eACZ,6DAA6D,EAAM,YAAY,UAChF,EAKL,eAAsB,EACpB,EACA,EACA,CAAE,aAAY,SACc,CAC5B,GAAI,EAAA,EAAA,EAAA,WAAc,EAAM,YAAY,CAClC,MAAM,IAAID,EAAAA,mBAAmBC,EAAAA,YAAY,eAAgB,wBAAwB,EAAM,cAAc,CAGvG,IAAM,EAAeC,EAAAA,qBAAqB,CAAE,MAAO,EAAM,YAAa,CAAC,CAEjE,EAAuBC,EAAAA,qBAAqB,EAAM,QAAS,EAAM,YAAY,QAAQ,CAE3F,GAAI,EAAA,EAAA,EAAA,WAAc,EAAqB,CACrC,MAAM,IAAIC,EAAAA,SAASH,EAAAA,YAAY,eAAgBI,EAAAA,UAAU,eAAgB,CACvE,QAAS,wEACV,CAAC,CAGJ,IAAM,EAAkBC,EAAAA,qBAAqB,EAAqB,CAC5D,EAAmB,EAAM,YAAY,QAAQ,aAAa,GAAK,EAAM,YAAY,QAAQ,aAAa,CAExG,EAAuB,GAC3B,GAAI,CAAC,EAAiB,CAEpB,IAAI,EAEE,CAAE,QAAS,GAAmB,MAAMC,EAAAA,uBACxC,EACAC,EAAAA,qBAAqB,EAAM,YAAY,QAAQ,C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,eAAe,GAchC,SAAS,EAAgC,EAA0E,CACjH,GAAI,CAAC,GAAQ,EAAK,OAAS,GACzB,OAAO,GAGT,IAAM,EAAO,IAAI,SAAS,EAAK,OAAQ,EAAK,WAAY,EAAK,WAAW,CAClE,EAA2B,EAAK,UAAU,EAAG,GAAK,CAExD,GAAI,IAA6B,GAAK,EAAK,QAAU,GACnD,OAAO,EAAK,aAAa,EAAG,GAAK,CAGnC,GAAI,IAA6B,GAAK,EAAK,QAAU,GAAI,CACvD,IACM,EAAa,OAAO,EAAK,aAAa,GAAe,GAAK,CAAC,CACjE,GAAI,CAAC,OAAO,cAAc,EAAW,EAAI,EAAa,EACpD,OAAO,GAGT,IAAM,EAAiB,GAAoB,EAK3C,OAJI,EAAiB,EAAI,EAAK,OACrB,GAGF,IAAI,SAAS,EAAK,OAAQ,EAAK,WAAa,EAAgB,EAAE,CAAC,aAAa,EAAG,GAAK,CAG7F,OAAO"}
|
|
1
|
+
{"version":3,"file":"estimate-native-fee.cjs","names":["isEvmNamespace","isSolanaNamespace","InvalidParamsError","ErrorReason","getEvmClientForChain","assetToAddressString","SdkError","ErrorCode","isTokenAddressNative","markrGetSpenderAddress","caip2ToEip155ChainId","erc20Abi","calculateMarkrMinimumAmountOut","markrSwap","isEvmSwapResponse","applyFeeUnitsBpsMargin","estimateEvmFeesPerGas","isSolanaSwapResponse","getSolanaRpcForChain","decodeMarkrRevertError","getMarkrSwapWrapperAbi"],"sources":["../../../../src/transfer-service/markr/_handlers/estimate-native-fee.ts"],"sourcesContent":["import {\n type CompiledTransactionMessage,\n getCompiledTransactionMessageDecoder,\n getTransactionDecoder,\n isAddress as isSolanaAddress,\n type Base64EncodedWireTransaction,\n type Rpc,\n type SolanaRpcApi,\n type TransactionMessageBytes,\n type TransactionMessageBytesBase64,\n} from '@solana/kit';\nimport { encodeFunctionData, erc20Abi, type Address as EvmAddress, isAddress as isEvmAddress } from 'viem';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { EstimateNativeFeeOptions, NativeFeeEstimate, TransferService } from '../../../types/service';\nimport { applyFeeUnitsBpsMargin, getEvmClientForChain, getSolanaRpcForChain } from '../../_utils';\nimport { estimateEvmFeesPerGas } from '../../_evm-gas';\nimport { markrGetSpenderAddress, markrSwap, type ApiOptions } from '../_api';\nimport {\n assetToAddressString,\n calculateMarkrMinimumAmountOut,\n decodeMarkrRevertError,\n getMarkrSwapWrapperAbi,\n isTokenAddressNative,\n} from '../_utils';\nimport type { WrappedSwapTransactionResponse } from '../_schema';\nimport { isEvmSwapResponse, isSolanaSwapResponse } from '../_type-guards';\nimport { caip2ToEip155ChainId } from '../../../utils/caip';\nimport type { Quote } from '../../../types/quote';\nimport { isEvmNamespace, isSolanaNamespace } from '../../../_utils/chain';\n\n/**\n * This is just a fallback value used in the case that an\n * allowance approval is needed, and Markr didn't return us any gas estimate data.\n *\n * Just based on my review of some quotes, I think this is a reasonable estimate\n * left on the higher end.\n *\n * Assume this could need to change.\n */\nconst EVM_SWAP_FALLBACK_GAS_ESTIMATE = 700_000n;\n\n/**\n * Compute Budget program address.\n *\n * Used to detect `SetComputeUnitPrice` instructions when deriving\n * the Solana priority fee component from transaction message bytes.\n */\nconst SOLANA_COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';\n\n/**\n * System Program address.\n *\n * Used to detect account-creation instructions and extract lamports\n * funded upfront for newly created system accounts.\n */\nconst SOLANA_SYSTEM_PROGRAM = '11111111111111111111111111111111';\n\n/**\n * Associated Token Account (ATA) program address.\n *\n * Used to detect ATA create instructions so the estimator can include\n * rent-exempt funding when the ATA does not already exist on-chain.\n */\nconst SOLANA_ASSOCIATED_TOKEN_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n\n/**\n * Legacy SPL Token program address.\n *\n * Used to detect close-account instructions that may refund lamports\n * from temporary token accounts back to the sender.\n */\nconst SOLANA_SPL_TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\n\n/**\n * SPL Token-2022 program address.\n *\n * Used alongside the legacy token program for close-account detection\n * when computing expected refundable lamports.\n */\nconst SOLANA_SPL_TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';\n\n/**\n * SPL token account size for rent-exemption calculations.\n *\n * Used with `getMinimumBalanceForRentExemption` to estimate ATA\n * creation funding requirements.\n */\nconst SPL_TOKEN_ACCOUNT_SIZE_BYTES = 165n;\n\nexport interface EstimateNativeFeeFactoryConfig {\n apiOptions: ApiOptions;\n appId: string;\n}\n\ninterface CreatedRentAccount {\n address: string;\n kind: 'ata' | 'system';\n lamports: bigint;\n refunded: boolean;\n}\n\ninterface SolanaRentEstimate {\n createdAccounts: CreatedRentAccount[];\n rentFee: bigint;\n rentFeeNet: bigint;\n refundable: bigint;\n}\n\nexport function estimateNativeFeeFactory(config: EstimateNativeFeeFactoryConfig): TransferService['estimateNativeFee'] {\n return async (quote, options) => {\n // Either the source chain is EVM or Solana, we need to call different functions that\n // calculate the native fee depending on the chain kind.\n\n if (isEvmNamespace(quote.sourceChain.chainId)) {\n return await _estimateNativeFeeEvm(quote, options, config);\n }\n\n if (isSolanaNamespace(quote.sourceChain.chainId)) {\n return await _estimateNativeFeeSolana(quote, options, config);\n }\n\n throw new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n `Unsupported source chain namespace for estimateNativeFee: ${quote.sourceChain.chainId}`,\n );\n };\n}\n\n/** @internal */\nexport async function _estimateNativeFeeEvm(\n quote: Quote,\n options: EstimateNativeFeeOptions | undefined,\n { apiOptions, appId }: EstimateNativeFeeFactoryConfig,\n): Promise<NativeFeeEstimate> {\n if (!isEvmAddress(quote.fromAddress)) {\n throw new InvalidParamsError(ErrorReason.INVALID_PARAMS, `Invalid fromAddress: ${quote.fromAddress}`);\n }\n\n const sourceClient = getEvmClientForChain({ chain: quote.sourceChain });\n\n const assetInAddressString = assetToAddressString(quote.assetIn, quote.sourceChain.chainId);\n\n if (!isEvmAddress(assetInAddressString)) {\n throw new SdkError(ErrorReason.INVALID_PARAMS, ErrorCode.INVALID_PARAMS, {\n details: `assetIn address is not a valid EVM address. Can not call estimateGas.`,\n });\n }\n\n const isAssetInNative = isTokenAddressNative(assetInAddressString);\n const isCrossChainSwap = quote.sourceChain.chainId.toLowerCase() !== quote.targetChain.chainId.toLowerCase();\n\n let allowanceApprovalGas = 0n;\n if (!isAssetInNative) {\n // Check if approval is needed, and if so, calculate the gas cost for the approval.\n let allowance: bigint;\n\n const { address: spenderAddress } = await markrGetSpenderAddress(apiOptions, {\n chainId: caip2ToEip155ChainId(quote.sourceChain.chainId),\n crossChainSwap: isCrossChainSwap,\n quoteId: quote.id,\n });\n\n try {\n allowance = await sourceClient.readContract({\n address: assetInAddressString,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [quote.fromAddress, spenderAddress],\n });\n } catch (error) {\n throw new SdkError('Error during allowance check', ErrorCode.VIEM_ERROR, {\n cause: error,\n details: 'Failed to read ERC20 allowance for Markr spender.',\n });\n }\n\n const approvalNeeded = allowance < quote.amountIn;\n\n if (approvalNeeded) {\n try {\n allowanceApprovalGas = await sourceClient.estimateGas({\n account: quote.fromAddress,\n to: assetInAddressString,\n data: encodeFunctionData({\n abi: erc20Abi,\n functionName: 'approve',\n args: [spenderAddress, quote.amountIn],\n }),\n value: 0n,\n });\n } catch (error) {\n throw new SdkError('Error during gas estimation', ErrorCode.VIEM_ERROR, {\n cause: error,\n details: 'Failed to estimate gas for ERC20 approval transaction.',\n });\n }\n }\n }\n\n const allowanceApprovalIsNeeded = allowanceApprovalGas > 0n;\n\n const minAmountOut = calculateMarkrMinimumAmountOut({\n amountOut: quote.amountOut,\n assetOut: quote.assetOut,\n slippageBps: quote.slippageBps,\n });\n\n const swap = await markrSwap(apiOptions, {\n amountIn: quote.amountIn.toString(),\n appId,\n minAmountOut: minAmountOut.toString(),\n tokenIn: assetInAddressString,\n tokenOut: assetToAddressString(quote.assetOut, quote.targetChain.chainId),\n uuid: quote.id,\n });\n\n if (!isEvmSwapResponse(swap)) {\n // Should hopefully never happen.\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: `Received non-EVM swap response from Markr. Expected EVM transaction data for gas estimation, but got response with chainType ${swap.chainType}.`,\n });\n }\n\n let gasWithMargin = 0n;\n\n // If an approval is needed, we can't call `eth_estimateGas` on the\n // swap transaction because no actual allowance approval was performed yet,\n // so a gas estimation would fail due to needing allowance.\n //\n // So if an allowance approval is needed, we fall back to some other logic for\n // estimating the swap tx gas.\n if (allowanceApprovalIsNeeded) {\n // Attempt to use the Markr provided `gasEstimate` first if available.\n // Otherwise we attempt to get the gas from the `fees` component that are applicable\n // to the source chain. If neither of those are available, we fall back to a hardcoded value.\n if (quote.gasEstimate) {\n gasWithMargin = applyFeeUnitsBpsMargin(quote.gasEstimate, options?.feeUnitsMarginBps);\n } else {\n const sourceGasFee = quote.fees\n .filter((fee) => fee.type === 'gas' && fee.chainId === quote.sourceChain.chainId)\n .reduce((acc, fee) => acc + fee.amount, 0n);\n\n gasWithMargin = applyFeeUnitsBpsMargin(\n sourceGasFee || EVM_SWAP_FALLBACK_GAS_ESTIMATE,\n options?.feeUnitsMarginBps,\n );\n }\n } else {\n gasWithMargin = await _estimateGasFromSwapResponse({\n crossChain: isCrossChainSwap,\n feeUnitsMarginBps: options?.feeUnitsMarginBps,\n fromAddress: quote.fromAddress,\n sourceClient,\n swap,\n });\n }\n\n const fees = await estimateEvmFeesPerGas(sourceClient, quote.sourceChain, options?.overrides?.feeRateTier);\n\n const maxFeePerGas = options?.overrides?.maxFeePerGas ?? fees.maxFeePerGas;\n const maxPriorityFeePerGas = options?.overrides?.maxPriorityFeePerGas ?? fees.maxPriorityFeePerGas;\n\n const totalFee =\n (gasWithMargin + applyFeeUnitsBpsMargin(allowanceApprovalGas, options?.feeUnitsMarginBps)) * maxFeePerGas;\n\n return {\n asset: quote.sourceChain.networkToken,\n totalFee,\n meta: {\n approvalFee: allowanceApprovalIsNeeded\n ? applyFeeUnitsBpsMargin(allowanceApprovalGas, options?.feeUnitsMarginBps) * maxFeePerGas\n : undefined,\n maxFeePerGas,\n maxPriorityFeePerGas,\n },\n };\n}\n\n/** @internal */\nexport async function _estimateNativeFeeSolana(\n quote: Quote,\n options: EstimateNativeFeeOptions | undefined,\n { apiOptions, appId }: EstimateNativeFeeFactoryConfig,\n): Promise<NativeFeeEstimate> {\n const assetInAddressString = assetToAddressString(quote.assetIn, quote.sourceChain.chainId);\n\n if (!isSolanaAddress(assetInAddressString)) {\n throw new SdkError(ErrorReason.INVALID_PARAMS, ErrorCode.INVALID_PARAMS, {\n details: `assetIn address is not a valid Solana address. Can not call estimateGas.`,\n });\n }\n\n const minAmountOut = calculateMarkrMinimumAmountOut({\n amountOut: quote.amountOut,\n assetOut: quote.assetOut,\n slippageBps: quote.slippageBps,\n });\n\n const swap = await markrSwap(apiOptions, {\n amountIn: quote.amountIn.toString(),\n appId,\n minAmountOut: minAmountOut.toString(),\n tokenIn: assetInAddressString,\n tokenOut: assetToAddressString(quote.assetOut, quote.targetChain.chainId),\n userPublicKey: quote.fromAddress,\n uuid: quote.id,\n });\n\n if (!isSolanaSwapResponse(swap)) {\n // Should hopefully never happen.\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: 'Received non-Solana swap response from Markr. Expected Solana transaction data for fee estimation.',\n });\n }\n\n const rpc = getSolanaRpcForChain({ chain: quote.sourceChain });\n\n const txBytes = base64ToBytes(swap.swapTransaction);\n const tx = getTransactionDecoder().decode(txBytes);\n\n const messageBase64: TransactionMessageBytesBase64 = _transactionMessageBytesToBase64(tx.messageBytes);\n\n // Base fee (signature fee etc.) in lamports.\n const feeForMessageResponse = await rpc.getFeeForMessage(messageBase64).send();\n\n if (!feeForMessageResponse.value) {\n // This can happen if the block hash is expired or invalid.\n // Most likely expired. Use a new \"swapTxBase64\" with a recent block hash and try again.\n throw new SdkError(\n 'Failed to get fee for message. Most likely the block hash in the transaction is expired.',\n ErrorCode.TIMEOUT,\n {\n details: 'Please use a new quote with a recent block hash and try again.',\n },\n );\n }\n\n const baseFeeLamports = feeForMessageResponse.value;\n\n const sim = await rpc\n .simulateTransaction(swap.swapTransaction as Base64EncodedWireTransaction, {\n encoding: 'base64',\n sigVerify: false,\n })\n .send();\n\n if (sim.value.err) {\n throw new SdkError('Failed to simulate transaction for estimating fee.', ErrorCode.SOLANA_ERROR, {\n cause: sim.value.err,\n });\n }\n\n const unitsConsumed = applyFeeUnitsBpsMargin(sim.value.unitsConsumed ?? 0n, options?.feeUnitsMarginBps);\n // Lamports\n const computeUnitPriceMicroLamports = _getComputeUnitPriceMicroLamports(tx.messageBytes);\n const priorityFee = (unitsConsumed * computeUnitPriceMicroLamports) / 1_000_000n;\n const rentEstimate = await _estimateRentFeesFromTransactionMessage({\n fromAddress: quote.fromAddress,\n rpc,\n transactionMessageBytes: tx.messageBytes,\n });\n const totalLamports = baseFeeLamports + priorityFee + rentEstimate.rentFee;\n\n return {\n asset: quote.sourceChain.networkToken,\n totalFee: totalLamports,\n refundable: rentEstimate.refundable,\n meta: {\n baseFee: baseFeeLamports,\n priorityFee,\n computeUnitPriceMicroLamports,\n unitsConsumed,\n createdAccounts: rentEstimate.createdAccounts,\n rentFee: rentEstimate.rentFee,\n rentFeeNet: rentEstimate.rentFeeNet,\n },\n };\n}\n\n/** @internal */\nexport async function _estimateGasFromSwapResponse({\n crossChain,\n feeUnitsMarginBps,\n fromAddress,\n sourceClient,\n swap,\n}: {\n crossChain: boolean;\n feeUnitsMarginBps?: number;\n fromAddress: EvmAddress;\n sourceClient: ReturnType<typeof getEvmClientForChain>;\n swap: WrappedSwapTransactionResponse;\n}): Promise<bigint> {\n try {\n const gasEstimate = await sourceClient.estimateGas({\n account: fromAddress,\n to: swap.to,\n data: swap.data,\n value: swap.value,\n });\n\n return applyFeeUnitsBpsMargin(gasEstimate, feeUnitsMarginBps);\n } catch (err) {\n let details = 'Failed to estimate gas for Markr swap transaction.';\n\n try {\n const markrSwapWrapperAbi = await getMarkrSwapWrapperAbi(crossChain);\n const decodedRevert = decodeMarkrRevertError(markrSwapWrapperAbi, err);\n\n if (decodedRevert) {\n details = `${details} Markr revert: ${decodedRevert}.`;\n }\n } catch {\n // Keep the base details message if revert decoding fails.\n }\n\n throw new SdkError('Error during gas estimation', ErrorCode.VIEM_ERROR, {\n cause: err,\n details,\n });\n }\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n}\n\nfunction _transactionMessageBytesToBase64(bytes: TransactionMessageBytes): TransactionMessageBytesBase64 {\n let binary = '';\n for (const b of bytes) {\n binary += String.fromCharCode(b);\n }\n return btoa(binary) as TransactionMessageBytesBase64;\n}\n\nfunction _getComputeUnitPriceMicroLamports(transactionMessageBytes: TransactionMessageBytes): bigint {\n const compiledTxMessage = getCompiledTransactionMessageDecoder().decode(transactionMessageBytes);\n\n for (const instruction of compiledTxMessage.instructions) {\n const programAddress = compiledTxMessage.staticAccounts[instruction.programAddressIndex];\n if (programAddress !== SOLANA_COMPUTE_BUDGET_PROGRAM) {\n continue;\n }\n\n const data = instruction.data;\n\n if (!data || data.length < 1 + 8) {\n continue;\n }\n\n // ComputeBudget: u8 discriminator, then args\n // discriminator 3 = SetComputeUnitPrice, args = u64 microLamports\n const discriminator = data[0];\n if (discriminator !== 3) {\n continue;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n return view.getBigUint64(1, true);\n }\n\n return 0n;\n}\n\nasync function _estimateRentFeesFromTransactionMessage({\n fromAddress,\n rpc,\n transactionMessageBytes,\n}: {\n fromAddress: string;\n rpc: Rpc<SolanaRpcApi>;\n transactionMessageBytes: TransactionMessageBytes;\n}): Promise<SolanaRentEstimate> {\n const compiledMessage: CompiledTransactionMessage =\n getCompiledTransactionMessageDecoder().decode(transactionMessageBytes);\n\n const createdAccounts = new Map<string, Omit<CreatedRentAccount, 'refunded'>>();\n const closedAccountDestinationByAddress = new Map<string, string>();\n\n let ataRentLamports: bigint | undefined;\n\n for (const instruction of compiledMessage.instructions) {\n const programAddress = compiledMessage.staticAccounts[instruction.programAddressIndex];\n\n if (programAddress === SOLANA_SYSTEM_PROGRAM) {\n const createdAccountAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n const lamports = _getSystemCreateAccountLamports(instruction.data);\n if (createdAccountAddress && lamports > 0n) {\n createdAccounts.set(createdAccountAddress, {\n address: createdAccountAddress,\n kind: 'system',\n lamports,\n });\n }\n continue;\n }\n\n if (programAddress === SOLANA_ASSOCIATED_TOKEN_PROGRAM) {\n const discriminator = instruction.data?.[0];\n const isAssociatedTokenCreateInstruction =\n discriminator === undefined || discriminator === 0 || discriminator === 1;\n\n if (!isAssociatedTokenCreateInstruction) {\n continue;\n }\n\n const associatedTokenAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n if (!associatedTokenAddress) {\n continue;\n }\n\n const accountInfo = await rpc.getAccountInfo(associatedTokenAddress).send();\n if (accountInfo.value) {\n continue;\n }\n\n if (ataRentLamports === undefined) {\n ataRentLamports = await rpc.getMinimumBalanceForRentExemption(SPL_TOKEN_ACCOUNT_SIZE_BYTES).send();\n }\n\n createdAccounts.set(associatedTokenAddress, {\n address: associatedTokenAddress,\n kind: 'ata',\n lamports: ataRentLamports,\n });\n\n continue;\n }\n\n const isSplTokenProgram =\n programAddress === SOLANA_SPL_TOKEN_PROGRAM || programAddress === SOLANA_SPL_TOKEN_2022_PROGRAM;\n if (!isSplTokenProgram) {\n continue;\n }\n\n const discriminator = instruction.data?.[0];\n if (discriminator !== 9) {\n continue;\n }\n\n const closedAccountAddress = _getInstructionAccountAddress(compiledMessage, instruction, 0);\n const refundDestinationAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n\n if (closedAccountAddress && refundDestinationAddress) {\n closedAccountDestinationByAddress.set(closedAccountAddress, refundDestinationAddress);\n }\n }\n\n const normalizedFromAddress = isSolanaAddress(fromAddress) ? fromAddress : undefined;\n const createdAccountEntries = Array.from(createdAccounts.values()).map((createdAccount) => {\n const refundDestinationAddress = closedAccountDestinationByAddress.get(createdAccount.address);\n const refunded = normalizedFromAddress !== undefined && refundDestinationAddress === normalizedFromAddress;\n\n return {\n ...createdAccount,\n refunded,\n } satisfies CreatedRentAccount;\n });\n\n const rentLamportsUpfront = createdAccountEntries.reduce((acc, account) => acc + account.lamports, 0n);\n const refundedLamports = createdAccountEntries.reduce(\n (acc, account) => acc + (account.refunded ? account.lamports : 0n),\n 0n,\n );\n const rentFeeNet = rentLamportsUpfront - refundedLamports;\n\n return {\n createdAccounts: createdAccountEntries,\n rentFee: rentLamportsUpfront,\n rentFeeNet,\n refundable: refundedLamports,\n };\n}\n\n/**\n * Resolves an account address used by a compiled instruction.\n *\n * Compiled instructions reference accounts by index into the transaction\n * message's `staticAccounts` list. This helper converts an instruction-local\n * `accountIndex` into the corresponding static account address.\n *\n * Returns `undefined` when the instruction does not provide an account at the\n * requested index.\n */\nfunction _getInstructionAccountAddress(\n message: CompiledTransactionMessage,\n instruction: CompiledTransactionMessage['instructions'][number],\n accountIndex: number,\n): CompiledTransactionMessage['staticAccounts'][number] | undefined {\n const messageAccountIndex = instruction.accountIndices?.[accountIndex];\n\n if (messageAccountIndex === undefined) {\n return undefined;\n }\n\n return message.staticAccounts[messageAccountIndex];\n}\n\n/**\n * Extracts lamports from System Program account-creation instruction data.\n *\n * Supported instruction layouts:\n * - `CreateAccount` (`u32 discriminator = 0`): lamports at byte offset `4`.\n * - `CreateAccountWithSeed` (`u32 discriminator = 3`): lamports are located\n * after the variable-length seed field.\n *\n * Returns `0n` when data is missing, malformed, or not one of the supported\n * System Program create-account variants.\n */\nfunction _getSystemCreateAccountLamports(data: CompiledTransactionMessage['instructions'][number]['data']): bigint {\n if (!data || data.length < 12) {\n return 0n;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const instructionDiscriminator = view.getUint32(0, true);\n\n if (instructionDiscriminator === 0 && data.length >= 12) {\n return view.getBigUint64(4, true);\n }\n\n if (instructionDiscriminator === 3 && data.length >= 44) {\n const seedLenOffset = 36;\n const seedLength = Number(view.getBigUint64(seedLenOffset, true));\n if (!Number.isSafeInteger(seedLength) || seedLength < 0) {\n return 0n;\n }\n\n const lamportsOffset = seedLenOffset + 8 + seedLength;\n if (lamportsOffset + 8 > data.length) {\n return 0n;\n }\n\n return new DataView(data.buffer, data.byteOffset + lamportsOffset, 8).getBigUint64(0, true);\n }\n\n return 0n;\n}\n"],"mappings":"wWA4GA,SAAgB,EAAyB,EAA8E,CACrH,OAAO,MAAO,EAAO,IAAY,CAI/B,GAAIA,EAAAA,eAAe,EAAM,YAAY,QAAQ,CAC3C,OAAO,MAAM,EAAsB,EAAO,EAAS,EAAO,CAG5D,GAAIC,EAAAA,kBAAkB,EAAM,YAAY,QAAQ,CAC9C,OAAO,MAAM,EAAyB,EAAO,EAAS,EAAO,CAG/D,MAAM,IAAIC,EAAAA,mBACRC,EAAAA,YAAY,eACZ,6DAA6D,EAAM,YAAY,UAChF,EAKL,eAAsB,EACpB,EACA,EACA,CAAE,aAAY,SACc,CAC5B,GAAI,EAAA,EAAA,EAAA,WAAc,EAAM,YAAY,CAClC,MAAM,IAAID,EAAAA,mBAAmBC,EAAAA,YAAY,eAAgB,wBAAwB,EAAM,cAAc,CAGvG,IAAM,EAAeC,EAAAA,qBAAqB,CAAE,MAAO,EAAM,YAAa,CAAC,CAEjE,EAAuBC,EAAAA,qBAAqB,EAAM,QAAS,EAAM,YAAY,QAAQ,CAE3F,GAAI,EAAA,EAAA,EAAA,WAAc,EAAqB,CACrC,MAAM,IAAIC,EAAAA,SAASH,EAAAA,YAAY,eAAgBI,EAAAA,UAAU,eAAgB,CACvE,QAAS,wEACV,CAAC,CAGJ,IAAM,EAAkBC,EAAAA,qBAAqB,EAAqB,CAC5D,EAA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EAAsB,QAC5C,EAAK,IAAY,GAAO,EAAQ,SAAW,EAAQ,SAAW,IAC/D,GACD,CAGD,MAAO,CACL,gBAAiB,EACjB,QAAS,EACT,WALiB,EAAsB,EAMvC,WAAY,EACb,CAaH,SAAS,EACP,EACA,EACA,EACkE,CAClE,IAAM,EAAsB,EAAY,iBAAiB,GAErD,OAAwB,IAAA,GAI5B,OAAO,EAAQ,eAAe,GAchC,SAAS,EAAgC,EAA0E,CACjH,GAAI,CAAC,GAAQ,EAAK,OAAS,GACzB,OAAO,GAGT,IAAM,EAAO,IAAI,SAAS,EAAK,OAAQ,EAAK,WAAY,EAAK,WAAW,CAClE,EAA2B,EAAK,UAAU,EAAG,GAAK,CAExD,GAAI,IAA6B,GAAK,EAAK,QAAU,GACnD,OAAO,EAAK,aAAa,EAAG,GAAK,CAGnC,GAAI,IAA6B,GAAK,EAAK,QAAU,GAAI,CACvD,IACM,EAAa,OAAO,EAAK,aAAa,GAAe,GAAK,CAAC,CACjE,GAAI,CAAC,OAAO,cAAc,EAAW,EAAI,EAAa,EACpD,OAAO,GAGT,IAAM,EAAiB,GAAoB,EAK3C,OAJI,EAAiB,EAAI,EAAK,OACrB,GAGF,IAAI,SAAS,EAAK,OAAQ,EAAK,WAAa,EAAgB,EAAE,CAAC,aAAa,EAAG,GAAK,CAG7F,OAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ErrorCode as e,ErrorReason as t,InvalidParamsError as n,SdkError as r}from"../../../errors.js";import{caip2ToEip155ChainId as i}from"../../../utils/caip.js";import{isEvmNamespace as a,isSolanaNamespace as o}from"../../../_utils/chain.js";import{applyFeeUnitsBpsMargin as s,getEvmClientForChain as c,getSolanaRpcForChain as l}from"../../_utils.js";import{estimateEvmFeesPerGas as u}from"../../_evm-gas.js";import{markrGetSpenderAddress as d,markrSwap as f}from"../_api.js";import{assetToAddressString as p,calculateMarkrMinimumAmountOut as m,decodeMarkrRevertError as h,getMarkrSwapWrapperAbi as g,isTokenAddressNative as _}from"../_utils.js";import{isEvmSwapResponse as v,isSolanaSwapResponse as y}from"../_type-guards.js";import{encodeFunctionData as b,erc20Abi as x,isAddress as S}from"viem";import{getCompiledTransactionMessageDecoder as C,getTransactionDecoder as w,isAddress as T}from"@solana/kit";function E(e){return async(r,i)=>{if(a(r.sourceChain.chainId))return await D(r,i,e);if(o(r.sourceChain.chainId))return await O(r,i,e);throw new n(t.INVALID_PARAMS,`Unsupported source chain namespace for estimateNativeFee: ${r.sourceChain.chainId}`)}}async function D(a,o,{apiOptions:l,appId:h}){if(!S(a.fromAddress))throw new n(t.INVALID_PARAMS,`Invalid fromAddress: ${a.fromAddress}`);let g=c({chain:a.sourceChain}),y=p(a.assetIn,a.sourceChain.chainId);if(!S(y))throw new r(t.INVALID_PARAMS,e.INVALID_PARAMS,{details:`assetIn address is not a valid EVM address. Can not call estimateGas.`});let C=_(y),w=a.sourceChain.chainId.toLowerCase()!==a.targetChain.chainId.toLowerCase(),T=0n;if(!C){let t,{address:n}=await d(l,i(a.sourceChain.chainId),w);try{t=await g.readContract({address:y,abi:x,functionName:`allowance`,args:[a.fromAddress,n]})}catch(t){throw new r(`Error during allowance check`,e.VIEM_ERROR,{cause:t,details:`Failed to read ERC20 allowance for Markr spender.`})}if(t<a.amountIn)try{T=await g.estimateGas({account:a.fromAddress,to:y,data:b({abi:x,functionName:`approve`,args:[n,a.amountIn]}),value:0n})}catch(t){throw new r(`Error during gas estimation`,e.VIEM_ERROR,{cause:t,details:`Failed to estimate gas for ERC20 approval transaction.`})}}let E=T>0n,D=m({amountOut:a.amountOut,assetOut:a.assetOut,slippageBps:a.slippageBps}),O=await f(l,{amountIn:a.amountIn.toString(),appId:h,minAmountOut:D.toString(),tokenIn:y,tokenOut:p(a.assetOut,a.targetChain.chainId),uuid:a.id});if(!v(O))throw new r(t.CHAIN_NOT_SUPPORTED,e.INVALID_PARAMS,{details:`Received non-EVM swap response from Markr. Expected EVM transaction data for gas estimation, but got response with chainType ${O.chainType}.`});let A=0n;A=E?a.gasEstimate?s(a.gasEstimate,o?.feeUnitsMarginBps):s(a.fees.filter(e=>e.type===`gas`&&e.chainId===a.sourceChain.chainId).reduce((e,t)=>e+t.amount,0n)||700000n,o?.feeUnitsMarginBps):await k({crossChain:w,feeUnitsMarginBps:o?.feeUnitsMarginBps,fromAddress:a.fromAddress,sourceClient:g,swap:O});let j=await u(g,a.sourceChain,o?.overrides?.feeRateTier),M=o?.overrides?.maxFeePerGas??j.maxFeePerGas,N=o?.overrides?.maxPriorityFeePerGas??j.maxPriorityFeePerGas,P=(A+s(T,o?.feeUnitsMarginBps))*M;return{asset:a.sourceChain.networkToken,totalFee:P,meta:{approvalFee:E?s(T,o?.feeUnitsMarginBps)*M:void 0,maxFeePerGas:M,maxPriorityFeePerGas:N}}}async function O(n,i,{apiOptions:a,appId:o}){let c=p(n.assetIn,n.sourceChain.chainId);if(!T(c))throw new r(t.INVALID_PARAMS,e.INVALID_PARAMS,{details:`assetIn address is not a valid Solana address. Can not call estimateGas.`});let u=m({amountOut:n.amountOut,assetOut:n.assetOut,slippageBps:n.slippageBps}),d=await f(a,{amountIn:n.amountIn.toString(),appId:o,minAmountOut:u.toString(),tokenIn:c,tokenOut:p(n.assetOut,n.targetChain.chainId),userPublicKey:n.fromAddress,uuid:n.id});if(!y(d))throw new r(t.CHAIN_NOT_SUPPORTED,e.INVALID_PARAMS,{details:`Received non-Solana swap response from Markr. Expected Solana transaction data for fee estimation.`});let h=l({chain:n.sourceChain}),g=A(d.swapTransaction),_=w().decode(g),v=j(_.messageBytes),b=await h.getFeeForMessage(v).send();if(!b.value)throw new r(`Failed to get fee for message. Most likely the block hash in the transaction is expired.`,e.TIMEOUT,{details:`Please use a new quote with a recent block hash and try again.`});let x=b.value,S=await h.simulateTransaction(d.swapTransaction,{encoding:`base64`,sigVerify:!1}).send();if(S.value.err)throw new r(`Failed to simulate transaction for estimating fee.`,e.SOLANA_ERROR,{cause:S.value.err});let C=s(S.value.unitsConsumed??0n,i?.feeUnitsMarginBps),E=M(_.messageBytes),D=C*E/1000000n,O=await N({fromAddress:n.fromAddress,rpc:h,transactionMessageBytes:_.messageBytes}),k=x+D+O.rentFee;return{asset:n.sourceChain.networkToken,totalFee:k,refundable:O.refundable,meta:{baseFee:x,priorityFee:D,computeUnitPriceMicroLamports:E,unitsConsumed:C,createdAccounts:O.createdAccounts,rentFee:O.rentFee,rentFeeNet:O.rentFeeNet}}}async function k({crossChain:t,feeUnitsMarginBps:n,fromAddress:i,sourceClient:a,swap:o}){try{return s(await a.estimateGas({account:i,to:o.to,data:o.data,value:o.value}),n)}catch(n){let i=`Failed to estimate gas for Markr swap transaction.`;try{let e=h(await g(t),n);e&&(i=`${i} Markr revert: ${e}.`)}catch{}throw new r(`Error during gas estimation`,e.VIEM_ERROR,{cause:n,details:i})}}function A(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function j(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function M(e){let t=C().decode(e);for(let e of t.instructions){if(t.staticAccounts[e.programAddressIndex]!==`ComputeBudget111111111111111111111111111111`)continue;let n=e.data;if(!(!n||n.length<9)&&n[0]===3)return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(1,!0)}return 0n}async function N({fromAddress:e,rpc:t,transactionMessageBytes:n}){let r=C().decode(n),i=new Map,a=new Map,o;for(let e of r.instructions){let n=r.staticAccounts[e.programAddressIndex];if(n===`11111111111111111111111111111111`){let t=P(r,e,1),n=F(e.data);t&&n>0n&&i.set(t,{address:t,kind:`system`,lamports:n});continue}if(n===`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`){let n=e.data?.[0];if(!(n===void 0||n===0||n===1))continue;let a=P(r,e,1);if(!a||(await t.getAccountInfo(a).send()).value)continue;o===void 0&&(o=await t.getMinimumBalanceForRentExemption(165n).send()),i.set(a,{address:a,kind:`ata`,lamports:o});continue}if(!(n===`TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA`||n===`TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`)||e.data?.[0]!==9)continue;let s=P(r,e,0),c=P(r,e,1);s&&c&&a.set(s,c)}let s=T(e)?e:void 0,c=Array.from(i.values()).map(e=>{let t=a.get(e.address),n=s!==void 0&&t===s;return{...e,refunded:n}}),l=c.reduce((e,t)=>e+t.lamports,0n),u=c.reduce((e,t)=>e+(t.refunded?t.lamports:0n),0n);return{createdAccounts:c,rentFee:l,rentFeeNet:l-u,refundable:u}}function P(e,t,n){let r=t.accountIndices?.[n];if(r!==void 0)return e.staticAccounts[r]}function F(e){if(!e||e.length<12)return 0n;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0);if(n===0&&e.length>=12)return t.getBigUint64(4,!0);if(n===3&&e.length>=44){let n=Number(t.getBigUint64(36,!0));if(!Number.isSafeInteger(n)||n<0)return 0n;let r=44+n;return r+8>e.length?0n:new DataView(e.buffer,e.byteOffset+r,8).getBigUint64(0,!0)}return 0n}export{k as _estimateGasFromSwapResponse,E as estimateNativeFeeFactory};
|
|
1
|
+
import{ErrorCode as e,ErrorReason as t,InvalidParamsError as n,SdkError as r}from"../../../errors.js";import{caip2ToEip155ChainId as i}from"../../../utils/caip.js";import{isEvmNamespace as a,isSolanaNamespace as o}from"../../../_utils/chain.js";import{applyFeeUnitsBpsMargin as s,getEvmClientForChain as c,getSolanaRpcForChain as l}from"../../_utils.js";import{estimateEvmFeesPerGas as u}from"../../_evm-gas.js";import{markrGetSpenderAddress as d,markrSwap as f}from"../_api.js";import{assetToAddressString as p,calculateMarkrMinimumAmountOut as m,decodeMarkrRevertError as h,getMarkrSwapWrapperAbi as g,isTokenAddressNative as _}from"../_utils.js";import{isEvmSwapResponse as v,isSolanaSwapResponse as y}from"../_type-guards.js";import{encodeFunctionData as b,erc20Abi as x,isAddress as S}from"viem";import{getCompiledTransactionMessageDecoder as C,getTransactionDecoder as w,isAddress as T}from"@solana/kit";function E(e){return async(r,i)=>{if(a(r.sourceChain.chainId))return await D(r,i,e);if(o(r.sourceChain.chainId))return await O(r,i,e);throw new n(t.INVALID_PARAMS,`Unsupported source chain namespace for estimateNativeFee: ${r.sourceChain.chainId}`)}}async function D(a,o,{apiOptions:l,appId:h}){if(!S(a.fromAddress))throw new n(t.INVALID_PARAMS,`Invalid fromAddress: ${a.fromAddress}`);let g=c({chain:a.sourceChain}),y=p(a.assetIn,a.sourceChain.chainId);if(!S(y))throw new r(t.INVALID_PARAMS,e.INVALID_PARAMS,{details:`assetIn address is not a valid EVM address. Can not call estimateGas.`});let C=_(y),w=a.sourceChain.chainId.toLowerCase()!==a.targetChain.chainId.toLowerCase(),T=0n;if(!C){let t,{address:n}=await d(l,{chainId:i(a.sourceChain.chainId),crossChainSwap:w,quoteId:a.id});try{t=await g.readContract({address:y,abi:x,functionName:`allowance`,args:[a.fromAddress,n]})}catch(t){throw new r(`Error during allowance check`,e.VIEM_ERROR,{cause:t,details:`Failed to read ERC20 allowance for Markr spender.`})}if(t<a.amountIn)try{T=await g.estimateGas({account:a.fromAddress,to:y,data:b({abi:x,functionName:`approve`,args:[n,a.amountIn]}),value:0n})}catch(t){throw new r(`Error during gas estimation`,e.VIEM_ERROR,{cause:t,details:`Failed to estimate gas for ERC20 approval transaction.`})}}let E=T>0n,D=m({amountOut:a.amountOut,assetOut:a.assetOut,slippageBps:a.slippageBps}),O=await f(l,{amountIn:a.amountIn.toString(),appId:h,minAmountOut:D.toString(),tokenIn:y,tokenOut:p(a.assetOut,a.targetChain.chainId),uuid:a.id});if(!v(O))throw new r(t.CHAIN_NOT_SUPPORTED,e.INVALID_PARAMS,{details:`Received non-EVM swap response from Markr. Expected EVM transaction data for gas estimation, but got response with chainType ${O.chainType}.`});let A=0n;A=E?a.gasEstimate?s(a.gasEstimate,o?.feeUnitsMarginBps):s(a.fees.filter(e=>e.type===`gas`&&e.chainId===a.sourceChain.chainId).reduce((e,t)=>e+t.amount,0n)||700000n,o?.feeUnitsMarginBps):await k({crossChain:w,feeUnitsMarginBps:o?.feeUnitsMarginBps,fromAddress:a.fromAddress,sourceClient:g,swap:O});let j=await u(g,a.sourceChain,o?.overrides?.feeRateTier),M=o?.overrides?.maxFeePerGas??j.maxFeePerGas,N=o?.overrides?.maxPriorityFeePerGas??j.maxPriorityFeePerGas,P=(A+s(T,o?.feeUnitsMarginBps))*M;return{asset:a.sourceChain.networkToken,totalFee:P,meta:{approvalFee:E?s(T,o?.feeUnitsMarginBps)*M:void 0,maxFeePerGas:M,maxPriorityFeePerGas:N}}}async function O(n,i,{apiOptions:a,appId:o}){let c=p(n.assetIn,n.sourceChain.chainId);if(!T(c))throw new r(t.INVALID_PARAMS,e.INVALID_PARAMS,{details:`assetIn address is not a valid Solana address. Can not call estimateGas.`});let u=m({amountOut:n.amountOut,assetOut:n.assetOut,slippageBps:n.slippageBps}),d=await f(a,{amountIn:n.amountIn.toString(),appId:o,minAmountOut:u.toString(),tokenIn:c,tokenOut:p(n.assetOut,n.targetChain.chainId),userPublicKey:n.fromAddress,uuid:n.id});if(!y(d))throw new r(t.CHAIN_NOT_SUPPORTED,e.INVALID_PARAMS,{details:`Received non-Solana swap response from Markr. Expected Solana transaction data for fee estimation.`});let h=l({chain:n.sourceChain}),g=A(d.swapTransaction),_=w().decode(g),v=j(_.messageBytes),b=await h.getFeeForMessage(v).send();if(!b.value)throw new r(`Failed to get fee for message. Most likely the block hash in the transaction is expired.`,e.TIMEOUT,{details:`Please use a new quote with a recent block hash and try again.`});let x=b.value,S=await h.simulateTransaction(d.swapTransaction,{encoding:`base64`,sigVerify:!1}).send();if(S.value.err)throw new r(`Failed to simulate transaction for estimating fee.`,e.SOLANA_ERROR,{cause:S.value.err});let C=s(S.value.unitsConsumed??0n,i?.feeUnitsMarginBps),E=M(_.messageBytes),D=C*E/1000000n,O=await N({fromAddress:n.fromAddress,rpc:h,transactionMessageBytes:_.messageBytes}),k=x+D+O.rentFee;return{asset:n.sourceChain.networkToken,totalFee:k,refundable:O.refundable,meta:{baseFee:x,priorityFee:D,computeUnitPriceMicroLamports:E,unitsConsumed:C,createdAccounts:O.createdAccounts,rentFee:O.rentFee,rentFeeNet:O.rentFeeNet}}}async function k({crossChain:t,feeUnitsMarginBps:n,fromAddress:i,sourceClient:a,swap:o}){try{return s(await a.estimateGas({account:i,to:o.to,data:o.data,value:o.value}),n)}catch(n){let i=`Failed to estimate gas for Markr swap transaction.`;try{let e=h(await g(t),n);e&&(i=`${i} Markr revert: ${e}.`)}catch{}throw new r(`Error during gas estimation`,e.VIEM_ERROR,{cause:n,details:i})}}function A(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function j(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function M(e){let t=C().decode(e);for(let e of t.instructions){if(t.staticAccounts[e.programAddressIndex]!==`ComputeBudget111111111111111111111111111111`)continue;let n=e.data;if(!(!n||n.length<9)&&n[0]===3)return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(1,!0)}return 0n}async function N({fromAddress:e,rpc:t,transactionMessageBytes:n}){let r=C().decode(n),i=new Map,a=new Map,o;for(let e of r.instructions){let n=r.staticAccounts[e.programAddressIndex];if(n===`11111111111111111111111111111111`){let t=P(r,e,1),n=F(e.data);t&&n>0n&&i.set(t,{address:t,kind:`system`,lamports:n});continue}if(n===`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`){let n=e.data?.[0];if(!(n===void 0||n===0||n===1))continue;let a=P(r,e,1);if(!a||(await t.getAccountInfo(a).send()).value)continue;o===void 0&&(o=await t.getMinimumBalanceForRentExemption(165n).send()),i.set(a,{address:a,kind:`ata`,lamports:o});continue}if(!(n===`TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA`||n===`TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`)||e.data?.[0]!==9)continue;let s=P(r,e,0),c=P(r,e,1);s&&c&&a.set(s,c)}let s=T(e)?e:void 0,c=Array.from(i.values()).map(e=>{let t=a.get(e.address),n=s!==void 0&&t===s;return{...e,refunded:n}}),l=c.reduce((e,t)=>e+t.lamports,0n),u=c.reduce((e,t)=>e+(t.refunded?t.lamports:0n),0n);return{createdAccounts:c,rentFee:l,rentFeeNet:l-u,refundable:u}}function P(e,t,n){let r=t.accountIndices?.[n];if(r!==void 0)return e.staticAccounts[r]}function F(e){if(!e||e.length<12)return 0n;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0);if(n===0&&e.length>=12)return t.getBigUint64(4,!0);if(n===3&&e.length>=44){let n=Number(t.getBigUint64(36,!0));if(!Number.isSafeInteger(n)||n<0)return 0n;let r=44+n;return r+8>e.length?0n:new DataView(e.buffer,e.byteOffset+r,8).getBigUint64(0,!0)}return 0n}export{k as _estimateGasFromSwapResponse,E as estimateNativeFeeFactory};
|
|
2
2
|
//# sourceMappingURL=estimate-native-fee.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"estimate-native-fee.js","names":["isEvmAddress","isSolanaAddress"],"sources":["../../../../src/transfer-service/markr/_handlers/estimate-native-fee.ts"],"sourcesContent":["import {\n type CompiledTransactionMessage,\n getCompiledTransactionMessageDecoder,\n getTransactionDecoder,\n isAddress as isSolanaAddress,\n type Base64EncodedWireTransaction,\n type Rpc,\n type SolanaRpcApi,\n type TransactionMessageBytes,\n type TransactionMessageBytesBase64,\n} from '@solana/kit';\nimport { encodeFunctionData, erc20Abi, type Address as EvmAddress, isAddress as isEvmAddress } from 'viem';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { EstimateNativeFeeOptions, NativeFeeEstimate, TransferService } from '../../../types/service';\nimport { applyFeeUnitsBpsMargin, getEvmClientForChain, getSolanaRpcForChain } from '../../_utils';\nimport { estimateEvmFeesPerGas } from '../../_evm-gas';\nimport { markrGetSpenderAddress, markrSwap, type ApiOptions } from '../_api';\nimport {\n assetToAddressString,\n calculateMarkrMinimumAmountOut,\n decodeMarkrRevertError,\n getMarkrSwapWrapperAbi,\n isTokenAddressNative,\n} from '../_utils';\nimport type { WrappedSwapTransactionResponse } from '../_schema';\nimport { isEvmSwapResponse, isSolanaSwapResponse } from '../_type-guards';\nimport { caip2ToEip155ChainId } from '../../../utils/caip';\nimport type { Quote } from '../../../types/quote';\nimport { isEvmNamespace, isSolanaNamespace } from '../../../_utils/chain';\n\n/**\n * This is just a fallback value used in the case that an\n * allowance approval is needed, and Markr didn't return us any gas estimate data.\n *\n * Just based on my review of some quotes, I think this is a reasonable estimate\n * left on the higher end.\n *\n * Assume this could need to change.\n */\nconst EVM_SWAP_FALLBACK_GAS_ESTIMATE = 700_000n;\n\n/**\n * Compute Budget program address.\n *\n * Used to detect `SetComputeUnitPrice` instructions when deriving\n * the Solana priority fee component from transaction message bytes.\n */\nconst SOLANA_COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';\n\n/**\n * System Program address.\n *\n * Used to detect account-creation instructions and extract lamports\n * funded upfront for newly created system accounts.\n */\nconst SOLANA_SYSTEM_PROGRAM = '11111111111111111111111111111111';\n\n/**\n * Associated Token Account (ATA) program address.\n *\n * Used to detect ATA create instructions so the estimator can include\n * rent-exempt funding when the ATA does not already exist on-chain.\n */\nconst SOLANA_ASSOCIATED_TOKEN_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n\n/**\n * Legacy SPL Token program address.\n *\n * Used to detect close-account instructions that may refund lamports\n * from temporary token accounts back to the sender.\n */\nconst SOLANA_SPL_TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\n\n/**\n * SPL Token-2022 program address.\n *\n * Used alongside the legacy token program for close-account detection\n * when computing expected refundable lamports.\n */\nconst SOLANA_SPL_TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';\n\n/**\n * SPL token account size for rent-exemption calculations.\n *\n * Used with `getMinimumBalanceForRentExemption` to estimate ATA\n * creation funding requirements.\n */\nconst SPL_TOKEN_ACCOUNT_SIZE_BYTES = 165n;\n\nexport interface EstimateNativeFeeFactoryConfig {\n apiOptions: ApiOptions;\n appId: string;\n}\n\ninterface CreatedRentAccount {\n address: string;\n kind: 'ata' | 'system';\n lamports: bigint;\n refunded: boolean;\n}\n\ninterface SolanaRentEstimate {\n createdAccounts: CreatedRentAccount[];\n rentFee: bigint;\n rentFeeNet: bigint;\n refundable: bigint;\n}\n\nexport function estimateNativeFeeFactory(config: EstimateNativeFeeFactoryConfig): TransferService['estimateNativeFee'] {\n return async (quote, options) => {\n // Either the source chain is EVM or Solana, we need to call different functions that\n // calculate the native fee depending on the chain kind.\n\n if (isEvmNamespace(quote.sourceChain.chainId)) {\n return await _estimateNativeFeeEvm(quote, options, config);\n }\n\n if (isSolanaNamespace(quote.sourceChain.chainId)) {\n return await _estimateNativeFeeSolana(quote, options, config);\n }\n\n throw new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n `Unsupported source chain namespace for estimateNativeFee: ${quote.sourceChain.chainId}`,\n );\n };\n}\n\n/** @internal */\nexport async function _estimateNativeFeeEvm(\n quote: Quote,\n options: EstimateNativeFeeOptions | undefined,\n { apiOptions, appId }: EstimateNativeFeeFactoryConfig,\n): Promise<NativeFeeEstimate> {\n if (!isEvmAddress(quote.fromAddress)) {\n throw new InvalidParamsError(ErrorReason.INVALID_PARAMS, `Invalid fromAddress: ${quote.fromAddress}`);\n }\n\n const sourceClient = getEvmClientForChain({ chain: quote.sourceChain });\n\n const assetInAddressString = assetToAddressString(quote.assetIn, quote.sourceChain.chainId);\n\n if (!isEvmAddress(assetInAddressString)) {\n throw new SdkError(ErrorReason.INVALID_PARAMS, ErrorCode.INVALID_PARAMS, {\n details: `assetIn address is not a valid EVM address. Can not call estimateGas.`,\n });\n }\n\n const isAssetInNative = isTokenAddressNative(assetInAddressString);\n const isCrossChainSwap = quote.sourceChain.chainId.toLowerCase() !== quote.targetChain.chainId.toLowerCase();\n\n let allowanceApprovalGas = 0n;\n if (!isAssetInNative) {\n // Check if approval is needed, and if so, calculate the gas cost for the approval.\n let allowance: bigint;\n\n const { address: spenderAddress } = await markrGetSpenderAddress(\n apiOptions,\n caip2ToEip155ChainId(quote.sourceChain.chainId),\n isCrossChainSwap,\n );\n\n try {\n allowance = await sourceClient.readContract({\n address: assetInAddressString,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [quote.fromAddress, spenderAddress],\n });\n } catch (error) {\n throw new SdkError('Error during allowance check', ErrorCode.VIEM_ERROR, {\n cause: error,\n details: 'Failed to read ERC20 allowance for Markr spender.',\n });\n }\n\n const approvalNeeded = allowance < quote.amountIn;\n\n if (approvalNeeded) {\n try {\n allowanceApprovalGas = await sourceClient.estimateGas({\n account: quote.fromAddress,\n to: assetInAddressString,\n data: encodeFunctionData({\n abi: erc20Abi,\n functionName: 'approve',\n args: [spenderAddress, quote.amountIn],\n }),\n value: 0n,\n });\n } catch (error) {\n throw new SdkError('Error during gas estimation', ErrorCode.VIEM_ERROR, {\n cause: error,\n details: 'Failed to estimate gas for ERC20 approval transaction.',\n });\n }\n }\n }\n\n const allowanceApprovalIsNeeded = allowanceApprovalGas > 0n;\n\n const minAmountOut = calculateMarkrMinimumAmountOut({\n amountOut: quote.amountOut,\n assetOut: quote.assetOut,\n slippageBps: quote.slippageBps,\n });\n\n const swap = await markrSwap(apiOptions, {\n amountIn: quote.amountIn.toString(),\n appId,\n minAmountOut: minAmountOut.toString(),\n tokenIn: assetInAddressString,\n tokenOut: assetToAddressString(quote.assetOut, quote.targetChain.chainId),\n uuid: quote.id,\n });\n\n if (!isEvmSwapResponse(swap)) {\n // Should hopefully never happen.\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: `Received non-EVM swap response from Markr. Expected EVM transaction data for gas estimation, but got response with chainType ${swap.chainType}.`,\n });\n }\n\n let gasWithMargin = 0n;\n\n // If an approval is needed, we can't call `eth_estimateGas` on the\n // swap transaction because no actual allowance approval was performed yet,\n // so a gas estimation would fail due to needing allowance.\n //\n // So if an allowance approval is needed, we fall back to some other logic for\n // estimating the swap tx gas.\n if (allowanceApprovalIsNeeded) {\n // Attempt to use the Markr provided `gasEstimate` first if available.\n // Otherwise we attempt to get the gas from the `fees` component that are applicable\n // to the source chain. If neither of those are available, we fall back to a hardcoded value.\n if (quote.gasEstimate) {\n gasWithMargin = applyFeeUnitsBpsMargin(quote.gasEstimate, options?.feeUnitsMarginBps);\n } else {\n const sourceGasFee = quote.fees\n .filter((fee) => fee.type === 'gas' && fee.chainId === quote.sourceChain.chainId)\n .reduce((acc, fee) => acc + fee.amount, 0n);\n\n gasWithMargin = applyFeeUnitsBpsMargin(\n sourceGasFee || EVM_SWAP_FALLBACK_GAS_ESTIMATE,\n options?.feeUnitsMarginBps,\n );\n }\n } else {\n gasWithMargin = await _estimateGasFromSwapResponse({\n crossChain: isCrossChainSwap,\n feeUnitsMarginBps: options?.feeUnitsMarginBps,\n fromAddress: quote.fromAddress,\n sourceClient,\n swap,\n });\n }\n\n const fees = await estimateEvmFeesPerGas(sourceClient, quote.sourceChain, options?.overrides?.feeRateTier);\n\n const maxFeePerGas = options?.overrides?.maxFeePerGas ?? fees.maxFeePerGas;\n const maxPriorityFeePerGas = options?.overrides?.maxPriorityFeePerGas ?? fees.maxPriorityFeePerGas;\n\n const totalFee =\n (gasWithMargin + applyFeeUnitsBpsMargin(allowanceApprovalGas, options?.feeUnitsMarginBps)) * maxFeePerGas;\n\n return {\n asset: quote.sourceChain.networkToken,\n totalFee,\n meta: {\n approvalFee: allowanceApprovalIsNeeded\n ? applyFeeUnitsBpsMargin(allowanceApprovalGas, options?.feeUnitsMarginBps) * maxFeePerGas\n : undefined,\n maxFeePerGas,\n maxPriorityFeePerGas,\n },\n };\n}\n\n/** @internal */\nexport async function _estimateNativeFeeSolana(\n quote: Quote,\n options: EstimateNativeFeeOptions | undefined,\n { apiOptions, appId }: EstimateNativeFeeFactoryConfig,\n): Promise<NativeFeeEstimate> {\n const assetInAddressString = assetToAddressString(quote.assetIn, quote.sourceChain.chainId);\n\n if (!isSolanaAddress(assetInAddressString)) {\n throw new SdkError(ErrorReason.INVALID_PARAMS, ErrorCode.INVALID_PARAMS, {\n details: `assetIn address is not a valid Solana address. Can not call estimateGas.`,\n });\n }\n\n const minAmountOut = calculateMarkrMinimumAmountOut({\n amountOut: quote.amountOut,\n assetOut: quote.assetOut,\n slippageBps: quote.slippageBps,\n });\n\n const swap = await markrSwap(apiOptions, {\n amountIn: quote.amountIn.toString(),\n appId,\n minAmountOut: minAmountOut.toString(),\n tokenIn: assetInAddressString,\n tokenOut: assetToAddressString(quote.assetOut, quote.targetChain.chainId),\n userPublicKey: quote.fromAddress,\n uuid: quote.id,\n });\n\n if (!isSolanaSwapResponse(swap)) {\n // Should hopefully never happen.\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: 'Received non-Solana swap response from Markr. Expected Solana transaction data for fee estimation.',\n });\n }\n\n const rpc = getSolanaRpcForChain({ chain: quote.sourceChain });\n\n const txBytes = base64ToBytes(swap.swapTransaction);\n const tx = getTransactionDecoder().decode(txBytes);\n\n const messageBase64: TransactionMessageBytesBase64 = _transactionMessageBytesToBase64(tx.messageBytes);\n\n // Base fee (signature fee etc.) in lamports.\n const feeForMessageResponse = await rpc.getFeeForMessage(messageBase64).send();\n\n if (!feeForMessageResponse.value) {\n // This can happen if the block hash is expired or invalid.\n // Most likely expired. Use a new \"swapTxBase64\" with a recent block hash and try again.\n throw new SdkError(\n 'Failed to get fee for message. Most likely the block hash in the transaction is expired.',\n ErrorCode.TIMEOUT,\n {\n details: 'Please use a new quote with a recent block hash and try again.',\n },\n );\n }\n\n const baseFeeLamports = feeForMessageResponse.value;\n\n const sim = await rpc\n .simulateTransaction(swap.swapTransaction as Base64EncodedWireTransaction, {\n encoding: 'base64',\n sigVerify: false,\n })\n .send();\n\n if (sim.value.err) {\n throw new SdkError('Failed to simulate transaction for estimating fee.', ErrorCode.SOLANA_ERROR, {\n cause: sim.value.err,\n });\n }\n\n const unitsConsumed = applyFeeUnitsBpsMargin(sim.value.unitsConsumed ?? 0n, options?.feeUnitsMarginBps);\n // Lamports\n const computeUnitPriceMicroLamports = _getComputeUnitPriceMicroLamports(tx.messageBytes);\n const priorityFee = (unitsConsumed * computeUnitPriceMicroLamports) / 1_000_000n;\n const rentEstimate = await _estimateRentFeesFromTransactionMessage({\n fromAddress: quote.fromAddress,\n rpc,\n transactionMessageBytes: tx.messageBytes,\n });\n const totalLamports = baseFeeLamports + priorityFee + rentEstimate.rentFee;\n\n return {\n asset: quote.sourceChain.networkToken,\n totalFee: totalLamports,\n refundable: rentEstimate.refundable,\n meta: {\n baseFee: baseFeeLamports,\n priorityFee,\n computeUnitPriceMicroLamports,\n unitsConsumed,\n createdAccounts: rentEstimate.createdAccounts,\n rentFee: rentEstimate.rentFee,\n rentFeeNet: rentEstimate.rentFeeNet,\n },\n };\n}\n\n/** @internal */\nexport async function _estimateGasFromSwapResponse({\n crossChain,\n feeUnitsMarginBps,\n fromAddress,\n sourceClient,\n swap,\n}: {\n crossChain: boolean;\n feeUnitsMarginBps?: number;\n fromAddress: EvmAddress;\n sourceClient: ReturnType<typeof getEvmClientForChain>;\n swap: WrappedSwapTransactionResponse;\n}): Promise<bigint> {\n try {\n const gasEstimate = await sourceClient.estimateGas({\n account: fromAddress,\n to: swap.to,\n data: swap.data,\n value: swap.value,\n });\n\n return applyFeeUnitsBpsMargin(gasEstimate, feeUnitsMarginBps);\n } catch (err) {\n let details = 'Failed to estimate gas for Markr swap transaction.';\n\n try {\n const markrSwapWrapperAbi = await getMarkrSwapWrapperAbi(crossChain);\n const decodedRevert = decodeMarkrRevertError(markrSwapWrapperAbi, err);\n\n if (decodedRevert) {\n details = `${details} Markr revert: ${decodedRevert}.`;\n }\n } catch {\n // Keep the base details message if revert decoding fails.\n }\n\n throw new SdkError('Error during gas estimation', ErrorCode.VIEM_ERROR, {\n cause: err,\n details,\n });\n }\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n}\n\nfunction _transactionMessageBytesToBase64(bytes: TransactionMessageBytes): TransactionMessageBytesBase64 {\n let binary = '';\n for (const b of bytes) {\n binary += String.fromCharCode(b);\n }\n return btoa(binary) as TransactionMessageBytesBase64;\n}\n\nfunction _getComputeUnitPriceMicroLamports(transactionMessageBytes: TransactionMessageBytes): bigint {\n const compiledTxMessage = getCompiledTransactionMessageDecoder().decode(transactionMessageBytes);\n\n for (const instruction of compiledTxMessage.instructions) {\n const programAddress = compiledTxMessage.staticAccounts[instruction.programAddressIndex];\n if (programAddress !== SOLANA_COMPUTE_BUDGET_PROGRAM) {\n continue;\n }\n\n const data = instruction.data;\n\n if (!data || data.length < 1 + 8) {\n continue;\n }\n\n // ComputeBudget: u8 discriminator, then args\n // discriminator 3 = SetComputeUnitPrice, args = u64 microLamports\n const discriminator = data[0];\n if (discriminator !== 3) {\n continue;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n return view.getBigUint64(1, true);\n }\n\n return 0n;\n}\n\nasync function _estimateRentFeesFromTransactionMessage({\n fromAddress,\n rpc,\n transactionMessageBytes,\n}: {\n fromAddress: string;\n rpc: Rpc<SolanaRpcApi>;\n transactionMessageBytes: TransactionMessageBytes;\n}): Promise<SolanaRentEstimate> {\n const compiledMessage: CompiledTransactionMessage =\n getCompiledTransactionMessageDecoder().decode(transactionMessageBytes);\n\n const createdAccounts = new Map<string, Omit<CreatedRentAccount, 'refunded'>>();\n const closedAccountDestinationByAddress = new Map<string, string>();\n\n let ataRentLamports: bigint | undefined;\n\n for (const instruction of compiledMessage.instructions) {\n const programAddress = compiledMessage.staticAccounts[instruction.programAddressIndex];\n\n if (programAddress === SOLANA_SYSTEM_PROGRAM) {\n const createdAccountAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n const lamports = _getSystemCreateAccountLamports(instruction.data);\n if (createdAccountAddress && lamports > 0n) {\n createdAccounts.set(createdAccountAddress, {\n address: createdAccountAddress,\n kind: 'system',\n lamports,\n });\n }\n continue;\n }\n\n if (programAddress === SOLANA_ASSOCIATED_TOKEN_PROGRAM) {\n const discriminator = instruction.data?.[0];\n const isAssociatedTokenCreateInstruction =\n discriminator === undefined || discriminator === 0 || discriminator === 1;\n\n if (!isAssociatedTokenCreateInstruction) {\n continue;\n }\n\n const associatedTokenAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n if (!associatedTokenAddress) {\n continue;\n }\n\n const accountInfo = await rpc.getAccountInfo(associatedTokenAddress).send();\n if (accountInfo.value) {\n continue;\n }\n\n if (ataRentLamports === undefined) {\n ataRentLamports = await rpc.getMinimumBalanceForRentExemption(SPL_TOKEN_ACCOUNT_SIZE_BYTES).send();\n }\n\n createdAccounts.set(associatedTokenAddress, {\n address: associatedTokenAddress,\n kind: 'ata',\n lamports: ataRentLamports,\n });\n\n continue;\n }\n\n const isSplTokenProgram =\n programAddress === SOLANA_SPL_TOKEN_PROGRAM || programAddress === SOLANA_SPL_TOKEN_2022_PROGRAM;\n if (!isSplTokenProgram) {\n continue;\n }\n\n const discriminator = instruction.data?.[0];\n if (discriminator !== 9) {\n continue;\n }\n\n const closedAccountAddress = _getInstructionAccountAddress(compiledMessage, instruction, 0);\n const refundDestinationAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n\n if (closedAccountAddress && refundDestinationAddress) {\n closedAccountDestinationByAddress.set(closedAccountAddress, refundDestinationAddress);\n }\n }\n\n const normalizedFromAddress = isSolanaAddress(fromAddress) ? fromAddress : undefined;\n const createdAccountEntries = Array.from(createdAccounts.values()).map((createdAccount) => {\n const refundDestinationAddress = closedAccountDestinationByAddress.get(createdAccount.address);\n const refunded = normalizedFromAddress !== undefined && refundDestinationAddress === normalizedFromAddress;\n\n return {\n ...createdAccount,\n refunded,\n } satisfies CreatedRentAccount;\n });\n\n const rentLamportsUpfront = createdAccountEntries.reduce((acc, account) => acc + account.lamports, 0n);\n const refundedLamports = createdAccountEntries.reduce(\n (acc, account) => acc + (account.refunded ? account.lamports : 0n),\n 0n,\n );\n const rentFeeNet = rentLamportsUpfront - refundedLamports;\n\n return {\n createdAccounts: createdAccountEntries,\n rentFee: rentLamportsUpfront,\n rentFeeNet,\n refundable: refundedLamports,\n };\n}\n\n/**\n * Resolves an account address used by a compiled instruction.\n *\n * Compiled instructions reference accounts by index into the transaction\n * message's `staticAccounts` list. This helper converts an instruction-local\n * `accountIndex` into the corresponding static account address.\n *\n * Returns `undefined` when the instruction does not provide an account at the\n * requested index.\n */\nfunction _getInstructionAccountAddress(\n message: CompiledTransactionMessage,\n instruction: CompiledTransactionMessage['instructions'][number],\n accountIndex: number,\n): CompiledTransactionMessage['staticAccounts'][number] | undefined {\n const messageAccountIndex = instruction.accountIndices?.[accountIndex];\n\n if (messageAccountIndex === undefined) {\n return undefined;\n }\n\n return message.staticAccounts[messageAccountIndex];\n}\n\n/**\n * Extracts lamports from System Program account-creation instruction data.\n *\n * Supported instruction layouts:\n * - `CreateAccount` (`u32 discriminator = 0`): lamports at byte offset `4`.\n * - `CreateAccountWithSeed` (`u32 discriminator = 3`): lamports are located\n * after the variable-length seed field.\n *\n * Returns `0n` when data is missing, malformed, or not one of the supported\n * System Program create-account variants.\n */\nfunction _getSystemCreateAccountLamports(data: CompiledTransactionMessage['instructions'][number]['data']): bigint {\n if (!data || data.length < 12) {\n return 0n;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const instructionDiscriminator = view.getUint32(0, true);\n\n if (instructionDiscriminator === 0 && data.length >= 12) {\n return view.getBigUint64(4, true);\n }\n\n if (instructionDiscriminator === 3 && data.length >= 44) {\n const seedLenOffset = 36;\n const seedLength = Number(view.getBigUint64(seedLenOffset, true));\n if (!Number.isSafeInteger(seedLength) || seedLength < 0) {\n return 0n;\n }\n\n const lamportsOffset = seedLenOffset + 8 + seedLength;\n if (lamportsOffset + 8 > data.length) {\n return 0n;\n }\n\n return new DataView(data.buffer, data.byteOffset + lamportsOffset, 8).getBigUint64(0, true);\n }\n\n return 0n;\n}\n"],"mappings":"84BA4GA,SAAgB,EAAyB,EAA8E,CACrH,OAAO,MAAO,EAAO,IAAY,CAI/B,GAAI,EAAe,EAAM,YAAY,QAAQ,CAC3C,OAAO,MAAM,EAAsB,EAAO,EAAS,EAAO,CAG5D,GAAI,EAAkB,EAAM,YAAY,QAAQ,CAC9C,OAAO,MAAM,EAAyB,EAAO,EAAS,EAAO,CAG/D,MAAM,IAAI,EACR,EAAY,eACZ,6DAA6D,EAAM,YAAY,UAChF,EAKL,eAAsB,EACpB,EACA,EACA,CAAE,aAAY,SACc,CAC5B,GAAI,CAACA,EAAa,EAAM,YAAY,CAClC,MAAM,IAAI,EAAmB,EAAY,eAAgB,wBAAwB,EAAM,cAAc,CAGvG,IAAM,EAAe,EAAqB,CAAE,MAAO,EAAM,YAAa,CAAC,CAEjE,EAAuB,EAAqB,EAAM,QAAS,EAAM,YAAY,QAAQ,CAE3F,GAAI,CAACA,EAAa,EAAqB,CACrC,MAAM,IAAI,EAAS,EAAY,eAAgB,EAAU,eAAgB,CACvE,QAAS,wEACV,CAAC,CAGJ,IAAM,EAAkB,EAAqB,EAAqB,CAC5D,EAAmB,EAAM,YAAY,QAAQ,aAAa,GAAK,EAAM,YAAY,QAAQ,aAAa,CAExG,EAAuB,GAC3B,GAAI,CAAC,EAAiB,CAEpB,IAAI,EAEE,CAAE,QAAS,GAAmB,MAAM,EACxC,EACA,EAAqB,EAAM,YAAY,QAAQ,CAC/C,EACD,CAED,GAAI,CACF,EAAY,MAAM,EAAa,aAAa,CAC1C,QAAS,EACT,IAAK,EACL,aAAc,YACd,KAAM,CAAC,EAAM,YAAa,EAAe,CAC1C,CAAC,OACK,EAAO,CACd,MAAM,IAAI,EAAS,+BAAgC,EAAU,WAAY,CACvE,MAAO,EACP,QAAS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olanaAddress"],"sources":["../../../../src/transfer-service/markr/_handlers/estimate-native-fee.ts"],"sourcesContent":["import {\n type CompiledTransactionMessage,\n getCompiledTransactionMessageDecoder,\n getTransactionDecoder,\n isAddress as isSolanaAddress,\n type Base64EncodedWireTransaction,\n type Rpc,\n type SolanaRpcApi,\n type TransactionMessageBytes,\n type TransactionMessageBytesBase64,\n} from '@solana/kit';\nimport { encodeFunctionData, erc20Abi, type Address as EvmAddress, isAddress as isEvmAddress } from 'viem';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { EstimateNativeFeeOptions, NativeFeeEstimate, TransferService } from '../../../types/service';\nimport { applyFeeUnitsBpsMargin, getEvmClientForChain, getSolanaRpcForChain } from '../../_utils';\nimport { estimateEvmFeesPerGas } from '../../_evm-gas';\nimport { markrGetSpenderAddress, markrSwap, type ApiOptions } from '../_api';\nimport {\n assetToAddressString,\n calculateMarkrMinimumAmountOut,\n decodeMarkrRevertError,\n getMarkrSwapWrapperAbi,\n isTokenAddressNative,\n} from '../_utils';\nimport type { WrappedSwapTransactionResponse } from '../_schema';\nimport { isEvmSwapResponse, isSolanaSwapResponse } from '../_type-guards';\nimport { caip2ToEip155ChainId } from '../../../utils/caip';\nimport type { Quote } from '../../../types/quote';\nimport { isEvmNamespace, isSolanaNamespace } from '../../../_utils/chain';\n\n/**\n * This is just a fallback value used in the case that an\n * allowance approval is needed, and Markr didn't return us any gas estimate data.\n *\n * Just based on my review of some quotes, I think this is a reasonable estimate\n * left on the higher end.\n *\n * Assume this could need to change.\n */\nconst EVM_SWAP_FALLBACK_GAS_ESTIMATE = 700_000n;\n\n/**\n * Compute Budget program address.\n *\n * Used to detect `SetComputeUnitPrice` instructions when deriving\n * the Solana priority fee component from transaction message bytes.\n */\nconst SOLANA_COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';\n\n/**\n * System Program address.\n *\n * Used to detect account-creation instructions and extract lamports\n * funded upfront for newly created system accounts.\n */\nconst SOLANA_SYSTEM_PROGRAM = '11111111111111111111111111111111';\n\n/**\n * Associated Token Account (ATA) program address.\n *\n * Used to detect ATA create instructions so the estimator can include\n * rent-exempt funding when the ATA does not already exist on-chain.\n */\nconst SOLANA_ASSOCIATED_TOKEN_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n\n/**\n * Legacy SPL Token program address.\n *\n * Used to detect close-account instructions that may refund lamports\n * from temporary token accounts back to the sender.\n */\nconst SOLANA_SPL_TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\n\n/**\n * SPL Token-2022 program address.\n *\n * Used alongside the legacy token program for close-account detection\n * when computing expected refundable lamports.\n */\nconst SOLANA_SPL_TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';\n\n/**\n * SPL token account size for rent-exemption calculations.\n *\n * Used with `getMinimumBalanceForRentExemption` to estimate ATA\n * creation funding requirements.\n */\nconst SPL_TOKEN_ACCOUNT_SIZE_BYTES = 165n;\n\nexport interface EstimateNativeFeeFactoryConfig {\n apiOptions: ApiOptions;\n appId: string;\n}\n\ninterface CreatedRentAccount {\n address: string;\n kind: 'ata' | 'system';\n lamports: bigint;\n refunded: boolean;\n}\n\ninterface SolanaRentEstimate {\n createdAccounts: CreatedRentAccount[];\n rentFee: bigint;\n rentFeeNet: bigint;\n refundable: bigint;\n}\n\nexport function estimateNativeFeeFactory(config: EstimateNativeFeeFactoryConfig): TransferService['estimateNativeFee'] {\n return async (quote, options) => {\n // Either the source chain is EVM or Solana, we need to call different functions that\n // calculate the native fee depending on the chain kind.\n\n if (isEvmNamespace(quote.sourceChain.chainId)) {\n return await _estimateNativeFeeEvm(quote, options, config);\n }\n\n if (isSolanaNamespace(quote.sourceChain.chainId)) {\n return await _estimateNativeFeeSolana(quote, options, config);\n }\n\n throw new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n `Unsupported source chain namespace for estimateNativeFee: ${quote.sourceChain.chainId}`,\n );\n };\n}\n\n/** @internal */\nexport async function _estimateNativeFeeEvm(\n quote: Quote,\n options: EstimateNativeFeeOptions | undefined,\n { apiOptions, appId }: EstimateNativeFeeFactoryConfig,\n): Promise<NativeFeeEstimate> {\n if (!isEvmAddress(quote.fromAddress)) {\n throw new InvalidParamsError(ErrorReason.INVALID_PARAMS, `Invalid fromAddress: ${quote.fromAddress}`);\n }\n\n const sourceClient = getEvmClientForChain({ chain: quote.sourceChain });\n\n const assetInAddressString = assetToAddressString(quote.assetIn, quote.sourceChain.chainId);\n\n if (!isEvmAddress(assetInAddressString)) {\n throw new SdkError(ErrorReason.INVALID_PARAMS, ErrorCode.INVALID_PARAMS, {\n details: `assetIn address is not a valid EVM address. Can not call estimateGas.`,\n });\n }\n\n const isAssetInNative = isTokenAddressNative(assetInAddressString);\n const isCrossChainSwap = quote.sourceChain.chainId.toLowerCase() !== quote.targetChain.chainId.toLowerCase();\n\n let allowanceApprovalGas = 0n;\n if (!isAssetInNative) {\n // Check if approval is needed, and if so, calculate the gas cost for the approval.\n let allowance: bigint;\n\n const { address: spenderAddress } = await markrGetSpenderAddress(apiOptions, {\n chainId: caip2ToEip155ChainId(quote.sourceChain.chainId),\n crossChainSwap: isCrossChainSwap,\n quoteId: quote.id,\n });\n\n try {\n allowance = await sourceClient.readContract({\n address: assetInAddressString,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [quote.fromAddress, spenderAddress],\n });\n } catch (error) {\n throw new SdkError('Error during allowance check', ErrorCode.VIEM_ERROR, {\n cause: error,\n details: 'Failed to read ERC20 allowance for Markr spender.',\n });\n }\n\n const approvalNeeded = allowance < quote.amountIn;\n\n if (approvalNeeded) {\n try {\n allowanceApprovalGas = await sourceClient.estimateGas({\n account: quote.fromAddress,\n to: assetInAddressString,\n data: encodeFunctionData({\n abi: erc20Abi,\n functionName: 'approve',\n args: [spenderAddress, quote.amountIn],\n }),\n value: 0n,\n });\n } catch (error) {\n throw new SdkError('Error during gas estimation', ErrorCode.VIEM_ERROR, {\n cause: error,\n details: 'Failed to estimate gas for ERC20 approval transaction.',\n });\n }\n }\n }\n\n const allowanceApprovalIsNeeded = allowanceApprovalGas > 0n;\n\n const minAmountOut = calculateMarkrMinimumAmountOut({\n amountOut: quote.amountOut,\n assetOut: quote.assetOut,\n slippageBps: quote.slippageBps,\n });\n\n const swap = await markrSwap(apiOptions, {\n amountIn: quote.amountIn.toString(),\n appId,\n minAmountOut: minAmountOut.toString(),\n tokenIn: assetInAddressString,\n tokenOut: assetToAddressString(quote.assetOut, quote.targetChain.chainId),\n uuid: quote.id,\n });\n\n if (!isEvmSwapResponse(swap)) {\n // Should hopefully never happen.\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: `Received non-EVM swap response from Markr. Expected EVM transaction data for gas estimation, but got response with chainType ${swap.chainType}.`,\n });\n }\n\n let gasWithMargin = 0n;\n\n // If an approval is needed, we can't call `eth_estimateGas` on the\n // swap transaction because no actual allowance approval was performed yet,\n // so a gas estimation would fail due to needing allowance.\n //\n // So if an allowance approval is needed, we fall back to some other logic for\n // estimating the swap tx gas.\n if (allowanceApprovalIsNeeded) {\n // Attempt to use the Markr provided `gasEstimate` first if available.\n // Otherwise we attempt to get the gas from the `fees` component that are applicable\n // to the source chain. If neither of those are available, we fall back to a hardcoded value.\n if (quote.gasEstimate) {\n gasWithMargin = applyFeeUnitsBpsMargin(quote.gasEstimate, options?.feeUnitsMarginBps);\n } else {\n const sourceGasFee = quote.fees\n .filter((fee) => fee.type === 'gas' && fee.chainId === quote.sourceChain.chainId)\n .reduce((acc, fee) => acc + fee.amount, 0n);\n\n gasWithMargin = applyFeeUnitsBpsMargin(\n sourceGasFee || EVM_SWAP_FALLBACK_GAS_ESTIMATE,\n options?.feeUnitsMarginBps,\n );\n }\n } else {\n gasWithMargin = await _estimateGasFromSwapResponse({\n crossChain: isCrossChainSwap,\n feeUnitsMarginBps: options?.feeUnitsMarginBps,\n fromAddress: quote.fromAddress,\n sourceClient,\n swap,\n });\n }\n\n const fees = await estimateEvmFeesPerGas(sourceClient, quote.sourceChain, options?.overrides?.feeRateTier);\n\n const maxFeePerGas = options?.overrides?.maxFeePerGas ?? fees.maxFeePerGas;\n const maxPriorityFeePerGas = options?.overrides?.maxPriorityFeePerGas ?? fees.maxPriorityFeePerGas;\n\n const totalFee =\n (gasWithMargin + applyFeeUnitsBpsMargin(allowanceApprovalGas, options?.feeUnitsMarginBps)) * maxFeePerGas;\n\n return {\n asset: quote.sourceChain.networkToken,\n totalFee,\n meta: {\n approvalFee: allowanceApprovalIsNeeded\n ? applyFeeUnitsBpsMargin(allowanceApprovalGas, options?.feeUnitsMarginBps) * maxFeePerGas\n : undefined,\n maxFeePerGas,\n maxPriorityFeePerGas,\n },\n };\n}\n\n/** @internal */\nexport async function _estimateNativeFeeSolana(\n quote: Quote,\n options: EstimateNativeFeeOptions | undefined,\n { apiOptions, appId }: EstimateNativeFeeFactoryConfig,\n): Promise<NativeFeeEstimate> {\n const assetInAddressString = assetToAddressString(quote.assetIn, quote.sourceChain.chainId);\n\n if (!isSolanaAddress(assetInAddressString)) {\n throw new SdkError(ErrorReason.INVALID_PARAMS, ErrorCode.INVALID_PARAMS, {\n details: `assetIn address is not a valid Solana address. Can not call estimateGas.`,\n });\n }\n\n const minAmountOut = calculateMarkrMinimumAmountOut({\n amountOut: quote.amountOut,\n assetOut: quote.assetOut,\n slippageBps: quote.slippageBps,\n });\n\n const swap = await markrSwap(apiOptions, {\n amountIn: quote.amountIn.toString(),\n appId,\n minAmountOut: minAmountOut.toString(),\n tokenIn: assetInAddressString,\n tokenOut: assetToAddressString(quote.assetOut, quote.targetChain.chainId),\n userPublicKey: quote.fromAddress,\n uuid: quote.id,\n });\n\n if (!isSolanaSwapResponse(swap)) {\n // Should hopefully never happen.\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: 'Received non-Solana swap response from Markr. Expected Solana transaction data for fee estimation.',\n });\n }\n\n const rpc = getSolanaRpcForChain({ chain: quote.sourceChain });\n\n const txBytes = base64ToBytes(swap.swapTransaction);\n const tx = getTransactionDecoder().decode(txBytes);\n\n const messageBase64: TransactionMessageBytesBase64 = _transactionMessageBytesToBase64(tx.messageBytes);\n\n // Base fee (signature fee etc.) in lamports.\n const feeForMessageResponse = await rpc.getFeeForMessage(messageBase64).send();\n\n if (!feeForMessageResponse.value) {\n // This can happen if the block hash is expired or invalid.\n // Most likely expired. Use a new \"swapTxBase64\" with a recent block hash and try again.\n throw new SdkError(\n 'Failed to get fee for message. Most likely the block hash in the transaction is expired.',\n ErrorCode.TIMEOUT,\n {\n details: 'Please use a new quote with a recent block hash and try again.',\n },\n );\n }\n\n const baseFeeLamports = feeForMessageResponse.value;\n\n const sim = await rpc\n .simulateTransaction(swap.swapTransaction as Base64EncodedWireTransaction, {\n encoding: 'base64',\n sigVerify: false,\n })\n .send();\n\n if (sim.value.err) {\n throw new SdkError('Failed to simulate transaction for estimating fee.', ErrorCode.SOLANA_ERROR, {\n cause: sim.value.err,\n });\n }\n\n const unitsConsumed = applyFeeUnitsBpsMargin(sim.value.unitsConsumed ?? 0n, options?.feeUnitsMarginBps);\n // Lamports\n const computeUnitPriceMicroLamports = _getComputeUnitPriceMicroLamports(tx.messageBytes);\n const priorityFee = (unitsConsumed * computeUnitPriceMicroLamports) / 1_000_000n;\n const rentEstimate = await _estimateRentFeesFromTransactionMessage({\n fromAddress: quote.fromAddress,\n rpc,\n transactionMessageBytes: tx.messageBytes,\n });\n const totalLamports = baseFeeLamports + priorityFee + rentEstimate.rentFee;\n\n return {\n asset: quote.sourceChain.networkToken,\n totalFee: totalLamports,\n refundable: rentEstimate.refundable,\n meta: {\n baseFee: baseFeeLamports,\n priorityFee,\n computeUnitPriceMicroLamports,\n unitsConsumed,\n createdAccounts: rentEstimate.createdAccounts,\n rentFee: rentEstimate.rentFee,\n rentFeeNet: rentEstimate.rentFeeNet,\n },\n };\n}\n\n/** @internal */\nexport async function _estimateGasFromSwapResponse({\n crossChain,\n feeUnitsMarginBps,\n fromAddress,\n sourceClient,\n swap,\n}: {\n crossChain: boolean;\n feeUnitsMarginBps?: number;\n fromAddress: EvmAddress;\n sourceClient: ReturnType<typeof getEvmClientForChain>;\n swap: WrappedSwapTransactionResponse;\n}): Promise<bigint> {\n try {\n const gasEstimate = await sourceClient.estimateGas({\n account: fromAddress,\n to: swap.to,\n data: swap.data,\n value: swap.value,\n });\n\n return applyFeeUnitsBpsMargin(gasEstimate, feeUnitsMarginBps);\n } catch (err) {\n let details = 'Failed to estimate gas for Markr swap transaction.';\n\n try {\n const markrSwapWrapperAbi = await getMarkrSwapWrapperAbi(crossChain);\n const decodedRevert = decodeMarkrRevertError(markrSwapWrapperAbi, err);\n\n if (decodedRevert) {\n details = `${details} Markr revert: ${decodedRevert}.`;\n }\n } catch {\n // Keep the base details message if revert decoding fails.\n }\n\n throw new SdkError('Error during gas estimation', ErrorCode.VIEM_ERROR, {\n cause: err,\n details,\n });\n }\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n}\n\nfunction _transactionMessageBytesToBase64(bytes: TransactionMessageBytes): TransactionMessageBytesBase64 {\n let binary = '';\n for (const b of bytes) {\n binary += String.fromCharCode(b);\n }\n return btoa(binary) as TransactionMessageBytesBase64;\n}\n\nfunction _getComputeUnitPriceMicroLamports(transactionMessageBytes: TransactionMessageBytes): bigint {\n const compiledTxMessage = getCompiledTransactionMessageDecoder().decode(transactionMessageBytes);\n\n for (const instruction of compiledTxMessage.instructions) {\n const programAddress = compiledTxMessage.staticAccounts[instruction.programAddressIndex];\n if (programAddress !== SOLANA_COMPUTE_BUDGET_PROGRAM) {\n continue;\n }\n\n const data = instruction.data;\n\n if (!data || data.length < 1 + 8) {\n continue;\n }\n\n // ComputeBudget: u8 discriminator, then args\n // discriminator 3 = SetComputeUnitPrice, args = u64 microLamports\n const discriminator = data[0];\n if (discriminator !== 3) {\n continue;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n return view.getBigUint64(1, true);\n }\n\n return 0n;\n}\n\nasync function _estimateRentFeesFromTransactionMessage({\n fromAddress,\n rpc,\n transactionMessageBytes,\n}: {\n fromAddress: string;\n rpc: Rpc<SolanaRpcApi>;\n transactionMessageBytes: TransactionMessageBytes;\n}): Promise<SolanaRentEstimate> {\n const compiledMessage: CompiledTransactionMessage =\n getCompiledTransactionMessageDecoder().decode(transactionMessageBytes);\n\n const createdAccounts = new Map<string, Omit<CreatedRentAccount, 'refunded'>>();\n const closedAccountDestinationByAddress = new Map<string, string>();\n\n let ataRentLamports: bigint | undefined;\n\n for (const instruction of compiledMessage.instructions) {\n const programAddress = compiledMessage.staticAccounts[instruction.programAddressIndex];\n\n if (programAddress === SOLANA_SYSTEM_PROGRAM) {\n const createdAccountAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n const lamports = _getSystemCreateAccountLamports(instruction.data);\n if (createdAccountAddress && lamports > 0n) {\n createdAccounts.set(createdAccountAddress, {\n address: createdAccountAddress,\n kind: 'system',\n lamports,\n });\n }\n continue;\n }\n\n if (programAddress === SOLANA_ASSOCIATED_TOKEN_PROGRAM) {\n const discriminator = instruction.data?.[0];\n const isAssociatedTokenCreateInstruction =\n discriminator === undefined || discriminator === 0 || discriminator === 1;\n\n if (!isAssociatedTokenCreateInstruction) {\n continue;\n }\n\n const associatedTokenAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n if (!associatedTokenAddress) {\n continue;\n }\n\n const accountInfo = await rpc.getAccountInfo(associatedTokenAddress).send();\n if (accountInfo.value) {\n continue;\n }\n\n if (ataRentLamports === undefined) {\n ataRentLamports = await rpc.getMinimumBalanceForRentExemption(SPL_TOKEN_ACCOUNT_SIZE_BYTES).send();\n }\n\n createdAccounts.set(associatedTokenAddress, {\n address: associatedTokenAddress,\n kind: 'ata',\n lamports: ataRentLamports,\n });\n\n continue;\n }\n\n const isSplTokenProgram =\n programAddress === SOLANA_SPL_TOKEN_PROGRAM || programAddress === SOLANA_SPL_TOKEN_2022_PROGRAM;\n if (!isSplTokenProgram) {\n continue;\n }\n\n const discriminator = instruction.data?.[0];\n if (discriminator !== 9) {\n continue;\n }\n\n const closedAccountAddress = _getInstructionAccountAddress(compiledMessage, instruction, 0);\n const refundDestinationAddress = _getInstructionAccountAddress(compiledMessage, instruction, 1);\n\n if (closedAccountAddress && refundDestinationAddress) {\n closedAccountDestinationByAddress.set(closedAccountAddress, refundDestinationAddress);\n }\n }\n\n const normalizedFromAddress = isSolanaAddress(fromAddress) ? fromAddress : undefined;\n const createdAccountEntries = Array.from(createdAccounts.values()).map((createdAccount) => {\n const refundDestinationAddress = closedAccountDestinationByAddress.get(createdAccount.address);\n const refunded = normalizedFromAddress !== undefined && refundDestinationAddress === normalizedFromAddress;\n\n return {\n ...createdAccount,\n refunded,\n } satisfies CreatedRentAccount;\n });\n\n const rentLamportsUpfront = createdAccountEntries.reduce((acc, account) => acc + account.lamports, 0n);\n const refundedLamports = createdAccountEntries.reduce(\n (acc, account) => acc + (account.refunded ? account.lamports : 0n),\n 0n,\n );\n const rentFeeNet = rentLamportsUpfront - refundedLamports;\n\n return {\n createdAccounts: createdAccountEntries,\n rentFee: rentLamportsUpfront,\n rentFeeNet,\n refundable: refundedLamports,\n };\n}\n\n/**\n * Resolves an account address used by a compiled instruction.\n *\n * Compiled instructions reference accounts by index into the transaction\n * message's `staticAccounts` list. This helper converts an instruction-local\n * `accountIndex` into the corresponding static account address.\n *\n * Returns `undefined` when the instruction does not provide an account at the\n * requested index.\n */\nfunction _getInstructionAccountAddress(\n message: CompiledTransactionMessage,\n instruction: CompiledTransactionMessage['instructions'][number],\n accountIndex: number,\n): CompiledTransactionMessage['staticAccounts'][number] | undefined {\n const messageAccountIndex = instruction.accountIndices?.[accountIndex];\n\n if (messageAccountIndex === undefined) {\n return undefined;\n }\n\n return message.staticAccounts[messageAccountIndex];\n}\n\n/**\n * Extracts lamports from System Program account-creation instruction data.\n *\n * Supported instruction layouts:\n * - `CreateAccount` (`u32 discriminator = 0`): lamports at byte offset `4`.\n * - `CreateAccountWithSeed` (`u32 discriminator = 3`): lamports are located\n * after the variable-length seed field.\n *\n * Returns `0n` when data is missing, malformed, or not one of the supported\n * System Program create-account variants.\n */\nfunction _getSystemCreateAccountLamports(data: CompiledTransactionMessage['instructions'][number]['data']): bigint {\n if (!data || data.length < 12) {\n return 0n;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const instructionDiscriminator = view.getUint32(0, true);\n\n if (instructionDiscriminator === 0 && data.length >= 12) {\n return view.getBigUint64(4, true);\n }\n\n if (instructionDiscriminator === 3 && data.length >= 44) {\n const seedLenOffset = 36;\n const seedLength = Number(view.getBigUint64(seedLenOffset, true));\n if (!Number.isSafeInteger(seedLength) || seedLength < 0) {\n return 0n;\n }\n\n const lamportsOffset = seedLenOffset + 8 + seedLength;\n if (lamportsOffset + 8 > data.length) {\n return 0n;\n }\n\n return new DataView(data.buffer, data.byteOffset + lamportsOffset, 8).getBigUint64(0, true);\n }\n\n return 0n;\n}\n"],"mappings":"84BA4GA,SAAgB,EAAyB,EAA8E,CACrH,OAAO,MAAO,EAAO,IAAY,CAI/B,GAAI,EAAe,EAAM,YAAY,QAAQ,CAC3C,OAAO,MAAM,EAAsB,EAAO,EAAS,EAAO,CAG5D,GAAI,EAAkB,EAAM,YAAY,QAAQ,CAC9C,OAAO,MAAM,EAAyB,EAAO,EAAS,EAAO,CAG/D,MAAM,IAAI,EACR,EAAY,eACZ,6DAA6D,EAAM,YAAY,UAChF,EAKL,eAAsB,EACpB,EACA,EACA,CAAE,aAAY,SACc,CAC5B,GAAI,CAACA,EAAa,EAAM,YAAY,CAClC,MAAM,IAAI,EAAmB,EAAY,eAAgB,wBAAwB,EAAM,cAAc,CAGvG,IAAM,EAAe,EAAqB,CAAE,MAAO,EAAM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,IAAA,GAI5B,OAAO,EAAQ,eAAe,GAchC,SAAS,EAAgC,EAA0E,CACjH,GAAI,CAAC,GAAQ,EAAK,OAAS,GACzB,OAAO,GAGT,IAAM,EAAO,IAAI,SAAS,EAAK,OAAQ,EAAK,WAAY,EAAK,WAAW,CAClE,EAA2B,EAAK,UAAU,EAAG,GAAK,CAExD,GAAI,IAA6B,GAAK,EAAK,QAAU,GACnD,OAAO,EAAK,aAAa,EAAG,GAAK,CAGnC,GAAI,IAA6B,GAAK,EAAK,QAAU,GAAI,CACvD,IACM,EAAa,OAAO,EAAK,aAAa,GAAe,GAAK,CAAC,CACjE,GAAI,CAAC,OAAO,cAAc,EAAW,EAAI,EAAa,EACpD,OAAO,GAGT,IAAM,EAAiB,GAAoB,EAK3C,OAJI,EAAiB,EAAI,EAAK,OACrB,GAGF,IAAI,SAAS,EAAK,OAAQ,EAAK,WAAa,EAAgB,EAAE,CAAC,aAAa,EAAG,GAAK,CAG7F,OAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../../../errors.cjs`),t=require(`../../../utils/caip.cjs`),n=require(`../../../utils/evm-address.cjs`),r=require(`../../../_utils/chain.cjs`),i=require(`../_api.cjs`),a=require(`../../../utils/sol-address.cjs`),o=require(`../_utils.cjs`);function s({apiOptions:e,appId:n,partnerFeeBps:a}){return(s,l)=>{let u=new AbortController,{userEvmAddress:d,userSolanaAddress:f,validationError:p}=c(s);return p?(l(`error`,p),l(`done`),{cancel:()=>{}}):(i.markrStreamQuote(e,{amount:s.amount.toString(),appId:n,chainId:r.isEvmNamespace(s.sourceChain.chainId)?t.caip2ToEip155ChainId(s.sourceChain.chainId):s.sourceChain.chainId,destinationChainId:s.sourceChain.chainId
|
|
1
|
+
const e=require(`../../../errors.cjs`),t=require(`../../../utils/caip.cjs`),n=require(`../../../utils/evm-address.cjs`),r=require(`../../../_utils/chain.cjs`),i=require(`../_api.cjs`),a=require(`../../../utils/sol-address.cjs`),o=require(`../_utils.cjs`);function s({apiOptions:e,appId:n,partnerFeeBps:a}){return(s,l)=>{let u=new AbortController,{userEvmAddress:d,userSolanaAddress:f,validationError:p}=c(s);return p?(l(`error`,p),l(`done`),{cancel:()=>{}}):(i.markrStreamQuote(e,{amount:s.amount.toString(),appId:n,chainId:r.isEvmNamespace(s.sourceChain.chainId)?t.caip2ToEip155ChainId(s.sourceChain.chainId):s.sourceChain.chainId,destinationChainId:s.sourceChain.chainId===s.targetChain.chainId?void 0:r.isEvmNamespace(s.targetChain.chainId)?t.caip2ToEip155ChainId(s.targetChain.chainId):s.targetChain.chainId,slippage:s.slippageBps,tokenIn:o.assetToAddressString(s.sourceAsset,s.sourceChain.chainId),tokenInDecimals:s.sourceAsset.decimals,tokenOut:o.assetToAddressString(s.targetAsset,s.targetChain.chainId),tokenOutDecimals:s.targetAsset.decimals,userEvmAddress:d,userSolanaAddress:f},{onDone:()=>{u.signal.aborted||l(`done`)},onError:e=>{u.signal.aborted||(l(`error`,e),l(`done`))},onQuote:e=>{u.signal.aborted||l(`quote`,o.quoteFromMarkrQuoteResponseData(e,s,a))},signal:u.signal}),{cancel:()=>{u.abort()}})}}function c(t){let i=t.sourceChain.chainId!==t.targetChain.chainId,o=r.isEvmNamespace(t.sourceChain.chainId),s=r.isEvmNamespace(t.targetChain.chainId),c=r.isSolanaNamespace(t.sourceChain.chainId),l=r.isSolanaNamespace(t.targetChain.chainId);return o&&!n.isEvmAddress(t.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid fromAddress for EVM source chain.`)}:s&&!n.isEvmAddress(t.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid toAddress for EVM target chain.`)}:c&&!a.isSolAddress(t.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid fromAddress for Solana source chain.`)}:l&&!a.isSolAddress(t.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid toAddress for Solana target chain.`)}:i&&(o&&s||c&&l)&&t.fromAddress!==t.toAddress?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`fromAddress and toAddress must match for same-namespace cross-chain swaps.`)}:i?{userEvmAddress:o&&n.isEvmAddress(t.fromAddress)?t.fromAddress:s&&n.isEvmAddress(t.toAddress)?t.toAddress:void 0,userSolanaAddress:c&&a.isSolAddress(t.fromAddress)?t.fromAddress:l&&a.isSolAddress(t.toAddress)?t.toAddress:void 0}:t.fromAddress===t.toAddress?{userEvmAddress:void 0,userSolanaAddress:void 0}:{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`fromAddress and toAddress must match for same-chain swaps.`)}}exports.streamQuotesFactory=s;
|
|
2
2
|
//# sourceMappingURL=stream-quotes.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream-quotes.cjs","names":["markrStreamQuote","isEvmNamespace","caip2ToEip155ChainId","assetToAddressString","quoteFromMarkrQuoteResponseData","isSolanaNamespace","isEvmAddress","InvalidParamsError","ErrorReason","isSolAddress"],"sources":["../../../../src/transfer-service/markr/_handlers/stream-quotes.ts"],"sourcesContent":["import { caip2ToEip155ChainId } from '../../../utils/caip';\nimport type { TransferService } from '../../../types/service';\nimport { markrStreamQuote, type ApiOptions, type MarkrStreamQuoteParams } from '../_api';\nimport { assetToAddressString, quoteFromMarkrQuoteResponseData } from '../_utils';\nimport { isEvmNamespace, isSolanaNamespace } from '../../../_utils/chain';\nimport { isEvmAddress } from '../../../utils/evm-address';\nimport { isSolAddress } from '../../../utils/sol-address';\nimport { ErrorReason, InvalidParamsError } from '../../../errors';\n\nexport interface StreamQuotesFactoryConfig {\n apiOptions: ApiOptions;\n appId: string;\n partnerFeeBps: number;\n}\n\nexport function streamQuotesFactory({\n apiOptions,\n appId,\n partnerFeeBps,\n}: StreamQuotesFactoryConfig): TransferService['streamQuotes'] {\n return (props, handler) => {\n const ac = new AbortController();\n const { userEvmAddress, userSolanaAddress, validationError } = _validateAndGetUserAddresses(props);\n\n if (validationError) {\n handler('error', validationError);\n handler('done');\n\n return {\n cancel: () => {},\n };\n }\n\n void markrStreamQuote(\n apiOptions,\n {\n amount: props.amount.toString(),\n appId,\n chainId: isEvmNamespace(props.sourceChain.chainId)\n ? caip2ToEip155ChainId(props.sourceChain.chainId)\n : props.sourceChain.chainId,\n //
|
|
1
|
+
{"version":3,"file":"stream-quotes.cjs","names":["markrStreamQuote","isEvmNamespace","caip2ToEip155ChainId","assetToAddressString","quoteFromMarkrQuoteResponseData","isSolanaNamespace","isEvmAddress","InvalidParamsError","ErrorReason","isSolAddress"],"sources":["../../../../src/transfer-service/markr/_handlers/stream-quotes.ts"],"sourcesContent":["import { caip2ToEip155ChainId } from '../../../utils/caip';\nimport type { TransferService } from '../../../types/service';\nimport { markrStreamQuote, type ApiOptions, type MarkrStreamQuoteParams } from '../_api';\nimport { assetToAddressString, quoteFromMarkrQuoteResponseData } from '../_utils';\nimport { isEvmNamespace, isSolanaNamespace } from '../../../_utils/chain';\nimport { isEvmAddress } from '../../../utils/evm-address';\nimport { isSolAddress } from '../../../utils/sol-address';\nimport { ErrorReason, InvalidParamsError } from '../../../errors';\n\nexport interface StreamQuotesFactoryConfig {\n apiOptions: ApiOptions;\n appId: string;\n partnerFeeBps: number;\n}\n\nexport function streamQuotesFactory({\n apiOptions,\n appId,\n partnerFeeBps,\n}: StreamQuotesFactoryConfig): TransferService['streamQuotes'] {\n return (props, handler) => {\n const ac = new AbortController();\n const { userEvmAddress, userSolanaAddress, validationError } = _validateAndGetUserAddresses(props);\n\n if (validationError) {\n handler('error', validationError);\n handler('done');\n\n return {\n cancel: () => {},\n };\n }\n\n void markrStreamQuote(\n apiOptions,\n {\n amount: props.amount.toString(),\n appId,\n chainId: isEvmNamespace(props.sourceChain.chainId)\n ? caip2ToEip155ChainId(props.sourceChain.chainId)\n : props.sourceChain.chainId,\n // For cross-chain requests, destinationChainId is required.\n // Use EVM numeric chain IDs for EVM targets and CAIP-2 IDs for non-EVM targets.\n destinationChainId:\n props.sourceChain.chainId !== props.targetChain.chainId\n ? isEvmNamespace(props.targetChain.chainId)\n ? caip2ToEip155ChainId(props.targetChain.chainId)\n : props.targetChain.chainId\n : undefined,\n slippage: props.slippageBps,\n tokenIn: assetToAddressString(props.sourceAsset, props.sourceChain.chainId),\n tokenInDecimals: props.sourceAsset.decimals,\n tokenOut: assetToAddressString(props.targetAsset, props.targetChain.chainId),\n tokenOutDecimals: props.targetAsset.decimals,\n userEvmAddress,\n userSolanaAddress,\n },\n {\n onDone: () => {\n if (!ac.signal.aborted) {\n handler('done');\n }\n },\n onError: (error) => {\n if (!ac.signal.aborted) {\n handler('error', error);\n handler('done');\n }\n },\n onQuote: (data) => {\n if (!ac.signal.aborted) {\n handler('quote', quoteFromMarkrQuoteResponseData(data, props, partnerFeeBps));\n }\n },\n signal: ac.signal,\n },\n );\n\n return {\n cancel: () => {\n ac.abort();\n },\n };\n };\n}\n\nexport function _validateAndGetUserAddresses(\n props: Parameters<TransferService['streamQuotes']>[0],\n): Pick<MarkrStreamQuoteParams, 'userEvmAddress' | 'userSolanaAddress'> & { validationError?: InvalidParamsError } {\n const isCrossChainSwap = props.sourceChain.chainId !== props.targetChain.chainId;\n const sourceIsEvm = isEvmNamespace(props.sourceChain.chainId);\n const targetIsEvm = isEvmNamespace(props.targetChain.chainId);\n const sourceIsSolana = isSolanaNamespace(props.sourceChain.chainId);\n const targetIsSolana = isSolanaNamespace(props.targetChain.chainId);\n\n if (sourceIsEvm && !isEvmAddress(props.fromAddress)) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(ErrorReason.INVALID_PARAMS, 'Invalid fromAddress for EVM source chain.'),\n };\n }\n\n if (targetIsEvm && !isEvmAddress(props.toAddress)) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(ErrorReason.INVALID_PARAMS, 'Invalid toAddress for EVM target chain.'),\n };\n }\n\n if (sourceIsSolana && !isSolAddress(props.fromAddress)) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n 'Invalid fromAddress for Solana source chain.',\n ),\n };\n }\n\n if (targetIsSolana && !isSolAddress(props.toAddress)) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(ErrorReason.INVALID_PARAMS, 'Invalid toAddress for Solana target chain.'),\n };\n }\n\n if (isCrossChainSwap && ((sourceIsEvm && targetIsEvm) || (sourceIsSolana && targetIsSolana))) {\n if (props.fromAddress !== props.toAddress) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n 'fromAddress and toAddress must match for same-namespace cross-chain swaps.',\n ),\n };\n }\n }\n\n if (!isCrossChainSwap) {\n if (props.fromAddress !== props.toAddress) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n 'fromAddress and toAddress must match for same-chain swaps.',\n ),\n };\n }\n\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n };\n }\n\n const userEvmAddress =\n sourceIsEvm && isEvmAddress(props.fromAddress)\n ? props.fromAddress\n : targetIsEvm && isEvmAddress(props.toAddress)\n ? props.toAddress\n : undefined;\n\n const userSolanaAddress =\n sourceIsSolana && isSolAddress(props.fromAddress)\n ? props.fromAddress\n : targetIsSolana && isSolAddress(props.toAddress)\n ? props.toAddress\n : undefined;\n\n return {\n userEvmAddress,\n userSolanaAddress,\n };\n}\n"],"mappings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A,GAChB,kBAAmB,IAAA,GACpB,CAbQ,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAIF,EAAAA,mBACnBC,EAAAA,YAAY,eACZ,6DACD,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ErrorReason as e,InvalidParamsError as t}from"../../../errors.js";import{caip2ToEip155ChainId as n}from"../../../utils/caip.js";import{isEvmAddress as r}from"../../../utils/evm-address.js";import{isEvmNamespace as i,isSolanaNamespace as a}from"../../../_utils/chain.js";import{markrStreamQuote as o}from"../_api.js";import{isSolAddress as s}from"../../../utils/sol-address.js";import{assetToAddressString as c,quoteFromMarkrQuoteResponseData as l}from"../_utils.js";function u({apiOptions:e,appId:t,partnerFeeBps:r}){return(a,s)=>{let u=new AbortController,{userEvmAddress:f,userSolanaAddress:p,validationError:m}=d(a);return m?(s(`error`,m),s(`done`),{cancel:()=>{}}):(o(e,{amount:a.amount.toString(),appId:t,chainId:i(a.sourceChain.chainId)?n(a.sourceChain.chainId):a.sourceChain.chainId,destinationChainId:a.sourceChain.chainId
|
|
1
|
+
import{ErrorReason as e,InvalidParamsError as t}from"../../../errors.js";import{caip2ToEip155ChainId as n}from"../../../utils/caip.js";import{isEvmAddress as r}from"../../../utils/evm-address.js";import{isEvmNamespace as i,isSolanaNamespace as a}from"../../../_utils/chain.js";import{markrStreamQuote as o}from"../_api.js";import{isSolAddress as s}from"../../../utils/sol-address.js";import{assetToAddressString as c,quoteFromMarkrQuoteResponseData as l}from"../_utils.js";function u({apiOptions:e,appId:t,partnerFeeBps:r}){return(a,s)=>{let u=new AbortController,{userEvmAddress:f,userSolanaAddress:p,validationError:m}=d(a);return m?(s(`error`,m),s(`done`),{cancel:()=>{}}):(o(e,{amount:a.amount.toString(),appId:t,chainId:i(a.sourceChain.chainId)?n(a.sourceChain.chainId):a.sourceChain.chainId,destinationChainId:a.sourceChain.chainId===a.targetChain.chainId?void 0:i(a.targetChain.chainId)?n(a.targetChain.chainId):a.targetChain.chainId,slippage:a.slippageBps,tokenIn:c(a.sourceAsset,a.sourceChain.chainId),tokenInDecimals:a.sourceAsset.decimals,tokenOut:c(a.targetAsset,a.targetChain.chainId),tokenOutDecimals:a.targetAsset.decimals,userEvmAddress:f,userSolanaAddress:p},{onDone:()=>{u.signal.aborted||s(`done`)},onError:e=>{u.signal.aborted||(s(`error`,e),s(`done`))},onQuote:e=>{u.signal.aborted||s(`quote`,l(e,a,r))},signal:u.signal}),{cancel:()=>{u.abort()}})}}function d(n){let o=n.sourceChain.chainId!==n.targetChain.chainId,c=i(n.sourceChain.chainId),l=i(n.targetChain.chainId),u=a(n.sourceChain.chainId),d=a(n.targetChain.chainId);return c&&!r(n.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid fromAddress for EVM source chain.`)}:l&&!r(n.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid toAddress for EVM target chain.`)}:u&&!s(n.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid fromAddress for Solana source chain.`)}:d&&!s(n.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid toAddress for Solana target chain.`)}:o&&(c&&l||u&&d)&&n.fromAddress!==n.toAddress?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`fromAddress and toAddress must match for same-namespace cross-chain swaps.`)}:o?{userEvmAddress:c&&r(n.fromAddress)?n.fromAddress:l&&r(n.toAddress)?n.toAddress:void 0,userSolanaAddress:u&&s(n.fromAddress)?n.fromAddress:d&&s(n.toAddress)?n.toAddress:void 0}:n.fromAddress===n.toAddress?{userEvmAddress:void 0,userSolanaAddress:void 0}:{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`fromAddress and toAddress must match for same-chain swaps.`)}}export{u as streamQuotesFactory};
|
|
2
2
|
//# sourceMappingURL=stream-quotes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream-quotes.js","names":[],"sources":["../../../../src/transfer-service/markr/_handlers/stream-quotes.ts"],"sourcesContent":["import { caip2ToEip155ChainId } from '../../../utils/caip';\nimport type { TransferService } from '../../../types/service';\nimport { markrStreamQuote, type ApiOptions, type MarkrStreamQuoteParams } from '../_api';\nimport { assetToAddressString, quoteFromMarkrQuoteResponseData } from '../_utils';\nimport { isEvmNamespace, isSolanaNamespace } from '../../../_utils/chain';\nimport { isEvmAddress } from '../../../utils/evm-address';\nimport { isSolAddress } from '../../../utils/sol-address';\nimport { ErrorReason, InvalidParamsError } from '../../../errors';\n\nexport interface StreamQuotesFactoryConfig {\n apiOptions: ApiOptions;\n appId: string;\n partnerFeeBps: number;\n}\n\nexport function streamQuotesFactory({\n apiOptions,\n appId,\n partnerFeeBps,\n}: StreamQuotesFactoryConfig): TransferService['streamQuotes'] {\n return (props, handler) => {\n const ac = new AbortController();\n const { userEvmAddress, userSolanaAddress, validationError } = _validateAndGetUserAddresses(props);\n\n if (validationError) {\n handler('error', validationError);\n handler('done');\n\n return {\n cancel: () => {},\n };\n }\n\n void markrStreamQuote(\n apiOptions,\n {\n amount: props.amount.toString(),\n appId,\n chainId: isEvmNamespace(props.sourceChain.chainId)\n ? caip2ToEip155ChainId(props.sourceChain.chainId)\n : props.sourceChain.chainId,\n //
|
|
1
|
+
{"version":3,"file":"stream-quotes.js","names":[],"sources":["../../../../src/transfer-service/markr/_handlers/stream-quotes.ts"],"sourcesContent":["import { caip2ToEip155ChainId } from '../../../utils/caip';\nimport type { TransferService } from '../../../types/service';\nimport { markrStreamQuote, type ApiOptions, type MarkrStreamQuoteParams } from '../_api';\nimport { assetToAddressString, quoteFromMarkrQuoteResponseData } from '../_utils';\nimport { isEvmNamespace, isSolanaNamespace } from '../../../_utils/chain';\nimport { isEvmAddress } from '../../../utils/evm-address';\nimport { isSolAddress } from '../../../utils/sol-address';\nimport { ErrorReason, InvalidParamsError } from '../../../errors';\n\nexport interface StreamQuotesFactoryConfig {\n apiOptions: ApiOptions;\n appId: string;\n partnerFeeBps: number;\n}\n\nexport function streamQuotesFactory({\n apiOptions,\n appId,\n partnerFeeBps,\n}: StreamQuotesFactoryConfig): TransferService['streamQuotes'] {\n return (props, handler) => {\n const ac = new AbortController();\n const { userEvmAddress, userSolanaAddress, validationError } = _validateAndGetUserAddresses(props);\n\n if (validationError) {\n handler('error', validationError);\n handler('done');\n\n return {\n cancel: () => {},\n };\n }\n\n void markrStreamQuote(\n apiOptions,\n {\n amount: props.amount.toString(),\n appId,\n chainId: isEvmNamespace(props.sourceChain.chainId)\n ? caip2ToEip155ChainId(props.sourceChain.chainId)\n : props.sourceChain.chainId,\n // For cross-chain requests, destinationChainId is required.\n // Use EVM numeric chain IDs for EVM targets and CAIP-2 IDs for non-EVM targets.\n destinationChainId:\n props.sourceChain.chainId !== props.targetChain.chainId\n ? isEvmNamespace(props.targetChain.chainId)\n ? caip2ToEip155ChainId(props.targetChain.chainId)\n : props.targetChain.chainId\n : undefined,\n slippage: props.slippageBps,\n tokenIn: assetToAddressString(props.sourceAsset, props.sourceChain.chainId),\n tokenInDecimals: props.sourceAsset.decimals,\n tokenOut: assetToAddressString(props.targetAsset, props.targetChain.chainId),\n tokenOutDecimals: props.targetAsset.decimals,\n userEvmAddress,\n userSolanaAddress,\n },\n {\n onDone: () => {\n if (!ac.signal.aborted) {\n handler('done');\n }\n },\n onError: (error) => {\n if (!ac.signal.aborted) {\n handler('error', error);\n handler('done');\n }\n },\n onQuote: (data) => {\n if (!ac.signal.aborted) {\n handler('quote', quoteFromMarkrQuoteResponseData(data, props, partnerFeeBps));\n }\n },\n signal: ac.signal,\n },\n );\n\n return {\n cancel: () => {\n ac.abort();\n },\n };\n };\n}\n\nexport function _validateAndGetUserAddresses(\n props: Parameters<TransferService['streamQuotes']>[0],\n): Pick<MarkrStreamQuoteParams, 'userEvmAddress' | 'userSolanaAddress'> & { validationError?: InvalidParamsError } {\n const isCrossChainSwap = props.sourceChain.chainId !== props.targetChain.chainId;\n const sourceIsEvm = isEvmNamespace(props.sourceChain.chainId);\n const targetIsEvm = isEvmNamespace(props.targetChain.chainId);\n const sourceIsSolana = isSolanaNamespace(props.sourceChain.chainId);\n const targetIsSolana = isSolanaNamespace(props.targetChain.chainId);\n\n if (sourceIsEvm && !isEvmAddress(props.fromAddress)) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(ErrorReason.INVALID_PARAMS, 'Invalid fromAddress for EVM source chain.'),\n };\n }\n\n if (targetIsEvm && !isEvmAddress(props.toAddress)) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(ErrorReason.INVALID_PARAMS, 'Invalid toAddress for EVM target chain.'),\n };\n }\n\n if (sourceIsSolana && !isSolAddress(props.fromAddress)) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n 'Invalid fromAddress for Solana source chain.',\n ),\n };\n }\n\n if (targetIsSolana && !isSolAddress(props.toAddress)) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(ErrorReason.INVALID_PARAMS, 'Invalid toAddress for Solana target chain.'),\n };\n }\n\n if (isCrossChainSwap && ((sourceIsEvm && targetIsEvm) || (sourceIsSolana && targetIsSolana))) {\n if (props.fromAddress !== props.toAddress) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n 'fromAddress and toAddress must match for same-namespace cross-chain swaps.',\n ),\n };\n }\n }\n\n if (!isCrossChainSwap) {\n if (props.fromAddress !== props.toAddress) {\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n validationError: new InvalidParamsError(\n ErrorReason.INVALID_PARAMS,\n 'fromAddress and toAddress must match for same-chain swaps.',\n ),\n };\n }\n\n return {\n userEvmAddress: undefined,\n userSolanaAddress: undefined,\n };\n }\n\n const userEvmAddress =\n sourceIsEvm && isEvmAddress(props.fromAddress)\n ? props.fromAddress\n : targetIsEvm && isEvmAddress(props.toAddress)\n ? props.toAddress\n : undefined;\n\n const userSolanaAddress =\n sourceIsSolana && isSolAddress(props.fromAddress)\n ? props.fromAddress\n : targetIsSolana && isSolAddress(props.toAddress)\n ? props.toAddress\n : undefined;\n\n return {\n userEvmAddress,\n userSolanaAddress,\n };\n}\n"],"mappings":"ydAeA,SAAgB,EAAoB,CAClC,aACA,QACA,iBAC6D,CAC7D,OAAQ,EAAO,IAAY,CACzB,IAAM,EAAK,IAAI,gBACT,CAAE,iBAAgB,oBAAmB,mBAAoB,EAA6B,EAAM,CAwDlG,OAtDI,GACF,EAAQ,QAAS,EAAgB,CACjC,EAAQ,OAAO,CAER,CACL,WAAc,GACf,GAGE,EACH,EACA,CACE,OAAQ,EAAM,OAAO,UAAU,CAC/B,QACA,QAAS,EAAe,EAAM,YAAY,QAAQ,CAC9C,EAAqB,EAAM,YAAY,QAAQ,CAC/C,EAAM,YAAY,QAGtB,mBACE,EAAM,YAAY,UAAY,EAAM,YAAY,QAI5C,IAAA,GAHA,EAAe,EAAM,YAAY,QAAQ,CACvC,EAAqB,EAAM,YAAY,QAAQ,CAC/C,EAAM,YAAY,QAE1B,SAAU,EAAM,YAChB,QAAS,EAAqB,EAAM,YAAa,EAAM,YAAY,QAAQ,CAC3E,gBAAiB,EAAM,YAAY,SACnC,SAAU,EAAqB,EAAM,YAAa,EAAM,YAAY,QAAQ,CAC5E,iBAAkB,EAAM,YAAY,SACpC,iBACA,oBACD,CACD,CACE,WAAc,CACP,EAAG,OAAO,SACb,EAAQ,OAAO,EAGnB,QAAU,GAAU,CACb,EAAG,OAAO,UACb,EAAQ,QAAS,EAAM,CACvB,EAAQ,OAAO,GAGnB,QAAU,GAAS,CACZ,EAAG,O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,GAAkB,EAAa,EAAM,UAAU,CAC/C,EAAM,UACN,IAAA,GAKL,CAlCK,EAAM,cAAgB,EAAM,UAWzB,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACpB,CAbQ,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAI,EACnB,EAAY,eACZ,6DACD,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
require(`../../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../../errors.cjs`),t=require(`../../../_utils/chain.cjs`),n=require(`../../_utils.cjs`),r=require(`../_api.cjs`),i=require(`../../_tracking-utilities.cjs`),a=require(`../constants.cjs`);let o=require(`viem`),s=require(`@solana/kit`);const c=3e3;function l({apiOptions:e}){return({transfer:n,updateListener:r})=>n.sourceChain.chainId===n.targetChain.chainId?t.isSolanaNamespace(n.sourceChain.chainId)?u({transfer:n,updateListener:r}):i.trackSameChainEvmTransfer({transfer:n,updateListener:r}):f({transfer:n,updateListener:r},e)}function u({transfer:e,updateListener:t}){let n=new AbortController,r=()=>n.abort();return e.status===`source-pending`?{cancel:r,result:d(e,t,n.signal)}:{cancel:r,result:Promise.resolve(e)}}async function d(t,r,i){let{txHash:o}=t.source;try{(0,s.assertIsSignature)(o)}catch{let n={...t,errorCode:e.ErrorCode.INVALID_PARAMS,failedAtMs:Date.now(),status:`failed`};return r(n),n}let c=n.getSolanaRpcForChain({chain:t.sourceChain}),l=Date.now();for(;!i.aborted;){if(Date.now()-l>a.SOLANA_TX_TIMEOUT_MS){let n={...t,errorCode:e.ErrorCode.TIMEOUT,failedAtMs:Date.now(),status:`failed`};return r(n),n}try{let{value:s}=await c.getSignatureStatuses([o],{searchTransactionHistory:!0}).send(),l=s[0];if(!l){await n.waitForTimeoutOrAbort({timeoutMs:a.SOLANA_POLLING_INTERVAL_MS,signal:i});continue}if(l.err!==null){let n={...t,errorCode:e.ErrorCode.TRANSACTION_REVERTED,failedAtMs:Date.now(),status:`failed`};return r(n),n}if(l.confirmationStatus===`finalized`){let e={...t,completedAtMs:Date.now(),source:{...t.source,confirmationCount:t.source.requiredConfirmationCount},status:`completed`,target:null};return r(e),e}let u=Number(l.confirmations??0),d=Math.min(u,t.source.requiredConfirmationCount-1);d!==t.source.confirmationCount&&(t={...t,source:{...t.source,confirmationCount:d}},r(t)),await n.waitForTimeoutOrAbort({timeoutMs:a.SOLANA_POLLING_INTERVAL_MS,signal:i})}catch(e){let i={...t,errorCode:n.getErrorCodeForSolanaRpcError(e),failedAtMs:Date.now(),status:`failed`};return r(i),i}}return t}function f({transfer:e,updateListener:t},n){let r=new AbortController;return{cancel:()=>{r.abort()},result:(async()=>{let i=structuredClone(e);for(;!r.signal.aborted;){let e=await p(i,n,r.signal);if(r.signal.aborted)break;if(i=e,t(e),e.status===`completed`||e.status===`failed`)return e;await new Promise(e=>{let t=setTimeout(e,c);r.signal.addEventListener(`abort`,()=>clearTimeout(t),{once:!0})})}return i})()}}async function p(i,a,c){if(i.status===`completed`||i.status===`failed`)return i;if(!g(i.source.txHash,i.sourceChain.chainId))return{...i,errorCode:e.ErrorCode.INVALID_PARAMS,errorReason:`Invalid source transaction hash`,failedAtMs:Date.now(),status:`failed`};if(i.status===`source-pending`){if(t.isEvmNamespace(i.sourceChain.chainId)){let t=i.source.txHash;if(!(0,o.isHash)(t))return{...i,errorCode:e.ErrorCode.INVALID_PARAMS,errorReason:`Invalid source transaction hash`,failedAtMs:Date.now(),status:`failed`};let r=n.getEvmClientForChain({chain:i.sourceChain});try{let a=await n.awaitOrAbort(r.waitForTransactionReceipt({hash:t}),c);if(a.status===`aborted`)return i;let o=a.value;return o.status===`reverted`?{...i,errorCode:e.ErrorCode.TRANSACTION_REVERTED,errorReason:`Source transaction was reverted`,failedAtMs:Date.now(),status:`failed`}:(await m(r,o.blockNumber,c)).status===`aborted`?i:v(i)}catch(e){return{...i,errorCode:n.getErrorCodeForViemError(e),errorReason:`Failed to confirm source transaction finality`,failedAtMs:Date.now(),status:`failed`}}}if(t.isSolanaNamespace(i.sourceChain.chainId)){let t=i.source.txHash;try{(0,s.assertIsSignature)(t)}catch{return{...i,errorCode:e.ErrorCode.INVALID_PARAMS,errorReason:`Invalid source transaction hash`,failedAtMs:Date.now(),status:`failed`}}let n=await h(i.sourceChain,t,c);return n.status===`aborted`?i:n.status===`failed`?{...i,errorCode:n.errorCode,errorReason:`Failed to confirm source transaction finality`,failedAtMs:Date.now(),status:`failed`}:v(i)}}try{let t=await r.markrGetCrossChainStatus(a,i.source.txHash,{signal:c});switch(t.status){case`failed`:return{...
|
|
1
|
+
require(`../../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../../errors.cjs`),t=require(`../../../_utils/chain.cjs`),n=require(`../../_utils.cjs`),r=require(`../_api.cjs`),i=require(`../../_tracking-utilities.cjs`),a=require(`../constants.cjs`);let o=require(`viem`),s=require(`@solana/kit`);const c=3e3;function l({apiOptions:e}){return({transfer:n,updateListener:r})=>n.sourceChain.chainId===n.targetChain.chainId?t.isSolanaNamespace(n.sourceChain.chainId)?u({transfer:n,updateListener:r}):i.trackSameChainEvmTransfer({transfer:n,updateListener:r}):f({transfer:n,updateListener:r},e)}function u({transfer:e,updateListener:t}){let n=new AbortController,r=()=>n.abort();return e.status===`source-pending`?{cancel:r,result:d(e,t,n.signal)}:{cancel:r,result:Promise.resolve(e)}}async function d(t,r,i){let{txHash:o}=t.source;try{(0,s.assertIsSignature)(o)}catch{let n={...t,errorCode:e.ErrorCode.INVALID_PARAMS,failedAtMs:Date.now(),status:`failed`};return r(n),n}let c=n.getSolanaRpcForChain({chain:t.sourceChain}),l=Date.now();for(;!i.aborted;){if(Date.now()-l>a.SOLANA_TX_TIMEOUT_MS){let n={...t,errorCode:e.ErrorCode.TIMEOUT,failedAtMs:Date.now(),status:`failed`};return r(n),n}try{let{value:s}=await c.getSignatureStatuses([o],{searchTransactionHistory:!0}).send(),l=s[0];if(!l){await n.waitForTimeoutOrAbort({timeoutMs:a.SOLANA_POLLING_INTERVAL_MS,signal:i});continue}if(l.err!==null){let n={...t,errorCode:e.ErrorCode.TRANSACTION_REVERTED,failedAtMs:Date.now(),status:`failed`};return r(n),n}if(l.confirmationStatus===`finalized`){let e={...t,completedAtMs:Date.now(),source:{...t.source,confirmationCount:t.source.requiredConfirmationCount},status:`completed`,target:null};return r(e),e}let u=Number(l.confirmations??0),d=Math.min(u,t.source.requiredConfirmationCount-1);d!==t.source.confirmationCount&&(t={...t,source:{...t.source,confirmationCount:d}},r(t)),await n.waitForTimeoutOrAbort({timeoutMs:a.SOLANA_POLLING_INTERVAL_MS,signal:i})}catch(e){let i={...t,errorCode:n.getErrorCodeForSolanaRpcError(e),failedAtMs:Date.now(),status:`failed`};return r(i),i}}return t}function f({transfer:e,updateListener:t},n){let r=new AbortController;return{cancel:()=>{r.abort()},result:(async()=>{let i=structuredClone(e);for(;!r.signal.aborted;){let e=await p(i,n,r.signal);if(r.signal.aborted)break;if(i=e,t(e),e.status===`completed`||e.status===`failed`)return e;await new Promise(e=>{let t=setTimeout(e,c);r.signal.addEventListener(`abort`,()=>clearTimeout(t),{once:!0})})}return i})()}}async function p(i,a,c){if(i.status===`completed`||i.status===`failed`)return i;if(!g(i.source.txHash,i.sourceChain.chainId))return{...i,errorCode:e.ErrorCode.INVALID_PARAMS,errorReason:`Invalid source transaction hash`,failedAtMs:Date.now(),status:`failed`};if(i.status===`source-pending`){if(t.isEvmNamespace(i.sourceChain.chainId)){let t=i.source.txHash;if(!(0,o.isHash)(t))return{...i,errorCode:e.ErrorCode.INVALID_PARAMS,errorReason:`Invalid source transaction hash`,failedAtMs:Date.now(),status:`failed`};let r=n.getEvmClientForChain({chain:i.sourceChain});try{let a=await n.awaitOrAbort(r.waitForTransactionReceipt({hash:t}),c);if(a.status===`aborted`)return i;let o=a.value;return o.status===`reverted`?{...i,errorCode:e.ErrorCode.TRANSACTION_REVERTED,errorReason:`Source transaction was reverted`,failedAtMs:Date.now(),status:`failed`}:(await m(r,o.blockNumber,c)).status===`aborted`?i:v(i)}catch(e){return{...i,errorCode:n.getErrorCodeForViemError(e),errorReason:`Failed to confirm source transaction finality`,failedAtMs:Date.now(),status:`failed`}}}if(t.isSolanaNamespace(i.sourceChain.chainId)){let t=i.source.txHash;try{(0,s.assertIsSignature)(t)}catch{return{...i,errorCode:e.ErrorCode.INVALID_PARAMS,errorReason:`Invalid source transaction hash`,failedAtMs:Date.now(),status:`failed`}}let n=await h(i.sourceChain,t,c);return n.status===`aborted`?i:n.status===`failed`?{...i,errorCode:n.errorCode,errorReason:`Failed to confirm source transaction finality`,failedAtMs:Date.now(),status:`failed`}:v(i)}}try{let t=await r.markrGetCrossChainStatus(a,i.source.txHash,{signal:c}),n=y(i,t);switch(t.status){case`failed`:return{...n,errorCode:e.ErrorCode.TRANSACTION_REVERTED,errorReason:`Transaction execution failed.`,failedAtMs:C(t),status:`failed`};case`pending`:return _(t.sourceChain.finalized)?v(n):n;case`committed`:case`pending_execution`:return b(n,t);case`completed`:return x(n,t);default:return S(n,t)}}catch(t){return console.error(`[Unified Asset Transfer] Error fetching cross-chain status from Markr API`,{error:t,now:Date.now()}),{...i,errorCode:e.ErrorCode.UNKNOWN,errorReason:`Failed to fetch cross-chain tx status`,failedAtMs:Date.now(),status:`failed`}}}async function m(e,t,r){for(;!r.aborted;){let i=await n.awaitOrAbort(e.getBlock({blockTag:`finalized`}),r);if(i.status===`aborted`)return{status:`aborted`};if(i.value.number>=t)return{status:`ok`};await n.waitForTimeoutOrAbort({timeoutMs:c,signal:r})}return{status:`aborted`}}async function h(t,r,i){let o=n.getSolanaRpcForChain({chain:t}),s=Date.now();for(;!i.aborted;){if(Date.now()-s>a.SOLANA_TX_TIMEOUT_MS)return{status:`failed`,errorCode:e.ErrorCode.TIMEOUT};try{let{value:t}=await o.getSignatureStatuses([r],{searchTransactionHistory:!0}).send(),s=t[0];if(!s){await n.waitForTimeoutOrAbort({timeoutMs:a.SOLANA_POLLING_INTERVAL_MS,signal:i});continue}if(s.err!==null)return{status:`failed`,errorCode:e.ErrorCode.TRANSACTION_REVERTED};if(s.confirmationStatus===`finalized`)return{status:`ok`};await n.waitForTimeoutOrAbort({timeoutMs:a.SOLANA_POLLING_INTERVAL_MS,signal:i})}catch(e){return{status:`failed`,errorCode:n.getErrorCodeForSolanaRpcError(e)}}}return{status:`aborted`}}function g(e,n){if(t.isEvmNamespace(n))return(0,o.isHash)(e);if(t.isSolanaNamespace(n))try{return(0,s.assertIsSignature)(e),!0}catch{return!1}return!1}function _(e){return e===!0||typeof e==`string`}function v(e){return{...e,source:{...e.source,confirmationCount:2,requiredConfirmationCount:2},status:`source-completed`}}function y(e,t){let n={...e.metadata??{}};return t.destinationChain.bridgeHash&&(n.bridgeHash=t.destinationChain.bridgeHash),t.debug&&(n.debug=t.debug),Object.keys(n).length===0?e:{...e,metadata:n}}function b(e,t){let{timestamp:n,transactionHash:r}=t.destinationChain;return{...e,source:{...e.source,confirmationCount:2,requiredConfirmationCount:2},status:`target-pending`,target:{confirmationCount:r?1:0,requiredConfirmationCount:2,startedAtMs:n?new Date(n).getTime():Date.now(),txHash:r??void 0}}}function x(e,t){let{timestamp:n,transactionHash:r}=t.destinationChain;return{...e,completedAtMs:C(t),status:`completed`,source:{...e.source,confirmationCount:2,requiredConfirmationCount:2},target:r?{txHash:r,confirmationCount:2,requiredConfirmationCount:2,startedAtMs:n?new Date(n).getTime():Date.now()}:null}}function S(e,t){return t.progress.executed===!0?x(e,t):t.progress.committed===!0?b(e,t):_(t.sourceChain.finalized)?v(e):{...e,source:{...e.source,confirmationCount:0,requiredConfirmationCount:2},status:`source-pending`}}function C(e){return e.destinationChain.finalized?new Date(e.destinationChain.finalized).getTime():e.destinationChain.timestamp?new Date(e.destinationChain.timestamp).getTime():e.sourceChain.finalized?typeof e.sourceChain.finalized==`boolean`&&e.sourceChain.finalized===!0?new Date(e.sourceChain.timestamp).getTime():new Date(e.sourceChain.finalized).getTime():new Date(e.sourceChain.timestamp).getTime()}exports.trackTransferFactory=l;
|
|
2
2
|
//# sourceMappingURL=track-transfer.cjs.map
|