@avalabs/fusion-sdk 0.19.0 → 0.20.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 CHANGED
@@ -11,7 +11,7 @@ import { AbortedError, ErrorCode, ErrorReason, EstimateNativeFeeError, EstimateN
11
11
  import { CompletedTransfer, FailedTransfer, RefundedTransfer, SourceCompletedTransfer, SourcePendingTransfer, TargetPendingTransfer, Transfer, TransferBase, TransferSourceProgress, TransferStatus, TransferStepDetails, TransferTargetProgress } from "./types/transfer.cjs";
12
12
  import { SolanaSendOptions, SolanaTransactionParams } from "./utils/solana-transaction.cjs";
13
13
  import { BtcDispatch, BtcSign, BtcSigner, BtcTransactionRequest, EvmDispatch, EvmSign, EvmSignBatch, EvmSignMessage, EvmSignTypedData, EvmSigner, EvmSignerWithMessage, EvmTransactionRequest, EvmTypedData, Hex, SolanaSign, SolanaSigner } from "./types/signer.cjs";
14
- import { AssetSearchQuery, AvalancheCctInitializer, AvalancheSendTxFunction, AvalancheSendTxParams, EstimateNativeFeeOptions, EvmServiceInitializer, GasSettings, GetBridgeableAssetsProps, GetBridgeableAssetsResult, GetMinimumTransferAmountProps, GetSupportedChainsResult, LombardServiceInitializer, MarkrServiceInitializer, MutableGetSupportedChainsResult, NativeFeeEstimate, ServiceInitializer, TrackTransferProps, TransferAssetProps, TransferService } from "./types/service.cjs";
14
+ import { AssetSearchQuery, AvalancheCctInitializer, AvalancheSendTxFunction, AvalancheSendTxParams, EstimateNativeFeeOptions, EvmServiceInitializer, GasSettings, GetBridgeableAssetsProps, GetBridgeableAssetsResult, GetMinimumTransferAmountProps, GetSupportedChainsResult, LombardServiceInitializer, MarkrServiceInitializer, MutableGetSupportedChainsResult, NativeFeeEstimate, ServiceInitializer, ServiceQuoteOptions, TrackTransferProps, TransferAssetProps, TransferService } from "./types/service.cjs";
15
15
  import { AssetBridgeMap, CreateTransferManagerOptions, ServiceStatus, ServiceStatusBaseRecord, ServiceStatusErrorRecord, ServiceStatusInitializedRecord, ServiceStatusRecord, ServiceStatusUnsupportedEnvironmentRecord, TransferManager, TransferManagerStatus, TransferManagerStatusServicesRecord } from "./types/transfer-manager.cjs";
16
16
  import { isEnvironment, isErc20Asset, isEvmBridgeInitializer, isLombardServiceInitializer, isMarkrServiceInitializer, isNativeAsset, isServiceInitializer, isSplAsset } from "./type-guards.cjs";
17
17
  import { createTransferManager } from "./transfer-manager.cjs";
@@ -19,4 +19,4 @@ import { caip2ToEip155ChainId, caip2ToEip155HexChainId, eip155ChainIdToCaip2, is
19
19
  import { dedupeBridgeableAssets } from "./utils/bridgeable-assets.cjs";
20
20
  import { calculatePriceImpactFromQuote } from "./utils/price-impact.cjs";
21
21
  import { parseTransfer, stringifyTransfer } from "./utils/transfer-utils.cjs";
22
- export { AVALANCHE_CAIP2_TO_BLOCKCHAIN_ID_BY_NETWORK, AVALANCHE_FUJI_CHAIN, AVALANCHE_FUJI_P_CHAIN, AVALANCHE_FUJI_X_CHAIN, AVALANCHE_MAINNET_CHAIN, AVALANCHE_MAINNET_P_CHAIN, AVALANCHE_MAINNET_X_CHAIN, AbortedError, ArrayElement, Asset, AssetBridgeMap, AssetSearchQuery, AssetWithExtras, AvalancheBlockchainAlias, AvalancheCctInitializer, AvalancheChainIds, AvalancheFujiBlockchainChainIds, AvalancheFujiBlockchainIds, AvalancheMainnetBlockchainChainIds, AvalancheMainnetBlockchainIds, AvalancheSendTxFunction, AvalancheSendTxParams, BITCOIN_MAINNET_CHAIN, BITCOIN_TESTNET_CHAIN, BTC_SERVICE_TYPES, BitcoinChainIds, BitcoinFeeRateTier, BitcoinFunctions, BitcoinInputUTXO, BitcoinInputUTXOWithOptionalScript, BitcoinOutputUTXO, BitcoinTx, Blockchain, Brand, BridgeableAsset, BridgeableUiAsset, BtcDispatch, BtcSign, BtcSigner, BtcTransactionRequest, Caip10AccountId, Caip2ChainId, Chain, ChainAssetMap, CompletedTransfer, CreateTransferManagerOptions, DeepMutable, DestinationInfo, ERC_ZERO_ADDRESS, ETHEREUM_MAINNET_CHAIN, ETHEREUM_SEPOLIA_CHAIN, EVM_SERVICE_TYPES, Environment, Erc20Asset, ErrorCode, ErrorReason, EstimateNativeFeeError, type EstimateNativeFeeErrorDetails, EstimateNativeFeeOptions, EthereumChainIds, EvmChainId, EvmDispatch, EvmServiceInitializer, EvmSign, EvmSignBatch, EvmSignMessage, EvmSignTypedData, EvmSigner, EvmSignerWithMessage, EvmTransactionRequest, EvmTypedData, FEE_RATE_TIER_TO_BITCOIN, FailedTransfer, FeeRateTier, Fetch, GasSettings, type GetAtomicUtxosCallback, GetBridgeableAssetsProps, GetBridgeableAssetsResult, type GetCoreEthAddressCallback, GetMinimumTransferAmountProps, GetSupportedChainsResult, type GetUtxosCallback, type GetWalletAddressesForChainAliasCallback, type GetWalletChangeAddressForChainAliasCallback, Hex, HttpError, HyperliquidChainIds, InsufficientFundsError, InvalidParamsError, LombardServiceInitializer, MarkrServiceInitializer, Mutable, MutableGetSupportedChainsResult, NATIVE_AVAX, NATIVE_ETH, NATIVE_SOL_ADDRESS, NativeAsset, NativeFeeEstimate, Quote, QuoteFee, QuoteFeeFundingModel, QuoteFeeToken, QuoteFeeType, QuoteFees, QuoterDonePayload, QuoterDonePayloadNoEligibleServices, QuoterDonePayloadNoQuotes, QuoterDonePayloadUnsubscribed, QuoterDoneReason, QuoterEventArgs, QuoterEventHandler, QuoterInterface, QuoterProps, QuotesTuple, RefundedTransfer, ResponseValidationError, SOLANA_DEVNET_CHAIN, SOLANA_MAINNET_CHAIN, SdkError, ServiceInitializationError, ServiceInitializer, ServiceQuoteEventArgs, ServiceQuoteEventHandler, ServiceStatus, ServiceStatusBaseRecord, ServiceStatusErrorRecord, ServiceStatusInitializedRecord, ServiceStatusRecord, ServiceStatusUnsupportedEnvironmentRecord, ServiceType, ServiceUnavailableError, SolanaChainIds, SolanaSendOptions, SolanaSign, SolanaSigner, SolanaTransactionParams, SourceCompletedTransfer, SourcePendingTransfer, SplAsset, TargetPendingTransfer, TimeoutError, TokenType, TrackTransferProps, Transfer, TransferAssetProps, TransferBase, TransferManager, TransferManagerStatus, TransferManagerStatusServicesRecord, TransferService, TransferSignatureReason, TransferSourceProgress, TransferStatus, TransferStepDetails, TransferTargetProgress, TransferableAsset, caip2ToEip155ChainId, caip2ToEip155HexChainId, calculatePriceImpactFromQuote, createTransferManager, dedupeBridgeableAssets, eip155ChainIdToCaip2, isAbortedError, isCaip2ChainId, isEnvironment, isErc20Asset, isEstimateNativeFeeError, isEvmBridgeInitializer, isHttpError, isInsufficientFundsError, isInvalidParamsError, isLombardServiceInitializer, isMarkrServiceInitializer, isNativeAsset, isResponseValidationError, isSdkError, isServiceInitializationError, isServiceInitializer, isServiceUnavailableError, isSplAsset, isTimeoutError, parseTransfer, splitCaip2ChainId, stringifyTransfer };
22
+ export { AVALANCHE_CAIP2_TO_BLOCKCHAIN_ID_BY_NETWORK, AVALANCHE_FUJI_CHAIN, AVALANCHE_FUJI_P_CHAIN, AVALANCHE_FUJI_X_CHAIN, AVALANCHE_MAINNET_CHAIN, AVALANCHE_MAINNET_P_CHAIN, AVALANCHE_MAINNET_X_CHAIN, AbortedError, ArrayElement, Asset, AssetBridgeMap, AssetSearchQuery, AssetWithExtras, AvalancheBlockchainAlias, AvalancheCctInitializer, AvalancheChainIds, AvalancheFujiBlockchainChainIds, AvalancheFujiBlockchainIds, AvalancheMainnetBlockchainChainIds, AvalancheMainnetBlockchainIds, AvalancheSendTxFunction, AvalancheSendTxParams, BITCOIN_MAINNET_CHAIN, BITCOIN_TESTNET_CHAIN, BTC_SERVICE_TYPES, BitcoinChainIds, BitcoinFeeRateTier, BitcoinFunctions, BitcoinInputUTXO, BitcoinInputUTXOWithOptionalScript, BitcoinOutputUTXO, BitcoinTx, Blockchain, Brand, BridgeableAsset, BridgeableUiAsset, BtcDispatch, BtcSign, BtcSigner, BtcTransactionRequest, Caip10AccountId, Caip2ChainId, Chain, ChainAssetMap, CompletedTransfer, CreateTransferManagerOptions, DeepMutable, DestinationInfo, ERC_ZERO_ADDRESS, ETHEREUM_MAINNET_CHAIN, ETHEREUM_SEPOLIA_CHAIN, EVM_SERVICE_TYPES, Environment, Erc20Asset, ErrorCode, ErrorReason, EstimateNativeFeeError, type EstimateNativeFeeErrorDetails, EstimateNativeFeeOptions, EthereumChainIds, EvmChainId, EvmDispatch, EvmServiceInitializer, EvmSign, EvmSignBatch, EvmSignMessage, EvmSignTypedData, EvmSigner, EvmSignerWithMessage, EvmTransactionRequest, EvmTypedData, FEE_RATE_TIER_TO_BITCOIN, FailedTransfer, FeeRateTier, Fetch, GasSettings, type GetAtomicUtxosCallback, GetBridgeableAssetsProps, GetBridgeableAssetsResult, type GetCoreEthAddressCallback, GetMinimumTransferAmountProps, GetSupportedChainsResult, type GetUtxosCallback, type GetWalletAddressesForChainAliasCallback, type GetWalletChangeAddressForChainAliasCallback, Hex, HttpError, HyperliquidChainIds, InsufficientFundsError, InvalidParamsError, LombardServiceInitializer, MarkrServiceInitializer, Mutable, MutableGetSupportedChainsResult, NATIVE_AVAX, NATIVE_ETH, NATIVE_SOL_ADDRESS, NativeAsset, NativeFeeEstimate, Quote, QuoteFee, QuoteFeeFundingModel, QuoteFeeToken, QuoteFeeType, QuoteFees, QuoterDonePayload, QuoterDonePayloadNoEligibleServices, QuoterDonePayloadNoQuotes, QuoterDonePayloadUnsubscribed, QuoterDoneReason, QuoterEventArgs, QuoterEventHandler, QuoterInterface, QuoterProps, QuotesTuple, RefundedTransfer, ResponseValidationError, SOLANA_DEVNET_CHAIN, SOLANA_MAINNET_CHAIN, SdkError, ServiceInitializationError, ServiceInitializer, ServiceQuoteEventArgs, ServiceQuoteEventHandler, ServiceQuoteOptions, ServiceStatus, ServiceStatusBaseRecord, ServiceStatusErrorRecord, ServiceStatusInitializedRecord, ServiceStatusRecord, ServiceStatusUnsupportedEnvironmentRecord, ServiceType, ServiceUnavailableError, SolanaChainIds, SolanaSendOptions, SolanaSign, SolanaSigner, SolanaTransactionParams, SourceCompletedTransfer, SourcePendingTransfer, SplAsset, TargetPendingTransfer, TimeoutError, TokenType, TrackTransferProps, Transfer, TransferAssetProps, TransferBase, TransferManager, TransferManagerStatus, TransferManagerStatusServicesRecord, TransferService, TransferSignatureReason, TransferSourceProgress, TransferStatus, TransferStepDetails, TransferTargetProgress, TransferableAsset, caip2ToEip155ChainId, caip2ToEip155HexChainId, calculatePriceImpactFromQuote, createTransferManager, dedupeBridgeableAssets, eip155ChainIdToCaip2, isAbortedError, isCaip2ChainId, isEnvironment, isErc20Asset, isEstimateNativeFeeError, isEvmBridgeInitializer, isHttpError, isInsufficientFundsError, isInvalidParamsError, isLombardServiceInitializer, isMarkrServiceInitializer, isNativeAsset, isResponseValidationError, isSdkError, isServiceInitializationError, isServiceInitializer, isServiceUnavailableError, isSplAsset, isTimeoutError, parseTransfer, splitCaip2ChainId, stringifyTransfer };
package/dist/mod.d.ts CHANGED
@@ -11,7 +11,7 @@ import { AbortedError, ErrorCode, ErrorReason, EstimateNativeFeeError, EstimateN
11
11
  import { CompletedTransfer, FailedTransfer, RefundedTransfer, SourceCompletedTransfer, SourcePendingTransfer, TargetPendingTransfer, Transfer, TransferBase, TransferSourceProgress, TransferStatus, TransferStepDetails, TransferTargetProgress } from "./types/transfer.js";
12
12
  import { SolanaSendOptions, SolanaTransactionParams } from "./utils/solana-transaction.js";
13
13
  import { BtcDispatch, BtcSign, BtcSigner, BtcTransactionRequest, EvmDispatch, EvmSign, EvmSignBatch, EvmSignMessage, EvmSignTypedData, EvmSigner, EvmSignerWithMessage, EvmTransactionRequest, EvmTypedData, Hex, SolanaSign, SolanaSigner } from "./types/signer.js";
14
- import { AssetSearchQuery, AvalancheCctInitializer, AvalancheSendTxFunction, AvalancheSendTxParams, EstimateNativeFeeOptions, EvmServiceInitializer, GasSettings, GetBridgeableAssetsProps, GetBridgeableAssetsResult, GetMinimumTransferAmountProps, GetSupportedChainsResult, LombardServiceInitializer, MarkrServiceInitializer, MutableGetSupportedChainsResult, NativeFeeEstimate, ServiceInitializer, TrackTransferProps, TransferAssetProps, TransferService } from "./types/service.js";
14
+ import { AssetSearchQuery, AvalancheCctInitializer, AvalancheSendTxFunction, AvalancheSendTxParams, EstimateNativeFeeOptions, EvmServiceInitializer, GasSettings, GetBridgeableAssetsProps, GetBridgeableAssetsResult, GetMinimumTransferAmountProps, GetSupportedChainsResult, LombardServiceInitializer, MarkrServiceInitializer, MutableGetSupportedChainsResult, NativeFeeEstimate, ServiceInitializer, ServiceQuoteOptions, TrackTransferProps, TransferAssetProps, TransferService } from "./types/service.js";
15
15
  import { AssetBridgeMap, CreateTransferManagerOptions, ServiceStatus, ServiceStatusBaseRecord, ServiceStatusErrorRecord, ServiceStatusInitializedRecord, ServiceStatusRecord, ServiceStatusUnsupportedEnvironmentRecord, TransferManager, TransferManagerStatus, TransferManagerStatusServicesRecord } from "./types/transfer-manager.js";
16
16
  import { isEnvironment, isErc20Asset, isEvmBridgeInitializer, isLombardServiceInitializer, isMarkrServiceInitializer, isNativeAsset, isServiceInitializer, isSplAsset } from "./type-guards.js";
17
17
  import { createTransferManager } from "./transfer-manager.js";
@@ -19,4 +19,4 @@ import { caip2ToEip155ChainId, caip2ToEip155HexChainId, eip155ChainIdToCaip2, is
19
19
  import { dedupeBridgeableAssets } from "./utils/bridgeable-assets.js";
20
20
  import { calculatePriceImpactFromQuote } from "./utils/price-impact.js";
21
21
  import { parseTransfer, stringifyTransfer } from "./utils/transfer-utils.js";
22
- export { AVALANCHE_CAIP2_TO_BLOCKCHAIN_ID_BY_NETWORK, AVALANCHE_FUJI_CHAIN, AVALANCHE_FUJI_P_CHAIN, AVALANCHE_FUJI_X_CHAIN, AVALANCHE_MAINNET_CHAIN, AVALANCHE_MAINNET_P_CHAIN, AVALANCHE_MAINNET_X_CHAIN, AbortedError, ArrayElement, Asset, AssetBridgeMap, AssetSearchQuery, AssetWithExtras, AvalancheBlockchainAlias, AvalancheCctInitializer, AvalancheChainIds, AvalancheFujiBlockchainChainIds, AvalancheFujiBlockchainIds, AvalancheMainnetBlockchainChainIds, AvalancheMainnetBlockchainIds, AvalancheSendTxFunction, AvalancheSendTxParams, BITCOIN_MAINNET_CHAIN, BITCOIN_TESTNET_CHAIN, BTC_SERVICE_TYPES, BitcoinChainIds, BitcoinFeeRateTier, BitcoinFunctions, BitcoinInputUTXO, BitcoinInputUTXOWithOptionalScript, BitcoinOutputUTXO, BitcoinTx, Blockchain, Brand, BridgeableAsset, BridgeableUiAsset, BtcDispatch, BtcSign, BtcSigner, BtcTransactionRequest, Caip10AccountId, Caip2ChainId, Chain, ChainAssetMap, CompletedTransfer, CreateTransferManagerOptions, DeepMutable, DestinationInfo, ERC_ZERO_ADDRESS, ETHEREUM_MAINNET_CHAIN, ETHEREUM_SEPOLIA_CHAIN, EVM_SERVICE_TYPES, Environment, Erc20Asset, ErrorCode, ErrorReason, EstimateNativeFeeError, type EstimateNativeFeeErrorDetails, EstimateNativeFeeOptions, EthereumChainIds, EvmChainId, EvmDispatch, EvmServiceInitializer, EvmSign, EvmSignBatch, EvmSignMessage, EvmSignTypedData, EvmSigner, EvmSignerWithMessage, EvmTransactionRequest, EvmTypedData, FEE_RATE_TIER_TO_BITCOIN, FailedTransfer, FeeRateTier, Fetch, GasSettings, type GetAtomicUtxosCallback, GetBridgeableAssetsProps, GetBridgeableAssetsResult, type GetCoreEthAddressCallback, GetMinimumTransferAmountProps, GetSupportedChainsResult, type GetUtxosCallback, type GetWalletAddressesForChainAliasCallback, type GetWalletChangeAddressForChainAliasCallback, Hex, HttpError, HyperliquidChainIds, InsufficientFundsError, InvalidParamsError, LombardServiceInitializer, MarkrServiceInitializer, Mutable, MutableGetSupportedChainsResult, NATIVE_AVAX, NATIVE_ETH, NATIVE_SOL_ADDRESS, NativeAsset, NativeFeeEstimate, Quote, QuoteFee, QuoteFeeFundingModel, QuoteFeeToken, QuoteFeeType, QuoteFees, QuoterDonePayload, QuoterDonePayloadNoEligibleServices, QuoterDonePayloadNoQuotes, QuoterDonePayloadUnsubscribed, QuoterDoneReason, QuoterEventArgs, QuoterEventHandler, QuoterInterface, QuoterProps, QuotesTuple, RefundedTransfer, ResponseValidationError, SOLANA_DEVNET_CHAIN, SOLANA_MAINNET_CHAIN, SdkError, ServiceInitializationError, ServiceInitializer, ServiceQuoteEventArgs, ServiceQuoteEventHandler, ServiceStatus, ServiceStatusBaseRecord, ServiceStatusErrorRecord, ServiceStatusInitializedRecord, ServiceStatusRecord, ServiceStatusUnsupportedEnvironmentRecord, ServiceType, ServiceUnavailableError, SolanaChainIds, SolanaSendOptions, SolanaSign, SolanaSigner, SolanaTransactionParams, SourceCompletedTransfer, SourcePendingTransfer, SplAsset, TargetPendingTransfer, TimeoutError, TokenType, TrackTransferProps, Transfer, TransferAssetProps, TransferBase, TransferManager, TransferManagerStatus, TransferManagerStatusServicesRecord, TransferService, TransferSignatureReason, TransferSourceProgress, TransferStatus, TransferStepDetails, TransferTargetProgress, TransferableAsset, caip2ToEip155ChainId, caip2ToEip155HexChainId, calculatePriceImpactFromQuote, createTransferManager, dedupeBridgeableAssets, eip155ChainIdToCaip2, isAbortedError, isCaip2ChainId, isEnvironment, isErc20Asset, isEstimateNativeFeeError, isEvmBridgeInitializer, isHttpError, isInsufficientFundsError, isInvalidParamsError, isLombardServiceInitializer, isMarkrServiceInitializer, isNativeAsset, isResponseValidationError, isSdkError, isServiceInitializationError, isServiceInitializer, isServiceUnavailableError, isSplAsset, isTimeoutError, parseTransfer, splitCaip2ChainId, stringifyTransfer };
22
+ export { AVALANCHE_CAIP2_TO_BLOCKCHAIN_ID_BY_NETWORK, AVALANCHE_FUJI_CHAIN, AVALANCHE_FUJI_P_CHAIN, AVALANCHE_FUJI_X_CHAIN, AVALANCHE_MAINNET_CHAIN, AVALANCHE_MAINNET_P_CHAIN, AVALANCHE_MAINNET_X_CHAIN, AbortedError, ArrayElement, Asset, AssetBridgeMap, AssetSearchQuery, AssetWithExtras, AvalancheBlockchainAlias, AvalancheCctInitializer, AvalancheChainIds, AvalancheFujiBlockchainChainIds, AvalancheFujiBlockchainIds, AvalancheMainnetBlockchainChainIds, AvalancheMainnetBlockchainIds, AvalancheSendTxFunction, AvalancheSendTxParams, BITCOIN_MAINNET_CHAIN, BITCOIN_TESTNET_CHAIN, BTC_SERVICE_TYPES, BitcoinChainIds, BitcoinFeeRateTier, BitcoinFunctions, BitcoinInputUTXO, BitcoinInputUTXOWithOptionalScript, BitcoinOutputUTXO, BitcoinTx, Blockchain, Brand, BridgeableAsset, BridgeableUiAsset, BtcDispatch, BtcSign, BtcSigner, BtcTransactionRequest, Caip10AccountId, Caip2ChainId, Chain, ChainAssetMap, CompletedTransfer, CreateTransferManagerOptions, DeepMutable, DestinationInfo, ERC_ZERO_ADDRESS, ETHEREUM_MAINNET_CHAIN, ETHEREUM_SEPOLIA_CHAIN, EVM_SERVICE_TYPES, Environment, Erc20Asset, ErrorCode, ErrorReason, EstimateNativeFeeError, type EstimateNativeFeeErrorDetails, EstimateNativeFeeOptions, EthereumChainIds, EvmChainId, EvmDispatch, EvmServiceInitializer, EvmSign, EvmSignBatch, EvmSignMessage, EvmSignTypedData, EvmSigner, EvmSignerWithMessage, EvmTransactionRequest, EvmTypedData, FEE_RATE_TIER_TO_BITCOIN, FailedTransfer, FeeRateTier, Fetch, GasSettings, type GetAtomicUtxosCallback, GetBridgeableAssetsProps, GetBridgeableAssetsResult, type GetCoreEthAddressCallback, GetMinimumTransferAmountProps, GetSupportedChainsResult, type GetUtxosCallback, type GetWalletAddressesForChainAliasCallback, type GetWalletChangeAddressForChainAliasCallback, Hex, HttpError, HyperliquidChainIds, InsufficientFundsError, InvalidParamsError, LombardServiceInitializer, MarkrServiceInitializer, Mutable, MutableGetSupportedChainsResult, NATIVE_AVAX, NATIVE_ETH, NATIVE_SOL_ADDRESS, NativeAsset, NativeFeeEstimate, Quote, QuoteFee, QuoteFeeFundingModel, QuoteFeeToken, QuoteFeeType, QuoteFees, QuoterDonePayload, QuoterDonePayloadNoEligibleServices, QuoterDonePayloadNoQuotes, QuoterDonePayloadUnsubscribed, QuoterDoneReason, QuoterEventArgs, QuoterEventHandler, QuoterInterface, QuoterProps, QuotesTuple, RefundedTransfer, ResponseValidationError, SOLANA_DEVNET_CHAIN, SOLANA_MAINNET_CHAIN, SdkError, ServiceInitializationError, ServiceInitializer, ServiceQuoteEventArgs, ServiceQuoteEventHandler, ServiceQuoteOptions, ServiceStatus, ServiceStatusBaseRecord, ServiceStatusErrorRecord, ServiceStatusInitializedRecord, ServiceStatusRecord, ServiceStatusUnsupportedEnvironmentRecord, ServiceType, ServiceUnavailableError, SolanaChainIds, SolanaSendOptions, SolanaSign, SolanaSigner, SolanaTransactionParams, SourceCompletedTransfer, SourcePendingTransfer, SplAsset, TargetPendingTransfer, TimeoutError, TokenType, TrackTransferProps, Transfer, TransferAssetProps, TransferBase, TransferManager, TransferManagerStatus, TransferManagerStatusServicesRecord, TransferService, TransferSignatureReason, TransferSourceProgress, TransferStatus, TransferStepDetails, TransferTargetProgress, TransferableAsset, caip2ToEip155ChainId, caip2ToEip155HexChainId, calculatePriceImpactFromQuote, createTransferManager, dedupeBridgeableAssets, eip155ChainIdToCaip2, isAbortedError, isCaip2ChainId, isEnvironment, isErc20Asset, isEstimateNativeFeeError, isEvmBridgeInitializer, isHttpError, isInsufficientFundsError, isInvalidParamsError, isLombardServiceInitializer, isMarkrServiceInitializer, isNativeAsset, isResponseValidationError, isSdkError, isServiceInitializationError, isServiceInitializer, isServiceUnavailableError, isSplAsset, isTimeoutError, parseTransfer, splitCaip2ChainId, stringifyTransfer };
@@ -1,2 +1,2 @@
1
- require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../constants.cjs`),t=require(`../type-guards.cjs`),n=require(`./_utils.cjs`),r=require(`./constants.cjs`);let i=require(`zod`),a=require(`viem`);var o=class{clock;props;pruneIntervalMs;transferServices;refreshBufferSeconds;quotes=[];subscribers=new Set;started=!1;done=!1;isStartingFromSubscribe=!1;pruneTimerId=null;lastBestId=null;hasReceivedAnyQuote=!1;id=crypto.randomUUID();serviceState=new Map;constructor(e,t,n={}){this.clock=n.clock??(()=>Math.floor(Date.now()/1e3)),this.props=e,this.pruneIntervalMs=n.pruneIntervalMs??1e3,this.transferServices=t,this.refreshBufferSeconds=n.refreshBufferSeconds??5}getQuotes(){let e=this.clock(),t=n.sortQuotes(n.pruneExpiredQuotes({quotes:this.quotes,nowSeconds:e}));return[t[0]??null,t]}subscribe(e){this.subscribers.add(e);let t=!1;if(!this.started){this.isStartingFromSubscribe=!0;try{this.start()}finally{this.isStartingFromSubscribe=!1}}return()=>{if(!t){if(t=!0,this.done){this.subscribers.delete(e);return}if(this.subscribers.size===1&&this.subscribers.has(e)){this.complete(`unsubscribed`);return}this.subscribers.delete(e)}}}start(){if(this.started=!0,this.done=!1,this.quotes=[],this.lastBestId=null,this.hasReceivedAnyQuote=!1,c(this.props)){this.complete(`no-eligible-services`);return}let e=!1;for(let t of this.transferServices)t.analyzeSupport({sourceAsset:this.props.sourceAsset,sourceChainId:this.props.sourceChain.chainId,targetAsset:this.props.targetAsset,targetChainId:this.props.targetChain.chainId})&&(e=!0,this.startStreamForService(t));if(!e){this.complete(`no-eligible-services`);return}this.pruneTimerId=setInterval(()=>this.onPruneTick(),this.pruneIntervalMs)}stop(){this.started=!1,this.pruneTimerId&&=(clearInterval(this.pruneTimerId),null);for(let[e,t]of this.serviceState){try{t.cancel()}catch{}t.refreshTimer&&clearTimeout(t.refreshTimer),t.retryTimer&&clearTimeout(t.retryTimer),this.serviceState.set(e,{cancel:()=>{},done:!1,hasErrored:!1,hasReturnedQuote:!1,retryAttempt:0,retryTimer:null,refreshTimer:null,refreshAtSeconds:null})}}startStreamForService(e){let t=this.serviceState.get(e.type);if(t){try{t.cancel()}catch{}t.refreshTimer&&clearTimeout(t.refreshTimer),t.retryTimer&&clearTimeout(t.retryTimer)}let n=this.makeServiceHandler(e.type),r=[],i=!0,{cancel:a}=e.streamQuotes(this.props,(...e)=>{if(i){r.push(e);return}n(...e)});i=!1,r.length>0&&queueMicrotask(()=>{for(let e of r)n(...e)}),this.serviceState.set(e.type,{cancel:a,done:!1,hasErrored:!1,hasReturnedQuote:!1,retryAttempt:t?.retryAttempt??0,retryTimer:null,refreshTimer:null,refreshAtSeconds:null})}makeServiceHandler(e){return(t,...n)=>{if(this.started){if(t===`quote`){let t=n[0];if(l(t)){if(t.serviceType!==e)return;let n=this.serviceState.get(e);n&&(n.hasReturnedQuote=!0),this.onIncomingQuote(t),this.scheduleServiceRefresh(e)}return}if(t===`done`){this.onServiceDone(e);return}if(t===`error`){let t=this.serviceState.get(e);t&&(t.hasErrored=!0);let r=n[0];r instanceof Error&&this.emitError(r)}}}}onIncomingQuote(e){let t=this.clock();if(n.isQuoteExpired({quote:e,nowSeconds:t}))return;this.hasReceivedAnyQuote=!0,this.resetRetryForService(e.serviceType),this.quotes=n.sortQuotes(n.pruneExpiredQuotes({quotes:n.upsertQuote(this.quotes,e),nowSeconds:t}));let r=this.quotes[0];r&&(this.lastBestId=r.id,this.emitQuote({bestQuote:r,quote:e,quotes:this.quotes}))}resetRetryForService(e){let t=this.serviceState.get(e);t&&(t.retryAttempt=0,t.retryTimer&&=(clearTimeout(t.retryTimer),null))}scheduleServiceRetry(e){let t=this.serviceState.get(e);if(!t)return;t.retryTimer&&=(clearTimeout(t.retryTimer),null);let n=Math.min(r.QUOTER_EMPTY_RETRY_MAX_DELAY_MS,r.QUOTER_EMPTY_RETRY_BASE_DELAY_MS*2**t.retryAttempt);t.retryAttempt+=1,t.retryTimer=setTimeout(()=>{let t=this.serviceState.get(e);if(t&&(t.retryTimer=null),!this.started)return;let n=this.transferServices.find(t=>t.type===e);n&&this.startStreamForService(n)},Math.max(0,n))}onServiceDone(e){let t=this.serviceState.get(e);t&&(t.done=!0,this.scheduleServiceRefresh(e),this.hasReceivedAnyQuote&&!t.hasErrored&&!t.hasReturnedQuote&&this.scheduleServiceRetry(e),this.maybeCompleteNoQuotes())}maybeCompleteNoQuotes(){!this.started||this.done||this.hasReceivedAnyQuote||this.serviceState.size===0||[...this.serviceState.values()].every(e=>e.done)&&this.complete(`no-quotes`)}complete(e){if(this.done)return;let t=this.makeDonePayload(e);if(this.done=!0,this.stop(),this.isStartingFromSubscribe){queueMicrotask(()=>{let e=[...this.subscribers];this.subscribers.clear();for(let n of e)n(`done`,t)});return}let n=[...this.subscribers];this.subscribers.clear();for(let e of n)e(`done`,t)}getInitializedServices(){return[...new Set(this.transferServices.map(e=>e.type))]}getEligibleServices(){return[...this.serviceState.keys()]}makeDonePayload(e){if(e===`unsubscribed`)return{reason:e,data:void 0};let t=this.getInitializedServices();return e===`no-eligible-services`?{reason:e,data:{initializedServices:t,quoterProps:this.props}}:{reason:e,data:{eligibleServices:this.getEligibleServices(),initializedServices:t,quoterProps:this.props}}}onPruneTick(){let e=this.clock(),t=n.pruneExpiredQuotes({quotes:this.quotes,nowSeconds:e});if(t.length!==this.quotes.length){this.quotes=n.sortQuotes(t);let e=this.quotes[0]??null,r=e?e.id:null;e&&r!==this.lastBestId?(this.lastBestId=r,this.emitQuote({bestQuote:e,quote:e,quotes:this.quotes})):e||(this.lastBestId=null)}for(let e of this.transferServices)this.serviceState.has(e.type)&&this.scheduleServiceRefresh(e.type)}scheduleServiceRefresh(e){let t=this.serviceState.get(e);if(!t)return;let r=this.clock(),i=n.earliestExpirationForService({quotes:this.quotes,serviceType:e,nowSeconds:r});if(i===null){t.refreshTimer&&=(clearTimeout(t.refreshTimer),null),t.refreshAtSeconds=null;return}let a=Math.max(0,i-this.refreshBufferSeconds);if(a<=r||t.refreshAtSeconds===a&&t.refreshTimer)return;t.refreshTimer&&clearTimeout(t.refreshTimer);let o=Math.max(0,(a-r)*1e3);t.refreshAtSeconds=a,t.refreshTimer=setTimeout(()=>{let t=this.serviceState.get(e);t&&(t.refreshTimer=null,t.refreshAtSeconds=null);let n=this.transferServices.find(t=>t.type===e);n&&this.startStreamForService(n)},o)}emitQuote(e){for(let t of this.subscribers)t(`quote`,e)}emitError(e){for(let t of this.subscribers)t(`error`,e)}};const s=i.z.object({id:i.z.string(),expiresAt:i.z.number().int().nonnegative(),amountOut:i.z.bigint().nonnegative(),amountIn:i.z.bigint().nonnegative(),serviceType:i.z.string()});function c(n){let{sourceAsset:r,sourceChain:i,targetAsset:o,targetChain:s}=n;return i.chainId===s.chainId?t.isNativeAsset(r)&&t.isNativeAsset(o)?!0:r.type===o.type?r.type===e.TokenType.ERC20&&o.type===e.TokenType.ERC20?(0,a.isAddressEqual)(r.address,o.address):r.type===e.TokenType.SPL&&o.type===e.TokenType.SPL?r.address===o.address:!1:!1:!1}function l(e){return s.safeParse(e).success}exports.Quoter=o;
1
+ require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../constants.cjs`),t=require(`../type-guards.cjs`),n=require(`./_utils.cjs`),r=require(`./constants.cjs`);let i=require(`zod`),a=require(`viem`);var o=class{clock;props;pruneIntervalMs;serviceQuoteOptions;transferServices;refreshBufferSeconds;quotes=[];subscribers=new Set;started=!1;done=!1;isStartingFromSubscribe=!1;pruneTimerId=null;lastBestId=null;hasReceivedAnyQuote=!1;id=crypto.randomUUID();serviceState=new Map;constructor(e,t,n={}){this.clock=n.clock??(()=>Math.floor(Date.now()/1e3)),this.props=e,this.pruneIntervalMs=n.pruneIntervalMs??1e3,this.serviceQuoteOptions={dangerouslyAllowAddressMismatch:n.dangerouslyAllowAddressMismatch},this.transferServices=t,this.refreshBufferSeconds=n.refreshBufferSeconds??5}getQuotes(){let e=this.clock(),t=n.sortQuotes(n.pruneExpiredQuotes({quotes:this.quotes,nowSeconds:e}));return[t[0]??null,t]}subscribe(e){this.subscribers.add(e);let t=!1;if(!this.started){this.isStartingFromSubscribe=!0;try{this.start()}finally{this.isStartingFromSubscribe=!1}}return()=>{if(!t){if(t=!0,this.done){this.subscribers.delete(e);return}if(this.subscribers.size===1&&this.subscribers.has(e)){this.complete(`unsubscribed`);return}this.subscribers.delete(e)}}}start(){if(this.started=!0,this.done=!1,this.quotes=[],this.lastBestId=null,this.hasReceivedAnyQuote=!1,c(this.props)){this.complete(`no-eligible-services`);return}let e=!1;for(let t of this.transferServices)t.analyzeSupport({sourceAsset:this.props.sourceAsset,sourceChainId:this.props.sourceChain.chainId,targetAsset:this.props.targetAsset,targetChainId:this.props.targetChain.chainId})&&(e=!0,this.startStreamForService(t));if(!e){this.complete(`no-eligible-services`);return}this.pruneTimerId=setInterval(()=>this.onPruneTick(),this.pruneIntervalMs)}stop(){this.started=!1,this.pruneTimerId&&=(clearInterval(this.pruneTimerId),null);for(let[e,t]of this.serviceState){try{t.cancel()}catch{}t.refreshTimer&&clearTimeout(t.refreshTimer),t.retryTimer&&clearTimeout(t.retryTimer),this.serviceState.set(e,{cancel:()=>{},done:!1,hasErrored:!1,hasReturnedQuote:!1,retryAttempt:0,retryTimer:null,refreshTimer:null,refreshAtSeconds:null})}}startStreamForService(e){let t=this.serviceState.get(e.type);if(t){try{t.cancel()}catch{}t.refreshTimer&&clearTimeout(t.refreshTimer),t.retryTimer&&clearTimeout(t.retryTimer)}let n=this.makeServiceHandler(e.type),r=[],i=!0,{cancel:a}=e.streamQuotes(this.props,(...e)=>{if(i){r.push(e);return}n(...e)},this.serviceQuoteOptions);i=!1,r.length>0&&queueMicrotask(()=>{for(let e of r)n(...e)}),this.serviceState.set(e.type,{cancel:a,done:!1,hasErrored:!1,hasReturnedQuote:!1,retryAttempt:t?.retryAttempt??0,retryTimer:null,refreshTimer:null,refreshAtSeconds:null})}makeServiceHandler(e){return(t,...n)=>{if(this.started){if(t===`quote`){let t=n[0];if(l(t)){if(t.serviceType!==e)return;let n=this.serviceState.get(e);n&&(n.hasReturnedQuote=!0),this.onIncomingQuote(t),this.scheduleServiceRefresh(e)}return}if(t===`done`){this.onServiceDone(e);return}if(t===`error`){let t=this.serviceState.get(e);t&&(t.hasErrored=!0);let r=n[0];r instanceof Error&&this.emitError(r)}}}}onIncomingQuote(e){let t=this.clock();if(n.isQuoteExpired({quote:e,nowSeconds:t}))return;this.hasReceivedAnyQuote=!0,this.resetRetryForService(e.serviceType),this.quotes=n.sortQuotes(n.pruneExpiredQuotes({quotes:n.upsertQuote(this.quotes,e),nowSeconds:t}));let r=this.quotes[0];r&&(this.lastBestId=r.id,this.emitQuote({bestQuote:r,quote:e,quotes:this.quotes}))}resetRetryForService(e){let t=this.serviceState.get(e);t&&(t.retryAttempt=0,t.retryTimer&&=(clearTimeout(t.retryTimer),null))}scheduleServiceRetry(e){let t=this.serviceState.get(e);if(!t)return;t.retryTimer&&=(clearTimeout(t.retryTimer),null);let n=Math.min(r.QUOTER_EMPTY_RETRY_MAX_DELAY_MS,r.QUOTER_EMPTY_RETRY_BASE_DELAY_MS*2**t.retryAttempt);t.retryAttempt+=1,t.retryTimer=setTimeout(()=>{let t=this.serviceState.get(e);if(t&&(t.retryTimer=null),!this.started)return;let n=this.transferServices.find(t=>t.type===e);n&&this.startStreamForService(n)},Math.max(0,n))}onServiceDone(e){let t=this.serviceState.get(e);t&&(t.done=!0,this.scheduleServiceRefresh(e),this.hasReceivedAnyQuote&&!t.hasErrored&&!t.hasReturnedQuote&&this.scheduleServiceRetry(e),this.maybeCompleteNoQuotes())}maybeCompleteNoQuotes(){!this.started||this.done||this.hasReceivedAnyQuote||this.serviceState.size===0||[...this.serviceState.values()].every(e=>e.done)&&this.complete(`no-quotes`)}complete(e){if(this.done)return;let t=this.makeDonePayload(e);if(this.done=!0,this.stop(),this.isStartingFromSubscribe){queueMicrotask(()=>{let e=[...this.subscribers];this.subscribers.clear();for(let n of e)n(`done`,t)});return}let n=[...this.subscribers];this.subscribers.clear();for(let e of n)e(`done`,t)}getInitializedServices(){return[...new Set(this.transferServices.map(e=>e.type))]}getEligibleServices(){return[...this.serviceState.keys()]}makeDonePayload(e){if(e===`unsubscribed`)return{reason:e,data:void 0};let t=this.getInitializedServices();return e===`no-eligible-services`?{reason:e,data:{initializedServices:t,quoterProps:this.props}}:{reason:e,data:{eligibleServices:this.getEligibleServices(),initializedServices:t,quoterProps:this.props}}}onPruneTick(){let e=this.clock(),t=n.pruneExpiredQuotes({quotes:this.quotes,nowSeconds:e});if(t.length!==this.quotes.length){this.quotes=n.sortQuotes(t);let e=this.quotes[0]??null,r=e?e.id:null;e&&r!==this.lastBestId?(this.lastBestId=r,this.emitQuote({bestQuote:e,quote:e,quotes:this.quotes})):e||(this.lastBestId=null)}for(let e of this.transferServices)this.serviceState.has(e.type)&&this.scheduleServiceRefresh(e.type)}scheduleServiceRefresh(e){let t=this.serviceState.get(e);if(!t)return;let r=this.clock(),i=n.earliestExpirationForService({quotes:this.quotes,serviceType:e,nowSeconds:r});if(i===null){t.refreshTimer&&=(clearTimeout(t.refreshTimer),null),t.refreshAtSeconds=null;return}let a=Math.max(0,i-this.refreshBufferSeconds);if(a<=r||t.refreshAtSeconds===a&&t.refreshTimer)return;t.refreshTimer&&clearTimeout(t.refreshTimer);let o=Math.max(0,(a-r)*1e3);t.refreshAtSeconds=a,t.refreshTimer=setTimeout(()=>{let t=this.serviceState.get(e);t&&(t.refreshTimer=null,t.refreshAtSeconds=null);let n=this.transferServices.find(t=>t.type===e);n&&this.startStreamForService(n)},o)}emitQuote(e){for(let t of this.subscribers)t(`quote`,e)}emitError(e){for(let t of this.subscribers)t(`error`,e)}};const s=i.z.object({id:i.z.string(),expiresAt:i.z.number().int().nonnegative(),amountOut:i.z.bigint().nonnegative(),amountIn:i.z.bigint().nonnegative(),serviceType:i.z.string()});function c(n){let{sourceAsset:r,sourceChain:i,targetAsset:o,targetChain:s}=n;return i.chainId===s.chainId?t.isNativeAsset(r)&&t.isNativeAsset(o)?!0:r.type===o.type?r.type===e.TokenType.ERC20&&o.type===e.TokenType.ERC20?(0,a.isAddressEqual)(r.address,o.address):r.type===e.TokenType.SPL&&o.type===e.TokenType.SPL?r.address===o.address:!1:!1:!1}function l(e){return s.safeParse(e).success}exports.Quoter=o;
2
2
  //# sourceMappingURL=quoter.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"quoter.cjs","names":["sortQuotes","pruneExpiredQuotes","isQuoteExpired","upsertQuote","QUOTER_EMPTY_RETRY_MAX_DELAY_MS","QUOTER_EMPTY_RETRY_BASE_DELAY_MS","earliestExpirationForService","z","isNativeAsset","TokenType"],"sources":["../../src/quoter/quoter.ts"],"sourcesContent":["import { z } from 'zod';\nimport type {\n Quote,\n QuoterDonePayload,\n QuoterDoneReason,\n QuoterEventHandler,\n QuoterInterface,\n QuoterProps,\n ServiceQuoteEventArgs,\n QuotesTuple,\n ServiceQuoteEventHandler,\n} from '../types/quote';\nimport type { TransferService } from '../types/service';\nimport { earliestExpirationForService, isQuoteExpired, pruneExpiredQuotes, sortQuotes, upsertQuote } from './_utils';\nimport {\n QUOTER_DEFAULT_PRUNE_INTERVAL_MS,\n QUOTER_DEFAULT_REFRESH_BUFFER_SECONDS,\n QUOTER_EMPTY_RETRY_BASE_DELAY_MS,\n QUOTER_EMPTY_RETRY_MAX_DELAY_MS,\n} from './constants';\nimport { ServiceType, TokenType } from '../constants';\nimport { isNativeAsset } from '../type-guards';\nimport { isAddressEqual } from 'viem';\n\n/**\n * Function that returns the current UNIX time in seconds.\n * Injected for deterministic testing.\n */\nexport type Clock = () => number;\n\n/**\n * Options for constructing a Quoter instance.\n *\n * These options tune how often quote state is maintained and when services are\n * proactively restarted before quote expiry.\n */\nexport interface QuoterOptions {\n /** Clock function returning current time in seconds (defaults to Date.now()/1000). */\n readonly clock?: Clock;\n /** Interval for pruning expired quotes (milliseconds).\n *\n * @default 1_000\n */\n readonly pruneIntervalMs?: number;\n /**\n * Amount of seconds to pre-buffer a stream restart before the earliest service quote\n * expiration. Helps ensure continuity before actual expiry is reached.\n *\n * @default 5\n */\n readonly refreshBufferSeconds?: number;\n}\n\n/**\n * Quoter orchestrates quote streaming across multiple transfer services and emits a unified event stream.\n *\n * High-level lifecycle:\n * - Idle until first subscriber.\n * - On first subscribe, starts all eligible services.\n * - Collects and ranks active quotes, pruning expired ones over time.\n * - Completes when explicitly unsubscribed (last subscriber), when no service is eligible,\n * or when all eligible services finish without producing any quote (`no-quotes`).\n *\n * Event model:\n * - Service `quote` -> Quoter upserts quote, recomputes best quote, emits `quote`.\n * - Service `error` -> Quoter emits `error` (non-terminal by itself).\n * - Service `done` -> Quoter marks that service attempt as completed and evaluates retry/complete rules.\n *\n * Retry/refresh behavior:\n * - Refresh: services that have active quotes are restarted shortly before the earliest quote expires.\n * - Retry: services that complete with no quote and no error are only retried after the quoter has\n * already observed at least one quote from any service in this session.\n *\n * This design keeps first-pass \"no quotes anywhere\" terminal and fast, while still allowing services\n * like Markr to be retried in sessions where other providers are returning quotes.\n */\nexport class Quoter implements QuoterInterface {\n private readonly clock: Clock;\n private readonly props: QuoterProps;\n private readonly pruneIntervalMs: number;\n private readonly transferServices: readonly TransferService[];\n private readonly refreshBufferSeconds: number;\n\n private quotes: Quote[] = [];\n private subscribers: Set<QuoterEventHandler> = new Set();\n private started = false;\n private done = false;\n private isStartingFromSubscribe = false;\n private pruneTimerId: ReturnType<typeof setInterval> | null = null;\n private lastBestId: string | null = null;\n private hasReceivedAnyQuote = false;\n\n public readonly id: string = crypto.randomUUID();\n\n /**\n * Per-service runtime state for the active quote session.\n *\n * This tracks whether a service has completed, errored, produced quotes,\n * and any pending timers used for retry/refresh orchestration.\n */\n private serviceState: Map<\n TransferService['type'],\n {\n cancel: () => void;\n done: boolean;\n hasErrored: boolean;\n hasReturnedQuote: boolean;\n retryAttempt: number;\n retryTimer: ReturnType<typeof setTimeout> | null;\n refreshTimer: ReturnType<typeof setTimeout> | null;\n refreshAtSeconds: number | null;\n }\n > = new Map();\n\n /**\n * Create a new Quoter instance.\n *\n * @param props Quoting request parameters shared across all services.\n * @param transferServices Candidate services; eligibility is resolved at `start()` time.\n * @param options Optional runtime tuning for pruning and refresh behavior.\n */\n constructor(props: QuoterProps, transferServices: readonly TransferService[], options: QuoterOptions = {}) {\n this.clock = options.clock ?? (() => Math.floor(Date.now() / 1_000));\n this.props = props;\n this.pruneIntervalMs = options.pruneIntervalMs ?? QUOTER_DEFAULT_PRUNE_INTERVAL_MS;\n this.transferServices = transferServices;\n this.refreshBufferSeconds = options.refreshBufferSeconds ?? QUOTER_DEFAULT_REFRESH_BUFFER_SECONDS;\n }\n\n /**\n * Get the current best quote and all active quotes (sorted by desirability).\n */\n public getQuotes(): QuotesTuple {\n const now = this.clock();\n const active = pruneExpiredQuotes({ quotes: this.quotes, nowSeconds: now });\n const sorted = sortQuotes(active);\n const best = sorted[0] ?? null;\n\n return [best, sorted];\n }\n\n /**\n * Subscribe for quoter events.\n *\n * First subscriber lazily starts orchestration.\n * Last subscriber triggers terminal completion with reason `unsubscribed`.\n *\n * @returns Unsubscribe function (idempotent).\n */\n public subscribe(handler: QuoterEventHandler): () => void {\n this.subscribers.add(handler);\n let unsubscribed = false;\n\n if (!this.started) {\n this.isStartingFromSubscribe = true;\n try {\n this.start();\n } finally {\n this.isStartingFromSubscribe = false;\n }\n }\n\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n\n if (this.done) {\n this.subscribers.delete(handler);\n return;\n }\n\n const wasLastSubscriber = this.subscribers.size === 1 && this.subscribers.has(handler);\n if (wasLastSubscriber) {\n this.complete('unsubscribed');\n return;\n }\n\n this.subscribers.delete(handler);\n };\n }\n\n // ----- Internal orchestration -----\n\n /**\n * Start a fresh quote session.\n *\n * Resets session-local state, validates basic request viability,\n * starts streams for eligible services, and begins prune ticks.\n */\n private start(): void {\n this.started = true;\n this.done = false;\n this.quotes = [];\n this.lastBestId = null;\n this.hasReceivedAnyQuote = false;\n\n // Same-chain quotes for the *same* asset are not a valid transfer scenario.\n if (isInvalidSameChainQuoteRequest(this.props)) {\n this.complete('no-eligible-services');\n return;\n }\n\n let hasEligibleService = false;\n\n // Start streams for eligible services\n for (const svc of this.transferServices) {\n const eligible = svc.analyzeSupport({\n sourceAsset: this.props.sourceAsset,\n sourceChainId: this.props.sourceChain.chainId,\n targetAsset: this.props.targetAsset,\n targetChainId: this.props.targetChain.chainId,\n });\n\n if (!eligible) continue;\n hasEligibleService = true;\n\n this.startStreamForService(svc);\n }\n\n if (!hasEligibleService) {\n this.complete('no-eligible-services');\n return;\n }\n\n // Start periodic prune\n this.pruneTimerId = setInterval(() => this.onPruneTick(), this.pruneIntervalMs);\n }\n\n /**\n * Stop all streams and timers.\n * Quotes are retained for snapshot access via getQuotes(), though they\n * can still be pruned due to expiration.\n */\n private stop(): void {\n this.started = false;\n\n if (this.pruneTimerId) {\n clearInterval(this.pruneTimerId);\n this.pruneTimerId = null;\n }\n\n for (const [type, state] of this.serviceState) {\n try {\n state.cancel();\n } catch {\n /* ignore */\n }\n\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n }\n\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n }\n\n this.serviceState.set(type, {\n cancel: () => {},\n done: false,\n hasErrored: false,\n hasReturnedQuote: false,\n retryAttempt: 0,\n retryTimer: null,\n refreshTimer: null,\n refreshAtSeconds: null,\n });\n }\n }\n\n /**\n * Begin or restart streaming for a specific service.\n *\n * Any previous stream/timers for that service are canceled before starting a new attempt.\n */\n private startStreamForService(svc: TransferService): void {\n // Clean up any existing stream and refresh timer\n const existing = this.serviceState.get(svc.type);\n\n if (existing) {\n try {\n existing.cancel();\n } catch {\n /* ignore */\n }\n\n if (existing.refreshTimer) clearTimeout(existing.refreshTimer);\n if (existing.retryTimer) clearTimeout(existing.retryTimer);\n }\n\n const handler = this.makeServiceHandler(svc.type);\n const bufferedEvents: ServiceQuoteEventArgs[] = [];\n let isStartingStream = true;\n\n // Some services emit quote/done synchronously inside streamQuotes().\n // If those events run before subscribe() returns, consumers can hit TDZ\n // when they reference the returned unsubscribe function in their callback.\n // Buffer startup emissions and flush them after stream initialization.\n const guardedHandler: ServiceQuoteEventHandler = (...eventArgs) => {\n if (isStartingStream) {\n bufferedEvents.push(eventArgs);\n return;\n }\n\n handler(...eventArgs);\n };\n\n const { cancel } = svc.streamQuotes(this.props, guardedHandler);\n isStartingStream = false;\n\n if (bufferedEvents.length > 0) {\n // Use a microtask so subscribe() can return before the first callback fires.\n // This preserves event order while avoiding re-entrancy during subscription.\n queueMicrotask(() => {\n for (const bufferedEvent of bufferedEvents) {\n handler(...bufferedEvent);\n }\n });\n }\n\n this.serviceState.set(svc.type, {\n cancel,\n done: false,\n hasErrored: false,\n hasReturnedQuote: false,\n retryAttempt: existing?.retryAttempt ?? 0,\n retryTimer: null,\n refreshTimer: null,\n refreshAtSeconds: null,\n });\n }\n\n /**\n * Create the service-scoped event handler consumed by `TransferService.streamQuotes`.\n *\n * The handler enforces service/quote consistency and translates service events into\n * quoter state transitions.\n */\n private makeServiceHandler(serviceType: TransferService['type']): ServiceQuoteEventHandler {\n return (event, ...args) => {\n // Ignore any service events once stopped to prevent post-stop mutations.\n if (!this.started) {\n return;\n }\n if (event === 'quote') {\n const maybeQuote = args[0];\n if (isQuoteValue(maybeQuote)) {\n // Enforce the quote belongs to the emitting service\n if (maybeQuote.serviceType !== serviceType) {\n // Ignore quotes mismatched to service; defensive\n return;\n }\n const state = this.serviceState.get(serviceType);\n if (state) {\n state.hasReturnedQuote = true;\n }\n this.onIncomingQuote(maybeQuote);\n this.scheduleServiceRefresh(serviceType);\n }\n\n return;\n }\n if (event === 'done') {\n this.onServiceDone(serviceType);\n\n return;\n }\n if (event === 'error') {\n const state = this.serviceState.get(serviceType);\n if (state) {\n state.hasErrored = true;\n }\n const maybeErr = args[0];\n if (maybeErr instanceof Error) {\n this.emitError(maybeErr);\n }\n }\n };\n }\n\n /**\n * Handle an incoming quote event.\n *\n * Expired quotes are ignored. Valid quotes are upserted into active state,\n * then sorted/pruned and emitted to subscribers.\n */\n private onIncomingQuote(quote: Quote): void {\n const now = this.clock();\n\n if (isQuoteExpired({ quote, nowSeconds: now })) {\n return;\n }\n\n this.hasReceivedAnyQuote = true;\n\n this.resetRetryForService(quote.serviceType);\n\n this.quotes = sortQuotes(pruneExpiredQuotes({ quotes: upsertQuote(this.quotes, quote), nowSeconds: now }));\n\n // Always emit on every incoming quote\n const best = this.quotes[0];\n if (best) {\n this.lastBestId = best.id;\n this.emitQuote({ bestQuote: best, quote, quotes: this.quotes });\n }\n }\n\n private resetRetryForService(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n state.retryAttempt = 0;\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n state.retryTimer = null;\n }\n }\n\n /**\n * Schedule a retry attempt for a service using exponential backoff.\n *\n * This is used only for quote-less successful completions once the overall session\n * has already produced at least one quote from some service.\n */\n private scheduleServiceRetry(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n state.retryTimer = null;\n }\n\n const delayMs = Math.min(\n QUOTER_EMPTY_RETRY_MAX_DELAY_MS,\n QUOTER_EMPTY_RETRY_BASE_DELAY_MS * 2 ** state.retryAttempt,\n );\n state.retryAttempt += 1;\n\n state.retryTimer = setTimeout(\n () => {\n const current = this.serviceState.get(serviceType);\n if (current) {\n current.retryTimer = null;\n }\n\n if (!this.started) {\n return;\n }\n\n const svc = this.transferServices.find((s) => s.type === serviceType);\n if (svc) {\n this.startStreamForService(svc);\n }\n },\n Math.max(0, delayMs),\n );\n }\n\n /**\n * Handle service completion (`done`).\n *\n * A completion may schedule:\n * - refresh (if the service has active quotes), and/or\n * - retry (quote-less/non-error completion, but only after any quote has existed in session).\n *\n * Then evaluates whether the full quoter can complete with `no-quotes`.\n */\n private onServiceDone(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n state.done = true;\n this.scheduleServiceRefresh(serviceType);\n\n if (this.hasReceivedAnyQuote && !state.hasErrored && !state.hasReturnedQuote) {\n this.scheduleServiceRetry(serviceType);\n }\n\n this.maybeCompleteNoQuotes();\n }\n\n /**\n * Complete with `no-quotes` when every eligible service has finished and\n * no quote was ever observed during this session.\n */\n private maybeCompleteNoQuotes(): void {\n if (!this.started || this.done || this.hasReceivedAnyQuote || this.serviceState.size === 0) {\n return;\n }\n\n const allServicesDone = [...this.serviceState.values()].every((state) => state.done);\n\n if (allServicesDone) {\n this.complete('no-quotes');\n }\n }\n\n /**\n * Finalize the quoter session and broadcast terminal reason exactly once.\n */\n private complete(reason: QuoterDoneReason): void {\n if (this.done) {\n return;\n }\n\n const payload = this.makeDonePayload(reason);\n\n this.done = true;\n this.stop();\n\n // When complete() happens during subscribe()->start(), emit done on a microtask\n // so callers can safely reference the returned unsubscribe in their handler.\n if (this.isStartingFromSubscribe) {\n queueMicrotask(() => {\n const handlers = [...this.subscribers];\n this.subscribers.clear();\n\n for (const handler of handlers) {\n handler('done', payload);\n }\n });\n return;\n }\n\n const handlers = [...this.subscribers];\n this.subscribers.clear();\n\n for (const handler of handlers) {\n handler('done', payload);\n }\n }\n\n private getInitializedServices(): ServiceType[] {\n return [...new Set(this.transferServices.map((service) => service.type))];\n }\n\n private getEligibleServices(): ServiceType[] {\n return [...this.serviceState.keys()];\n }\n\n private makeDonePayload(reason: QuoterDoneReason): QuoterDonePayload {\n if (reason === 'unsubscribed') {\n return { reason, data: undefined };\n }\n\n const initializedServices = this.getInitializedServices();\n\n if (reason === 'no-eligible-services') {\n return {\n reason,\n data: {\n initializedServices,\n quoterProps: this.props,\n },\n };\n }\n\n return {\n reason,\n data: {\n eligibleServices: this.getEligibleServices(),\n initializedServices,\n quoterProps: this.props,\n },\n };\n }\n\n /** Periodic prune tick to evict expired quotes and emit best changes. */\n private onPruneTick(): void {\n const now = this.clock();\n const pruned = pruneExpiredQuotes({ quotes: this.quotes, nowSeconds: now });\n\n if (pruned.length !== this.quotes.length) {\n this.quotes = sortQuotes(pruned);\n const best = this.quotes[0] ?? null;\n const bestId = best ? best.id : null;\n\n if (best && bestId !== this.lastBestId) {\n this.lastBestId = bestId;\n this.emitQuote({ bestQuote: best, quote: best, quotes: this.quotes });\n } else if (!best) {\n this.lastBestId = null;\n }\n }\n\n // Re-evaluate refresh scheduling for all services on prune tick\n for (const svc of this.transferServices) {\n if (this.serviceState.has(svc.type)) {\n this.scheduleServiceRefresh(svc.type);\n }\n }\n }\n\n /** Schedule a refresh (restart) of streaming for the service at its earliest quote expiration. */\n private scheduleServiceRefresh(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) return;\n\n const now = this.clock();\n const earliest = earliestExpirationForService({ quotes: this.quotes, serviceType, nowSeconds: now });\n\n if (earliest === null) {\n // No quotes -> clear any pending refresh\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n state.refreshTimer = null;\n }\n state.refreshAtSeconds = null;\n return;\n }\n\n // Only reschedule if earlier than currently scheduled or no timer\n const targetAt = Math.max(0, earliest - this.refreshBufferSeconds);\n\n // If target time has already passed, do not schedule another refresh here.\n if (targetAt <= now) {\n return;\n }\n\n // Reschedule only when the desired refresh time changes (earlier OR later).\n // We key refresh off the soonest-expiring active quote for this service.\n if (state.refreshAtSeconds === targetAt && state.refreshTimer) {\n return;\n }\n\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n }\n\n const delayMs = Math.max(0, (targetAt - now) * 1_000);\n state.refreshAtSeconds = targetAt;\n state.refreshTimer = setTimeout(() => {\n // Clear timer/marker before restarting to avoid stale state if restart fails.\n const current = this.serviceState.get(serviceType);\n if (current) {\n current.refreshTimer = null;\n current.refreshAtSeconds = null;\n }\n\n // Restart stream and clear timer/marker\n const svc = this.transferServices.find((s) => s.type === serviceType);\n\n if (svc) {\n this.startStreamForService(svc);\n }\n }, delayMs);\n }\n\n // ----- Emission helpers -----\n /** Emit a quote event to all subscribers. */\n private emitQuote(payload: { bestQuote: Quote; quote: Quote; quotes: readonly Quote[] }): void {\n for (const handler of this.subscribers) {\n handler('quote', payload);\n }\n }\n\n /** Emit an error event to all subscribers. */\n private emitError(error: Error): void {\n for (const handler of this.subscribers) {\n handler('error', error);\n }\n }\n}\n\n/**\n * Zod schema to validate the minimal Quote fields used for runtime gating.\n *\n * This is a simple schema, and is not a fully safe runtime validate for Quote.\n * That isn't necessary here since we only need to verify basic structure before\n * using the quote in internal logic.\n *\n * @internal\n */\nconst QuoteSchema = z.object({\n id: z.string(),\n expiresAt: z.number().int().nonnegative(),\n amountOut: z.bigint().nonnegative(),\n amountIn: z.bigint().nonnegative(),\n serviceType: z.string(),\n});\n\nfunction isInvalidSameChainQuoteRequest(props: QuoterProps): boolean {\n const { sourceAsset, sourceChain, targetAsset, targetChain } = props;\n\n if (sourceChain.chainId !== targetChain.chainId) {\n return false;\n }\n\n // Native -> native on the same chain is a no-op.\n if (isNativeAsset(sourceAsset) && isNativeAsset(targetAsset)) {\n return true;\n }\n\n // If token types differ, it's potentially a swap on the same chain.\n if (sourceAsset.type !== targetAsset.type) {\n return false;\n }\n\n // Same token type and address on the same chain is a no-op.\n if (sourceAsset.type === TokenType.ERC20 && targetAsset.type === TokenType.ERC20) {\n return isAddressEqual(sourceAsset.address, targetAsset.address);\n }\n\n if (sourceAsset.type === TokenType.SPL && targetAsset.type === TokenType.SPL) {\n return sourceAsset.address === targetAsset.address;\n }\n\n return false;\n}\n\nfunction isQuoteValue(value: unknown): value is Quote {\n const result = QuoteSchema.safeParse(value);\n\n return result.success;\n}\n"],"mappings":"+MA4EA,IAAa,EAAb,KAA+C,CAC7C,MACA,MACA,gBACA,iBACA,qBAEA,OAA0B,EAAE,CAC5B,YAA+C,IAAI,IACnD,QAAkB,GAClB,KAAe,GACf,wBAAkC,GAClC,aAA8D,KAC9D,WAAoC,KACpC,oBAA8B,GAE9B,GAA6B,OAAO,YAAY,CAQhD,aAYI,IAAI,IASR,YAAY,EAAoB,EAA8C,EAAyB,EAAE,CAAE,CACzG,KAAK,MAAQ,EAAQ,YAAgB,KAAK,MAAM,KAAK,KAAK,CAAG,IAAM,EACnE,KAAK,MAAQ,EACb,KAAK,gBAAkB,EAAQ,iBAAA,IAC/B,KAAK,iBAAmB,EACxB,KAAK,qBAAuB,EAAQ,sBAAA,EAMtC,WA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,EAAM,KAAK,iBAAiB,KAAM,GAAM,EAAE,OAAS,EAAY,CAEjE,GACF,KAAK,sBAAsB,EAAI,EAEhC,EAAQ,CAKb,UAAkB,EAA6E,CAC7F,IAAK,IAAM,KAAW,KAAK,YACzB,EAAQ,QAAS,EAAQ,CAK7B,UAAkB,EAAoB,CACpC,IAAK,IAAM,KAAW,KAAK,YACzB,EAAQ,QAAS,EAAM,GAc7B,MAAM,EAAcC,EAAAA,EAAE,OAAO,CAC3B,GAAIA,EAAAA,EAAE,QAAQ,CACd,UAAWA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CACzC,UAAWA,EAAAA,EAAE,QAAQ,CAAC,aAAa,CACnC,SAAUA,EAAAA,EAAE,QAAQ,CAAC,aAAa,CAClC,YAAaA,EAAAA,EAAE,QAAQ,CACxB,CAAC,CAEF,SAAS,EAA+B,EAA6B,CACnE,GAAM,CAAE,cAAa,cAAa,cAAa,eAAgB,EAyB/D,OAvBI,EAAY,UAAY,EAAY,QAKpCC,EAAAA,cAAc,EAAY,EAAIA,EAAAA,cAAc,EAAY,CACnD,GAIL,EAAY,OAAS,EAAY,KAKjC,EAAY,OAASC,EAAAA,UAAU,OAAS,EAAY,OAASA,EAAAA,UAAU,OACzE,EAAA,EAAA,gBAAsB,EAAY,QAAS,EAAY,QAAQ,CAG7D,EAAY,OAASA,EAAAA,UAAU,KAAO,EAAY,OAASA,EAAAA,UAAU,IAChE,EAAY,UAAY,EAAY,QAGtC,GAZE,GAVA,GAyBX,SAAS,EAAa,EAAgC,CAGpD,OAFe,EAAY,UAAU,EAAM,CAE7B"}
1
+ {"version":3,"file":"quoter.cjs","names":["sortQuotes","pruneExpiredQuotes","isQuoteExpired","upsertQuote","QUOTER_EMPTY_RETRY_MAX_DELAY_MS","QUOTER_EMPTY_RETRY_BASE_DELAY_MS","earliestExpirationForService","z","isNativeAsset","TokenType"],"sources":["../../src/quoter/quoter.ts"],"sourcesContent":["import { z } from 'zod';\nimport type {\n Quote,\n QuoterDonePayload,\n QuoterDoneReason,\n QuoterEventHandler,\n QuoterInterface,\n QuoterProps,\n ServiceQuoteEventArgs,\n QuotesTuple,\n ServiceQuoteEventHandler,\n} from '../types/quote';\nimport type { ServiceQuoteOptions, TransferService } from '../types/service';\nimport { earliestExpirationForService, isQuoteExpired, pruneExpiredQuotes, sortQuotes, upsertQuote } from './_utils';\nimport {\n QUOTER_DEFAULT_PRUNE_INTERVAL_MS,\n QUOTER_DEFAULT_REFRESH_BUFFER_SECONDS,\n QUOTER_EMPTY_RETRY_BASE_DELAY_MS,\n QUOTER_EMPTY_RETRY_MAX_DELAY_MS,\n} from './constants';\nimport { ServiceType, TokenType } from '../constants';\nimport { isNativeAsset } from '../type-guards';\nimport { isAddressEqual } from 'viem';\n\n/**\n * Function that returns the current UNIX time in seconds.\n * Injected for deterministic testing.\n */\nexport type Clock = () => number;\n\n/**\n * Options for constructing a Quoter instance.\n *\n * These options tune how often quote state is maintained and when services are\n * proactively restarted before quote expiry.\n */\nexport interface QuoterOptions {\n /**\n * Dangerously allows cross-chain quotes where fromAddress and toAddress differ\n * even when a service would otherwise require them to match.\n *\n * This is intended for explicit proxy-recipient funding flows. By default,\n * services preserve their existing address safety checks.\n */\n readonly dangerouslyAllowAddressMismatch?: boolean;\n /** Clock function returning current time in seconds (defaults to Date.now()/1000). */\n readonly clock?: Clock;\n /** Interval for pruning expired quotes (milliseconds).\n *\n * @default 1_000\n */\n readonly pruneIntervalMs?: number;\n /**\n * Amount of seconds to pre-buffer a stream restart before the earliest service quote\n * expiration. Helps ensure continuity before actual expiry is reached.\n *\n * @default 5\n */\n readonly refreshBufferSeconds?: number;\n}\n\n/**\n * Quoter orchestrates quote streaming across multiple transfer services and emits a unified event stream.\n *\n * High-level lifecycle:\n * - Idle until first subscriber.\n * - On first subscribe, starts all eligible services.\n * - Collects and ranks active quotes, pruning expired ones over time.\n * - Completes when explicitly unsubscribed (last subscriber), when no service is eligible,\n * or when all eligible services finish without producing any quote (`no-quotes`).\n *\n * Event model:\n * - Service `quote` -> Quoter upserts quote, recomputes best quote, emits `quote`.\n * - Service `error` -> Quoter emits `error` (non-terminal by itself).\n * - Service `done` -> Quoter marks that service attempt as completed and evaluates retry/complete rules.\n *\n * Retry/refresh behavior:\n * - Refresh: services that have active quotes are restarted shortly before the earliest quote expires.\n * - Retry: services that complete with no quote and no error are only retried after the quoter has\n * already observed at least one quote from any service in this session.\n *\n * This design keeps first-pass \"no quotes anywhere\" terminal and fast, while still allowing services\n * like Markr to be retried in sessions where other providers are returning quotes.\n */\nexport class Quoter implements QuoterInterface {\n private readonly clock: Clock;\n private readonly props: QuoterProps;\n private readonly pruneIntervalMs: number;\n private readonly serviceQuoteOptions: ServiceQuoteOptions;\n private readonly transferServices: readonly TransferService[];\n private readonly refreshBufferSeconds: number;\n\n private quotes: Quote[] = [];\n private subscribers: Set<QuoterEventHandler> = new Set();\n private started = false;\n private done = false;\n private isStartingFromSubscribe = false;\n private pruneTimerId: ReturnType<typeof setInterval> | null = null;\n private lastBestId: string | null = null;\n private hasReceivedAnyQuote = false;\n\n public readonly id: string = crypto.randomUUID();\n\n /**\n * Per-service runtime state for the active quote session.\n *\n * This tracks whether a service has completed, errored, produced quotes,\n * and any pending timers used for retry/refresh orchestration.\n */\n private serviceState: Map<\n TransferService['type'],\n {\n cancel: () => void;\n done: boolean;\n hasErrored: boolean;\n hasReturnedQuote: boolean;\n retryAttempt: number;\n retryTimer: ReturnType<typeof setTimeout> | null;\n refreshTimer: ReturnType<typeof setTimeout> | null;\n refreshAtSeconds: number | null;\n }\n > = new Map();\n\n /**\n * Create a new Quoter instance.\n *\n * @param props Quoting request parameters shared across all services.\n * @param transferServices Candidate services; eligibility is resolved at `start()` time.\n * @param options Optional runtime tuning for pruning and refresh behavior.\n */\n constructor(props: QuoterProps, transferServices: readonly TransferService[], options: QuoterOptions = {}) {\n this.clock = options.clock ?? (() => Math.floor(Date.now() / 1_000));\n this.props = props;\n this.pruneIntervalMs = options.pruneIntervalMs ?? QUOTER_DEFAULT_PRUNE_INTERVAL_MS;\n this.serviceQuoteOptions = {\n dangerouslyAllowAddressMismatch: options.dangerouslyAllowAddressMismatch,\n };\n this.transferServices = transferServices;\n this.refreshBufferSeconds = options.refreshBufferSeconds ?? QUOTER_DEFAULT_REFRESH_BUFFER_SECONDS;\n }\n\n /**\n * Get the current best quote and all active quotes (sorted by desirability).\n */\n public getQuotes(): QuotesTuple {\n const now = this.clock();\n const active = pruneExpiredQuotes({ quotes: this.quotes, nowSeconds: now });\n const sorted = sortQuotes(active);\n const best = sorted[0] ?? null;\n\n return [best, sorted];\n }\n\n /**\n * Subscribe for quoter events.\n *\n * First subscriber lazily starts orchestration.\n * Last subscriber triggers terminal completion with reason `unsubscribed`.\n *\n * @returns Unsubscribe function (idempotent).\n */\n public subscribe(handler: QuoterEventHandler): () => void {\n this.subscribers.add(handler);\n let unsubscribed = false;\n\n if (!this.started) {\n this.isStartingFromSubscribe = true;\n try {\n this.start();\n } finally {\n this.isStartingFromSubscribe = false;\n }\n }\n\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n\n if (this.done) {\n this.subscribers.delete(handler);\n return;\n }\n\n const wasLastSubscriber = this.subscribers.size === 1 && this.subscribers.has(handler);\n if (wasLastSubscriber) {\n this.complete('unsubscribed');\n return;\n }\n\n this.subscribers.delete(handler);\n };\n }\n\n // ----- Internal orchestration -----\n\n /**\n * Start a fresh quote session.\n *\n * Resets session-local state, validates basic request viability,\n * starts streams for eligible services, and begins prune ticks.\n */\n private start(): void {\n this.started = true;\n this.done = false;\n this.quotes = [];\n this.lastBestId = null;\n this.hasReceivedAnyQuote = false;\n\n // Same-chain quotes for the *same* asset are not a valid transfer scenario.\n if (isInvalidSameChainQuoteRequest(this.props)) {\n this.complete('no-eligible-services');\n return;\n }\n\n let hasEligibleService = false;\n\n // Start streams for eligible services\n for (const svc of this.transferServices) {\n const eligible = svc.analyzeSupport({\n sourceAsset: this.props.sourceAsset,\n sourceChainId: this.props.sourceChain.chainId,\n targetAsset: this.props.targetAsset,\n targetChainId: this.props.targetChain.chainId,\n });\n\n if (!eligible) continue;\n hasEligibleService = true;\n\n this.startStreamForService(svc);\n }\n\n if (!hasEligibleService) {\n this.complete('no-eligible-services');\n return;\n }\n\n // Start periodic prune\n this.pruneTimerId = setInterval(() => this.onPruneTick(), this.pruneIntervalMs);\n }\n\n /**\n * Stop all streams and timers.\n * Quotes are retained for snapshot access via getQuotes(), though they\n * can still be pruned due to expiration.\n */\n private stop(): void {\n this.started = false;\n\n if (this.pruneTimerId) {\n clearInterval(this.pruneTimerId);\n this.pruneTimerId = null;\n }\n\n for (const [type, state] of this.serviceState) {\n try {\n state.cancel();\n } catch {\n /* ignore */\n }\n\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n }\n\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n }\n\n this.serviceState.set(type, {\n cancel: () => {},\n done: false,\n hasErrored: false,\n hasReturnedQuote: false,\n retryAttempt: 0,\n retryTimer: null,\n refreshTimer: null,\n refreshAtSeconds: null,\n });\n }\n }\n\n /**\n * Begin or restart streaming for a specific service.\n *\n * Any previous stream/timers for that service are canceled before starting a new attempt.\n */\n private startStreamForService(svc: TransferService): void {\n // Clean up any existing stream and refresh timer\n const existing = this.serviceState.get(svc.type);\n\n if (existing) {\n try {\n existing.cancel();\n } catch {\n /* ignore */\n }\n\n if (existing.refreshTimer) clearTimeout(existing.refreshTimer);\n if (existing.retryTimer) clearTimeout(existing.retryTimer);\n }\n\n const handler = this.makeServiceHandler(svc.type);\n const bufferedEvents: ServiceQuoteEventArgs[] = [];\n let isStartingStream = true;\n\n // Some services emit quote/done synchronously inside streamQuotes().\n // If those events run before subscribe() returns, consumers can hit TDZ\n // when they reference the returned unsubscribe function in their callback.\n // Buffer startup emissions and flush them after stream initialization.\n const guardedHandler: ServiceQuoteEventHandler = (...eventArgs) => {\n if (isStartingStream) {\n bufferedEvents.push(eventArgs);\n return;\n }\n\n handler(...eventArgs);\n };\n\n const { cancel } = svc.streamQuotes(this.props, guardedHandler, this.serviceQuoteOptions);\n isStartingStream = false;\n\n if (bufferedEvents.length > 0) {\n // Use a microtask so subscribe() can return before the first callback fires.\n // This preserves event order while avoiding re-entrancy during subscription.\n queueMicrotask(() => {\n for (const bufferedEvent of bufferedEvents) {\n handler(...bufferedEvent);\n }\n });\n }\n\n this.serviceState.set(svc.type, {\n cancel,\n done: false,\n hasErrored: false,\n hasReturnedQuote: false,\n retryAttempt: existing?.retryAttempt ?? 0,\n retryTimer: null,\n refreshTimer: null,\n refreshAtSeconds: null,\n });\n }\n\n /**\n * Create the service-scoped event handler consumed by `TransferService.streamQuotes`.\n *\n * The handler enforces service/quote consistency and translates service events into\n * quoter state transitions.\n */\n private makeServiceHandler(serviceType: TransferService['type']): ServiceQuoteEventHandler {\n return (event, ...args) => {\n // Ignore any service events once stopped to prevent post-stop mutations.\n if (!this.started) {\n return;\n }\n if (event === 'quote') {\n const maybeQuote = args[0];\n if (isQuoteValue(maybeQuote)) {\n // Enforce the quote belongs to the emitting service\n if (maybeQuote.serviceType !== serviceType) {\n // Ignore quotes mismatched to service; defensive\n return;\n }\n const state = this.serviceState.get(serviceType);\n if (state) {\n state.hasReturnedQuote = true;\n }\n this.onIncomingQuote(maybeQuote);\n this.scheduleServiceRefresh(serviceType);\n }\n\n return;\n }\n if (event === 'done') {\n this.onServiceDone(serviceType);\n\n return;\n }\n if (event === 'error') {\n const state = this.serviceState.get(serviceType);\n if (state) {\n state.hasErrored = true;\n }\n const maybeErr = args[0];\n if (maybeErr instanceof Error) {\n this.emitError(maybeErr);\n }\n }\n };\n }\n\n /**\n * Handle an incoming quote event.\n *\n * Expired quotes are ignored. Valid quotes are upserted into active state,\n * then sorted/pruned and emitted to subscribers.\n */\n private onIncomingQuote(quote: Quote): void {\n const now = this.clock();\n\n if (isQuoteExpired({ quote, nowSeconds: now })) {\n return;\n }\n\n this.hasReceivedAnyQuote = true;\n\n this.resetRetryForService(quote.serviceType);\n\n this.quotes = sortQuotes(pruneExpiredQuotes({ quotes: upsertQuote(this.quotes, quote), nowSeconds: now }));\n\n // Always emit on every incoming quote\n const best = this.quotes[0];\n if (best) {\n this.lastBestId = best.id;\n this.emitQuote({ bestQuote: best, quote, quotes: this.quotes });\n }\n }\n\n private resetRetryForService(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n state.retryAttempt = 0;\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n state.retryTimer = null;\n }\n }\n\n /**\n * Schedule a retry attempt for a service using exponential backoff.\n *\n * This is used only for quote-less successful completions once the overall session\n * has already produced at least one quote from some service.\n */\n private scheduleServiceRetry(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n state.retryTimer = null;\n }\n\n const delayMs = Math.min(\n QUOTER_EMPTY_RETRY_MAX_DELAY_MS,\n QUOTER_EMPTY_RETRY_BASE_DELAY_MS * 2 ** state.retryAttempt,\n );\n state.retryAttempt += 1;\n\n state.retryTimer = setTimeout(\n () => {\n const current = this.serviceState.get(serviceType);\n if (current) {\n current.retryTimer = null;\n }\n\n if (!this.started) {\n return;\n }\n\n const svc = this.transferServices.find((s) => s.type === serviceType);\n if (svc) {\n this.startStreamForService(svc);\n }\n },\n Math.max(0, delayMs),\n );\n }\n\n /**\n * Handle service completion (`done`).\n *\n * A completion may schedule:\n * - refresh (if the service has active quotes), and/or\n * - retry (quote-less/non-error completion, but only after any quote has existed in session).\n *\n * Then evaluates whether the full quoter can complete with `no-quotes`.\n */\n private onServiceDone(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n state.done = true;\n this.scheduleServiceRefresh(serviceType);\n\n if (this.hasReceivedAnyQuote && !state.hasErrored && !state.hasReturnedQuote) {\n this.scheduleServiceRetry(serviceType);\n }\n\n this.maybeCompleteNoQuotes();\n }\n\n /**\n * Complete with `no-quotes` when every eligible service has finished and\n * no quote was ever observed during this session.\n */\n private maybeCompleteNoQuotes(): void {\n if (!this.started || this.done || this.hasReceivedAnyQuote || this.serviceState.size === 0) {\n return;\n }\n\n const allServicesDone = [...this.serviceState.values()].every((state) => state.done);\n\n if (allServicesDone) {\n this.complete('no-quotes');\n }\n }\n\n /**\n * Finalize the quoter session and broadcast terminal reason exactly once.\n */\n private complete(reason: QuoterDoneReason): void {\n if (this.done) {\n return;\n }\n\n const payload = this.makeDonePayload(reason);\n\n this.done = true;\n this.stop();\n\n // When complete() happens during subscribe()->start(), emit done on a microtask\n // so callers can safely reference the returned unsubscribe in their handler.\n if (this.isStartingFromSubscribe) {\n queueMicrotask(() => {\n const handlers = [...this.subscribers];\n this.subscribers.clear();\n\n for (const handler of handlers) {\n handler('done', payload);\n }\n });\n return;\n }\n\n const handlers = [...this.subscribers];\n this.subscribers.clear();\n\n for (const handler of handlers) {\n handler('done', payload);\n }\n }\n\n private getInitializedServices(): ServiceType[] {\n return [...new Set(this.transferServices.map((service) => service.type))];\n }\n\n private getEligibleServices(): ServiceType[] {\n return [...this.serviceState.keys()];\n }\n\n private makeDonePayload(reason: QuoterDoneReason): QuoterDonePayload {\n if (reason === 'unsubscribed') {\n return { reason, data: undefined };\n }\n\n const initializedServices = this.getInitializedServices();\n\n if (reason === 'no-eligible-services') {\n return {\n reason,\n data: {\n initializedServices,\n quoterProps: this.props,\n },\n };\n }\n\n return {\n reason,\n data: {\n eligibleServices: this.getEligibleServices(),\n initializedServices,\n quoterProps: this.props,\n },\n };\n }\n\n /** Periodic prune tick to evict expired quotes and emit best changes. */\n private onPruneTick(): void {\n const now = this.clock();\n const pruned = pruneExpiredQuotes({ quotes: this.quotes, nowSeconds: now });\n\n if (pruned.length !== this.quotes.length) {\n this.quotes = sortQuotes(pruned);\n const best = this.quotes[0] ?? null;\n const bestId = best ? best.id : null;\n\n if (best && bestId !== this.lastBestId) {\n this.lastBestId = bestId;\n this.emitQuote({ bestQuote: best, quote: best, quotes: this.quotes });\n } else if (!best) {\n this.lastBestId = null;\n }\n }\n\n // Re-evaluate refresh scheduling for all services on prune tick\n for (const svc of this.transferServices) {\n if (this.serviceState.has(svc.type)) {\n this.scheduleServiceRefresh(svc.type);\n }\n }\n }\n\n /** Schedule a refresh (restart) of streaming for the service at its earliest quote expiration. */\n private scheduleServiceRefresh(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) return;\n\n const now = this.clock();\n const earliest = earliestExpirationForService({ quotes: this.quotes, serviceType, nowSeconds: now });\n\n if (earliest === null) {\n // No quotes -> clear any pending refresh\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n state.refreshTimer = null;\n }\n state.refreshAtSeconds = null;\n return;\n }\n\n // Only reschedule if earlier than currently scheduled or no timer\n const targetAt = Math.max(0, earliest - this.refreshBufferSeconds);\n\n // If target time has already passed, do not schedule another refresh here.\n if (targetAt <= now) {\n return;\n }\n\n // Reschedule only when the desired refresh time changes (earlier OR later).\n // We key refresh off the soonest-expiring active quote for this service.\n if (state.refreshAtSeconds === targetAt && state.refreshTimer) {\n return;\n }\n\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n }\n\n const delayMs = Math.max(0, (targetAt - now) * 1_000);\n state.refreshAtSeconds = targetAt;\n state.refreshTimer = setTimeout(() => {\n // Clear timer/marker before restarting to avoid stale state if restart fails.\n const current = this.serviceState.get(serviceType);\n if (current) {\n current.refreshTimer = null;\n current.refreshAtSeconds = null;\n }\n\n // Restart stream and clear timer/marker\n const svc = this.transferServices.find((s) => s.type === serviceType);\n\n if (svc) {\n this.startStreamForService(svc);\n }\n }, delayMs);\n }\n\n // ----- Emission helpers -----\n /** Emit a quote event to all subscribers. */\n private emitQuote(payload: { bestQuote: Quote; quote: Quote; quotes: readonly Quote[] }): void {\n for (const handler of this.subscribers) {\n handler('quote', payload);\n }\n }\n\n /** Emit an error event to all subscribers. */\n private emitError(error: Error): void {\n for (const handler of this.subscribers) {\n handler('error', error);\n }\n }\n}\n\n/**\n * Zod schema to validate the minimal Quote fields used for runtime gating.\n *\n * This is a simple schema, and is not a fully safe runtime validate for Quote.\n * That isn't necessary here since we only need to verify basic structure before\n * using the quote in internal logic.\n *\n * @internal\n */\nconst QuoteSchema = z.object({\n id: z.string(),\n expiresAt: z.number().int().nonnegative(),\n amountOut: z.bigint().nonnegative(),\n amountIn: z.bigint().nonnegative(),\n serviceType: z.string(),\n});\n\nfunction isInvalidSameChainQuoteRequest(props: QuoterProps): boolean {\n const { sourceAsset, sourceChain, targetAsset, targetChain } = props;\n\n if (sourceChain.chainId !== targetChain.chainId) {\n return false;\n }\n\n // Native -> native on the same chain is a no-op.\n if (isNativeAsset(sourceAsset) && isNativeAsset(targetAsset)) {\n return true;\n }\n\n // If token types differ, it's potentially a swap on the same chain.\n if (sourceAsset.type !== targetAsset.type) {\n return false;\n }\n\n // Same token type and address on the same chain is a no-op.\n if (sourceAsset.type === TokenType.ERC20 && targetAsset.type === TokenType.ERC20) {\n return isAddressEqual(sourceAsset.address, targetAsset.address);\n }\n\n if (sourceAsset.type === TokenType.SPL && targetAsset.type === TokenType.SPL) {\n return sourceAsset.address === targetAsset.address;\n }\n\n return false;\n}\n\nfunction isQuoteValue(value: unknown): value is Quote {\n const result = QuoteSchema.safeParse(value);\n\n return result.success;\n}\n"],"mappings":"+MAoFA,IAAa,EAAb,KAA+C,CAC7C,MACA,MACA,gBACA,oBACA,iBACA,qBAEA,OAA0B,EAAE,CAC5B,YAA+C,IAAI,IACnD,QAAkB,GAClB,KAAe,GACf,wBAAkC,GAClC,aAA8D,KAC9D,WAAoC,KACpC,oBAA8B,GAE9B,GAA6B,OAAO,YAAY,CAQhD,aAYI,IAAI,IASR,YAAY,EAAoB,EAA8C,EAAyB,EAAE,CAAE,CACzG,KAAK,MAAQ,EAAQ,YAAgB,KAAK,MAAM,KAAK,KAAK,CAAG,IAAM,EACnE,KAAK,MAAQ,E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face QuoterOptions {
14
+ /**
15
+ * Dangerously allows cross-chain quotes where fromAddress and toAddress differ
16
+ * even when a service would otherwise require them to match.
17
+ *
18
+ * This is intended for explicit proxy-recipient funding flows. By default,
19
+ * services preserve their existing address safety checks.
20
+ */
21
+ readonly dangerouslyAllowAddressMismatch?: boolean;
14
22
  /** Clock function returning current time in seconds (defaults to Date.now()/1000). */
15
23
  readonly clock?: Clock;
16
24
  /** Interval for pruning expired quotes (milliseconds).
@@ -11,6 +11,14 @@ type Clock = () => number;
11
11
  * proactively restarted before quote expiry.
12
12
  */
13
13
  interface QuoterOptions {
14
+ /**
15
+ * Dangerously allows cross-chain quotes where fromAddress and toAddress differ
16
+ * even when a service would otherwise require them to match.
17
+ *
18
+ * This is intended for explicit proxy-recipient funding flows. By default,
19
+ * services preserve their existing address safety checks.
20
+ */
21
+ readonly dangerouslyAllowAddressMismatch?: boolean;
14
22
  /** Clock function returning current time in seconds (defaults to Date.now()/1000). */
15
23
  readonly clock?: Clock;
16
24
  /** Interval for pruning expired quotes (milliseconds).
@@ -1,2 +1,2 @@
1
- import{TokenType as e}from"../constants.js";import{isNativeAsset as t}from"../type-guards.js";import{earliestExpirationForService as n,isQuoteExpired as r,pruneExpiredQuotes as i,sortQuotes as a,upsertQuote as o}from"./_utils.js";import{QUOTER_EMPTY_RETRY_BASE_DELAY_MS as s,QUOTER_EMPTY_RETRY_MAX_DELAY_MS as c}from"./constants.js";import{z as l}from"zod";import{isAddressEqual as u}from"viem";var d=class{clock;props;pruneIntervalMs;transferServices;refreshBufferSeconds;quotes=[];subscribers=new Set;started=!1;done=!1;isStartingFromSubscribe=!1;pruneTimerId=null;lastBestId=null;hasReceivedAnyQuote=!1;id=crypto.randomUUID();serviceState=new Map;constructor(e,t,n={}){this.clock=n.clock??(()=>Math.floor(Date.now()/1e3)),this.props=e,this.pruneIntervalMs=n.pruneIntervalMs??1e3,this.transferServices=t,this.refreshBufferSeconds=n.refreshBufferSeconds??5}getQuotes(){let e=this.clock(),t=a(i({quotes:this.quotes,nowSeconds:e}));return[t[0]??null,t]}subscribe(e){this.subscribers.add(e);let t=!1;if(!this.started){this.isStartingFromSubscribe=!0;try{this.start()}finally{this.isStartingFromSubscribe=!1}}return()=>{if(!t){if(t=!0,this.done){this.subscribers.delete(e);return}if(this.subscribers.size===1&&this.subscribers.has(e)){this.complete(`unsubscribed`);return}this.subscribers.delete(e)}}}start(){if(this.started=!0,this.done=!1,this.quotes=[],this.lastBestId=null,this.hasReceivedAnyQuote=!1,p(this.props)){this.complete(`no-eligible-services`);return}let e=!1;for(let t of this.transferServices)t.analyzeSupport({sourceAsset:this.props.sourceAsset,sourceChainId:this.props.sourceChain.chainId,targetAsset:this.props.targetAsset,targetChainId:this.props.targetChain.chainId})&&(e=!0,this.startStreamForService(t));if(!e){this.complete(`no-eligible-services`);return}this.pruneTimerId=setInterval(()=>this.onPruneTick(),this.pruneIntervalMs)}stop(){this.started=!1,this.pruneTimerId&&=(clearInterval(this.pruneTimerId),null);for(let[e,t]of this.serviceState){try{t.cancel()}catch{}t.refreshTimer&&clearTimeout(t.refreshTimer),t.retryTimer&&clearTimeout(t.retryTimer),this.serviceState.set(e,{cancel:()=>{},done:!1,hasErrored:!1,hasReturnedQuote:!1,retryAttempt:0,retryTimer:null,refreshTimer:null,refreshAtSeconds:null})}}startStreamForService(e){let t=this.serviceState.get(e.type);if(t){try{t.cancel()}catch{}t.refreshTimer&&clearTimeout(t.refreshTimer),t.retryTimer&&clearTimeout(t.retryTimer)}let n=this.makeServiceHandler(e.type),r=[],i=!0,{cancel:a}=e.streamQuotes(this.props,(...e)=>{if(i){r.push(e);return}n(...e)});i=!1,r.length>0&&queueMicrotask(()=>{for(let e of r)n(...e)}),this.serviceState.set(e.type,{cancel:a,done:!1,hasErrored:!1,hasReturnedQuote:!1,retryAttempt:t?.retryAttempt??0,retryTimer:null,refreshTimer:null,refreshAtSeconds:null})}makeServiceHandler(e){return(t,...n)=>{if(this.started){if(t===`quote`){let t=n[0];if(m(t)){if(t.serviceType!==e)return;let n=this.serviceState.get(e);n&&(n.hasReturnedQuote=!0),this.onIncomingQuote(t),this.scheduleServiceRefresh(e)}return}if(t===`done`){this.onServiceDone(e);return}if(t===`error`){let t=this.serviceState.get(e);t&&(t.hasErrored=!0);let r=n[0];r instanceof Error&&this.emitError(r)}}}}onIncomingQuote(e){let t=this.clock();if(r({quote:e,nowSeconds:t}))return;this.hasReceivedAnyQuote=!0,this.resetRetryForService(e.serviceType),this.quotes=a(i({quotes:o(this.quotes,e),nowSeconds:t}));let n=this.quotes[0];n&&(this.lastBestId=n.id,this.emitQuote({bestQuote:n,quote:e,quotes:this.quotes}))}resetRetryForService(e){let t=this.serviceState.get(e);t&&(t.retryAttempt=0,t.retryTimer&&=(clearTimeout(t.retryTimer),null))}scheduleServiceRetry(e){let t=this.serviceState.get(e);if(!t)return;t.retryTimer&&=(clearTimeout(t.retryTimer),null);let n=Math.min(c,s*2**t.retryAttempt);t.retryAttempt+=1,t.retryTimer=setTimeout(()=>{let t=this.serviceState.get(e);if(t&&(t.retryTimer=null),!this.started)return;let n=this.transferServices.find(t=>t.type===e);n&&this.startStreamForService(n)},Math.max(0,n))}onServiceDone(e){let t=this.serviceState.get(e);t&&(t.done=!0,this.scheduleServiceRefresh(e),this.hasReceivedAnyQuote&&!t.hasErrored&&!t.hasReturnedQuote&&this.scheduleServiceRetry(e),this.maybeCompleteNoQuotes())}maybeCompleteNoQuotes(){!this.started||this.done||this.hasReceivedAnyQuote||this.serviceState.size===0||[...this.serviceState.values()].every(e=>e.done)&&this.complete(`no-quotes`)}complete(e){if(this.done)return;let t=this.makeDonePayload(e);if(this.done=!0,this.stop(),this.isStartingFromSubscribe){queueMicrotask(()=>{let e=[...this.subscribers];this.subscribers.clear();for(let n of e)n(`done`,t)});return}let n=[...this.subscribers];this.subscribers.clear();for(let e of n)e(`done`,t)}getInitializedServices(){return[...new Set(this.transferServices.map(e=>e.type))]}getEligibleServices(){return[...this.serviceState.keys()]}makeDonePayload(e){if(e===`unsubscribed`)return{reason:e,data:void 0};let t=this.getInitializedServices();return e===`no-eligible-services`?{reason:e,data:{initializedServices:t,quoterProps:this.props}}:{reason:e,data:{eligibleServices:this.getEligibleServices(),initializedServices:t,quoterProps:this.props}}}onPruneTick(){let e=this.clock(),t=i({quotes:this.quotes,nowSeconds:e});if(t.length!==this.quotes.length){this.quotes=a(t);let e=this.quotes[0]??null,n=e?e.id:null;e&&n!==this.lastBestId?(this.lastBestId=n,this.emitQuote({bestQuote:e,quote:e,quotes:this.quotes})):e||(this.lastBestId=null)}for(let e of this.transferServices)this.serviceState.has(e.type)&&this.scheduleServiceRefresh(e.type)}scheduleServiceRefresh(e){let t=this.serviceState.get(e);if(!t)return;let r=this.clock(),i=n({quotes:this.quotes,serviceType:e,nowSeconds:r});if(i===null){t.refreshTimer&&=(clearTimeout(t.refreshTimer),null),t.refreshAtSeconds=null;return}let a=Math.max(0,i-this.refreshBufferSeconds);if(a<=r||t.refreshAtSeconds===a&&t.refreshTimer)return;t.refreshTimer&&clearTimeout(t.refreshTimer);let o=Math.max(0,(a-r)*1e3);t.refreshAtSeconds=a,t.refreshTimer=setTimeout(()=>{let t=this.serviceState.get(e);t&&(t.refreshTimer=null,t.refreshAtSeconds=null);let n=this.transferServices.find(t=>t.type===e);n&&this.startStreamForService(n)},o)}emitQuote(e){for(let t of this.subscribers)t(`quote`,e)}emitError(e){for(let t of this.subscribers)t(`error`,e)}};const f=l.object({id:l.string(),expiresAt:l.number().int().nonnegative(),amountOut:l.bigint().nonnegative(),amountIn:l.bigint().nonnegative(),serviceType:l.string()});function p(n){let{sourceAsset:r,sourceChain:i,targetAsset:a,targetChain:o}=n;return i.chainId===o.chainId?t(r)&&t(a)?!0:r.type===a.type?r.type===e.ERC20&&a.type===e.ERC20?u(r.address,a.address):r.type===e.SPL&&a.type===e.SPL?r.address===a.address:!1:!1:!1}function m(e){return f.safeParse(e).success}export{d as Quoter};
1
+ import{TokenType as e}from"../constants.js";import{isNativeAsset as t}from"../type-guards.js";import{earliestExpirationForService as n,isQuoteExpired as r,pruneExpiredQuotes as i,sortQuotes as a,upsertQuote as o}from"./_utils.js";import{QUOTER_EMPTY_RETRY_BASE_DELAY_MS as s,QUOTER_EMPTY_RETRY_MAX_DELAY_MS as c}from"./constants.js";import{z as l}from"zod";import{isAddressEqual as u}from"viem";var d=class{clock;props;pruneIntervalMs;serviceQuoteOptions;transferServices;refreshBufferSeconds;quotes=[];subscribers=new Set;started=!1;done=!1;isStartingFromSubscribe=!1;pruneTimerId=null;lastBestId=null;hasReceivedAnyQuote=!1;id=crypto.randomUUID();serviceState=new Map;constructor(e,t,n={}){this.clock=n.clock??(()=>Math.floor(Date.now()/1e3)),this.props=e,this.pruneIntervalMs=n.pruneIntervalMs??1e3,this.serviceQuoteOptions={dangerouslyAllowAddressMismatch:n.dangerouslyAllowAddressMismatch},this.transferServices=t,this.refreshBufferSeconds=n.refreshBufferSeconds??5}getQuotes(){let e=this.clock(),t=a(i({quotes:this.quotes,nowSeconds:e}));return[t[0]??null,t]}subscribe(e){this.subscribers.add(e);let t=!1;if(!this.started){this.isStartingFromSubscribe=!0;try{this.start()}finally{this.isStartingFromSubscribe=!1}}return()=>{if(!t){if(t=!0,this.done){this.subscribers.delete(e);return}if(this.subscribers.size===1&&this.subscribers.has(e)){this.complete(`unsubscribed`);return}this.subscribers.delete(e)}}}start(){if(this.started=!0,this.done=!1,this.quotes=[],this.lastBestId=null,this.hasReceivedAnyQuote=!1,p(this.props)){this.complete(`no-eligible-services`);return}let e=!1;for(let t of this.transferServices)t.analyzeSupport({sourceAsset:this.props.sourceAsset,sourceChainId:this.props.sourceChain.chainId,targetAsset:this.props.targetAsset,targetChainId:this.props.targetChain.chainId})&&(e=!0,this.startStreamForService(t));if(!e){this.complete(`no-eligible-services`);return}this.pruneTimerId=setInterval(()=>this.onPruneTick(),this.pruneIntervalMs)}stop(){this.started=!1,this.pruneTimerId&&=(clearInterval(this.pruneTimerId),null);for(let[e,t]of this.serviceState){try{t.cancel()}catch{}t.refreshTimer&&clearTimeout(t.refreshTimer),t.retryTimer&&clearTimeout(t.retryTimer),this.serviceState.set(e,{cancel:()=>{},done:!1,hasErrored:!1,hasReturnedQuote:!1,retryAttempt:0,retryTimer:null,refreshTimer:null,refreshAtSeconds:null})}}startStreamForService(e){let t=this.serviceState.get(e.type);if(t){try{t.cancel()}catch{}t.refreshTimer&&clearTimeout(t.refreshTimer),t.retryTimer&&clearTimeout(t.retryTimer)}let n=this.makeServiceHandler(e.type),r=[],i=!0,{cancel:a}=e.streamQuotes(this.props,(...e)=>{if(i){r.push(e);return}n(...e)},this.serviceQuoteOptions);i=!1,r.length>0&&queueMicrotask(()=>{for(let e of r)n(...e)}),this.serviceState.set(e.type,{cancel:a,done:!1,hasErrored:!1,hasReturnedQuote:!1,retryAttempt:t?.retryAttempt??0,retryTimer:null,refreshTimer:null,refreshAtSeconds:null})}makeServiceHandler(e){return(t,...n)=>{if(this.started){if(t===`quote`){let t=n[0];if(m(t)){if(t.serviceType!==e)return;let n=this.serviceState.get(e);n&&(n.hasReturnedQuote=!0),this.onIncomingQuote(t),this.scheduleServiceRefresh(e)}return}if(t===`done`){this.onServiceDone(e);return}if(t===`error`){let t=this.serviceState.get(e);t&&(t.hasErrored=!0);let r=n[0];r instanceof Error&&this.emitError(r)}}}}onIncomingQuote(e){let t=this.clock();if(r({quote:e,nowSeconds:t}))return;this.hasReceivedAnyQuote=!0,this.resetRetryForService(e.serviceType),this.quotes=a(i({quotes:o(this.quotes,e),nowSeconds:t}));let n=this.quotes[0];n&&(this.lastBestId=n.id,this.emitQuote({bestQuote:n,quote:e,quotes:this.quotes}))}resetRetryForService(e){let t=this.serviceState.get(e);t&&(t.retryAttempt=0,t.retryTimer&&=(clearTimeout(t.retryTimer),null))}scheduleServiceRetry(e){let t=this.serviceState.get(e);if(!t)return;t.retryTimer&&=(clearTimeout(t.retryTimer),null);let n=Math.min(c,s*2**t.retryAttempt);t.retryAttempt+=1,t.retryTimer=setTimeout(()=>{let t=this.serviceState.get(e);if(t&&(t.retryTimer=null),!this.started)return;let n=this.transferServices.find(t=>t.type===e);n&&this.startStreamForService(n)},Math.max(0,n))}onServiceDone(e){let t=this.serviceState.get(e);t&&(t.done=!0,this.scheduleServiceRefresh(e),this.hasReceivedAnyQuote&&!t.hasErrored&&!t.hasReturnedQuote&&this.scheduleServiceRetry(e),this.maybeCompleteNoQuotes())}maybeCompleteNoQuotes(){!this.started||this.done||this.hasReceivedAnyQuote||this.serviceState.size===0||[...this.serviceState.values()].every(e=>e.done)&&this.complete(`no-quotes`)}complete(e){if(this.done)return;let t=this.makeDonePayload(e);if(this.done=!0,this.stop(),this.isStartingFromSubscribe){queueMicrotask(()=>{let e=[...this.subscribers];this.subscribers.clear();for(let n of e)n(`done`,t)});return}let n=[...this.subscribers];this.subscribers.clear();for(let e of n)e(`done`,t)}getInitializedServices(){return[...new Set(this.transferServices.map(e=>e.type))]}getEligibleServices(){return[...this.serviceState.keys()]}makeDonePayload(e){if(e===`unsubscribed`)return{reason:e,data:void 0};let t=this.getInitializedServices();return e===`no-eligible-services`?{reason:e,data:{initializedServices:t,quoterProps:this.props}}:{reason:e,data:{eligibleServices:this.getEligibleServices(),initializedServices:t,quoterProps:this.props}}}onPruneTick(){let e=this.clock(),t=i({quotes:this.quotes,nowSeconds:e});if(t.length!==this.quotes.length){this.quotes=a(t);let e=this.quotes[0]??null,n=e?e.id:null;e&&n!==this.lastBestId?(this.lastBestId=n,this.emitQuote({bestQuote:e,quote:e,quotes:this.quotes})):e||(this.lastBestId=null)}for(let e of this.transferServices)this.serviceState.has(e.type)&&this.scheduleServiceRefresh(e.type)}scheduleServiceRefresh(e){let t=this.serviceState.get(e);if(!t)return;let r=this.clock(),i=n({quotes:this.quotes,serviceType:e,nowSeconds:r});if(i===null){t.refreshTimer&&=(clearTimeout(t.refreshTimer),null),t.refreshAtSeconds=null;return}let a=Math.max(0,i-this.refreshBufferSeconds);if(a<=r||t.refreshAtSeconds===a&&t.refreshTimer)return;t.refreshTimer&&clearTimeout(t.refreshTimer);let o=Math.max(0,(a-r)*1e3);t.refreshAtSeconds=a,t.refreshTimer=setTimeout(()=>{let t=this.serviceState.get(e);t&&(t.refreshTimer=null,t.refreshAtSeconds=null);let n=this.transferServices.find(t=>t.type===e);n&&this.startStreamForService(n)},o)}emitQuote(e){for(let t of this.subscribers)t(`quote`,e)}emitError(e){for(let t of this.subscribers)t(`error`,e)}};const f=l.object({id:l.string(),expiresAt:l.number().int().nonnegative(),amountOut:l.bigint().nonnegative(),amountIn:l.bigint().nonnegative(),serviceType:l.string()});function p(n){let{sourceAsset:r,sourceChain:i,targetAsset:a,targetChain:o}=n;return i.chainId===o.chainId?t(r)&&t(a)?!0:r.type===a.type?r.type===e.ERC20&&a.type===e.ERC20?u(r.address,a.address):r.type===e.SPL&&a.type===e.SPL?r.address===a.address:!1:!1:!1}function m(e){return f.safeParse(e).success}export{d as Quoter};
2
2
  //# sourceMappingURL=quoter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"quoter.js","names":[],"sources":["../../src/quoter/quoter.ts"],"sourcesContent":["import { z } from 'zod';\nimport type {\n Quote,\n QuoterDonePayload,\n QuoterDoneReason,\n QuoterEventHandler,\n QuoterInterface,\n QuoterProps,\n ServiceQuoteEventArgs,\n QuotesTuple,\n ServiceQuoteEventHandler,\n} from '../types/quote';\nimport type { TransferService } from '../types/service';\nimport { earliestExpirationForService, isQuoteExpired, pruneExpiredQuotes, sortQuotes, upsertQuote } from './_utils';\nimport {\n QUOTER_DEFAULT_PRUNE_INTERVAL_MS,\n QUOTER_DEFAULT_REFRESH_BUFFER_SECONDS,\n QUOTER_EMPTY_RETRY_BASE_DELAY_MS,\n QUOTER_EMPTY_RETRY_MAX_DELAY_MS,\n} from './constants';\nimport { ServiceType, TokenType } from '../constants';\nimport { isNativeAsset } from '../type-guards';\nimport { isAddressEqual } from 'viem';\n\n/**\n * Function that returns the current UNIX time in seconds.\n * Injected for deterministic testing.\n */\nexport type Clock = () => number;\n\n/**\n * Options for constructing a Quoter instance.\n *\n * These options tune how often quote state is maintained and when services are\n * proactively restarted before quote expiry.\n */\nexport interface QuoterOptions {\n /** Clock function returning current time in seconds (defaults to Date.now()/1000). */\n readonly clock?: Clock;\n /** Interval for pruning expired quotes (milliseconds).\n *\n * @default 1_000\n */\n readonly pruneIntervalMs?: number;\n /**\n * Amount of seconds to pre-buffer a stream restart before the earliest service quote\n * expiration. Helps ensure continuity before actual expiry is reached.\n *\n * @default 5\n */\n readonly refreshBufferSeconds?: number;\n}\n\n/**\n * Quoter orchestrates quote streaming across multiple transfer services and emits a unified event stream.\n *\n * High-level lifecycle:\n * - Idle until first subscriber.\n * - On first subscribe, starts all eligible services.\n * - Collects and ranks active quotes, pruning expired ones over time.\n * - Completes when explicitly unsubscribed (last subscriber), when no service is eligible,\n * or when all eligible services finish without producing any quote (`no-quotes`).\n *\n * Event model:\n * - Service `quote` -> Quoter upserts quote, recomputes best quote, emits `quote`.\n * - Service `error` -> Quoter emits `error` (non-terminal by itself).\n * - Service `done` -> Quoter marks that service attempt as completed and evaluates retry/complete rules.\n *\n * Retry/refresh behavior:\n * - Refresh: services that have active quotes are restarted shortly before the earliest quote expires.\n * - Retry: services that complete with no quote and no error are only retried after the quoter has\n * already observed at least one quote from any service in this session.\n *\n * This design keeps first-pass \"no quotes anywhere\" terminal and fast, while still allowing services\n * like Markr to be retried in sessions where other providers are returning quotes.\n */\nexport class Quoter implements QuoterInterface {\n private readonly clock: Clock;\n private readonly props: QuoterProps;\n private readonly pruneIntervalMs: number;\n private readonly transferServices: readonly TransferService[];\n private readonly refreshBufferSeconds: number;\n\n private quotes: Quote[] = [];\n private subscribers: Set<QuoterEventHandler> = new Set();\n private started = false;\n private done = false;\n private isStartingFromSubscribe = false;\n private pruneTimerId: ReturnType<typeof setInterval> | null = null;\n private lastBestId: string | null = null;\n private hasReceivedAnyQuote = false;\n\n public readonly id: string = crypto.randomUUID();\n\n /**\n * Per-service runtime state for the active quote session.\n *\n * This tracks whether a service has completed, errored, produced quotes,\n * and any pending timers used for retry/refresh orchestration.\n */\n private serviceState: Map<\n TransferService['type'],\n {\n cancel: () => void;\n done: boolean;\n hasErrored: boolean;\n hasReturnedQuote: boolean;\n retryAttempt: number;\n retryTimer: ReturnType<typeof setTimeout> | null;\n refreshTimer: ReturnType<typeof setTimeout> | null;\n refreshAtSeconds: number | null;\n }\n > = new Map();\n\n /**\n * Create a new Quoter instance.\n *\n * @param props Quoting request parameters shared across all services.\n * @param transferServices Candidate services; eligibility is resolved at `start()` time.\n * @param options Optional runtime tuning for pruning and refresh behavior.\n */\n constructor(props: QuoterProps, transferServices: readonly TransferService[], options: QuoterOptions = {}) {\n this.clock = options.clock ?? (() => Math.floor(Date.now() / 1_000));\n this.props = props;\n this.pruneIntervalMs = options.pruneIntervalMs ?? QUOTER_DEFAULT_PRUNE_INTERVAL_MS;\n this.transferServices = transferServices;\n this.refreshBufferSeconds = options.refreshBufferSeconds ?? QUOTER_DEFAULT_REFRESH_BUFFER_SECONDS;\n }\n\n /**\n * Get the current best quote and all active quotes (sorted by desirability).\n */\n public getQuotes(): QuotesTuple {\n const now = this.clock();\n const active = pruneExpiredQuotes({ quotes: this.quotes, nowSeconds: now });\n const sorted = sortQuotes(active);\n const best = sorted[0] ?? null;\n\n return [best, sorted];\n }\n\n /**\n * Subscribe for quoter events.\n *\n * First subscriber lazily starts orchestration.\n * Last subscriber triggers terminal completion with reason `unsubscribed`.\n *\n * @returns Unsubscribe function (idempotent).\n */\n public subscribe(handler: QuoterEventHandler): () => void {\n this.subscribers.add(handler);\n let unsubscribed = false;\n\n if (!this.started) {\n this.isStartingFromSubscribe = true;\n try {\n this.start();\n } finally {\n this.isStartingFromSubscribe = false;\n }\n }\n\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n\n if (this.done) {\n this.subscribers.delete(handler);\n return;\n }\n\n const wasLastSubscriber = this.subscribers.size === 1 && this.subscribers.has(handler);\n if (wasLastSubscriber) {\n this.complete('unsubscribed');\n return;\n }\n\n this.subscribers.delete(handler);\n };\n }\n\n // ----- Internal orchestration -----\n\n /**\n * Start a fresh quote session.\n *\n * Resets session-local state, validates basic request viability,\n * starts streams for eligible services, and begins prune ticks.\n */\n private start(): void {\n this.started = true;\n this.done = false;\n this.quotes = [];\n this.lastBestId = null;\n this.hasReceivedAnyQuote = false;\n\n // Same-chain quotes for the *same* asset are not a valid transfer scenario.\n if (isInvalidSameChainQuoteRequest(this.props)) {\n this.complete('no-eligible-services');\n return;\n }\n\n let hasEligibleService = false;\n\n // Start streams for eligible services\n for (const svc of this.transferServices) {\n const eligible = svc.analyzeSupport({\n sourceAsset: this.props.sourceAsset,\n sourceChainId: this.props.sourceChain.chainId,\n targetAsset: this.props.targetAsset,\n targetChainId: this.props.targetChain.chainId,\n });\n\n if (!eligible) continue;\n hasEligibleService = true;\n\n this.startStreamForService(svc);\n }\n\n if (!hasEligibleService) {\n this.complete('no-eligible-services');\n return;\n }\n\n // Start periodic prune\n this.pruneTimerId = setInterval(() => this.onPruneTick(), this.pruneIntervalMs);\n }\n\n /**\n * Stop all streams and timers.\n * Quotes are retained for snapshot access via getQuotes(), though they\n * can still be pruned due to expiration.\n */\n private stop(): void {\n this.started = false;\n\n if (this.pruneTimerId) {\n clearInterval(this.pruneTimerId);\n this.pruneTimerId = null;\n }\n\n for (const [type, state] of this.serviceState) {\n try {\n state.cancel();\n } catch {\n /* ignore */\n }\n\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n }\n\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n }\n\n this.serviceState.set(type, {\n cancel: () => {},\n done: false,\n hasErrored: false,\n hasReturnedQuote: false,\n retryAttempt: 0,\n retryTimer: null,\n refreshTimer: null,\n refreshAtSeconds: null,\n });\n }\n }\n\n /**\n * Begin or restart streaming for a specific service.\n *\n * Any previous stream/timers for that service are canceled before starting a new attempt.\n */\n private startStreamForService(svc: TransferService): void {\n // Clean up any existing stream and refresh timer\n const existing = this.serviceState.get(svc.type);\n\n if (existing) {\n try {\n existing.cancel();\n } catch {\n /* ignore */\n }\n\n if (existing.refreshTimer) clearTimeout(existing.refreshTimer);\n if (existing.retryTimer) clearTimeout(existing.retryTimer);\n }\n\n const handler = this.makeServiceHandler(svc.type);\n const bufferedEvents: ServiceQuoteEventArgs[] = [];\n let isStartingStream = true;\n\n // Some services emit quote/done synchronously inside streamQuotes().\n // If those events run before subscribe() returns, consumers can hit TDZ\n // when they reference the returned unsubscribe function in their callback.\n // Buffer startup emissions and flush them after stream initialization.\n const guardedHandler: ServiceQuoteEventHandler = (...eventArgs) => {\n if (isStartingStream) {\n bufferedEvents.push(eventArgs);\n return;\n }\n\n handler(...eventArgs);\n };\n\n const { cancel } = svc.streamQuotes(this.props, guardedHandler);\n isStartingStream = false;\n\n if (bufferedEvents.length > 0) {\n // Use a microtask so subscribe() can return before the first callback fires.\n // This preserves event order while avoiding re-entrancy during subscription.\n queueMicrotask(() => {\n for (const bufferedEvent of bufferedEvents) {\n handler(...bufferedEvent);\n }\n });\n }\n\n this.serviceState.set(svc.type, {\n cancel,\n done: false,\n hasErrored: false,\n hasReturnedQuote: false,\n retryAttempt: existing?.retryAttempt ?? 0,\n retryTimer: null,\n refreshTimer: null,\n refreshAtSeconds: null,\n });\n }\n\n /**\n * Create the service-scoped event handler consumed by `TransferService.streamQuotes`.\n *\n * The handler enforces service/quote consistency and translates service events into\n * quoter state transitions.\n */\n private makeServiceHandler(serviceType: TransferService['type']): ServiceQuoteEventHandler {\n return (event, ...args) => {\n // Ignore any service events once stopped to prevent post-stop mutations.\n if (!this.started) {\n return;\n }\n if (event === 'quote') {\n const maybeQuote = args[0];\n if (isQuoteValue(maybeQuote)) {\n // Enforce the quote belongs to the emitting service\n if (maybeQuote.serviceType !== serviceType) {\n // Ignore quotes mismatched to service; defensive\n return;\n }\n const state = this.serviceState.get(serviceType);\n if (state) {\n state.hasReturnedQuote = true;\n }\n this.onIncomingQuote(maybeQuote);\n this.scheduleServiceRefresh(serviceType);\n }\n\n return;\n }\n if (event === 'done') {\n this.onServiceDone(serviceType);\n\n return;\n }\n if (event === 'error') {\n const state = this.serviceState.get(serviceType);\n if (state) {\n state.hasErrored = true;\n }\n const maybeErr = args[0];\n if (maybeErr instanceof Error) {\n this.emitError(maybeErr);\n }\n }\n };\n }\n\n /**\n * Handle an incoming quote event.\n *\n * Expired quotes are ignored. Valid quotes are upserted into active state,\n * then sorted/pruned and emitted to subscribers.\n */\n private onIncomingQuote(quote: Quote): void {\n const now = this.clock();\n\n if (isQuoteExpired({ quote, nowSeconds: now })) {\n return;\n }\n\n this.hasReceivedAnyQuote = true;\n\n this.resetRetryForService(quote.serviceType);\n\n this.quotes = sortQuotes(pruneExpiredQuotes({ quotes: upsertQuote(this.quotes, quote), nowSeconds: now }));\n\n // Always emit on every incoming quote\n const best = this.quotes[0];\n if (best) {\n this.lastBestId = best.id;\n this.emitQuote({ bestQuote: best, quote, quotes: this.quotes });\n }\n }\n\n private resetRetryForService(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n state.retryAttempt = 0;\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n state.retryTimer = null;\n }\n }\n\n /**\n * Schedule a retry attempt for a service using exponential backoff.\n *\n * This is used only for quote-less successful completions once the overall session\n * has already produced at least one quote from some service.\n */\n private scheduleServiceRetry(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n state.retryTimer = null;\n }\n\n const delayMs = Math.min(\n QUOTER_EMPTY_RETRY_MAX_DELAY_MS,\n QUOTER_EMPTY_RETRY_BASE_DELAY_MS * 2 ** state.retryAttempt,\n );\n state.retryAttempt += 1;\n\n state.retryTimer = setTimeout(\n () => {\n const current = this.serviceState.get(serviceType);\n if (current) {\n current.retryTimer = null;\n }\n\n if (!this.started) {\n return;\n }\n\n const svc = this.transferServices.find((s) => s.type === serviceType);\n if (svc) {\n this.startStreamForService(svc);\n }\n },\n Math.max(0, delayMs),\n );\n }\n\n /**\n * Handle service completion (`done`).\n *\n * A completion may schedule:\n * - refresh (if the service has active quotes), and/or\n * - retry (quote-less/non-error completion, but only after any quote has existed in session).\n *\n * Then evaluates whether the full quoter can complete with `no-quotes`.\n */\n private onServiceDone(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n state.done = true;\n this.scheduleServiceRefresh(serviceType);\n\n if (this.hasReceivedAnyQuote && !state.hasErrored && !state.hasReturnedQuote) {\n this.scheduleServiceRetry(serviceType);\n }\n\n this.maybeCompleteNoQuotes();\n }\n\n /**\n * Complete with `no-quotes` when every eligible service has finished and\n * no quote was ever observed during this session.\n */\n private maybeCompleteNoQuotes(): void {\n if (!this.started || this.done || this.hasReceivedAnyQuote || this.serviceState.size === 0) {\n return;\n }\n\n const allServicesDone = [...this.serviceState.values()].every((state) => state.done);\n\n if (allServicesDone) {\n this.complete('no-quotes');\n }\n }\n\n /**\n * Finalize the quoter session and broadcast terminal reason exactly once.\n */\n private complete(reason: QuoterDoneReason): void {\n if (this.done) {\n return;\n }\n\n const payload = this.makeDonePayload(reason);\n\n this.done = true;\n this.stop();\n\n // When complete() happens during subscribe()->start(), emit done on a microtask\n // so callers can safely reference the returned unsubscribe in their handler.\n if (this.isStartingFromSubscribe) {\n queueMicrotask(() => {\n const handlers = [...this.subscribers];\n this.subscribers.clear();\n\n for (const handler of handlers) {\n handler('done', payload);\n }\n });\n return;\n }\n\n const handlers = [...this.subscribers];\n this.subscribers.clear();\n\n for (const handler of handlers) {\n handler('done', payload);\n }\n }\n\n private getInitializedServices(): ServiceType[] {\n return [...new Set(this.transferServices.map((service) => service.type))];\n }\n\n private getEligibleServices(): ServiceType[] {\n return [...this.serviceState.keys()];\n }\n\n private makeDonePayload(reason: QuoterDoneReason): QuoterDonePayload {\n if (reason === 'unsubscribed') {\n return { reason, data: undefined };\n }\n\n const initializedServices = this.getInitializedServices();\n\n if (reason === 'no-eligible-services') {\n return {\n reason,\n data: {\n initializedServices,\n quoterProps: this.props,\n },\n };\n }\n\n return {\n reason,\n data: {\n eligibleServices: this.getEligibleServices(),\n initializedServices,\n quoterProps: this.props,\n },\n };\n }\n\n /** Periodic prune tick to evict expired quotes and emit best changes. */\n private onPruneTick(): void {\n const now = this.clock();\n const pruned = pruneExpiredQuotes({ quotes: this.quotes, nowSeconds: now });\n\n if (pruned.length !== this.quotes.length) {\n this.quotes = sortQuotes(pruned);\n const best = this.quotes[0] ?? null;\n const bestId = best ? best.id : null;\n\n if (best && bestId !== this.lastBestId) {\n this.lastBestId = bestId;\n this.emitQuote({ bestQuote: best, quote: best, quotes: this.quotes });\n } else if (!best) {\n this.lastBestId = null;\n }\n }\n\n // Re-evaluate refresh scheduling for all services on prune tick\n for (const svc of this.transferServices) {\n if (this.serviceState.has(svc.type)) {\n this.scheduleServiceRefresh(svc.type);\n }\n }\n }\n\n /** Schedule a refresh (restart) of streaming for the service at its earliest quote expiration. */\n private scheduleServiceRefresh(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) return;\n\n const now = this.clock();\n const earliest = earliestExpirationForService({ quotes: this.quotes, serviceType, nowSeconds: now });\n\n if (earliest === null) {\n // No quotes -> clear any pending refresh\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n state.refreshTimer = null;\n }\n state.refreshAtSeconds = null;\n return;\n }\n\n // Only reschedule if earlier than currently scheduled or no timer\n const targetAt = Math.max(0, earliest - this.refreshBufferSeconds);\n\n // If target time has already passed, do not schedule another refresh here.\n if (targetAt <= now) {\n return;\n }\n\n // Reschedule only when the desired refresh time changes (earlier OR later).\n // We key refresh off the soonest-expiring active quote for this service.\n if (state.refreshAtSeconds === targetAt && state.refreshTimer) {\n return;\n }\n\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n }\n\n const delayMs = Math.max(0, (targetAt - now) * 1_000);\n state.refreshAtSeconds = targetAt;\n state.refreshTimer = setTimeout(() => {\n // Clear timer/marker before restarting to avoid stale state if restart fails.\n const current = this.serviceState.get(serviceType);\n if (current) {\n current.refreshTimer = null;\n current.refreshAtSeconds = null;\n }\n\n // Restart stream and clear timer/marker\n const svc = this.transferServices.find((s) => s.type === serviceType);\n\n if (svc) {\n this.startStreamForService(svc);\n }\n }, delayMs);\n }\n\n // ----- Emission helpers -----\n /** Emit a quote event to all subscribers. */\n private emitQuote(payload: { bestQuote: Quote; quote: Quote; quotes: readonly Quote[] }): void {\n for (const handler of this.subscribers) {\n handler('quote', payload);\n }\n }\n\n /** Emit an error event to all subscribers. */\n private emitError(error: Error): void {\n for (const handler of this.subscribers) {\n handler('error', error);\n }\n }\n}\n\n/**\n * Zod schema to validate the minimal Quote fields used for runtime gating.\n *\n * This is a simple schema, and is not a fully safe runtime validate for Quote.\n * That isn't necessary here since we only need to verify basic structure before\n * using the quote in internal logic.\n *\n * @internal\n */\nconst QuoteSchema = z.object({\n id: z.string(),\n expiresAt: z.number().int().nonnegative(),\n amountOut: z.bigint().nonnegative(),\n amountIn: z.bigint().nonnegative(),\n serviceType: z.string(),\n});\n\nfunction isInvalidSameChainQuoteRequest(props: QuoterProps): boolean {\n const { sourceAsset, sourceChain, targetAsset, targetChain } = props;\n\n if (sourceChain.chainId !== targetChain.chainId) {\n return false;\n }\n\n // Native -> native on the same chain is a no-op.\n if (isNativeAsset(sourceAsset) && isNativeAsset(targetAsset)) {\n return true;\n }\n\n // If token types differ, it's potentially a swap on the same chain.\n if (sourceAsset.type !== targetAsset.type) {\n return false;\n }\n\n // Same token type and address on the same chain is a no-op.\n if (sourceAsset.type === TokenType.ERC20 && targetAsset.type === TokenType.ERC20) {\n return isAddressEqual(sourceAsset.address, targetAsset.address);\n }\n\n if (sourceAsset.type === TokenType.SPL && targetAsset.type === TokenType.SPL) {\n return sourceAsset.address === targetAsset.address;\n }\n\n return false;\n}\n\nfunction isQuoteValue(value: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C,GAZE,GAVA,GAyBX,SAAS,EAAa,EAAgC,CAGpD,OAFe,EAAY,UAAU,EAAM,CAE7B"}
1
+ {"version":3,"file":"quoter.js","names":[],"sources":["../../src/quoter/quoter.ts"],"sourcesContent":["import { z } from 'zod';\nimport type {\n Quote,\n QuoterDonePayload,\n QuoterDoneReason,\n QuoterEventHandler,\n QuoterInterface,\n QuoterProps,\n ServiceQuoteEventArgs,\n QuotesTuple,\n ServiceQuoteEventHandler,\n} from '../types/quote';\nimport type { ServiceQuoteOptions, TransferService } from '../types/service';\nimport { earliestExpirationForService, isQuoteExpired, pruneExpiredQuotes, sortQuotes, upsertQuote } from './_utils';\nimport {\n QUOTER_DEFAULT_PRUNE_INTERVAL_MS,\n QUOTER_DEFAULT_REFRESH_BUFFER_SECONDS,\n QUOTER_EMPTY_RETRY_BASE_DELAY_MS,\n QUOTER_EMPTY_RETRY_MAX_DELAY_MS,\n} from './constants';\nimport { ServiceType, TokenType } from '../constants';\nimport { isNativeAsset } from '../type-guards';\nimport { isAddressEqual } from 'viem';\n\n/**\n * Function that returns the current UNIX time in seconds.\n * Injected for deterministic testing.\n */\nexport type Clock = () => number;\n\n/**\n * Options for constructing a Quoter instance.\n *\n * These options tune how often quote state is maintained and when services are\n * proactively restarted before quote expiry.\n */\nexport interface QuoterOptions {\n /**\n * Dangerously allows cross-chain quotes where fromAddress and toAddress differ\n * even when a service would otherwise require them to match.\n *\n * This is intended for explicit proxy-recipient funding flows. By default,\n * services preserve their existing address safety checks.\n */\n readonly dangerouslyAllowAddressMismatch?: boolean;\n /** Clock function returning current time in seconds (defaults to Date.now()/1000). */\n readonly clock?: Clock;\n /** Interval for pruning expired quotes (milliseconds).\n *\n * @default 1_000\n */\n readonly pruneIntervalMs?: number;\n /**\n * Amount of seconds to pre-buffer a stream restart before the earliest service quote\n * expiration. Helps ensure continuity before actual expiry is reached.\n *\n * @default 5\n */\n readonly refreshBufferSeconds?: number;\n}\n\n/**\n * Quoter orchestrates quote streaming across multiple transfer services and emits a unified event stream.\n *\n * High-level lifecycle:\n * - Idle until first subscriber.\n * - On first subscribe, starts all eligible services.\n * - Collects and ranks active quotes, pruning expired ones over time.\n * - Completes when explicitly unsubscribed (last subscriber), when no service is eligible,\n * or when all eligible services finish without producing any quote (`no-quotes`).\n *\n * Event model:\n * - Service `quote` -> Quoter upserts quote, recomputes best quote, emits `quote`.\n * - Service `error` -> Quoter emits `error` (non-terminal by itself).\n * - Service `done` -> Quoter marks that service attempt as completed and evaluates retry/complete rules.\n *\n * Retry/refresh behavior:\n * - Refresh: services that have active quotes are restarted shortly before the earliest quote expires.\n * - Retry: services that complete with no quote and no error are only retried after the quoter has\n * already observed at least one quote from any service in this session.\n *\n * This design keeps first-pass \"no quotes anywhere\" terminal and fast, while still allowing services\n * like Markr to be retried in sessions where other providers are returning quotes.\n */\nexport class Quoter implements QuoterInterface {\n private readonly clock: Clock;\n private readonly props: QuoterProps;\n private readonly pruneIntervalMs: number;\n private readonly serviceQuoteOptions: ServiceQuoteOptions;\n private readonly transferServices: readonly TransferService[];\n private readonly refreshBufferSeconds: number;\n\n private quotes: Quote[] = [];\n private subscribers: Set<QuoterEventHandler> = new Set();\n private started = false;\n private done = false;\n private isStartingFromSubscribe = false;\n private pruneTimerId: ReturnType<typeof setInterval> | null = null;\n private lastBestId: string | null = null;\n private hasReceivedAnyQuote = false;\n\n public readonly id: string = crypto.randomUUID();\n\n /**\n * Per-service runtime state for the active quote session.\n *\n * This tracks whether a service has completed, errored, produced quotes,\n * and any pending timers used for retry/refresh orchestration.\n */\n private serviceState: Map<\n TransferService['type'],\n {\n cancel: () => void;\n done: boolean;\n hasErrored: boolean;\n hasReturnedQuote: boolean;\n retryAttempt: number;\n retryTimer: ReturnType<typeof setTimeout> | null;\n refreshTimer: ReturnType<typeof setTimeout> | null;\n refreshAtSeconds: number | null;\n }\n > = new Map();\n\n /**\n * Create a new Quoter instance.\n *\n * @param props Quoting request parameters shared across all services.\n * @param transferServices Candidate services; eligibility is resolved at `start()` time.\n * @param options Optional runtime tuning for pruning and refresh behavior.\n */\n constructor(props: QuoterProps, transferServices: readonly TransferService[], options: QuoterOptions = {}) {\n this.clock = options.clock ?? (() => Math.floor(Date.now() / 1_000));\n this.props = props;\n this.pruneIntervalMs = options.pruneIntervalMs ?? QUOTER_DEFAULT_PRUNE_INTERVAL_MS;\n this.serviceQuoteOptions = {\n dangerouslyAllowAddressMismatch: options.dangerouslyAllowAddressMismatch,\n };\n this.transferServices = transferServices;\n this.refreshBufferSeconds = options.refreshBufferSeconds ?? QUOTER_DEFAULT_REFRESH_BUFFER_SECONDS;\n }\n\n /**\n * Get the current best quote and all active quotes (sorted by desirability).\n */\n public getQuotes(): QuotesTuple {\n const now = this.clock();\n const active = pruneExpiredQuotes({ quotes: this.quotes, nowSeconds: now });\n const sorted = sortQuotes(active);\n const best = sorted[0] ?? null;\n\n return [best, sorted];\n }\n\n /**\n * Subscribe for quoter events.\n *\n * First subscriber lazily starts orchestration.\n * Last subscriber triggers terminal completion with reason `unsubscribed`.\n *\n * @returns Unsubscribe function (idempotent).\n */\n public subscribe(handler: QuoterEventHandler): () => void {\n this.subscribers.add(handler);\n let unsubscribed = false;\n\n if (!this.started) {\n this.isStartingFromSubscribe = true;\n try {\n this.start();\n } finally {\n this.isStartingFromSubscribe = false;\n }\n }\n\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n\n if (this.done) {\n this.subscribers.delete(handler);\n return;\n }\n\n const wasLastSubscriber = this.subscribers.size === 1 && this.subscribers.has(handler);\n if (wasLastSubscriber) {\n this.complete('unsubscribed');\n return;\n }\n\n this.subscribers.delete(handler);\n };\n }\n\n // ----- Internal orchestration -----\n\n /**\n * Start a fresh quote session.\n *\n * Resets session-local state, validates basic request viability,\n * starts streams for eligible services, and begins prune ticks.\n */\n private start(): void {\n this.started = true;\n this.done = false;\n this.quotes = [];\n this.lastBestId = null;\n this.hasReceivedAnyQuote = false;\n\n // Same-chain quotes for the *same* asset are not a valid transfer scenario.\n if (isInvalidSameChainQuoteRequest(this.props)) {\n this.complete('no-eligible-services');\n return;\n }\n\n let hasEligibleService = false;\n\n // Start streams for eligible services\n for (const svc of this.transferServices) {\n const eligible = svc.analyzeSupport({\n sourceAsset: this.props.sourceAsset,\n sourceChainId: this.props.sourceChain.chainId,\n targetAsset: this.props.targetAsset,\n targetChainId: this.props.targetChain.chainId,\n });\n\n if (!eligible) continue;\n hasEligibleService = true;\n\n this.startStreamForService(svc);\n }\n\n if (!hasEligibleService) {\n this.complete('no-eligible-services');\n return;\n }\n\n // Start periodic prune\n this.pruneTimerId = setInterval(() => this.onPruneTick(), this.pruneIntervalMs);\n }\n\n /**\n * Stop all streams and timers.\n * Quotes are retained for snapshot access via getQuotes(), though they\n * can still be pruned due to expiration.\n */\n private stop(): void {\n this.started = false;\n\n if (this.pruneTimerId) {\n clearInterval(this.pruneTimerId);\n this.pruneTimerId = null;\n }\n\n for (const [type, state] of this.serviceState) {\n try {\n state.cancel();\n } catch {\n /* ignore */\n }\n\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n }\n\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n }\n\n this.serviceState.set(type, {\n cancel: () => {},\n done: false,\n hasErrored: false,\n hasReturnedQuote: false,\n retryAttempt: 0,\n retryTimer: null,\n refreshTimer: null,\n refreshAtSeconds: null,\n });\n }\n }\n\n /**\n * Begin or restart streaming for a specific service.\n *\n * Any previous stream/timers for that service are canceled before starting a new attempt.\n */\n private startStreamForService(svc: TransferService): void {\n // Clean up any existing stream and refresh timer\n const existing = this.serviceState.get(svc.type);\n\n if (existing) {\n try {\n existing.cancel();\n } catch {\n /* ignore */\n }\n\n if (existing.refreshTimer) clearTimeout(existing.refreshTimer);\n if (existing.retryTimer) clearTimeout(existing.retryTimer);\n }\n\n const handler = this.makeServiceHandler(svc.type);\n const bufferedEvents: ServiceQuoteEventArgs[] = [];\n let isStartingStream = true;\n\n // Some services emit quote/done synchronously inside streamQuotes().\n // If those events run before subscribe() returns, consumers can hit TDZ\n // when they reference the returned unsubscribe function in their callback.\n // Buffer startup emissions and flush them after stream initialization.\n const guardedHandler: ServiceQuoteEventHandler = (...eventArgs) => {\n if (isStartingStream) {\n bufferedEvents.push(eventArgs);\n return;\n }\n\n handler(...eventArgs);\n };\n\n const { cancel } = svc.streamQuotes(this.props, guardedHandler, this.serviceQuoteOptions);\n isStartingStream = false;\n\n if (bufferedEvents.length > 0) {\n // Use a microtask so subscribe() can return before the first callback fires.\n // This preserves event order while avoiding re-entrancy during subscription.\n queueMicrotask(() => {\n for (const bufferedEvent of bufferedEvents) {\n handler(...bufferedEvent);\n }\n });\n }\n\n this.serviceState.set(svc.type, {\n cancel,\n done: false,\n hasErrored: false,\n hasReturnedQuote: false,\n retryAttempt: existing?.retryAttempt ?? 0,\n retryTimer: null,\n refreshTimer: null,\n refreshAtSeconds: null,\n });\n }\n\n /**\n * Create the service-scoped event handler consumed by `TransferService.streamQuotes`.\n *\n * The handler enforces service/quote consistency and translates service events into\n * quoter state transitions.\n */\n private makeServiceHandler(serviceType: TransferService['type']): ServiceQuoteEventHandler {\n return (event, ...args) => {\n // Ignore any service events once stopped to prevent post-stop mutations.\n if (!this.started) {\n return;\n }\n if (event === 'quote') {\n const maybeQuote = args[0];\n if (isQuoteValue(maybeQuote)) {\n // Enforce the quote belongs to the emitting service\n if (maybeQuote.serviceType !== serviceType) {\n // Ignore quotes mismatched to service; defensive\n return;\n }\n const state = this.serviceState.get(serviceType);\n if (state) {\n state.hasReturnedQuote = true;\n }\n this.onIncomingQuote(maybeQuote);\n this.scheduleServiceRefresh(serviceType);\n }\n\n return;\n }\n if (event === 'done') {\n this.onServiceDone(serviceType);\n\n return;\n }\n if (event === 'error') {\n const state = this.serviceState.get(serviceType);\n if (state) {\n state.hasErrored = true;\n }\n const maybeErr = args[0];\n if (maybeErr instanceof Error) {\n this.emitError(maybeErr);\n }\n }\n };\n }\n\n /**\n * Handle an incoming quote event.\n *\n * Expired quotes are ignored. Valid quotes are upserted into active state,\n * then sorted/pruned and emitted to subscribers.\n */\n private onIncomingQuote(quote: Quote): void {\n const now = this.clock();\n\n if (isQuoteExpired({ quote, nowSeconds: now })) {\n return;\n }\n\n this.hasReceivedAnyQuote = true;\n\n this.resetRetryForService(quote.serviceType);\n\n this.quotes = sortQuotes(pruneExpiredQuotes({ quotes: upsertQuote(this.quotes, quote), nowSeconds: now }));\n\n // Always emit on every incoming quote\n const best = this.quotes[0];\n if (best) {\n this.lastBestId = best.id;\n this.emitQuote({ bestQuote: best, quote, quotes: this.quotes });\n }\n }\n\n private resetRetryForService(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n state.retryAttempt = 0;\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n state.retryTimer = null;\n }\n }\n\n /**\n * Schedule a retry attempt for a service using exponential backoff.\n *\n * This is used only for quote-less successful completions once the overall session\n * has already produced at least one quote from some service.\n */\n private scheduleServiceRetry(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n if (state.retryTimer) {\n clearTimeout(state.retryTimer);\n state.retryTimer = null;\n }\n\n const delayMs = Math.min(\n QUOTER_EMPTY_RETRY_MAX_DELAY_MS,\n QUOTER_EMPTY_RETRY_BASE_DELAY_MS * 2 ** state.retryAttempt,\n );\n state.retryAttempt += 1;\n\n state.retryTimer = setTimeout(\n () => {\n const current = this.serviceState.get(serviceType);\n if (current) {\n current.retryTimer = null;\n }\n\n if (!this.started) {\n return;\n }\n\n const svc = this.transferServices.find((s) => s.type === serviceType);\n if (svc) {\n this.startStreamForService(svc);\n }\n },\n Math.max(0, delayMs),\n );\n }\n\n /**\n * Handle service completion (`done`).\n *\n * A completion may schedule:\n * - refresh (if the service has active quotes), and/or\n * - retry (quote-less/non-error completion, but only after any quote has existed in session).\n *\n * Then evaluates whether the full quoter can complete with `no-quotes`.\n */\n private onServiceDone(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) {\n return;\n }\n\n state.done = true;\n this.scheduleServiceRefresh(serviceType);\n\n if (this.hasReceivedAnyQuote && !state.hasErrored && !state.hasReturnedQuote) {\n this.scheduleServiceRetry(serviceType);\n }\n\n this.maybeCompleteNoQuotes();\n }\n\n /**\n * Complete with `no-quotes` when every eligible service has finished and\n * no quote was ever observed during this session.\n */\n private maybeCompleteNoQuotes(): void {\n if (!this.started || this.done || this.hasReceivedAnyQuote || this.serviceState.size === 0) {\n return;\n }\n\n const allServicesDone = [...this.serviceState.values()].every((state) => state.done);\n\n if (allServicesDone) {\n this.complete('no-quotes');\n }\n }\n\n /**\n * Finalize the quoter session and broadcast terminal reason exactly once.\n */\n private complete(reason: QuoterDoneReason): void {\n if (this.done) {\n return;\n }\n\n const payload = this.makeDonePayload(reason);\n\n this.done = true;\n this.stop();\n\n // When complete() happens during subscribe()->start(), emit done on a microtask\n // so callers can safely reference the returned unsubscribe in their handler.\n if (this.isStartingFromSubscribe) {\n queueMicrotask(() => {\n const handlers = [...this.subscribers];\n this.subscribers.clear();\n\n for (const handler of handlers) {\n handler('done', payload);\n }\n });\n return;\n }\n\n const handlers = [...this.subscribers];\n this.subscribers.clear();\n\n for (const handler of handlers) {\n handler('done', payload);\n }\n }\n\n private getInitializedServices(): ServiceType[] {\n return [...new Set(this.transferServices.map((service) => service.type))];\n }\n\n private getEligibleServices(): ServiceType[] {\n return [...this.serviceState.keys()];\n }\n\n private makeDonePayload(reason: QuoterDoneReason): QuoterDonePayload {\n if (reason === 'unsubscribed') {\n return { reason, data: undefined };\n }\n\n const initializedServices = this.getInitializedServices();\n\n if (reason === 'no-eligible-services') {\n return {\n reason,\n data: {\n initializedServices,\n quoterProps: this.props,\n },\n };\n }\n\n return {\n reason,\n data: {\n eligibleServices: this.getEligibleServices(),\n initializedServices,\n quoterProps: this.props,\n },\n };\n }\n\n /** Periodic prune tick to evict expired quotes and emit best changes. */\n private onPruneTick(): void {\n const now = this.clock();\n const pruned = pruneExpiredQuotes({ quotes: this.quotes, nowSeconds: now });\n\n if (pruned.length !== this.quotes.length) {\n this.quotes = sortQuotes(pruned);\n const best = this.quotes[0] ?? null;\n const bestId = best ? best.id : null;\n\n if (best && bestId !== this.lastBestId) {\n this.lastBestId = bestId;\n this.emitQuote({ bestQuote: best, quote: best, quotes: this.quotes });\n } else if (!best) {\n this.lastBestId = null;\n }\n }\n\n // Re-evaluate refresh scheduling for all services on prune tick\n for (const svc of this.transferServices) {\n if (this.serviceState.has(svc.type)) {\n this.scheduleServiceRefresh(svc.type);\n }\n }\n }\n\n /** Schedule a refresh (restart) of streaming for the service at its earliest quote expiration. */\n private scheduleServiceRefresh(serviceType: TransferService['type']): void {\n const state = this.serviceState.get(serviceType);\n\n if (!state) return;\n\n const now = this.clock();\n const earliest = earliestExpirationForService({ quotes: this.quotes, serviceType, nowSeconds: now });\n\n if (earliest === null) {\n // No quotes -> clear any pending refresh\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n state.refreshTimer = null;\n }\n state.refreshAtSeconds = null;\n return;\n }\n\n // Only reschedule if earlier than currently scheduled or no timer\n const targetAt = Math.max(0, earliest - this.refreshBufferSeconds);\n\n // If target time has already passed, do not schedule another refresh here.\n if (targetAt <= now) {\n return;\n }\n\n // Reschedule only when the desired refresh time changes (earlier OR later).\n // We key refresh off the soonest-expiring active quote for this service.\n if (state.refreshAtSeconds === targetAt && state.refreshTimer) {\n return;\n }\n\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n }\n\n const delayMs = Math.max(0, (targetAt - now) * 1_000);\n state.refreshAtSeconds = targetAt;\n state.refreshTimer = setTimeout(() => {\n // Clear timer/marker before restarting to avoid stale state if restart fails.\n const current = this.serviceState.get(serviceType);\n if (current) {\n current.refreshTimer = null;\n current.refreshAtSeconds = null;\n }\n\n // Restart stream and clear timer/marker\n const svc = this.transferServices.find((s) => s.type === serviceType);\n\n if (svc) {\n this.startStreamForService(svc);\n }\n }, delayMs);\n }\n\n // ----- Emission helpers -----\n /** Emit a quote event to all subscribers. */\n private emitQuote(payload: { bestQuote: Quote; quote: Quote; quotes: readonly Quote[] }): void {\n for (const handler of this.subscribers) {\n handler('quote', payload);\n }\n }\n\n /** Emit an error event to all subscribers. */\n private emitError(error: Error): void {\n for (const handler of this.subscribers) {\n handler('error', error);\n }\n }\n}\n\n/**\n * Zod schema to validate the minimal Quote fields used for runtime gating.\n *\n * This is a simple schema, and is not a fully safe runtime validate for Quote.\n * That isn't necessary here since we only need to verify basic structure before\n * using the quote in internal logic.\n *\n * @internal\n */\nconst QuoteSchema = z.object({\n id: z.string(),\n expiresAt: z.number().int().nonnegative(),\n amountOut: z.bigint().nonnegative(),\n amountIn: z.bigint().nonnegative(),\n serviceType: z.string(),\n});\n\nfunction isInvalidSameChainQuoteRequest(props: QuoterProps): boolean {\n const { sourceAsset, sourceChain, targetAsset, targetChain } = props;\n\n if (sourceChain.chainId !== targetChain.chainId) {\n return false;\n }\n\n // Native -> native on the same chain is a no-op.\n if (isNativeAsset(sourceAsset) && isNativeAsset(targetAsset)) {\n return true;\n }\n\n // If token types differ, it's potentially a swap on the same chain.\n if (sourceAsset.type !== targetAsset.type) {\n return false;\n }\n\n // Same token type and address on the same chain is a no-op.\n if (sourceAsset.type === TokenType.ERC20 && targetAsset.type === TokenType.ERC20) {\n return isAddressEqual(sourceAsset.address, targetAsset.address);\n }\n\n if (sourceAsset.type === TokenType.SPL && targetAsset.type === TokenType.SPL) {\n return sourceAsset.address === targetAsset.address;\n }\n\n return false;\n}\n\nfunction isQuoteValue(value: unknown): value is Quote {\n const result = QuoteSchema.safeParse(value);\n\n return result.success;\n}\n"],"mappings":"2YAoFA,IAAa,EAAb,KAA+C,CAC7C,MACA,MACA,gBACA,oBACA,iBACA,qBAEA,OAA0B,EAAE,CAC5B,YAA+C,IAAI,IACnD,QAAkB,GAClB,KAAe,GACf,wBAAkC,GAClC,aAA8D,KAC9D,WAAoC,KACpC,oBAA8B,GAE9B,GAA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js`),r=require(`../_type-guards.cjs`);let i=require(`viem`);function a({clock:a=()=>Math.floor(Date.now()/1e3),environment:o,getAtomicUtxos:s}){return(c,l)=>{let u=new AbortController,d=()=>u.abort();if(o!==e.Environment.PROD&&o!==e.Environment.TEST)return u.signal.aborted||(l(`error`,new t.InvalidParamsError(`Unsupported environment for Avalanche CCT service.`)),l(`done`)),{cancel:d};let f=o===e.Environment.TEST,p=c.fromAddress,m=c.toAddress,h=f?e.AvalancheFujiBlockchainChainIds.C:e.AvalancheMainnetBlockchainChainIds.C,g=c.sourceChain.chainId===h,_=c.targetChain.chainId===h,v=g?(0,i.isAddress)(p):r.isXpAddressFullyValid(p)&&n.xpAddressMatchesNetwork(p,f),y=_?(0,i.isAddress)(m):r.isXpAddressFullyValid(m)&&n.xpAddressMatchesNetwork(m,f);if(!v||!y)return u.signal.aborted||(l(`error`,new t.InvalidParamsError(`Invalid fromAddress or toAddress for the specified environment.`,`Address types must match chain type: C-Chain uses EVM addresses, P/X chains use XP bech32 addresses for the selected environment.`)),l(`done`)),{cancel:d};let b=g||_;return b&&p===m?(u.signal.aborted||(l(`error`,new t.InvalidParamsError(`fromAddress and toAddress must be different when C-Chain is involved.`)),l(`done`)),{cancel:d}):!b&&n.stripAddressPrefix(p)!==n.stripAddressPrefix(m)?(u.signal.aborted||(l(`error`,new t.InvalidParamsError(`fromAddress and toAddress must be the same for P↔X transfers.`)),l(`done`)),{cancel:d}):((async()=>{let t=n.getChainAlias(c.sourceChain.chainId,f),r=n.getChainAlias(c.targetChain.chainId,f),i=n.getUtxosTotalAmount((await s(r,t)).getUTXOs());if(t===`C`&&c.amount!==0n&&c.amount<1000000000n){u.signal.aborted||l(`done`);return}if(c.amount===0n&&i===0n){u.signal.aborted||l(`done`);return}let o=n.getNativeTokenForChainAlias(t),d=n.getNativeTokenForChainAlias(r),p=n.getOutputAmountForAvalancheCct({amountIn:c.amount,sourceAsset:o,targetAsset:d});if(p===0n){u.signal.aborted||l(`done`);return}let m=n.getOutputAmountForAvalancheCct({amountIn:i,sourceAsset:n.getNativeTokenForChainAlias(`P`),targetAsset:d}),h={aggregator:{id:`avalanche-cct`,name:`Avalanche CCT`},amountIn:c.amount,amountOut:p+m,assetIn:o,assetOut:d,expiresAt:a()+60,fees:[],fromAddress:c.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:e.ServiceType.AVALANCHE_CCT,slippageBps:0,sourceChain:c.sourceChain,targetChain:c.targetChain,toAddress:c.toAddress};u.signal.aborted||(l(`quote`,h),l(`done`))})().catch(e=>{u.signal.aborted||(l(`error`,new t.SdkError(t.ErrorReason.UNKNOWN,t.ErrorCode.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),l(`done`))}),{cancel:d})}}exports.streamQuotesFactory=a;
1
+ require(`../../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../../constants.cjs`),t=require(`../../../errors.cjs`),n=require(`../_utils.cjs`),r=require(`../_type-guards.cjs`);let i=require(`viem`);function a({clock:a=()=>Math.floor(Date.now()/1e3),environment:o,getAtomicUtxos:s}){return(c,l)=>{let u=new AbortController,d=()=>u.abort();if(o!==e.Environment.PROD&&o!==e.Environment.TEST)return u.signal.aborted||(l(`error`,new t.InvalidParamsError(`Unsupported environment for Avalanche CCT service.`)),l(`done`)),{cancel:d};let f=o===e.Environment.TEST,p=c.fromAddress,m=c.toAddress,h=f?e.AvalancheFujiBlockchainChainIds.C:e.AvalancheMainnetBlockchainChainIds.C,g=c.sourceChain.chainId===h,_=c.targetChain.chainId===h,v=g?(0,i.isAddress)(p):r.isXpAddressFullyValid(p)&&n.xpAddressMatchesNetwork(p,f),y=_?(0,i.isAddress)(m):r.isXpAddressFullyValid(m)&&n.xpAddressMatchesNetwork(m,f);if(!v||!y)return u.signal.aborted||(l(`error`,new t.InvalidParamsError(`Invalid fromAddress or toAddress for the specified environment.`,`Address types must match chain type: C-Chain uses EVM addresses, P/X chains use XP bech32 addresses for the selected environment.`)),l(`done`)),{cancel:d};let b=g||_;return b&&p===m?(u.signal.aborted||(l(`error`,new t.InvalidParamsError(`fromAddress and toAddress must be different when C-Chain is involved.`)),l(`done`)),{cancel:d}):!b&&n.stripAddressPrefix(p)!==n.stripAddressPrefix(m)?(u.signal.aborted||(l(`error`,new t.InvalidParamsError(`fromAddress and toAddress must be the same for P↔X transfers.`)),l(`done`)),{cancel:d}):((async()=>{let t=n.getChainAlias(c.sourceChain.chainId,f),r=n.getChainAlias(c.targetChain.chainId,f),i=n.getUtxosTotalAmount((await s(r,t)).getUTXOs());if(t===`C`&&c.amount!==0n&&c.amount<1000000000n){u.signal.aborted||l(`done`);return}if(c.amount===0n&&i===0n){u.signal.aborted||l(`done`);return}let o=n.getNativeTokenForChainAlias(t),d=n.getNativeTokenForChainAlias(r),p=n.getOutputAmountForAvalancheCct({amountIn:c.amount,sourceAsset:o,targetAsset:d});if(p===0n&&i===0n){u.signal.aborted||l(`done`);return}let m=n.getOutputAmountForAvalancheCct({amountIn:i,sourceAsset:n.getNativeTokenForChainAlias(`P`),targetAsset:d}),h={aggregator:{id:`avalanche-cct`,name:`Avalanche CCT`},amountIn:c.amount,amountOut:p+m,assetIn:o,assetOut:d,expiresAt:a()+60,fees:[],fromAddress:c.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:e.ServiceType.AVALANCHE_CCT,slippageBps:0,sourceChain:c.sourceChain,targetChain:c.targetChain,toAddress:c.toAddress};u.signal.aborted||(l(`quote`,h),l(`done`))})().catch(e=>{u.signal.aborted||(l(`error`,new t.SdkError(t.ErrorReason.UNKNOWN,t.ErrorCode.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),l(`done`))}),{cancel:d})}}exports.streamQuotesFactory=a;
2
2
  //# sourceMappingURL=stream-quotes.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"stream-quotes.cjs","names":["Environment","InvalidParamsError","AvalancheFujiBlockchainChainIds","AvalancheMainnetBlockchainChainIds","isXpAddressFullyValid","xpAddressMatchesNetwork","stripAddressPrefix","getChainAlias","getUtxosTotalAmount","getNativeTokenForChainAlias","getOutputAmountForAvalancheCct","ServiceType","SdkError","ErrorReason","ErrorCode"],"sources":["../../../../src/transfer-service/avalanche-cct/_handlers/stream-quotes.ts"],"sourcesContent":["import { isAddress } from 'viem';\nimport {\n AvalancheFujiBlockchainChainIds,\n AvalancheMainnetBlockchainChainIds,\n Environment,\n ServiceType,\n type AvalancheBlockchainAlias,\n} from '../../../constants';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { TransferService } from '../../../types/service';\nimport type { Quote } from '../../../types/quote';\nimport { isXpAddressFullyValid } from '../_type-guards';\nimport {\n getChainAlias,\n getNativeTokenForChainAlias,\n getOutputAmountForAvalancheCct,\n getUtxosTotalAmount,\n stripAddressPrefix,\n xpAddressMatchesNetwork,\n} from '../_utils';\nimport type { GetAtomicUtxosCallback } from '../types';\n\nexport interface StreamQuotesOptions {\n clock?: () => number;\n environment: Environment;\n getAtomicUtxos: GetAtomicUtxosCallback;\n}\n\nexport function streamQuotesFactory({\n clock = () => Math.floor(Date.now() / 1000),\n environment,\n getAtomicUtxos,\n}: StreamQuotesOptions): TransferService['streamQuotes'] {\n return (props, handler) => {\n const ac = new AbortController();\n const cancel = () => ac.abort();\n\n if (environment !== Environment.PROD && environment !== Environment.TEST) {\n if (!ac.signal.aborted) {\n handler('error', new InvalidParamsError('Unsupported environment for Avalanche CCT service.'));\n handler('done');\n }\n\n return { cancel };\n }\n\n const isTestnet = environment === Environment.TEST;\n\n const fromAddress = props.fromAddress;\n const toAddress = props.toAddress;\n const cChainId = isTestnet ? AvalancheFujiBlockchainChainIds.C : AvalancheMainnetBlockchainChainIds.C;\n const isSourceChainC = props.sourceChain.chainId === cChainId;\n const isTargetChainC = props.targetChain.chainId === cChainId;\n\n const isFromAddressValid = isSourceChainC\n ? isAddress(fromAddress)\n : isXpAddressFullyValid(fromAddress) && xpAddressMatchesNetwork(fromAddress, isTestnet);\n\n const isToAddressValid = isTargetChainC\n ? isAddress(toAddress)\n : isXpAddressFullyValid(toAddress) && xpAddressMatchesNetwork(toAddress, isTestnet);\n\n if (!isFromAddressValid || !isToAddressValid) {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new InvalidParamsError(\n 'Invalid fromAddress or toAddress for the specified environment.',\n 'Address types must match chain type: C-Chain uses EVM addresses, P/X chains use XP bech32 addresses for the selected environment.',\n ),\n );\n handler('done');\n }\n\n return {\n cancel,\n };\n }\n\n // Validate addresses equal if both chains are P/X and different if either chain is C.\n const isEitherChainC = isSourceChainC || isTargetChainC;\n\n if (isEitherChainC && fromAddress === toAddress) {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new InvalidParamsError('fromAddress and toAddress must be different when C-Chain is involved.'),\n );\n handler('done');\n }\n\n return { cancel };\n }\n\n if (!isEitherChainC && stripAddressPrefix(fromAddress) !== stripAddressPrefix(toAddress)) {\n if (!ac.signal.aborted) {\n handler('error', new InvalidParamsError('fromAddress and toAddress must be the same for P↔X transfers.'));\n handler('done');\n }\n\n return { cancel };\n }\n\n (async () => {\n const sourceChainAlias: AvalancheBlockchainAlias = getChainAlias(props.sourceChain.chainId, isTestnet);\n const destinationChainAlias: AvalancheBlockchainAlias = getChainAlias(props.targetChain.chainId, isTestnet);\n const atomicUtxoSet = await getAtomicUtxos(destinationChainAlias, sourceChainAlias);\n const atomicUtxos = atomicUtxoSet.getUTXOs();\n const atomicUtxosTotalAmount = getUtxosTotalAmount(atomicUtxos);\n\n // If source is C-Chain, the props amount must be either `0n` or _at least_ one nano AVAX.\n // Otherwise, we should just emit a \"done\" event.\n if (sourceChainAlias === 'C' && props.amount !== 0n && props.amount < 1_000_000_000n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n // Special case for 0 amount transfers where user intends to finish stuck atomic imports.\n if (props.amount === 0n && atomicUtxosTotalAmount === 0n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n const assetIn = getNativeTokenForChainAlias(sourceChainAlias);\n const assetOut = getNativeTokenForChainAlias(destinationChainAlias);\n const amountIn = getOutputAmountForAvalancheCct({\n amountIn: props.amount,\n sourceAsset: assetIn,\n targetAsset: assetOut,\n });\n\n // Emit no quotes if `amountIn` is 0\n // This can happen if the user tries to transfer an amount below 1 nano AVAX from the C-Chain.\n if (amountIn === 0n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n // TODO: Do we need to account for subtracting import fees from these UTXOs\n // in order to give an accurate picture of how much the user will receive on the other side?\n const amountOutFromAtomicUtxos = getOutputAmountForAvalancheCct({\n amountIn: atomicUtxosTotalAmount,\n sourceAsset: getNativeTokenForChainAlias('P'),\n targetAsset: assetOut,\n });\n\n const quote: Quote = {\n aggregator: {\n id: 'avalanche-cct',\n name: 'Avalanche CCT',\n },\n amountIn: props.amount,\n amountOut: amountIn + amountOutFromAtomicUtxos,\n assetIn,\n assetOut,\n expiresAt: clock() + 60, // Expire in 1 minute.\n fees: [],\n fromAddress: props.fromAddress,\n id: crypto.randomUUID(),\n partnerFeeBps: null,\n serviceType: ServiceType.AVALANCHE_CCT,\n slippageBps: 0,\n sourceChain: props.sourceChain,\n targetChain: props.targetChain,\n toAddress: props.toAddress,\n };\n\n if (!ac.signal.aborted) {\n handler('quote', quote);\n handler('done');\n }\n })().catch((error) => {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new SdkError(ErrorReason.UNKNOWN, ErrorCode.UNKNOWN, { cause: error, details: 'Failed to stream quotes' }),\n );\n handler('done');\n }\n });\n\n return {\n cancel,\n };\n };\n}\n"],"mappings":"gNA4BA,SAAgB,EAAoB,CAClC,YAAc,KAAK,MAAM,KAAK,KAAK,CAAG,IAAK,CAC3C,cACA,kBACuD,CACvD,OAAQ,EAAO,IAAY,CACzB,IAAM,EAAK,IAAI,gBACT,MAAe,EAAG,OAAO,CAE/B,GAAI,IAAgBA,EAAAA,YAAY,MAAQ,IAAgBA,EAAAA,YAAY,KAMlE,OALK,EAAG,OAAO,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W,IAAM,EAAM,OAAS,YAAgB,CAC/E,EAAG,OAAO,SACb,EAAQ,OAAO,CAGjB,OAIF,GAAI,EAAM,SAAW,IAAM,IAA2B,GAAI,CACnD,EAAG,OAAO,SACb,EAAQ,OAAO,CAGjB,OAGF,IAAM,EAAUC,EAAAA,4BAA4B,EAAiB,CACvD,EAAWA,EAAAA,4BAA4B,EAAsB,CAC7D,EAAWC,EAAAA,+BAA+B,CAC9C,SAAU,EAAM,OAChB,YAAa,EACb,YAAa,EACd,CAAC,CAIF,GAAI,IAAa,GAAI,CACd,EAAG,OAAO,SACb,EAAQ,OAAO,CAGjB,OAKF,IAAM,EAA2BA,EAAAA,+BAA+B,CAC9D,SAAU,EACV,YAAaD,EAAAA,4BAA4B,IAAI,CAC7C,YAAa,EACd,CAAC,CAEI,EAAe,CACnB,WAAY,CACV,GAAI,gBACJ,KAAM,gBACP,CACD,SAAU,EAAM,OAChB,UAAW,EAAW,EACtB,UACA,WACA,UAAW,GAAO,CAAG,GACrB,KAAM,EAAE,CACR,YAAa,EAAM,YACnB,GAAI,OAAO,YAAY,CACvB,cAAe,KACf,YAAaE,EAAAA,YAAY,cACzB,YAAa,EACb,YAAa,EAAM,YACnB,YAAa,EAAM,YACnB,UAAW,EAAM,UAClB,CAEI,EAAG,OAAO,UACb,EAAQ,QAAS,EAAM,CACvB,EAAQ,OAAO,KAEf,CAAC,MAAO,GAAU,CACf,EAAG,OAAO,UACb,EACE,QACA,IAAIC,EAAAA,SAASC,EAAAA,YAAY,QAASC,EAAAA,UAAU,QAAS,CAAE,MAAO,EAAO,QAAS,0BAA2B,CAAC,CAC3G,CACD,EAAQ,OAAO,GAEjB,CAEK,CACL,SACD"}
1
+ {"version":3,"file":"stream-quotes.cjs","names":["Environment","InvalidParamsError","AvalancheFujiBlockchainChainIds","AvalancheMainnetBlockchainChainIds","isXpAddressFullyValid","xpAddressMatchesNetwork","stripAddressPrefix","getChainAlias","getUtxosTotalAmount","getNativeTokenForChainAlias","getOutputAmountForAvalancheCct","ServiceType","SdkError","ErrorReason","ErrorCode"],"sources":["../../../../src/transfer-service/avalanche-cct/_handlers/stream-quotes.ts"],"sourcesContent":["import { isAddress } from 'viem';\nimport {\n AvalancheFujiBlockchainChainIds,\n AvalancheMainnetBlockchainChainIds,\n Environment,\n ServiceType,\n type AvalancheBlockchainAlias,\n} from '../../../constants';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { TransferService } from '../../../types/service';\nimport type { Quote } from '../../../types/quote';\nimport { isXpAddressFullyValid } from '../_type-guards';\nimport {\n getChainAlias,\n getNativeTokenForChainAlias,\n getOutputAmountForAvalancheCct,\n getUtxosTotalAmount,\n stripAddressPrefix,\n xpAddressMatchesNetwork,\n} from '../_utils';\nimport type { GetAtomicUtxosCallback } from '../types';\n\nexport interface StreamQuotesOptions {\n clock?: () => number;\n environment: Environment;\n getAtomicUtxos: GetAtomicUtxosCallback;\n}\n\nexport function streamQuotesFactory({\n clock = () => Math.floor(Date.now() / 1000),\n environment,\n getAtomicUtxos,\n}: StreamQuotesOptions): TransferService['streamQuotes'] {\n return (props, handler) => {\n const ac = new AbortController();\n const cancel = () => ac.abort();\n\n if (environment !== Environment.PROD && environment !== Environment.TEST) {\n if (!ac.signal.aborted) {\n handler('error', new InvalidParamsError('Unsupported environment for Avalanche CCT service.'));\n handler('done');\n }\n\n return { cancel };\n }\n\n const isTestnet = environment === Environment.TEST;\n\n const fromAddress = props.fromAddress;\n const toAddress = props.toAddress;\n const cChainId = isTestnet ? AvalancheFujiBlockchainChainIds.C : AvalancheMainnetBlockchainChainIds.C;\n const isSourceChainC = props.sourceChain.chainId === cChainId;\n const isTargetChainC = props.targetChain.chainId === cChainId;\n\n const isFromAddressValid = isSourceChainC\n ? isAddress(fromAddress)\n : isXpAddressFullyValid(fromAddress) && xpAddressMatchesNetwork(fromAddress, isTestnet);\n\n const isToAddressValid = isTargetChainC\n ? isAddress(toAddress)\n : isXpAddressFullyValid(toAddress) && xpAddressMatchesNetwork(toAddress, isTestnet);\n\n if (!isFromAddressValid || !isToAddressValid) {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new InvalidParamsError(\n 'Invalid fromAddress or toAddress for the specified environment.',\n 'Address types must match chain type: C-Chain uses EVM addresses, P/X chains use XP bech32 addresses for the selected environment.',\n ),\n );\n handler('done');\n }\n\n return {\n cancel,\n };\n }\n\n // Validate addresses equal if both chains are P/X and different if either chain is C.\n const isEitherChainC = isSourceChainC || isTargetChainC;\n\n if (isEitherChainC && fromAddress === toAddress) {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new InvalidParamsError('fromAddress and toAddress must be different when C-Chain is involved.'),\n );\n handler('done');\n }\n\n return { cancel };\n }\n\n if (!isEitherChainC && stripAddressPrefix(fromAddress) !== stripAddressPrefix(toAddress)) {\n if (!ac.signal.aborted) {\n handler('error', new InvalidParamsError('fromAddress and toAddress must be the same for P↔X transfers.'));\n handler('done');\n }\n\n return { cancel };\n }\n\n (async () => {\n const sourceChainAlias: AvalancheBlockchainAlias = getChainAlias(props.sourceChain.chainId, isTestnet);\n const destinationChainAlias: AvalancheBlockchainAlias = getChainAlias(props.targetChain.chainId, isTestnet);\n const atomicUtxoSet = await getAtomicUtxos(destinationChainAlias, sourceChainAlias);\n const atomicUtxos = atomicUtxoSet.getUTXOs();\n const atomicUtxosTotalAmount = getUtxosTotalAmount(atomicUtxos);\n\n // If source is C-Chain, the props amount must be either `0n` or _at least_ one nano AVAX.\n // Otherwise, we should just emit a \"done\" event.\n if (sourceChainAlias === 'C' && props.amount !== 0n && props.amount < 1_000_000_000n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n // Special case for 0 amount transfers where user intends to finish stuck atomic imports.\n if (props.amount === 0n && atomicUtxosTotalAmount === 0n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n const assetIn = getNativeTokenForChainAlias(sourceChainAlias);\n const assetOut = getNativeTokenForChainAlias(destinationChainAlias);\n const amountIn = getOutputAmountForAvalancheCct({\n amountIn: props.amount,\n sourceAsset: assetIn,\n targetAsset: assetOut,\n });\n\n // Emit no quotes if `amountIn` is 0 and there are no atomic UTXOs.\n // Zero-amount requests with atomic UTXOs should still emit a quote to unblock stuck imports.\n if (amountIn === 0n && atomicUtxosTotalAmount === 0n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n const amountOutFromAtomicUtxos = getOutputAmountForAvalancheCct({\n amountIn: atomicUtxosTotalAmount,\n sourceAsset: getNativeTokenForChainAlias('P'),\n targetAsset: assetOut,\n });\n\n const quote: Quote = {\n aggregator: {\n id: 'avalanche-cct',\n name: 'Avalanche CCT',\n },\n amountIn: props.amount,\n amountOut: amountIn + amountOutFromAtomicUtxos,\n assetIn,\n assetOut,\n expiresAt: clock() + 60, // Expire in 1 minute.\n fees: [],\n fromAddress: props.fromAddress,\n id: crypto.randomUUID(),\n partnerFeeBps: null,\n serviceType: ServiceType.AVALANCHE_CCT,\n slippageBps: 0,\n sourceChain: props.sourceChain,\n targetChain: props.targetChain,\n toAddress: props.toAddress,\n };\n\n if (!ac.signal.aborted) {\n handler('quote', quote);\n handler('done');\n }\n })().catch((error) => {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new SdkError(ErrorReason.UNKNOWN, ErrorCode.UNKNOWN, { cause: error, details: 'Failed to stream quotes' }),\n );\n handler('done');\n }\n });\n\n return {\n cancel,\n };\n };\n}\n"],"mappings":"gNA4BA,SAAgB,EAAoB,CAClC,YAAc,KAAK,MAAM,KAAK,KAAK,CAAG,IAAK,CAC3C,cACA,kBACuD,CACvD,OAAQ,EAAO,IAAY,CACzB,IAAM,EAAK,IAAI,gBACT,MAAe,EAAG,OAAO,CAE/B,GAAI,IAAgBA,EAAAA,YAAY,MAAQ,IAAgBA,EAAAA,YAAY,KAMlE,OALK,EAAG,OAAO,UACb,EAAQ,QAAS,IAAIC,EAAAA,mBAAmB,qDAAqD,CAAC,CAC9F,EAAQ,O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,OAIF,GAAI,EAAM,SAAW,IAAM,IAA2B,GAAI,CACnD,EAAG,OAAO,SACb,EAAQ,OAAO,CAGjB,OAGF,IAAM,EAAUC,EAAAA,4BAA4B,EAAiB,CACvD,EAAWA,EAAAA,4BAA4B,EAAsB,CAC7D,EAAWC,EAAAA,+BAA+B,CAC9C,SAAU,EAAM,OAChB,YAAa,EACb,YAAa,EACd,CAAC,CAIF,GAAI,IAAa,IAAM,IAA2B,GAAI,CAC/C,EAAG,OAAO,SACb,EAAQ,OAAO,CAGjB,OAGF,IAAM,EAA2BA,EAAAA,+BAA+B,CAC9D,SAAU,EACV,YAAaD,EAAAA,4BAA4B,IAAI,CAC7C,YAAa,EACd,CAAC,CAEI,EAAe,CACnB,WAAY,CACV,GAAI,gBACJ,KAAM,gBACP,CACD,SAAU,EAAM,OAChB,UAAW,EAAW,EACtB,UACA,WACA,UAAW,GAAO,CAAG,GACrB,KAAM,EAAE,CACR,YAAa,EAAM,YACnB,GAAI,OAAO,YAAY,CACvB,cAAe,KACf,YAAaE,EAAAA,YAAY,cACzB,YAAa,EACb,YAAa,EAAM,YACnB,YAAa,EAAM,YACnB,UAAW,EAAM,UAClB,CAEI,EAAG,OAAO,UACb,EAAQ,QAAS,EAAM,CACvB,EAAQ,OAAO,KAEf,CAAC,MAAO,GAAU,CACf,EAAG,OAAO,UACb,EACE,QACA,IAAIC,EAAAA,SAASC,EAAAA,YAAY,QAASC,EAAAA,UAAU,QAAS,CAAE,MAAO,EAAO,QAAS,0BAA2B,CAAC,CAC3G,CACD,EAAQ,OAAO,GAEjB,CAEK,CACL,SACD"}
@@ -1,2 +1,2 @@
1
- import{AvalancheFujiBlockchainChainIds as e,AvalancheMainnetBlockchainChainIds as t,Environment as n,ServiceType as r}from"../../../constants.js";import{ErrorCode as i,ErrorReason as a,InvalidParamsError as o,SdkError as s}from"../../../errors.js";import{getChainAlias as c,getNativeTokenForChainAlias as l,getOutputAmountForAvalancheCct as u,getUtxosTotalAmount as d,stripAddressPrefix as f,xpAddressMatchesNetwork as p}from"../_utils.js";import{isXpAddressFullyValid as m}from"../_type-guards.js";import{isAddress as h}from"viem";function g({clock:g=()=>Math.floor(Date.now()/1e3),environment:_,getAtomicUtxos:v}){return(y,b)=>{let x=new AbortController,S=()=>x.abort();if(_!==n.PROD&&_!==n.TEST)return x.signal.aborted||(b(`error`,new o(`Unsupported environment for Avalanche CCT service.`)),b(`done`)),{cancel:S};let C=_===n.TEST,w=y.fromAddress,T=y.toAddress,E=C?e.C:t.C,D=y.sourceChain.chainId===E,O=y.targetChain.chainId===E,k=D?h(w):m(w)&&p(w,C),A=O?h(T):m(T)&&p(T,C);if(!k||!A)return x.signal.aborted||(b(`error`,new o(`Invalid fromAddress or toAddress for the specified environment.`,`Address types must match chain type: C-Chain uses EVM addresses, P/X chains use XP bech32 addresses for the selected environment.`)),b(`done`)),{cancel:S};let j=D||O;return j&&w===T?(x.signal.aborted||(b(`error`,new o(`fromAddress and toAddress must be different when C-Chain is involved.`)),b(`done`)),{cancel:S}):!j&&f(w)!==f(T)?(x.signal.aborted||(b(`error`,new o(`fromAddress and toAddress must be the same for P↔X transfers.`)),b(`done`)),{cancel:S}):((async()=>{let e=c(y.sourceChain.chainId,C),t=c(y.targetChain.chainId,C),n=d((await v(t,e)).getUTXOs());if(e===`C`&&y.amount!==0n&&y.amount<1000000000n){x.signal.aborted||b(`done`);return}if(y.amount===0n&&n===0n){x.signal.aborted||b(`done`);return}let i=l(e),a=l(t),o=u({amountIn:y.amount,sourceAsset:i,targetAsset:a});if(o===0n){x.signal.aborted||b(`done`);return}let s=u({amountIn:n,sourceAsset:l(`P`),targetAsset:a}),f={aggregator:{id:`avalanche-cct`,name:`Avalanche CCT`},amountIn:y.amount,amountOut:o+s,assetIn:i,assetOut:a,expiresAt:g()+60,fees:[],fromAddress:y.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:r.AVALANCHE_CCT,slippageBps:0,sourceChain:y.sourceChain,targetChain:y.targetChain,toAddress:y.toAddress};x.signal.aborted||(b(`quote`,f),b(`done`))})().catch(e=>{x.signal.aborted||(b(`error`,new s(a.UNKNOWN,i.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),b(`done`))}),{cancel:S})}}export{g as streamQuotesFactory};
1
+ import{AvalancheFujiBlockchainChainIds as e,AvalancheMainnetBlockchainChainIds as t,Environment as n,ServiceType as r}from"../../../constants.js";import{ErrorCode as i,ErrorReason as a,InvalidParamsError as o,SdkError as s}from"../../../errors.js";import{getChainAlias as c,getNativeTokenForChainAlias as l,getOutputAmountForAvalancheCct as u,getUtxosTotalAmount as d,stripAddressPrefix as f,xpAddressMatchesNetwork as p}from"../_utils.js";import{isXpAddressFullyValid as m}from"../_type-guards.js";import{isAddress as h}from"viem";function g({clock:g=()=>Math.floor(Date.now()/1e3),environment:_,getAtomicUtxos:v}){return(y,b)=>{let x=new AbortController,S=()=>x.abort();if(_!==n.PROD&&_!==n.TEST)return x.signal.aborted||(b(`error`,new o(`Unsupported environment for Avalanche CCT service.`)),b(`done`)),{cancel:S};let C=_===n.TEST,w=y.fromAddress,T=y.toAddress,E=C?e.C:t.C,D=y.sourceChain.chainId===E,O=y.targetChain.chainId===E,k=D?h(w):m(w)&&p(w,C),A=O?h(T):m(T)&&p(T,C);if(!k||!A)return x.signal.aborted||(b(`error`,new o(`Invalid fromAddress or toAddress for the specified environment.`,`Address types must match chain type: C-Chain uses EVM addresses, P/X chains use XP bech32 addresses for the selected environment.`)),b(`done`)),{cancel:S};let j=D||O;return j&&w===T?(x.signal.aborted||(b(`error`,new o(`fromAddress and toAddress must be different when C-Chain is involved.`)),b(`done`)),{cancel:S}):!j&&f(w)!==f(T)?(x.signal.aborted||(b(`error`,new o(`fromAddress and toAddress must be the same for P↔X transfers.`)),b(`done`)),{cancel:S}):((async()=>{let e=c(y.sourceChain.chainId,C),t=c(y.targetChain.chainId,C),n=d((await v(t,e)).getUTXOs());if(e===`C`&&y.amount!==0n&&y.amount<1000000000n){x.signal.aborted||b(`done`);return}if(y.amount===0n&&n===0n){x.signal.aborted||b(`done`);return}let i=l(e),a=l(t),o=u({amountIn:y.amount,sourceAsset:i,targetAsset:a});if(o===0n&&n===0n){x.signal.aborted||b(`done`);return}let s=u({amountIn:n,sourceAsset:l(`P`),targetAsset:a}),f={aggregator:{id:`avalanche-cct`,name:`Avalanche CCT`},amountIn:y.amount,amountOut:o+s,assetIn:i,assetOut:a,expiresAt:g()+60,fees:[],fromAddress:y.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:r.AVALANCHE_CCT,slippageBps:0,sourceChain:y.sourceChain,targetChain:y.targetChain,toAddress:y.toAddress};x.signal.aborted||(b(`quote`,f),b(`done`))})().catch(e=>{x.signal.aborted||(b(`error`,new s(a.UNKNOWN,i.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),b(`done`))}),{cancel:S})}}export{g as streamQuotesFactory};
2
2
  //# sourceMappingURL=stream-quotes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"stream-quotes.js","names":[],"sources":["../../../../src/transfer-service/avalanche-cct/_handlers/stream-quotes.ts"],"sourcesContent":["import { isAddress } from 'viem';\nimport {\n AvalancheFujiBlockchainChainIds,\n AvalancheMainnetBlockchainChainIds,\n Environment,\n ServiceType,\n type AvalancheBlockchainAlias,\n} from '../../../constants';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { TransferService } from '../../../types/service';\nimport type { Quote } from '../../../types/quote';\nimport { isXpAddressFullyValid } from '../_type-guards';\nimport {\n getChainAlias,\n getNativeTokenForChainAlias,\n getOutputAmountForAvalancheCct,\n getUtxosTotalAmount,\n stripAddressPrefix,\n xpAddressMatchesNetwork,\n} from '../_utils';\nimport type { GetAtomicUtxosCallback } from '../types';\n\nexport interface StreamQuotesOptions {\n clock?: () => number;\n environment: Environment;\n getAtomicUtxos: GetAtomicUtxosCallback;\n}\n\nexport function streamQuotesFactory({\n clock = () => Math.floor(Date.now() / 1000),\n environment,\n getAtomicUtxos,\n}: StreamQuotesOptions): TransferService['streamQuotes'] {\n return (props, handler) => {\n const ac = new AbortController();\n const cancel = () => ac.abort();\n\n if (environment !== Environment.PROD && environment !== Environment.TEST) {\n if (!ac.signal.aborted) {\n handler('error', new InvalidParamsError('Unsupported environment for Avalanche CCT service.'));\n handler('done');\n }\n\n return { cancel };\n }\n\n const isTestnet = environment === Environment.TEST;\n\n const fromAddress = props.fromAddress;\n const toAddress = props.toAddress;\n const cChainId = isTestnet ? AvalancheFujiBlockchainChainIds.C : AvalancheMainnetBlockchainChainIds.C;\n const isSourceChainC = props.sourceChain.chainId === cChainId;\n const isTargetChainC = props.targetChain.chainId === cChainId;\n\n const isFromAddressValid = isSourceChainC\n ? isAddress(fromAddress)\n : isXpAddressFullyValid(fromAddress) && xpAddressMatchesNetwork(fromAddress, isTestnet);\n\n const isToAddressValid = isTargetChainC\n ? isAddress(toAddress)\n : isXpAddressFullyValid(toAddress) && xpAddressMatchesNetwork(toAddress, isTestnet);\n\n if (!isFromAddressValid || !isToAddressValid) {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new InvalidParamsError(\n 'Invalid fromAddress or toAddress for the specified environment.',\n 'Address types must match chain type: C-Chain uses EVM addresses, P/X chains use XP bech32 addresses for the selected environment.',\n ),\n );\n handler('done');\n }\n\n return {\n cancel,\n };\n }\n\n // Validate addresses equal if both chains are P/X and different if either chain is C.\n const isEitherChainC = isSourceChainC || isTargetChainC;\n\n if (isEitherChainC && fromAddress === toAddress) {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new InvalidParamsError('fromAddress and toAddress must be different when C-Chain is involved.'),\n );\n handler('done');\n }\n\n return { cancel };\n }\n\n if (!isEitherChainC && stripAddressPrefix(fromAddress) !== stripAddressPrefix(toAddress)) {\n if (!ac.signal.aborted) {\n handler('error', new InvalidParamsError('fromAddress and toAddress must be the same for P↔X transfers.'));\n handler('done');\n }\n\n return { cancel };\n }\n\n (async () => {\n const sourceChainAlias: AvalancheBlockchainAlias = getChainAlias(props.sourceChain.chainId, isTestnet);\n const destinationChainAlias: AvalancheBlockchainAlias = getChainAlias(props.targetChain.chainId, isTestnet);\n const atomicUtxoSet = await getAtomicUtxos(destinationChainAlias, sourceChainAlias);\n const atomicUtxos = atomicUtxoSet.getUTXOs();\n const atomicUtxosTotalAmount = getUtxosTotalAmount(atomicUtxos);\n\n // If source is C-Chain, the props amount must be either `0n` or _at least_ one nano AVAX.\n // Otherwise, we should just emit a \"done\" event.\n if (sourceChainAlias === 'C' && props.amount !== 0n && props.amount < 1_000_000_000n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n // Special case for 0 amount transfers where user intends to finish stuck atomic imports.\n if (props.amount === 0n && atomicUtxosTotalAmount === 0n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n const assetIn = getNativeTokenForChainAlias(sourceChainAlias);\n const assetOut = getNativeTokenForChainAlias(destinationChainAlias);\n const amountIn = getOutputAmountForAvalancheCct({\n amountIn: props.amount,\n sourceAsset: assetIn,\n targetAsset: assetOut,\n });\n\n // Emit no quotes if `amountIn` is 0\n // This can happen if the user tries to transfer an amount below 1 nano AVAX from the C-Chain.\n if (amountIn === 0n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n // TODO: Do we need to account for subtracting import fees from these UTXOs\n // in order to give an accurate picture of how much the user will receive on the other side?\n const amountOutFromAtomicUtxos = getOutputAmountForAvalancheCct({\n amountIn: atomicUtxosTotalAmount,\n sourceAsset: getNativeTokenForChainAlias('P'),\n targetAsset: assetOut,\n });\n\n const quote: Quote = {\n aggregator: {\n id: 'avalanche-cct',\n name: 'Avalanche CCT',\n },\n amountIn: props.amount,\n amountOut: amountIn + amountOutFromAtomicUtxos,\n assetIn,\n assetOut,\n expiresAt: clock() + 60, // Expire in 1 minute.\n fees: [],\n fromAddress: props.fromAddress,\n id: crypto.randomUUID(),\n partnerFeeBps: null,\n serviceType: ServiceType.AVALANCHE_CCT,\n slippageBps: 0,\n sourceChain: props.sourceChain,\n targetChain: props.targetChain,\n toAddress: props.toAddress,\n };\n\n if (!ac.signal.aborted) {\n handler('quote', quote);\n handler('done');\n }\n })().catch((error) => {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new SdkError(ErrorReason.UNKNOWN, ErrorCode.UNKNOWN, { cause: error, details: 'Failed to stream quotes' }),\n );\n handler('done');\n }\n });\n\n return {\n cancel,\n };\n };\n}\n"],"mappings":"ohBA4BA,SAAgB,EAAoB,CAClC,YAAc,KAAK,MAAM,KAAK,KAAK,CAAG,IAAK,CAC3C,cACA,kBACuD,CACvD,OAAQ,EAAO,IAAY,CACzB,IAAM,EAAK,IAAI,gBACT,MAAe,EAAG,OAAO,CAE/B,GAAI,IAAgB,EAAY,MAAQ,IAAgB,EAAY,KAMlE,OALK,EAAG,OAAO,UACb,EAAQ,QAAS,IAAI,EAAmB,qDAAqD,CAAC,CAC9F,EAAQ,OAAO,EAGV,CAAE,SAAQ,CAGnB,IAAM,EAAY,IAAgB,EAAY,KAExC,EAAc,EAAM,YACpB,EAAY,EAAM,UAClB,EAAW,EAAY,EAAgC,EAAI,EAAmC,EAC9F,EAAiB,EAAM,YAAY,UAAY,EAC/C,EAAiB,EAAM,YAAY,UAAY,EAE/C,EAAqB,EACvB,EAAU,EAAY,CACtB,EAAsB,EAAY,EAAI,EAAwB,EAAa,EAAU,CAEnF,EAAmB,EACrB,EAAU,EAAU,CACpB,EAAsB,EAAU,EAAI,EAAwB,EAAW,EAAU,CAErF,GAAI,CAAC,GAAsB,CAAC,EAY1B,OAXK,EAAG,OAAO,UACb,EACE,QACA,IAAI,EACF,kEACA,oIACD,CACF,CACD,EAAQ,OAAO,EAGV,CACL,SACD,CAIH,IAAM,EAAiB,GAAkB,EA8GzC,OA5GI,GAAkB,IAAgB,GAC/B,EAAG,OAAO,UACb,EACE,QACA,IAAI,EAAmB,wEAAwE,CAChG,CACD,EAAQ,OAAO,EAGV,CAAE,SAAQ,EAGf,C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CAAE,MAAO,EAAO,QAAS,0BAA2B,CAAC,CAC3G,CACD,EAAQ,OAAO,GAEjB,CAEK,CACL,SACD"}
1
+ {"version":3,"file":"stream-quotes.js","names":[],"sources":["../../../../src/transfer-service/avalanche-cct/_handlers/stream-quotes.ts"],"sourcesContent":["import { isAddress } from 'viem';\nimport {\n AvalancheFujiBlockchainChainIds,\n AvalancheMainnetBlockchainChainIds,\n Environment,\n ServiceType,\n type AvalancheBlockchainAlias,\n} from '../../../constants';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { TransferService } from '../../../types/service';\nimport type { Quote } from '../../../types/quote';\nimport { isXpAddressFullyValid } from '../_type-guards';\nimport {\n getChainAlias,\n getNativeTokenForChainAlias,\n getOutputAmountForAvalancheCct,\n getUtxosTotalAmount,\n stripAddressPrefix,\n xpAddressMatchesNetwork,\n} from '../_utils';\nimport type { GetAtomicUtxosCallback } from '../types';\n\nexport interface StreamQuotesOptions {\n clock?: () => number;\n environment: Environment;\n getAtomicUtxos: GetAtomicUtxosCallback;\n}\n\nexport function streamQuotesFactory({\n clock = () => Math.floor(Date.now() / 1000),\n environment,\n getAtomicUtxos,\n}: StreamQuotesOptions): TransferService['streamQuotes'] {\n return (props, handler) => {\n const ac = new AbortController();\n const cancel = () => ac.abort();\n\n if (environment !== Environment.PROD && environment !== Environment.TEST) {\n if (!ac.signal.aborted) {\n handler('error', new InvalidParamsError('Unsupported environment for Avalanche CCT service.'));\n handler('done');\n }\n\n return { cancel };\n }\n\n const isTestnet = environment === Environment.TEST;\n\n const fromAddress = props.fromAddress;\n const toAddress = props.toAddress;\n const cChainId = isTestnet ? AvalancheFujiBlockchainChainIds.C : AvalancheMainnetBlockchainChainIds.C;\n const isSourceChainC = props.sourceChain.chainId === cChainId;\n const isTargetChainC = props.targetChain.chainId === cChainId;\n\n const isFromAddressValid = isSourceChainC\n ? isAddress(fromAddress)\n : isXpAddressFullyValid(fromAddress) && xpAddressMatchesNetwork(fromAddress, isTestnet);\n\n const isToAddressValid = isTargetChainC\n ? isAddress(toAddress)\n : isXpAddressFullyValid(toAddress) && xpAddressMatchesNetwork(toAddress, isTestnet);\n\n if (!isFromAddressValid || !isToAddressValid) {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new InvalidParamsError(\n 'Invalid fromAddress or toAddress for the specified environment.',\n 'Address types must match chain type: C-Chain uses EVM addresses, P/X chains use XP bech32 addresses for the selected environment.',\n ),\n );\n handler('done');\n }\n\n return {\n cancel,\n };\n }\n\n // Validate addresses equal if both chains are P/X and different if either chain is C.\n const isEitherChainC = isSourceChainC || isTargetChainC;\n\n if (isEitherChainC && fromAddress === toAddress) {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new InvalidParamsError('fromAddress and toAddress must be different when C-Chain is involved.'),\n );\n handler('done');\n }\n\n return { cancel };\n }\n\n if (!isEitherChainC && stripAddressPrefix(fromAddress) !== stripAddressPrefix(toAddress)) {\n if (!ac.signal.aborted) {\n handler('error', new InvalidParamsError('fromAddress and toAddress must be the same for P↔X transfers.'));\n handler('done');\n }\n\n return { cancel };\n }\n\n (async () => {\n const sourceChainAlias: AvalancheBlockchainAlias = getChainAlias(props.sourceChain.chainId, isTestnet);\n const destinationChainAlias: AvalancheBlockchainAlias = getChainAlias(props.targetChain.chainId, isTestnet);\n const atomicUtxoSet = await getAtomicUtxos(destinationChainAlias, sourceChainAlias);\n const atomicUtxos = atomicUtxoSet.getUTXOs();\n const atomicUtxosTotalAmount = getUtxosTotalAmount(atomicUtxos);\n\n // If source is C-Chain, the props amount must be either `0n` or _at least_ one nano AVAX.\n // Otherwise, we should just emit a \"done\" event.\n if (sourceChainAlias === 'C' && props.amount !== 0n && props.amount < 1_000_000_000n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n // Special case for 0 amount transfers where user intends to finish stuck atomic imports.\n if (props.amount === 0n && atomicUtxosTotalAmount === 0n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n const assetIn = getNativeTokenForChainAlias(sourceChainAlias);\n const assetOut = getNativeTokenForChainAlias(destinationChainAlias);\n const amountIn = getOutputAmountForAvalancheCct({\n amountIn: props.amount,\n sourceAsset: assetIn,\n targetAsset: assetOut,\n });\n\n // Emit no quotes if `amountIn` is 0 and there are no atomic UTXOs.\n // Zero-amount requests with atomic UTXOs should still emit a quote to unblock stuck imports.\n if (amountIn === 0n && atomicUtxosTotalAmount === 0n) {\n if (!ac.signal.aborted) {\n handler('done');\n }\n\n return;\n }\n\n const amountOutFromAtomicUtxos = getOutputAmountForAvalancheCct({\n amountIn: atomicUtxosTotalAmount,\n sourceAsset: getNativeTokenForChainAlias('P'),\n targetAsset: assetOut,\n });\n\n const quote: Quote = {\n aggregator: {\n id: 'avalanche-cct',\n name: 'Avalanche CCT',\n },\n amountIn: props.amount,\n amountOut: amountIn + amountOutFromAtomicUtxos,\n assetIn,\n assetOut,\n expiresAt: clock() + 60, // Expire in 1 minute.\n fees: [],\n fromAddress: props.fromAddress,\n id: crypto.randomUUID(),\n partnerFeeBps: null,\n serviceType: ServiceType.AVALANCHE_CCT,\n slippageBps: 0,\n sourceChain: props.sourceChain,\n targetChain: props.targetChain,\n toAddress: props.toAddress,\n };\n\n if (!ac.signal.aborted) {\n handler('quote', quote);\n handler('done');\n }\n })().catch((error) => {\n if (!ac.signal.aborted) {\n handler(\n 'error',\n new SdkError(ErrorReason.UNKNOWN, ErrorCode.UNKNOWN, { cause: error, details: 'Failed to stream quotes' }),\n );\n handler('done');\n }\n });\n\n return {\n cancel,\n };\n };\n}\n"],"mappings":"ohBA4BA,SAAgB,EAAoB,CAClC,YAAc,KAAK,MAAM,KAAK,KAAK,CAAG,IAAK,CAC3C,cACA,kBACuD,CACvD,OAAQ,EAAO,IAAY,CACzB,IAAM,EAAK,IAAI,gBACT,MAAe,EAAG,OAAO,CAE/B,GAAI,IAAgB,EAAY,MAAQ,IAAgB,EAAY,KAMlE,OALK,EAAG,OAAO,UACb,EAA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B,EAAiB,CACvD,EAAW,EAA4B,EAAsB,CAC7D,EAAW,EAA+B,CAC9C,SAAU,EAAM,OAChB,YAAa,EACb,YAAa,EACd,CAAC,CAIF,GAAI,IAAa,IAAM,IAA2B,GAAI,CAC/C,EAAG,OAAO,SACb,EAAQ,OAAO,CAGjB,OAGF,IAAM,EAA2B,EAA+B,CAC9D,SAAU,EACV,YAAa,EAA4B,IAAI,CAC7C,YAAa,EACd,CAAC,CAEI,EAAe,CACnB,WAAY,CACV,GAAI,gBACJ,KAAM,gBACP,CACD,SAAU,EAAM,OAChB,UAAW,EAAW,EACtB,UACA,WACA,UAAW,GAAO,CAAG,GACrB,KAAM,EAAE,CACR,YAAa,EAAM,YACnB,GAAI,OAAO,YAAY,CACvB,cAAe,KACf,YAAa,EAAY,cACzB,YAAa,EACb,YAAa,EAAM,YACnB,YAAa,EAAM,YACnB,UAAW,EAAM,UAClB,CAEI,EAAG,OAAO,UACb,EAAQ,QAAS,EAAM,CACvB,EAAQ,OAAO,KAEf,CAAC,MAAO,GAAU,CACf,EAAG,OAAO,UACb,EACE,QACA,IAAI,EAAS,EAAY,QAAS,EAAU,QAAS,CAAE,MAAO,EAAO,QAAS,0BAA2B,CAAC,CAC3G,CACD,EAAQ,OAAO,GAEjB,CAEK,CACL,SACD"}
@@ -1,2 +1,2 @@
1
- const e=require(`../../../errors.cjs`),t=require(`../../../utils/caip.cjs`),n=require(`../../../_utils/chain.cjs`),r=require(`../../../utils/evm-address.cjs`),i=require(`../_api.cjs`),a=require(`../../../utils/sol-address.cjs`),o=require(`../_utils.cjs`);function s({apiOptions:e,appId:r,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:r,chainId:n.isEvmNamespace(s.sourceChain.chainId)?t.caip2ToEip155ChainId(s.sourceChain.chainId):s.sourceChain.chainId,destinationChainId:s.sourceChain.chainId===s.targetChain.chainId?void 0:n.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=n.isEvmNamespace(t.sourceChain.chainId),s=n.isEvmNamespace(t.targetChain.chainId),c=n.isSolanaNamespace(t.sourceChain.chainId),l=n.isSolanaNamespace(t.targetChain.chainId);return o&&!r.isEvmAddress(t.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid fromAddress for EVM source chain.`)}:s&&!r.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&&r.isEvmAddress(t.fromAddress)?t.fromAddress:s&&r.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;
1
+ const e=require(`../../../errors.cjs`),t=require(`../../../utils/caip.cjs`),n=require(`../../../_utils/chain.cjs`),r=require(`../../../utils/evm-address.cjs`),i=require(`../_api.cjs`),a=require(`../../../utils/sol-address.cjs`),o=require(`../_utils.cjs`);function s({apiOptions:e,appId:r,partnerFeeBps:a}){return(s,l,u)=>{let d=new AbortController,{userEvmAddress:f,userSolanaAddress:p,validationError:m}=c(s,u);return m?(l(`error`,m),l(`done`),{cancel:()=>{}}):(i.markrStreamQuote(e,{amount:s.amount.toString(),appId:r,chainId:n.isEvmNamespace(s.sourceChain.chainId)?t.caip2ToEip155ChainId(s.sourceChain.chainId):s.sourceChain.chainId,destinationChainId:s.sourceChain.chainId===s.targetChain.chainId?void 0:n.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:f,userSolanaAddress:p},{onDone:()=>{d.signal.aborted||l(`done`)},onError:e=>{d.signal.aborted||(l(`error`,e),l(`done`))},onQuote:e=>{d.signal.aborted||l(`quote`,o.quoteFromMarkrQuoteResponseData(e,s,a))},signal:d.signal}),{cancel:()=>{d.abort()}})}}function c(t,i){let o=t.sourceChain.chainId!==t.targetChain.chainId,s=n.isEvmNamespace(t.sourceChain.chainId),c=n.isEvmNamespace(t.targetChain.chainId),l=n.isSolanaNamespace(t.sourceChain.chainId),u=n.isSolanaNamespace(t.targetChain.chainId);return s&&!r.isEvmAddress(t.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid fromAddress for EVM source chain.`)}:c&&!r.isEvmAddress(t.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid toAddress for EVM target chain.`)}:l&&!a.isSolAddress(t.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid fromAddress for Solana source chain.`)}:u&&!a.isSolAddress(t.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid toAddress for Solana target chain.`)}:o&&(s&&c||l&&u)&&!i?.dangerouslyAllowAddressMismatch&&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.`)}:o?{userEvmAddress:c&&r.isEvmAddress(t.toAddress)?t.toAddress:s&&r.isEvmAddress(t.fromAddress)?t.fromAddress:void 0,userSolanaAddress:u&&a.isSolAddress(t.toAddress)?t.toAddress:l&&a.isSolAddress(t.fromAddress)?t.fromAddress: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 // 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":"+PAeA,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,GAGEA,EAAAA,iBACH,EACA,CACE,OAAQ,EAAM,OAAO,UAAU,CAC/B,QACA,QAASC,EAAAA,eAAe,EAAM,YAAY,QAAQ,CAC9CC,EAAAA,qBAAqB,EAAM,YAAY,QAAQ,CAC/C,EAAM,YAAY,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AAA,YAAY,eAAgB,0CAA0C,CAC/G,CAGC,GAAkB,CAACC,EAAAA,aAAa,EAAM,YAAY,CAC7C,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAIF,EAAAA,mBACnBC,EAAAA,YAAY,eACZ,+CACD,CACF,CAGC,GAAkB,CAACC,EAAAA,aAAa,EAAM,UAAU,CAC3C,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAIF,EAAAA,mBAAmBC,EAAAA,YAAY,eAAgB,6CAA6C,CAClH,CAGC,IAAsB,GAAe,GAAiB,GAAkB,IACtE,EAAM,cAAgB,EAAM,UACvB,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAID,EAAAA,mBACnBC,EAAAA,YAAY,eACZ,6EACD,CACF,CAIA,EAgCE,CACL,eAdA,GAAeF,EAAAA,aAAa,EAAM,YAAY,CAC1C,EAAM,YACN,GAAeA,EAAAA,aAAa,EAAM,UAAU,CAC5C,EAAM,UACN,IAAA,GAWJ,kBARA,GAAkBG,EAAAA,aAAa,EAAM,YAAY,CAC7C,EAAM,YACN,GAAkBA,EAAAA,aAAa,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,IAAIF,EAAAA,mBACnBC,EAAAA,YAAY,eACZ,6DACD,CACF"}
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 { ServiceQuoteOptions, 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, options) => {\n const ac = new AbortController();\n const { userEvmAddress, userSolanaAddress, validationError } = _validateAndGetUserAddresses(props, options);\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 options?: ServiceQuoteOptions,\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 (\n isCrossChainSwap &&\n ((sourceIsEvm && targetIsEvm) || (sourceIsSolana && targetIsSolana)) &&\n !options?.dangerouslyAllowAddressMismatch\n ) {\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 targetIsEvm && isEvmAddress(props.toAddress)\n ? props.toAddress\n : sourceIsEvm && isEvmAddress(props.fromAddress)\n ? props.fromAddress\n : undefined;\n\n const userSolanaAddress =\n targetIsSolana && isSolAddress(props.toAddress)\n ? props.toAddress\n : sourceIsSolana && isSolAddress(props.fromAddress)\n ? props.fromAddress\n : undefined;\n\n return {\n userEvmAddress,\n userSolanaAddress,\n };\n}\n"],"mappings":"+PAeA,SAAgB,EAAoB,CAClC,aACA,QACA,iBAC6D,CAC7D,OAAQ,EAAO,EAAS,IAAY,CAClC,IAAM,EAAK,IAAI,gBACT,CAAE,iBAAgB,oBAAmB,mBAAoB,EAA6B,EAAO,EAAQ,CAwD3G,OAtDI,GACF,EAAQ,QAAS,EAAgB,CACjC,EAAQ,OAAO,CAER,CACL,WAAc,GACf,GAGEA,EAAAA,iBACH,EACA,CACE,OAAQ,EAAM,OAAO,UAAU,CAC/B,QACA,QAASC,EAAAA,eAAe,EAAM,YAAY,QAAQ,CAC9CC,EAAAA,qBAAqB,EAAM,YAAY,QAAQ,CAC/C,EAAM,YAAY,QAGtB,mBACE,EAAM,YAAY,UAAY,EAAM,YAAY,QAI5C,IAAA,GAHAD,EAAAA,eAAe,EAAM,YAAY,QAAQ,CACvCC,EAAAA,qBAAqB,EAAM,YAAY,QAAQ,CAC/C,EAAM,YAAY,QAE1B,SAAU,EAAM,YAChB,QAASC,EAAAA,q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GC,GAAkB,CAACC,EAAAA,aAAa,EAAM,UAAU,CAC3C,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAIF,EAAAA,mBAAmBC,EAAAA,YAAY,eAAgB,6CAA6C,CAClH,CAID,IACE,GAAe,GAAiB,GAAkB,IACpD,CAAC,GAAS,iCAEN,EAAM,cAAgB,EAAM,UACvB,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAID,EAAAA,mBACnBC,EAAAA,YAAY,eACZ,6EACD,CACF,CAIA,EAgCE,CACL,eAdA,GAAeF,EAAAA,aAAa,EAAM,UAAU,CACxC,EAAM,UACN,GAAeA,EAAAA,aAAa,EAAM,YAAY,CAC9C,EAAM,YACN,IAAA,GAWJ,kBARA,GAAkBG,EAAAA,aAAa,EAAM,UAAU,CAC3C,EAAM,UACN,GAAkBA,EAAAA,aAAa,EAAM,YAAY,CACjD,EAAM,YACN,IAAA,GAKL,CAlCK,EAAM,cAAgB,EAAM,UAWzB,CACL,eAAgB,IAAA,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{isEvmNamespace as r,isSolanaNamespace as i}from"../../../_utils/chain.js";import{isEvmAddress as a}from"../../../utils/evm-address.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:i}){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:r(a.sourceChain.chainId)?n(a.sourceChain.chainId):a.sourceChain.chainId,destinationChainId:a.sourceChain.chainId===a.targetChain.chainId?void 0:r(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,i))},signal:u.signal}),{cancel:()=>{u.abort()}})}}function d(n){let o=n.sourceChain.chainId!==n.targetChain.chainId,c=r(n.sourceChain.chainId),l=r(n.targetChain.chainId),u=i(n.sourceChain.chainId),d=i(n.targetChain.chainId);return c&&!a(n.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid fromAddress for EVM source chain.`)}:l&&!a(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&&a(n.fromAddress)?n.fromAddress:l&&a(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};
1
+ import{ErrorReason as e,InvalidParamsError as t}from"../../../errors.js";import{caip2ToEip155ChainId as n}from"../../../utils/caip.js";import{isEvmNamespace as r,isSolanaNamespace as i}from"../../../_utils/chain.js";import{isEvmAddress as a}from"../../../utils/evm-address.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:i}){return(a,s,u)=>{let f=new AbortController,{userEvmAddress:p,userSolanaAddress:m,validationError:h}=d(a,u);return h?(s(`error`,h),s(`done`),{cancel:()=>{}}):(o(e,{amount:a.amount.toString(),appId:t,chainId:r(a.sourceChain.chainId)?n(a.sourceChain.chainId):a.sourceChain.chainId,destinationChainId:a.sourceChain.chainId===a.targetChain.chainId?void 0:r(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:p,userSolanaAddress:m},{onDone:()=>{f.signal.aborted||s(`done`)},onError:e=>{f.signal.aborted||(s(`error`,e),s(`done`))},onQuote:e=>{f.signal.aborted||s(`quote`,l(e,a,i))},signal:f.signal}),{cancel:()=>{f.abort()}})}}function d(n,o){let c=n.sourceChain.chainId!==n.targetChain.chainId,l=r(n.sourceChain.chainId),u=r(n.targetChain.chainId),d=i(n.sourceChain.chainId),f=i(n.targetChain.chainId);return l&&!a(n.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid fromAddress for EVM source chain.`)}:u&&!a(n.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid toAddress for EVM target chain.`)}:d&&!s(n.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid fromAddress for Solana source chain.`)}:f&&!s(n.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid toAddress for Solana target chain.`)}:c&&(l&&u||d&&f)&&!o?.dangerouslyAllowAddressMismatch&&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.`)}:c?{userEvmAddress:u&&a(n.toAddress)?n.toAddress:l&&a(n.fromAddress)?n.fromAddress:void 0,userSolanaAddress:f&&s(n.toAddress)?n.toAddress:d&&s(n.fromAddress)?n.fromAddress: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 // 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,OAAO,SACb,EAAQ,QAAS,EAAgC,EAAM,EAAO,EAAc,CAAC,EAGjF,OAAQ,EAAG,OACZ,CACF,CAEM,CACL,WAAc,CACZ,EAAG,OAAO,EA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IAAA,GACpB,CAbQ,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAI,EACnB,EAAY,eACZ,6DACD,CACF"}
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 { ServiceQuoteOptions, 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, options) => {\n const ac = new AbortController();\n const { userEvmAddress, userSolanaAddress, validationError } = _validateAndGetUserAddresses(props, options);\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 options?: ServiceQuoteOptions,\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 (\n isCrossChainSwap &&\n ((sourceIsEvm && targetIsEvm) || (sourceIsSolana && targetIsSolana)) &&\n !options?.dangerouslyAllowAddressMismatch\n ) {\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 targetIsEvm && isEvmAddress(props.toAddress)\n ? props.toAddress\n : sourceIsEvm && isEvmAddress(props.fromAddress)\n ? props.fromAddress\n : undefined;\n\n const userSolanaAddress =\n targetIsSolana && isSolAddress(props.toAddress)\n ? props.toAddress\n : sourceIsSolana && isSolAddress(props.fromAddress)\n ? props.fromAddress\n : undefined;\n\n return {\n userEvmAddress,\n userSolanaAddress,\n };\n}\n"],"mappings":"ydAeA,SAAgB,EAAoB,CAClC,aACA,QACA,iBAC6D,CAC7D,OAAQ,EAAO,EAAS,IAAY,CAClC,IAAM,EAAK,IAAI,gBACT,CAAE,iBAAgB,oBAAmB,mBAAoB,EAA6B,EAAO,EAAQ,CAwD3G,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,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B,IAAA,GACnB,gBAAiB,IAAI,EACnB,EAAY,eACZ,+CACD,CACF,CAGC,GAAkB,CAAC,EAAa,EAAM,UAAU,CAC3C,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAI,EAAmB,EAAY,eAAgB,6CAA6C,CAClH,CAID,IACE,GAAe,GAAiB,GAAkB,IACpD,CAAC,GAAS,iCAEN,EAAM,cAAgB,EAAM,UACvB,CACL,eAAgB,IAAA,GAChB,kBAAmB,IAAA,GACnB,gBAAiB,IAAI,EACnB,EAAY,eACZ,6EACD,CACF,CAIA,EAgCE,CACL,eAdA,GAAe,EAAa,EAAM,UAAU,CACxC,EAAM,UACN,GAAe,EAAa,EAAM,YAAY,CAC9C,EAAM,YACN,IAAA,GAWJ,kBARA,GAAkB,EAAa,EAAM,UAAU,CAC3C,EAAM,UACN,GAAkB,EAAa,EAAM,YAAY,CACjD,EAAM,YACN,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"}
@@ -123,6 +123,16 @@ interface EstimateNativeFeeOptions {
123
123
  maxPriorityFeePerGas?: bigint;
124
124
  }>;
125
125
  }
126
+ interface ServiceQuoteOptions {
127
+ /**
128
+ * Dangerously allows cross-chain quotes where fromAddress and toAddress differ
129
+ * even when a service would otherwise require them to match.
130
+ *
131
+ * This is intended for explicit proxy-recipient funding flows. Services should
132
+ * preserve their default address safety checks unless this is set.
133
+ */
134
+ readonly dangerouslyAllowAddressMismatch?: boolean;
135
+ }
126
136
  /**
127
137
  * Asset search input used by bridgeable-assets queries.
128
138
  *
@@ -187,7 +197,7 @@ interface TransferService {
187
197
  /** Get all supported chains for this service. */
188
198
  getSupportedChains(): Promise<GetSupportedChainsResult>;
189
199
  /** Stream time-sensitive quotes. */
190
- streamQuotes(props: QuoterProps, handler: ServiceQuoteEventHandler): {
200
+ streamQuotes(props: QuoterProps, handler: ServiceQuoteEventHandler, options?: ServiceQuoteOptions): {
191
201
  cancel: () => void;
192
202
  };
193
203
  /** Begin tracking a submitted transfer. */
@@ -304,5 +314,5 @@ type MarkrServiceInitializer = {
304
314
  };
305
315
  type ServiceInitializer = AvalancheCctInitializer | EvmServiceInitializer | LombardServiceInitializer | MarkrServiceInitializer;
306
316
  //#endregion
307
- export { AssetSearchQuery, AvalancheCctInitializer, AvalancheSendTxFunction, AvalancheSendTxParams, EstimateNativeFeeOptions, EvmServiceInitializer, GasSettings, GetBridgeableAssetsProps, GetBridgeableAssetsResult, GetMinimumTransferAmountProps, GetSupportedChainsResult, LombardServiceInitializer, MarkrServiceInitializer, MutableGetSupportedChainsResult, NativeFeeEstimate, ServiceInitializer, TrackTransferProps, TransferAssetProps, TransferService };
317
+ export { AssetSearchQuery, AvalancheCctInitializer, AvalancheSendTxFunction, AvalancheSendTxParams, EstimateNativeFeeOptions, EvmServiceInitializer, GasSettings, GetBridgeableAssetsProps, GetBridgeableAssetsResult, GetMinimumTransferAmountProps, GetSupportedChainsResult, LombardServiceInitializer, MarkrServiceInitializer, MutableGetSupportedChainsResult, NativeFeeEstimate, ServiceInitializer, ServiceQuoteOptions, TrackTransferProps, TransferAssetProps, TransferService };
308
318
  //# sourceMappingURL=service.d.cts.map
@@ -123,6 +123,16 @@ interface EstimateNativeFeeOptions {
123
123
  maxPriorityFeePerGas?: bigint;
124
124
  }>;
125
125
  }
126
+ interface ServiceQuoteOptions {
127
+ /**
128
+ * Dangerously allows cross-chain quotes where fromAddress and toAddress differ
129
+ * even when a service would otherwise require them to match.
130
+ *
131
+ * This is intended for explicit proxy-recipient funding flows. Services should
132
+ * preserve their default address safety checks unless this is set.
133
+ */
134
+ readonly dangerouslyAllowAddressMismatch?: boolean;
135
+ }
126
136
  /**
127
137
  * Asset search input used by bridgeable-assets queries.
128
138
  *
@@ -187,7 +197,7 @@ interface TransferService {
187
197
  /** Get all supported chains for this service. */
188
198
  getSupportedChains(): Promise<GetSupportedChainsResult>;
189
199
  /** Stream time-sensitive quotes. */
190
- streamQuotes(props: QuoterProps, handler: ServiceQuoteEventHandler): {
200
+ streamQuotes(props: QuoterProps, handler: ServiceQuoteEventHandler, options?: ServiceQuoteOptions): {
191
201
  cancel: () => void;
192
202
  };
193
203
  /** Begin tracking a submitted transfer. */
@@ -304,5 +314,5 @@ type MarkrServiceInitializer = {
304
314
  };
305
315
  type ServiceInitializer = AvalancheCctInitializer | EvmServiceInitializer | LombardServiceInitializer | MarkrServiceInitializer;
306
316
  //#endregion
307
- export { AssetSearchQuery, AvalancheCctInitializer, AvalancheSendTxFunction, AvalancheSendTxParams, EstimateNativeFeeOptions, EvmServiceInitializer, GasSettings, GetBridgeableAssetsProps, GetBridgeableAssetsResult, GetMinimumTransferAmountProps, GetSupportedChainsResult, LombardServiceInitializer, MarkrServiceInitializer, MutableGetSupportedChainsResult, NativeFeeEstimate, ServiceInitializer, TrackTransferProps, TransferAssetProps, TransferService };
317
+ export { AssetSearchQuery, AvalancheCctInitializer, AvalancheSendTxFunction, AvalancheSendTxParams, EstimateNativeFeeOptions, EvmServiceInitializer, GasSettings, GetBridgeableAssetsProps, GetBridgeableAssetsResult, GetMinimumTransferAmountProps, GetSupportedChainsResult, LombardServiceInitializer, MarkrServiceInitializer, MutableGetSupportedChainsResult, NativeFeeEstimate, ServiceInitializer, ServiceQuoteOptions, TrackTransferProps, TransferAssetProps, TransferService };
308
318
  //# sourceMappingURL=service.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@avalabs/fusion-sdk",
3
3
  "license": "Limited Ecosystem License",
4
- "version": "0.19.0",
4
+ "version": "0.20.0",
5
5
  "type": "module",
6
6
  "main": "./dist/mod.cjs",
7
7
  "module": "./dist/mod.js",