@avalabs/fusion-sdk 0.7.0 → 0.8.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.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./constants.cjs`),t=require(`./errors.cjs`),n=require(`./type-guards.cjs`),r=require(`./utils/caip.cjs`),i=require(`./transfer-manager.cjs`),a=require(`./utils/transfer-utils.cjs`);exports.AVALANCHE_FUJI_CHAIN=e.AVALANCHE_FUJI_CHAIN,exports.AVALANCHE_MAINNET_CHAIN=e.AVALANCHE_MAINNET_CHAIN,exports.AbortedError=t.AbortedError,exports.AvalancheChainIds=e.AvalancheChainIds,exports.BITCOIN_MAINNET_CHAIN=e.BITCOIN_MAINNET_CHAIN,exports.BITCOIN_TESTNET_CHAIN=e.BITCOIN_TESTNET_CHAIN,exports.BTC_SERVICE_TYPES=e.BTC_SERVICE_TYPES,exports.BitcoinChainIds=e.BitcoinChainIds,exports.Blockchain=e.Blockchain,exports.ERC_ZERO_ADDRESS=e.ERC_ZERO_ADDRESS,exports.ETHEREUM_MAINNET_CHAIN=e.ETHEREUM_MAINNET_CHAIN,exports.ETHEREUM_SEPOLIA_CHAIN=e.ETHEREUM_SEPOLIA_CHAIN,exports.EVM_SERVICE_TYPES=e.EVM_SERVICE_TYPES,exports.Environment=e.Environment,exports.ErrorCode=t.ErrorCode,exports.ErrorReason=t.ErrorReason,exports.EthereumChainIds=e.EthereumChainIds,exports.EvmChainId=e.EvmChainId,exports.FEE_RATE_TIER_TO_BITCOIN=e.FEE_RATE_TIER_TO_BITCOIN,exports.HttpError=t.HttpError,exports.InvalidParamsError=t.InvalidParamsError,exports.NATIVE_AVAX=e.NATIVE_AVAX,exports.NATIVE_ETH=e.NATIVE_ETH,exports.ResponseValidationError=t.ResponseValidationError,exports.SOLANA_DEVNET_CHAIN=e.SOLANA_DEVNET_CHAIN,exports.SOLANA_MAINNET_CHAIN=e.SOLANA_MAINNET_CHAIN,exports.SOL_MINT_ADDRESS=e.SOL_MINT_ADDRESS,exports.SdkError=t.SdkError,exports.ServiceInitializationError=t.ServiceInitializationError,exports.ServiceType=e.ServiceType,exports.ServiceUnavailableError=t.ServiceUnavailableError,exports.SolanaChainIds=e.SolanaChainIds,exports.TimeoutError=t.TimeoutError,exports.TokenType=e.TokenType,exports.TransferSignatureReason=e.TransferSignatureReason,exports.caip2ToEip155ChainId=r.caip2ToEip155ChainId,exports.caip2ToEip155HexChainId=r.caip2ToEip155HexChainId,exports.createTransferManager=i.createTransferManager,exports.eip155ChainIdToCaip2=r.eip155ChainIdToCaip2,exports.isAbortedError=t.isAbortedError,exports.isCaip2ChainId=r.isCaip2ChainId,exports.isEnvironment=n.isEnvironment,exports.isErc20Asset=n.isErc20Asset,exports.isEvmBridgeInitializer=n.isEvmBridgeInitializer,exports.isHttpError=t.isHttpError,exports.isInvalidParamsError=t.isInvalidParamsError,exports.isLombardServiceInitializer=n.isLombardServiceInitializer,exports.isMarkrServiceInitializer=n.isMarkrServiceInitializer,exports.isNativeAsset=n.isNativeAsset,exports.isResponseValidationError=t.isResponseValidationError,exports.isSdkError=t.isSdkError,exports.isServiceInitializationError=t.isServiceInitializationError,exports.isServiceInitializer=n.isServiceInitializer,exports.isServiceUnavailableError=t.isServiceUnavailableError,exports.isSplAsset=n.isSplAsset,exports.isTimeoutError=t.isTimeoutError,exports.parseTransfer=a.parseTransfer,exports.splitCaip2ChainId=r.splitCaip2ChainId,exports.stringifyTransfer=a.stringifyTransfer;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./constants.cjs`),t=require(`./errors.cjs`),n=require(`./type-guards.cjs`),r=require(`./transfer-manager.cjs`),i=require(`./utils/caip.cjs`),a=require(`./utils/transfer-utils.cjs`);exports.AVALANCHE_FUJI_CHAIN=e.AVALANCHE_FUJI_CHAIN,exports.AVALANCHE_MAINNET_CHAIN=e.AVALANCHE_MAINNET_CHAIN,exports.AbortedError=t.AbortedError,exports.AvalancheChainIds=e.AvalancheChainIds,exports.BITCOIN_MAINNET_CHAIN=e.BITCOIN_MAINNET_CHAIN,exports.BITCOIN_TESTNET_CHAIN=e.BITCOIN_TESTNET_CHAIN,exports.BTC_SERVICE_TYPES=e.BTC_SERVICE_TYPES,exports.BitcoinChainIds=e.BitcoinChainIds,exports.Blockchain=e.Blockchain,exports.ERC_ZERO_ADDRESS=e.ERC_ZERO_ADDRESS,exports.ETHEREUM_MAINNET_CHAIN=e.ETHEREUM_MAINNET_CHAIN,exports.ETHEREUM_SEPOLIA_CHAIN=e.ETHEREUM_SEPOLIA_CHAIN,exports.EVM_SERVICE_TYPES=e.EVM_SERVICE_TYPES,exports.Environment=e.Environment,exports.ErrorCode=t.ErrorCode,exports.ErrorReason=t.ErrorReason,exports.EthereumChainIds=e.EthereumChainIds,exports.EvmChainId=e.EvmChainId,exports.FEE_RATE_TIER_TO_BITCOIN=e.FEE_RATE_TIER_TO_BITCOIN,exports.HttpError=t.HttpError,exports.InvalidParamsError=t.InvalidParamsError,exports.NATIVE_AVAX=e.NATIVE_AVAX,exports.NATIVE_ETH=e.NATIVE_ETH,exports.ResponseValidationError=t.ResponseValidationError,exports.SOLANA_DEVNET_CHAIN=e.SOLANA_DEVNET_CHAIN,exports.SOLANA_MAINNET_CHAIN=e.SOLANA_MAINNET_CHAIN,exports.SOL_MINT_ADDRESS=e.SOL_MINT_ADDRESS,exports.SdkError=t.SdkError,exports.ServiceInitializationError=t.ServiceInitializationError,exports.ServiceType=e.ServiceType,exports.ServiceUnavailableError=t.ServiceUnavailableError,exports.SolanaChainIds=e.SolanaChainIds,exports.TimeoutError=t.TimeoutError,exports.TokenType=e.TokenType,exports.TransferSignatureReason=e.TransferSignatureReason,exports.caip2ToEip155ChainId=i.caip2ToEip155ChainId,exports.caip2ToEip155HexChainId=i.caip2ToEip155HexChainId,exports.createTransferManager=r.createTransferManager,exports.eip155ChainIdToCaip2=i.eip155ChainIdToCaip2,exports.isAbortedError=t.isAbortedError,exports.isCaip2ChainId=i.isCaip2ChainId,exports.isEnvironment=n.isEnvironment,exports.isErc20Asset=n.isErc20Asset,exports.isEvmBridgeInitializer=n.isEvmBridgeInitializer,exports.isHttpError=t.isHttpError,exports.isInvalidParamsError=t.isInvalidParamsError,exports.isLombardServiceInitializer=n.isLombardServiceInitializer,exports.isMarkrServiceInitializer=n.isMarkrServiceInitializer,exports.isNativeAsset=n.isNativeAsset,exports.isResponseValidationError=t.isResponseValidationError,exports.isSdkError=t.isSdkError,exports.isServiceInitializationError=t.isServiceInitializationError,exports.isServiceInitializer=n.isServiceInitializer,exports.isServiceUnavailableError=t.isServiceUnavailableError,exports.isSplAsset=n.isSplAsset,exports.isTimeoutError=t.isTimeoutError,exports.parseTransfer=a.parseTransfer,exports.splitCaip2ChainId=i.splitCaip2ChainId,exports.stringifyTransfer=a.stringifyTransfer;
package/dist/mod.js CHANGED
@@ -1 +1 @@
1
- import{AVALANCHE_FUJI_CHAIN as e,AVALANCHE_MAINNET_CHAIN as t,AvalancheChainIds as n,BITCOIN_MAINNET_CHAIN as r,BITCOIN_TESTNET_CHAIN as i,BTC_SERVICE_TYPES as a,BitcoinChainIds as o,Blockchain as s,ERC_ZERO_ADDRESS as c,ETHEREUM_MAINNET_CHAIN as l,ETHEREUM_SEPOLIA_CHAIN as u,EVM_SERVICE_TYPES as d,Environment as f,EthereumChainIds as p,EvmChainId as m,FEE_RATE_TIER_TO_BITCOIN as h,NATIVE_AVAX as g,NATIVE_ETH as _,SOLANA_DEVNET_CHAIN as v,SOLANA_MAINNET_CHAIN as y,SOL_MINT_ADDRESS as b,ServiceType as x,SolanaChainIds as S,TokenType as C,TransferSignatureReason as w}from"./constants.js";import{AbortedError as T,ErrorCode as E,ErrorReason as D,HttpError as O,InvalidParamsError as k,ResponseValidationError as A,SdkError as j,ServiceInitializationError as M,ServiceUnavailableError as N,TimeoutError as P,isAbortedError as F,isHttpError as I,isInvalidParamsError as L,isResponseValidationError as R,isSdkError as z,isServiceInitializationError as B,isServiceUnavailableError as V,isTimeoutError as H}from"./errors.js";import{isEnvironment as U,isErc20Asset as W,isEvmBridgeInitializer as G,isLombardServiceInitializer as K,isMarkrServiceInitializer as q,isNativeAsset as J,isServiceInitializer as Y,isSplAsset as X}from"./type-guards.js";import{caip2ToEip155ChainId as Z,caip2ToEip155HexChainId as Q,eip155ChainIdToCaip2 as $,isCaip2ChainId as ee,splitCaip2ChainId as te}from"./utils/caip.js";import{createTransferManager as ne}from"./transfer-manager.js";import{parseTransfer as re,stringifyTransfer as ie}from"./utils/transfer-utils.js";export{e as AVALANCHE_FUJI_CHAIN,t as AVALANCHE_MAINNET_CHAIN,T as AbortedError,n as AvalancheChainIds,r as BITCOIN_MAINNET_CHAIN,i as BITCOIN_TESTNET_CHAIN,a as BTC_SERVICE_TYPES,o as BitcoinChainIds,s as Blockchain,c as ERC_ZERO_ADDRESS,l as ETHEREUM_MAINNET_CHAIN,u as ETHEREUM_SEPOLIA_CHAIN,d as EVM_SERVICE_TYPES,f as Environment,E as ErrorCode,D as ErrorReason,p as EthereumChainIds,m as EvmChainId,h as FEE_RATE_TIER_TO_BITCOIN,O as HttpError,k as InvalidParamsError,g as NATIVE_AVAX,_ as NATIVE_ETH,A as ResponseValidationError,v as SOLANA_DEVNET_CHAIN,y as SOLANA_MAINNET_CHAIN,b as SOL_MINT_ADDRESS,j as SdkError,M as ServiceInitializationError,x as ServiceType,N as ServiceUnavailableError,S as SolanaChainIds,P as TimeoutError,C as TokenType,w as TransferSignatureReason,Z as caip2ToEip155ChainId,Q as caip2ToEip155HexChainId,ne as createTransferManager,$ as eip155ChainIdToCaip2,F as isAbortedError,ee as isCaip2ChainId,U as isEnvironment,W as isErc20Asset,G as isEvmBridgeInitializer,I as isHttpError,L as isInvalidParamsError,K as isLombardServiceInitializer,q as isMarkrServiceInitializer,J as isNativeAsset,R as isResponseValidationError,z as isSdkError,B as isServiceInitializationError,Y as isServiceInitializer,V as isServiceUnavailableError,X as isSplAsset,H as isTimeoutError,re as parseTransfer,te as splitCaip2ChainId,ie as stringifyTransfer};
1
+ import{AVALANCHE_FUJI_CHAIN as e,AVALANCHE_MAINNET_CHAIN as t,AvalancheChainIds as n,BITCOIN_MAINNET_CHAIN as r,BITCOIN_TESTNET_CHAIN as i,BTC_SERVICE_TYPES as a,BitcoinChainIds as o,Blockchain as s,ERC_ZERO_ADDRESS as c,ETHEREUM_MAINNET_CHAIN as l,ETHEREUM_SEPOLIA_CHAIN as u,EVM_SERVICE_TYPES as d,Environment as f,EthereumChainIds as p,EvmChainId as m,FEE_RATE_TIER_TO_BITCOIN as h,NATIVE_AVAX as g,NATIVE_ETH as _,SOLANA_DEVNET_CHAIN as v,SOLANA_MAINNET_CHAIN as y,SOL_MINT_ADDRESS as b,ServiceType as x,SolanaChainIds as S,TokenType as C,TransferSignatureReason as w}from"./constants.js";import{AbortedError as T,ErrorCode as E,ErrorReason as D,HttpError as O,InvalidParamsError as k,ResponseValidationError as A,SdkError as j,ServiceInitializationError as M,ServiceUnavailableError as N,TimeoutError as P,isAbortedError as F,isHttpError as I,isInvalidParamsError as L,isResponseValidationError as R,isSdkError as z,isServiceInitializationError as B,isServiceUnavailableError as V,isTimeoutError as H}from"./errors.js";import{isEnvironment as U,isErc20Asset as W,isEvmBridgeInitializer as G,isLombardServiceInitializer as K,isMarkrServiceInitializer as q,isNativeAsset as J,isServiceInitializer as Y,isSplAsset as X}from"./type-guards.js";import{createTransferManager as Z}from"./transfer-manager.js";import{caip2ToEip155ChainId as Q,caip2ToEip155HexChainId as $,eip155ChainIdToCaip2 as ee,isCaip2ChainId as te,splitCaip2ChainId as ne}from"./utils/caip.js";import{parseTransfer as re,stringifyTransfer as ie}from"./utils/transfer-utils.js";export{e as AVALANCHE_FUJI_CHAIN,t as AVALANCHE_MAINNET_CHAIN,T as AbortedError,n as AvalancheChainIds,r as BITCOIN_MAINNET_CHAIN,i as BITCOIN_TESTNET_CHAIN,a as BTC_SERVICE_TYPES,o as BitcoinChainIds,s as Blockchain,c as ERC_ZERO_ADDRESS,l as ETHEREUM_MAINNET_CHAIN,u as ETHEREUM_SEPOLIA_CHAIN,d as EVM_SERVICE_TYPES,f as Environment,E as ErrorCode,D as ErrorReason,p as EthereumChainIds,m as EvmChainId,h as FEE_RATE_TIER_TO_BITCOIN,O as HttpError,k as InvalidParamsError,g as NATIVE_AVAX,_ as NATIVE_ETH,A as ResponseValidationError,v as SOLANA_DEVNET_CHAIN,y as SOLANA_MAINNET_CHAIN,b as SOL_MINT_ADDRESS,j as SdkError,M as ServiceInitializationError,x as ServiceType,N as ServiceUnavailableError,S as SolanaChainIds,P as TimeoutError,C as TokenType,w as TransferSignatureReason,Q as caip2ToEip155ChainId,$ as caip2ToEip155HexChainId,Z as createTransferManager,ee as eip155ChainIdToCaip2,F as isAbortedError,te as isCaip2ChainId,U as isEnvironment,W as isErc20Asset,G as isEvmBridgeInitializer,I as isHttpError,L as isInvalidParamsError,K as isLombardServiceInitializer,q as isMarkrServiceInitializer,J as isNativeAsset,R as isResponseValidationError,z as isSdkError,B as isServiceInitializationError,Y as isServiceInitializer,V as isServiceUnavailableError,X as isSplAsset,H as isTimeoutError,re as parseTransfer,ne as splitCaip2ChainId,ie as stringifyTransfer};
@@ -1,2 +1,2 @@
1
- const e=require(`./constants.cjs`),t=require(`./errors.cjs`),n=require(`./type-guards.cjs`),r=require(`./quoter/quoter.cjs`),i=require(`./utils/caip.cjs`),a=require(`./_utils/merge-assets.cjs`),o=require(`./utils/asset-id.cjs`),s=e=>{if(!n.isEnvironment(e))throw new t.ServiceInitializationError(t.ErrorReason.ENVIRONMENT_NOT_SUPPORTED)},c=e=>{if(e.length===0)throw new t.ServiceInitializationError(`No service initializers provided.`);if(e.some(e=>!n.isServiceInitializer(e)))throw new t.ServiceInitializationError(`One or more service initializers are invalid.`);let r=new Set;for(let n of e){if(r.has(n.type))throw new t.ServiceInitializationError(t.ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,`Service type "${n.type}" has been initialized more than once.`);r.add(n.type)}},l=async({environment:n,serviceInitializers:r,fetch:i})=>{let a=new Map,o={},s=(e,n)=>{if(n instanceof t.ServiceInitializationError)return n;let r=n instanceof Error?n.message:String(n);return new t.ServiceInitializationError(t.ErrorReason.UNKNOWN,`Failed to initialize service type "${e}". ${r}`,n)},c=async(e,t)=>{try{let n=await t();a.set(e,n),o[e]={status:`initialized`}}catch(t){o[e]={status:`error`,error:s(e,t)}}};for(let s of r){if(a.has(s.type))throw new t.ServiceInitializationError(t.ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,`Service type "${s.type}" has been initialized more than once.`);switch(s.type){case e.ServiceType.AVALANCHE_EVM:await c(e.ServiceType.AVALANCHE_EVM,async()=>{let{createAvalancheEvmService:e}=await Promise.resolve().then(()=>require(`./transfer-service/avalanche-evm/avalanche-evm-service.cjs`));return await e({environment:n,evmSigner:s.evmSigner,fetch:i})});break;case e.ServiceType.LOMBARD_BTCB_TO_BTC:await c(e.ServiceType.LOMBARD_BTCB_TO_BTC,async()=>{let{createBtcbToBtcService:e}=await Promise.resolve().then(()=>require(`./transfer-service/lombard/btcb-to-btc-service.cjs`));return await e({bitcoinFunctions:s.btcFunctions,environment:n,evmSigner:s.evmSigner,fetch:i})});break;case e.ServiceType.LOMBARD_BTC_TO_BTCB:await c(e.ServiceType.LOMBARD_BTC_TO_BTCB,async()=>{let{createBtcToBtcbService:e}=await Promise.resolve().then(()=>require(`./transfer-service/lombard/btc-to-btcb-service.cjs`));return await e({bitcoinFunctions:s.btcFunctions,btcSigner:s.btcSigner,environment:n,evmSigner:s.evmSigner,fetch:i})});break;case e.ServiceType.MARKR:if(n!==e.Environment.PROD){o[e.ServiceType.MARKR]={status:`unsupported-environment`,message:`Service type "${e.ServiceType.MARKR}" is only supported in production environment.`};break}await c(e.ServiceType.MARKR,async()=>{let{createMarkrService:e}=await Promise.resolve().then(()=>require(`./transfer-service/markr/markr-service.cjs`));return await e({apiBaseUrl:s.markrApiUrl,apiToken:s.markrApiToken,appId:s.markrAppId,disableCrossChainSwaps:s.disableCrossChainSwaps,fetch:i,environment:n,evmSigner:s.evmSigner,getTargetChainAssets:s.getTargetChainAssets,solanaSigner:s.solanaSigner})});break;case e.ServiceType.WRAP_UNWRAP:await c(e.ServiceType.WRAP_UNWRAP,async()=>{let{createWrapUnwrapService:e}=await Promise.resolve().then(()=>require(`./transfer-service/wrap-unwrap/wrap-unwrap-service.cjs`));return await e({environment:n,evmSigner:s.evmSigner,fetch:i})});break;default:break}}return{services:a,status:{environment:n,services:o}}},u=async e=>{let t=[];for(let n of e.values()){let e=await n.getAssets();t.push(e)}return a.mergeChainAssetMaps(t)},d=async({environment:n,fetch:a,serviceInitializers:d})=>{s(n),c(d);let{services:f,status:p}=await l({environment:n,serviceInitializers:d,fetch:a});return{id:crypto.randomUUID(),estimateNativeFee:async(e,n)=>{let r=Math.floor(Date.now()/1e3);if(e.expiresAt<=r){let n=r-e.expiresAt;throw new t.InvalidParamsError(t.ErrorReason.QUOTE_EXPIRED,`Quote expired ${n} seconds ago.`)}let i=f.get(e.serviceType);if(!i)throw new t.ServiceUnavailableError(t.ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);return await i.estimateNativeFee(e,n)},getAssetBridgeMap:async({sourceAsset:t,sourceChainId:n})=>{let r=await u(f),a=r[n];if(!a)return null;let o=a.find(n=>t.type===e.TokenType.NATIVE?n.type===e.TokenType.NATIVE:n.type===t.type&&n.address===t.address);if(!o||!o.destinations)return null;let s=o.destinations,c={};for(let[t,n]of Object.entries(s)){if(!i.isCaip2ChainId(t))continue;let a=r[t];if(!a)continue;let o=a.find(t=>n.address===e.TokenType.NATIVE?t.type===e.TokenType.NATIVE:t.type!==e.TokenType.NATIVE&&t.address===n.address);if(!o)continue;let{destinations:s,swapProviders:l,...u}=o;c[t]={bridgedAsset:u,bridgeProviders:n.bridgeProviders}}return Object.keys(c).length>0?c:null},getMinimumTransferAmount:async e=>{let t={};for(let n of f.values())if(n.analyzeSupport(e)){let r=await n.getMinimumTransferAmount(e);t[n.type]=r}return Object.keys(t).length>0?t:null},getSupportedChains:async()=>{let e=new Map,t=await Promise.all(Array.from(f.values()).map(e=>e.getSupportedChains()));for(let n of t)for(let[t,r]of n.entries()){let n=e.get(t);n||(n=new Set,e.set(t,n));for(let e of r)n.add(e)}return e},getQuoter:(e,t)=>new r.Quoter(e,Array.from(f.values()),t),status:()=>p,trackTransfer:e=>{let{transfer:n}=e,r=f.get(n.type);if(!r)throw new t.ServiceUnavailableError(t.ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);return r.trackTransfer(e)},transferAsset:async e=>{let{quote:n}=e,r=f.get(n.serviceType);if(!r)throw new t.ServiceUnavailableError(t.ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);return await r.transferAsset(e)},getBridgeableAssets:async({sourceAsset:e,sourceChainId:t,targetChainId:n})=>{let r=await Promise.allSettled(Array.from(f.values()).map(r=>r.getBridgeableAssets({sourceAsset:e,sourceChainId:t,targetChainId:n}))),i=new Map;for(let e of r)if(e.status===`fulfilled`)for(let t of e.value){let{bridgeProviders:e,...r}=t,a=o.getAssetId(n,r),s=i.get(a);if(s){let t=[...new Set([...s.bridgeProviders,...e])];i.set(a,{...s,bridgeProviders:t})}else i.set(a,{...r,bridgeProviders:[...e]})}return Array.from(i.values())}}};exports.createTransferManager=d;
1
+ const e=require(`./constants.cjs`),t=require(`./errors.cjs`),n=require(`./type-guards.cjs`),r=require(`./quoter/quoter.cjs`),i=require(`./utils/asset-id.cjs`),a=e=>{if(!n.isEnvironment(e))throw new t.ServiceInitializationError(t.ErrorReason.ENVIRONMENT_NOT_SUPPORTED)},o=e=>{if(e.length===0)throw new t.ServiceInitializationError(`No service initializers provided.`);if(e.some(e=>!n.isServiceInitializer(e)))throw new t.ServiceInitializationError(`One or more service initializers are invalid.`);let r=new Set;for(let n of e){if(r.has(n.type))throw new t.ServiceInitializationError(t.ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,`Service type "${n.type}" has been initialized more than once.`);r.add(n.type)}},s=async({environment:n,serviceInitializers:r,fetch:i})=>{let a=new Map,o={},s=(e,n)=>{if(n instanceof t.ServiceInitializationError)return n;let r=n instanceof Error?n.message:String(n);return new t.ServiceInitializationError(t.ErrorReason.UNKNOWN,`Failed to initialize service type "${e}". ${r}`,n)},c=async(e,t)=>{try{let n=await t();a.set(e,n),o[e]={status:`initialized`}}catch(t){o[e]={status:`error`,error:s(e,t)}}};for(let s of r){if(a.has(s.type))throw new t.ServiceInitializationError(t.ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,`Service type "${s.type}" has been initialized more than once.`);switch(s.type){case e.ServiceType.AVALANCHE_EVM:await c(e.ServiceType.AVALANCHE_EVM,async()=>{let{createAvalancheEvmService:e}=await Promise.resolve().then(()=>require(`./transfer-service/avalanche-evm/avalanche-evm-service.cjs`));return await e({environment:n,evmSigner:s.evmSigner,fetch:i})});break;case e.ServiceType.LOMBARD_BTCB_TO_BTC:await c(e.ServiceType.LOMBARD_BTCB_TO_BTC,async()=>{let{createBtcbToBtcService:e}=await Promise.resolve().then(()=>require(`./transfer-service/lombard/btcb-to-btc-service.cjs`));return await e({bitcoinFunctions:s.btcFunctions,environment:n,evmSigner:s.evmSigner,fetch:i})});break;case e.ServiceType.LOMBARD_BTC_TO_BTCB:await c(e.ServiceType.LOMBARD_BTC_TO_BTCB,async()=>{let{createBtcToBtcbService:e}=await Promise.resolve().then(()=>require(`./transfer-service/lombard/btc-to-btcb-service.cjs`));return await e({bitcoinFunctions:s.btcFunctions,btcSigner:s.btcSigner,environment:n,evmSigner:s.evmSigner,fetch:i})});break;case e.ServiceType.MARKR:if(n!==e.Environment.PROD){o[e.ServiceType.MARKR]={status:`unsupported-environment`,message:`Service type "${e.ServiceType.MARKR}" is only supported in production environment.`};break}await c(e.ServiceType.MARKR,async()=>{let{createMarkrService:e}=await Promise.resolve().then(()=>require(`./transfer-service/markr/markr-service.cjs`));return await e({apiBaseUrl:s.markrApiUrl,apiToken:s.markrApiToken,appId:s.markrAppId,disableCrossChainSwaps:s.disableCrossChainSwaps,fetch:i,environment:n,evmSigner:s.evmSigner,getTargetChainAssets:s.getTargetChainAssets,solanaSigner:s.solanaSigner})});break;case e.ServiceType.WRAP_UNWRAP:await c(e.ServiceType.WRAP_UNWRAP,async()=>{let{createWrapUnwrapService:e}=await Promise.resolve().then(()=>require(`./transfer-service/wrap-unwrap/wrap-unwrap-service.cjs`));return await e({environment:n,evmSigner:s.evmSigner,fetch:i})});break;default:break}}return{services:a,status:{environment:n,services:o}}},c=async({environment:e,fetch:n,serviceInitializers:c})=>{a(e),o(c);let{services:l,status:u}=await s({environment:e,serviceInitializers:c,fetch:n});return{id:crypto.randomUUID(),estimateNativeFee:async(e,n)=>{let r=Math.floor(Date.now()/1e3);if(e.expiresAt<=r){let n=r-e.expiresAt;throw new t.InvalidParamsError(t.ErrorReason.QUOTE_EXPIRED,`Quote expired ${n} seconds ago.`)}let i=l.get(e.serviceType);if(!i)throw new t.ServiceUnavailableError(t.ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);return await i.estimateNativeFee(e,n)},getBridgeableAssets:async({sourceAsset:e,sourceChainId:t,targetChainId:n})=>{let r=await Promise.allSettled(Array.from(l.values()).map(r=>r.getBridgeableAssets({sourceAsset:e,sourceChainId:t,targetChainId:n}))),a=new Map;for(let e of r)if(e.status===`fulfilled`)for(let t of e.value){let{bridgeProviders:e,...r}=t,o=i.getAssetId(n,r),s=a.get(o);if(s){let t=[...new Set([...s.bridgeProviders,...e])];a.set(o,{...s,bridgeProviders:t})}else a.set(o,{...r,bridgeProviders:[...e]})}return Array.from(a.values())},getMinimumTransferAmount:async e=>{let t={};for(let n of l.values())if(n.analyzeSupport(e)){let r=await n.getMinimumTransferAmount(e);t[n.type]=r}return Object.keys(t).length>0?t:null},getSupportedChains:async()=>{let e=new Map,t=await Promise.all(Array.from(l.values()).map(e=>e.getSupportedChains()));for(let n of t)for(let[t,r]of n.entries()){let n=e.get(t);n||(n=new Set,e.set(t,n));for(let e of r)n.add(e)}return e},getQuoter:(e,t)=>new r.Quoter(e,Array.from(l.values()),t),status:()=>u,trackTransfer:e=>{let{transfer:n}=e,r=l.get(n.type);if(!r)throw new t.ServiceUnavailableError(t.ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);return r.trackTransfer(e)},transferAsset:async e=>{let{quote:n}=e,r=l.get(n.serviceType);if(!r)throw new t.ServiceUnavailableError(t.ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);return await r.transferAsset(e)}}};exports.createTransferManager=c;
2
2
  //# sourceMappingURL=transfer-manager.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"transfer-manager.cjs","names":["isEnvironment","ServiceInitializationError","ErrorReason","isServiceInitializer","ServiceType","Environment","mergeChainAssetMaps","InvalidParamsError","ServiceUnavailableError","TokenType","isCaip2ChainId","Quoter","getAssetId"],"sources":["../src/transfer-manager.ts"],"sourcesContent":["import { Environment, ServiceType, TokenType } from './constants';\nimport { ErrorReason, InvalidParamsError, ServiceInitializationError, ServiceUnavailableError } from './errors';\nimport type { Asset, BridgeableUiAsset, ChainAssetMap } from './types/asset';\nimport { isEnvironment, isServiceInitializer } from './type-guards';\nimport type { MutableGetSupportedChainsResult, ServiceInitializer, TransferService } from './types/service';\nimport type {\n CreateTransferManagerOptions,\n TransferManager,\n TransferManagerStatus,\n TransferManagerStatusServicesRecord,\n} from './types/transfer-manager';\nimport { Quoter } from './quoter/quoter';\nimport { mergeChainAssetMaps } from './_utils/merge-assets';\nimport { getAssetId } from './utils/asset-id';\nimport { isCaip2ChainId } from './utils/caip';\nimport type { Caip2ChainId } from './types/caip';\nimport type { Fetch } from './types/utility-types';\n\n/**\n * Validates the provided \"environment\" option.\n *\n * @throws {ServiceInitializationError} If the environment is invalid.\n */\nconst validateEnvironment = (environment: Environment): void => {\n if (!isEnvironment(environment)) {\n throw new ServiceInitializationError(ErrorReason.ENVIRONMENT_NOT_SUPPORTED);\n }\n};\n\n/**\n * Validates the provided \"serviceInitializers\" option.\n *\n * Checks for the following:\n * - At least one service initializer is provided.\n * - All service initializers are valid.\n * - No duplicate service types are initialized.\n *\n * @throws {ServiceInitializationError} If the service initializers are invalid.\n */\nconst validateServiceInitializers = (serviceInitializers: readonly ServiceInitializer[]): void => {\n if (serviceInitializers.length === 0) {\n throw new ServiceInitializationError('No service initializers provided.');\n }\n\n if (serviceInitializers.some((serviceInitializer) => !isServiceInitializer(serviceInitializer))) {\n throw new ServiceInitializationError('One or more service initializers are invalid.');\n }\n\n const serviceInitializerTypes = new Set<ServiceType>();\n for (const initializer of serviceInitializers) {\n if (serviceInitializerTypes.has(initializer.type)) {\n throw new ServiceInitializationError(\n ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,\n `Service type \"${initializer.type}\" has been initialized more than once.`,\n );\n }\n serviceInitializerTypes.add(initializer.type);\n }\n};\n\nconst initializeServices = async ({\n environment,\n serviceInitializers,\n fetch: customFetch,\n}: {\n environment: Environment;\n serviceInitializers: readonly ServiceInitializer[];\n fetch?: Fetch;\n}): Promise<{\n services: Map<ServiceType, TransferService>;\n status: TransferManagerStatus;\n}> => {\n const initializedServicesMap: Map<ServiceType, TransferService> = new Map();\n const serviceStatuses: TransferManagerStatusServicesRecord = {};\n\n const wrapInitializationError = (serviceType: ServiceType, error: unknown): ServiceInitializationError => {\n if (error instanceof ServiceInitializationError) {\n return error;\n }\n\n const details = error instanceof Error ? error.message : String(error);\n\n return new ServiceInitializationError(\n ErrorReason.UNKNOWN,\n `Failed to initialize service type \"${serviceType}\". ${details}`,\n error,\n );\n };\n\n const initializeService = async (\n serviceType: ServiceType,\n initializer: () => Promise<TransferService>,\n ): Promise<void> => {\n try {\n const service = await initializer();\n initializedServicesMap.set(serviceType, service);\n serviceStatuses[serviceType] = { status: 'initialized' };\n } catch (error) {\n const wrappedError = wrapInitializationError(serviceType, error);\n\n serviceStatuses[serviceType] = {\n status: 'error',\n error: wrappedError,\n };\n }\n };\n\n for (const initializer of serviceInitializers) {\n // Error on duplicate initialization attempts.\n if (initializedServicesMap.has(initializer.type)) {\n throw new ServiceInitializationError(\n ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,\n `Service type \"${initializer.type}\" has been initialized more than once.`,\n );\n }\n\n switch (initializer.type) {\n case ServiceType.AVALANCHE_EVM: {\n await initializeService(ServiceType.AVALANCHE_EVM, async () => {\n const { createAvalancheEvmService } = await import('./transfer-service/avalanche-evm/avalanche-evm-service');\n\n return await createAvalancheEvmService({\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.LOMBARD_BTCB_TO_BTC: {\n await initializeService(ServiceType.LOMBARD_BTCB_TO_BTC, async () => {\n const { createBtcbToBtcService } = await import('./transfer-service/lombard/btcb-to-btc-service');\n\n return await createBtcbToBtcService({\n bitcoinFunctions: initializer.btcFunctions,\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.LOMBARD_BTC_TO_BTCB: {\n await initializeService(ServiceType.LOMBARD_BTC_TO_BTCB, async () => {\n const { createBtcToBtcbService } = await import('./transfer-service/lombard/btc-to-btcb-service');\n\n return await createBtcToBtcbService({\n bitcoinFunctions: initializer.btcFunctions,\n btcSigner: initializer.btcSigner,\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.MARKR: {\n if (environment !== Environment.PROD) {\n serviceStatuses[ServiceType.MARKR] = {\n status: 'unsupported-environment',\n message: `Service type \"${ServiceType.MARKR}\" is only supported in production environment.`,\n };\n break;\n }\n\n await initializeService(ServiceType.MARKR, async () => {\n const { createMarkrService } = await import('./transfer-service/markr/markr-service');\n\n return await createMarkrService({\n apiBaseUrl: initializer.markrApiUrl,\n apiToken: initializer.markrApiToken,\n appId: initializer.markrAppId,\n disableCrossChainSwaps: initializer.disableCrossChainSwaps,\n fetch: customFetch,\n environment,\n evmSigner: initializer.evmSigner,\n getTargetChainAssets: initializer.getTargetChainAssets,\n solanaSigner: initializer.solanaSigner,\n });\n });\n\n break;\n }\n\n case ServiceType.WRAP_UNWRAP: {\n await initializeService(ServiceType.WRAP_UNWRAP, async () => {\n const { createWrapUnwrapService } = await import('./transfer-service/wrap-unwrap/wrap-unwrap-service');\n\n return await createWrapUnwrapService({\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n default: {\n break;\n }\n }\n }\n\n return {\n services: initializedServicesMap,\n status: {\n environment,\n services: serviceStatuses,\n },\n };\n};\n\nconst _getAssets = async (services: Map<ServiceType, TransferService>): Promise<ChainAssetMap> => {\n const assetMaps: ChainAssetMap[] = [];\n\n for (const service of services.values()) {\n const serviceAssets = await service.getAssets();\n assetMaps.push(serviceAssets);\n }\n\n return mergeChainAssetMaps(assetMaps);\n};\n\n/**\n * Creates a TransferManager instance.\n *\n * @returns {Promise<TransferManager>} The TransferManager instance.\n * @throws {ServiceInitializationError} If the provided options are invalid.\n */\nexport const createTransferManager = async ({\n environment,\n fetch: customFetch,\n serviceInitializers,\n}: CreateTransferManagerOptions): Promise<TransferManager> => {\n // Validate environment.\n validateEnvironment(environment);\n validateServiceInitializers(serviceInitializers);\n\n const { services, status } = await initializeServices({ environment, serviceInitializers, fetch: customFetch });\n\n return {\n id: crypto.randomUUID(),\n estimateNativeFee: async (quote, options) => {\n const now = Math.floor(Date.now() / 1_000);\n\n if (quote.expiresAt <= now) {\n const expiredSecondsAgo = now - quote.expiresAt;\n\n throw new InvalidParamsError(ErrorReason.QUOTE_EXPIRED, `Quote expired ${expiredSecondsAgo} seconds ago.`);\n }\n\n const service = services.get(quote.serviceType);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return await service.estimateNativeFee(quote, options);\n },\n getAssetBridgeMap: async ({ sourceAsset, sourceChainId }) => {\n const assets = await _getAssets(services);\n\n const chainAssets = assets[sourceChainId];\n\n if (!chainAssets) {\n return null;\n }\n\n const chainAsset = chainAssets.find((asset) => {\n if (sourceAsset.type === TokenType.NATIVE) {\n return asset.type === TokenType.NATIVE;\n } else {\n return asset.type === sourceAsset.type && asset.address === sourceAsset.address;\n }\n });\n\n if (!chainAsset || !chainAsset.destinations) {\n return null;\n }\n\n const destinations = chainAsset.destinations;\n\n // map destinations to the required format, lookup bridged asset from assets map\n const result: {\n [chainId: string]: {\n bridgedAsset: Asset;\n bridgeProviders: readonly ServiceType[];\n };\n } = {};\n\n for (const [destChainId, destInfo] of Object.entries(destinations)) {\n if (!isCaip2ChainId(destChainId)) {\n continue;\n }\n\n const destChainAssets = assets[destChainId];\n\n if (!destChainAssets) {\n continue;\n }\n\n // bridgedAsset is the asset from the assets map that matches the destInfo address\n const bridgedAsset = destChainAssets.find((asset) => {\n if (destInfo.address === TokenType.NATIVE) {\n return asset.type === TokenType.NATIVE;\n }\n\n return asset.type !== TokenType.NATIVE && asset.address === destInfo.address;\n });\n\n if (!bridgedAsset) {\n continue;\n }\n\n // Convert the TransferableAsset to Asset by omitting the 'destinations' field\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { destinations: _omit, swapProviders: _omitSwapProviders, ...convertedBridgedAsset } = bridgedAsset;\n\n result[destChainId] = {\n bridgedAsset: convertedBridgedAsset,\n bridgeProviders: destInfo.bridgeProviders,\n };\n }\n\n return Object.keys(result).length > 0 ? result : null;\n },\n getMinimumTransferAmount: async (props) => {\n const serviceMinimums: { [key in ServiceType]?: bigint } = {};\n\n for (const service of services.values()) {\n if (service.analyzeSupport(props)) {\n const serviceMinAmount = await service.getMinimumTransferAmount(props);\n serviceMinimums[service.type] = serviceMinAmount;\n }\n }\n\n return Object.keys(serviceMinimums).length > 0 ? serviceMinimums : null;\n },\n getSupportedChains: async () => {\n const supportedChainsMap: MutableGetSupportedChainsResult = new Map();\n\n // Fetch supported chains from all configured services in parallel.\n const serviceResults = await Promise.all(\n Array.from(services.values()).map((service) => service.getSupportedChains()),\n );\n\n // Merge results: union destination sets for identical source chain IDs.\n for (const result of serviceResults) {\n for (const [sourceChainId, targetChainIds] of result.entries()) {\n let mergedTargets = supportedChainsMap.get(sourceChainId);\n if (!mergedTargets) {\n mergedTargets = new Set<Caip2ChainId>();\n supportedChainsMap.set(sourceChainId, mergedTargets);\n }\n\n for (const targetChainId of targetChainIds) {\n mergedTargets.add(targetChainId);\n }\n }\n }\n\n return supportedChainsMap;\n },\n getQuoter: (props, options) => {\n return new Quoter(props, Array.from(services.values()), options);\n },\n status: () => status,\n trackTransfer: (props) => {\n const { transfer } = props;\n const service = services.get(transfer.type);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return service.trackTransfer(props);\n },\n transferAsset: async (props) => {\n const { quote } = props;\n const service = services.get(quote.serviceType);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return await service.transferAsset(props);\n },\n getBridgeableAssets: async ({ sourceAsset, sourceChainId, targetChainId }) => {\n const settledResults = await Promise.allSettled(\n Array.from(services.values()).map((service) =>\n service.getBridgeableAssets({ sourceAsset, sourceChainId, targetChainId }),\n ),\n );\n\n const merged = new Map<string, BridgeableUiAsset>();\n\n for (const settled of settledResults) {\n if (settled.status !== 'fulfilled') continue;\n for (const result of settled.value) {\n const { bridgeProviders, ...asset } = result;\n const key = getAssetId(targetChainId, asset);\n\n const existing = merged.get(key);\n if (existing) {\n const combined = [...new Set([...existing.bridgeProviders, ...bridgeProviders])];\n merged.set(key, { ...existing, bridgeProviders: combined });\n } else {\n merged.set(key, { ...asset, bridgeProviders: [...bridgeProviders] });\n }\n }\n }\n\n return Array.from(merged.values());\n },\n } satisfies TransferManager;\n};\n"],"mappings":"oOAuBM,EAAuB,GAAmC,CAC9D,GAAI,CAACA,EAAAA,cAAc,EAAY,CAC7B,MAAM,IAAIC,EAAAA,2BAA2BC,EAAAA,YAAY,0BA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,CAAC,CAK1E,OAAO,MAAM,KAAK,EAAO,QAAQ,CAAC,EAErC"}
1
+ {"version":3,"file":"transfer-manager.cjs","names":["isEnvironment","ServiceInitializationError","ErrorReason","isServiceInitializer","ServiceType","Environment","InvalidParamsError","ServiceUnavailableError","getAssetId","Quoter"],"sources":["../src/transfer-manager.ts"],"sourcesContent":["import { Environment, ServiceType } from './constants';\nimport { ErrorReason, InvalidParamsError, ServiceInitializationError, ServiceUnavailableError } from './errors';\nimport type { BridgeableUiAsset } from './types/asset';\nimport { isEnvironment, isServiceInitializer } from './type-guards';\nimport type { MutableGetSupportedChainsResult, ServiceInitializer, TransferService } from './types/service';\nimport type {\n CreateTransferManagerOptions,\n TransferManager,\n TransferManagerStatus,\n TransferManagerStatusServicesRecord,\n} from './types/transfer-manager';\nimport { Quoter } from './quoter/quoter';\nimport { getAssetId } from './utils/asset-id';\nimport type { Caip2ChainId } from './types/caip';\nimport type { Fetch } from './types/utility-types';\n\n/**\n * Validates the provided \"environment\" option.\n *\n * @throws {ServiceInitializationError} If the environment is invalid.\n */\nconst validateEnvironment = (environment: Environment): void => {\n if (!isEnvironment(environment)) {\n throw new ServiceInitializationError(ErrorReason.ENVIRONMENT_NOT_SUPPORTED);\n }\n};\n\n/**\n * Validates the provided \"serviceInitializers\" option.\n *\n * Checks for the following:\n * - At least one service initializer is provided.\n * - All service initializers are valid.\n * - No duplicate service types are initialized.\n *\n * @throws {ServiceInitializationError} If the service initializers are invalid.\n */\nconst validateServiceInitializers = (serviceInitializers: readonly ServiceInitializer[]): void => {\n if (serviceInitializers.length === 0) {\n throw new ServiceInitializationError('No service initializers provided.');\n }\n\n if (serviceInitializers.some((serviceInitializer) => !isServiceInitializer(serviceInitializer))) {\n throw new ServiceInitializationError('One or more service initializers are invalid.');\n }\n\n const serviceInitializerTypes = new Set<ServiceType>();\n for (const initializer of serviceInitializers) {\n if (serviceInitializerTypes.has(initializer.type)) {\n throw new ServiceInitializationError(\n ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,\n `Service type \"${initializer.type}\" has been initialized more than once.`,\n );\n }\n serviceInitializerTypes.add(initializer.type);\n }\n};\n\nconst initializeServices = async ({\n environment,\n serviceInitializers,\n fetch: customFetch,\n}: {\n environment: Environment;\n serviceInitializers: readonly ServiceInitializer[];\n fetch?: Fetch;\n}): Promise<{\n services: Map<ServiceType, TransferService>;\n status: TransferManagerStatus;\n}> => {\n const initializedServicesMap: Map<ServiceType, TransferService> = new Map();\n const serviceStatuses: TransferManagerStatusServicesRecord = {};\n\n const wrapInitializationError = (serviceType: ServiceType, error: unknown): ServiceInitializationError => {\n if (error instanceof ServiceInitializationError) {\n return error;\n }\n\n const details = error instanceof Error ? error.message : String(error);\n\n return new ServiceInitializationError(\n ErrorReason.UNKNOWN,\n `Failed to initialize service type \"${serviceType}\". ${details}`,\n error,\n );\n };\n\n const initializeService = async (\n serviceType: ServiceType,\n initializer: () => Promise<TransferService>,\n ): Promise<void> => {\n try {\n const service = await initializer();\n initializedServicesMap.set(serviceType, service);\n serviceStatuses[serviceType] = { status: 'initialized' };\n } catch (error) {\n const wrappedError = wrapInitializationError(serviceType, error);\n\n serviceStatuses[serviceType] = {\n status: 'error',\n error: wrappedError,\n };\n }\n };\n\n for (const initializer of serviceInitializers) {\n // Error on duplicate initialization attempts.\n if (initializedServicesMap.has(initializer.type)) {\n throw new ServiceInitializationError(\n ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,\n `Service type \"${initializer.type}\" has been initialized more than once.`,\n );\n }\n\n switch (initializer.type) {\n case ServiceType.AVALANCHE_EVM: {\n await initializeService(ServiceType.AVALANCHE_EVM, async () => {\n const { createAvalancheEvmService } = await import('./transfer-service/avalanche-evm/avalanche-evm-service');\n\n return await createAvalancheEvmService({\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.LOMBARD_BTCB_TO_BTC: {\n await initializeService(ServiceType.LOMBARD_BTCB_TO_BTC, async () => {\n const { createBtcbToBtcService } = await import('./transfer-service/lombard/btcb-to-btc-service');\n\n return await createBtcbToBtcService({\n bitcoinFunctions: initializer.btcFunctions,\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.LOMBARD_BTC_TO_BTCB: {\n await initializeService(ServiceType.LOMBARD_BTC_TO_BTCB, async () => {\n const { createBtcToBtcbService } = await import('./transfer-service/lombard/btc-to-btcb-service');\n\n return await createBtcToBtcbService({\n bitcoinFunctions: initializer.btcFunctions,\n btcSigner: initializer.btcSigner,\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.MARKR: {\n if (environment !== Environment.PROD) {\n serviceStatuses[ServiceType.MARKR] = {\n status: 'unsupported-environment',\n message: `Service type \"${ServiceType.MARKR}\" is only supported in production environment.`,\n };\n break;\n }\n\n await initializeService(ServiceType.MARKR, async () => {\n const { createMarkrService } = await import('./transfer-service/markr/markr-service');\n\n return await createMarkrService({\n apiBaseUrl: initializer.markrApiUrl,\n apiToken: initializer.markrApiToken,\n appId: initializer.markrAppId,\n disableCrossChainSwaps: initializer.disableCrossChainSwaps,\n fetch: customFetch,\n environment,\n evmSigner: initializer.evmSigner,\n getTargetChainAssets: initializer.getTargetChainAssets,\n solanaSigner: initializer.solanaSigner,\n });\n });\n\n break;\n }\n\n case ServiceType.WRAP_UNWRAP: {\n await initializeService(ServiceType.WRAP_UNWRAP, async () => {\n const { createWrapUnwrapService } = await import('./transfer-service/wrap-unwrap/wrap-unwrap-service');\n\n return await createWrapUnwrapService({\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n default: {\n break;\n }\n }\n }\n\n return {\n services: initializedServicesMap,\n status: {\n environment,\n services: serviceStatuses,\n },\n };\n};\n\n/**\n * Creates a TransferManager instance.\n *\n * @returns {Promise<TransferManager>} The TransferManager instance.\n * @throws {ServiceInitializationError} If the provided options are invalid.\n */\nexport const createTransferManager = async ({\n environment,\n fetch: customFetch,\n serviceInitializers,\n}: CreateTransferManagerOptions): Promise<TransferManager> => {\n // Validate environment.\n validateEnvironment(environment);\n validateServiceInitializers(serviceInitializers);\n\n const { services, status } = await initializeServices({ environment, serviceInitializers, fetch: customFetch });\n\n return {\n id: crypto.randomUUID(),\n estimateNativeFee: async (quote, options) => {\n const now = Math.floor(Date.now() / 1_000);\n\n if (quote.expiresAt <= now) {\n const expiredSecondsAgo = now - quote.expiresAt;\n\n throw new InvalidParamsError(ErrorReason.QUOTE_EXPIRED, `Quote expired ${expiredSecondsAgo} seconds ago.`);\n }\n\n const service = services.get(quote.serviceType);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return await service.estimateNativeFee(quote, options);\n },\n getBridgeableAssets: async ({ sourceAsset, sourceChainId, targetChainId }) => {\n const settledResults = await Promise.allSettled(\n Array.from(services.values()).map((service) =>\n service.getBridgeableAssets({ sourceAsset, sourceChainId, targetChainId }),\n ),\n );\n\n const merged = new Map<string, BridgeableUiAsset>();\n\n for (const settled of settledResults) {\n if (settled.status !== 'fulfilled') continue;\n for (const result of settled.value) {\n const { bridgeProviders, ...asset } = result;\n const key = getAssetId(targetChainId, asset);\n\n const existing = merged.get(key);\n if (existing) {\n const combined = [...new Set([...existing.bridgeProviders, ...bridgeProviders])];\n merged.set(key, { ...existing, bridgeProviders: combined });\n } else {\n merged.set(key, { ...asset, bridgeProviders: [...bridgeProviders] });\n }\n }\n }\n\n return Array.from(merged.values());\n },\n getMinimumTransferAmount: async (props) => {\n const serviceMinimums: { [key in ServiceType]?: bigint } = {};\n\n for (const service of services.values()) {\n if (service.analyzeSupport(props)) {\n const serviceMinAmount = await service.getMinimumTransferAmount(props);\n serviceMinimums[service.type] = serviceMinAmount;\n }\n }\n\n return Object.keys(serviceMinimums).length > 0 ? serviceMinimums : null;\n },\n getSupportedChains: async () => {\n const supportedChainsMap: MutableGetSupportedChainsResult = new Map();\n\n // Fetch supported chains from all configured services in parallel.\n const serviceResults = await Promise.all(\n Array.from(services.values()).map((service) => service.getSupportedChains()),\n );\n\n // Merge results: union destination sets for identical source chain IDs.\n for (const result of serviceResults) {\n for (const [sourceChainId, targetChainIds] of result.entries()) {\n let mergedTargets = supportedChainsMap.get(sourceChainId);\n if (!mergedTargets) {\n mergedTargets = new Set<Caip2ChainId>();\n supportedChainsMap.set(sourceChainId, mergedTargets);\n }\n\n for (const targetChainId of targetChainIds) {\n mergedTargets.add(targetChainId);\n }\n }\n }\n\n return supportedChainsMap;\n },\n getQuoter: (props, options) => {\n return new Quoter(props, Array.from(services.values()), options);\n },\n status: () => status,\n trackTransfer: (props) => {\n const { transfer } = props;\n const service = services.get(transfer.type);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return service.trackTransfer(props);\n },\n transferAsset: async (props) => {\n const { quote } = props;\n const service = services.get(quote.serviceType);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return await service.transferAsset(props);\n },\n } satisfies TransferManager;\n};\n"],"mappings":"+JAqBM,EAAuB,GAAmC,CAC9D,GAAI,CAACA,EAAAA,cAAc,EAAY,CAC7B,MAAM,IAAIC,EAAAA,2BAA2BC,EAAAA,YAAY,0BAA0B,EAczE,EAA+B,GAA6D,CAChG,GAAI,EAAoB,SAAW,EACjC,MAAM,IAAID,EAAAA,2BAA2B,oCAAoC,CAG3E,GAAI,EAAoB,KAAM,GAAuB,CAACE,EAAAA,qBAAqB,EAAmB,CAAC,CAC7F,MAAM,IAAIF,EAAAA,2BAA2B,gDAAgD,CAGvF,IAAM,EAA0B,IAAI,IACpC,IAAK,IAAM,KAAe,EAAqB,CAC7C,GAAI,EAAwB,IAAI,EAAY,KAAK,CAC/C,MAAM,IAAIA,EAAAA,2BACRC,EAAAA,YAAY,iCACZ,iBAAiB,EAAY,KA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,QAAQ,CACrC,GAAI,EAAQ,eAAe,EAAM,CAAE,CACjC,IAAM,EAAmB,MAAM,EAAQ,yBAAyB,EAAM,CACtE,EAAgB,EAAQ,MAAQ,EAIpC,OAAO,OAAO,KAAK,EAAgB,CAAC,OAAS,EAAI,EAAkB,MAErE,mBAAoB,SAAY,CAC9B,IAAM,EAAsD,IAAI,IAG1D,EAAiB,MAAM,QAAQ,IACnC,MAAM,KAAK,EAAS,QAAQ,CAAC,CAAC,IAAK,GAAY,EAAQ,oBAAoB,CAAC,CAC7E,CAGD,IAAK,IAAM,KAAU,EACnB,IAAK,GAAM,CAAC,EAAe,KAAmB,EAAO,SAAS,CAAE,CAC9D,IAAI,EAAgB,EAAmB,IAAI,EAAc,CACpD,IACH,EAAgB,IAAI,IACpB,EAAmB,IAAI,EAAe,EAAc,EAGtD,IAAK,IAAM,KAAiB,EAC1B,EAAc,IAAI,EAAc,CAKtC,OAAO,GAET,WAAY,EAAO,IACV,IAAIC,EAAAA,OAAO,EAAO,MAAM,KAAK,EAAS,QAAQ,CAAC,CAAE,EAAQ,CAElE,WAAc,EACd,cAAgB,GAAU,CACxB,GAAM,CAAE,YAAa,EACf,EAAU,EAAS,IAAI,EAAS,KAAK,CAE3C,GAAI,CAAC,EACH,MAAM,IAAIF,EAAAA,wBAAwBL,EAAAA,YAAY,4BAA4B,CAG5E,OAAO,EAAQ,cAAc,EAAM,EAErC,cAAe,KAAO,IAAU,CAC9B,GAAM,CAAE,SAAU,EACZ,EAAU,EAAS,IAAI,EAAM,YAAY,CAE/C,GAAI,CAAC,EACH,MAAM,IAAIK,EAAAA,wBAAwBL,EAAAA,YAAY,4BAA4B,CAG5E,OAAO,MAAM,EAAQ,cAAc,EAAM,EAE5C"}
@@ -1,2 +1,2 @@
1
- import{Environment as e,ServiceType as t,TokenType as n}from"./constants.js";import{ErrorReason as r,InvalidParamsError as i,ServiceInitializationError as a,ServiceUnavailableError as o}from"./errors.js";import{isEnvironment as s,isServiceInitializer as c}from"./type-guards.js";import{Quoter as l}from"./quoter/quoter.js";import{isCaip2ChainId as u}from"./utils/caip.js";import{mergeChainAssetMaps as d}from"./_utils/merge-assets.js";import{getAssetId as f}from"./utils/asset-id.js";const p=e=>{if(!s(e))throw new a(r.ENVIRONMENT_NOT_SUPPORTED)},m=e=>{if(e.length===0)throw new a(`No service initializers provided.`);if(e.some(e=>!c(e)))throw new a(`One or more service initializers are invalid.`);let t=new Set;for(let n of e){if(t.has(n.type))throw new a(r.DUPLICATE_SERVICE_INITIALIZATION,`Service type "${n.type}" has been initialized more than once.`);t.add(n.type)}},h=async({environment:n,serviceInitializers:i,fetch:o})=>{let s=new Map,c={},l=(e,t)=>{if(t instanceof a)return t;let n=t instanceof Error?t.message:String(t);return new a(r.UNKNOWN,`Failed to initialize service type "${e}". ${n}`,t)},u=async(e,t)=>{try{let n=await t();s.set(e,n),c[e]={status:`initialized`}}catch(t){c[e]={status:`error`,error:l(e,t)}}};for(let l of i){if(s.has(l.type))throw new a(r.DUPLICATE_SERVICE_INITIALIZATION,`Service type "${l.type}" has been initialized more than once.`);switch(l.type){case t.AVALANCHE_EVM:await u(t.AVALANCHE_EVM,async()=>{let{createAvalancheEvmService:e}=await import(`./transfer-service/avalanche-evm/avalanche-evm-service.js`);return await e({environment:n,evmSigner:l.evmSigner,fetch:o})});break;case t.LOMBARD_BTCB_TO_BTC:await u(t.LOMBARD_BTCB_TO_BTC,async()=>{let{createBtcbToBtcService:e}=await import(`./transfer-service/lombard/btcb-to-btc-service.js`);return await e({bitcoinFunctions:l.btcFunctions,environment:n,evmSigner:l.evmSigner,fetch:o})});break;case t.LOMBARD_BTC_TO_BTCB:await u(t.LOMBARD_BTC_TO_BTCB,async()=>{let{createBtcToBtcbService:e}=await import(`./transfer-service/lombard/btc-to-btcb-service.js`);return await e({bitcoinFunctions:l.btcFunctions,btcSigner:l.btcSigner,environment:n,evmSigner:l.evmSigner,fetch:o})});break;case t.MARKR:if(n!==e.PROD){c[t.MARKR]={status:`unsupported-environment`,message:`Service type "${t.MARKR}" is only supported in production environment.`};break}await u(t.MARKR,async()=>{let{createMarkrService:e}=await import(`./transfer-service/markr/markr-service.js`);return await e({apiBaseUrl:l.markrApiUrl,apiToken:l.markrApiToken,appId:l.markrAppId,disableCrossChainSwaps:l.disableCrossChainSwaps,fetch:o,environment:n,evmSigner:l.evmSigner,getTargetChainAssets:l.getTargetChainAssets,solanaSigner:l.solanaSigner})});break;case t.WRAP_UNWRAP:await u(t.WRAP_UNWRAP,async()=>{let{createWrapUnwrapService:e}=await import(`./transfer-service/wrap-unwrap/wrap-unwrap-service.js`);return await e({environment:n,evmSigner:l.evmSigner,fetch:o})});break;default:break}}return{services:s,status:{environment:n,services:c}}},g=async e=>{let t=[];for(let n of e.values()){let e=await n.getAssets();t.push(e)}return d(t)},_=async({environment:e,fetch:t,serviceInitializers:a})=>{p(e),m(a);let{services:s,status:c}=await h({environment:e,serviceInitializers:a,fetch:t});return{id:crypto.randomUUID(),estimateNativeFee:async(e,t)=>{let n=Math.floor(Date.now()/1e3);if(e.expiresAt<=n){let t=n-e.expiresAt;throw new i(r.QUOTE_EXPIRED,`Quote expired ${t} seconds ago.`)}let a=s.get(e.serviceType);if(!a)throw new o(r.SERVICE_TYPE_NOT_CONFIGURED);return await a.estimateNativeFee(e,t)},getAssetBridgeMap:async({sourceAsset:e,sourceChainId:t})=>{let r=await g(s),i=r[t];if(!i)return null;let a=i.find(t=>e.type===n.NATIVE?t.type===n.NATIVE:t.type===e.type&&t.address===e.address);if(!a||!a.destinations)return null;let o=a.destinations,c={};for(let[e,t]of Object.entries(o)){if(!u(e))continue;let i=r[e];if(!i)continue;let a=i.find(e=>t.address===n.NATIVE?e.type===n.NATIVE:e.type!==n.NATIVE&&e.address===t.address);if(!a)continue;let{destinations:o,swapProviders:s,...l}=a;c[e]={bridgedAsset:l,bridgeProviders:t.bridgeProviders}}return Object.keys(c).length>0?c:null},getMinimumTransferAmount:async e=>{let t={};for(let n of s.values())if(n.analyzeSupport(e)){let r=await n.getMinimumTransferAmount(e);t[n.type]=r}return Object.keys(t).length>0?t:null},getSupportedChains:async()=>{let e=new Map,t=await Promise.all(Array.from(s.values()).map(e=>e.getSupportedChains()));for(let n of t)for(let[t,r]of n.entries()){let n=e.get(t);n||(n=new Set,e.set(t,n));for(let e of r)n.add(e)}return e},getQuoter:(e,t)=>new l(e,Array.from(s.values()),t),status:()=>c,trackTransfer:e=>{let{transfer:t}=e,n=s.get(t.type);if(!n)throw new o(r.SERVICE_TYPE_NOT_CONFIGURED);return n.trackTransfer(e)},transferAsset:async e=>{let{quote:t}=e,n=s.get(t.serviceType);if(!n)throw new o(r.SERVICE_TYPE_NOT_CONFIGURED);return await n.transferAsset(e)},getBridgeableAssets:async({sourceAsset:e,sourceChainId:t,targetChainId:n})=>{let r=await Promise.allSettled(Array.from(s.values()).map(r=>r.getBridgeableAssets({sourceAsset:e,sourceChainId:t,targetChainId:n}))),i=new Map;for(let e of r)if(e.status===`fulfilled`)for(let t of e.value){let{bridgeProviders:e,...r}=t,a=f(n,r),o=i.get(a);if(o){let t=[...new Set([...o.bridgeProviders,...e])];i.set(a,{...o,bridgeProviders:t})}else i.set(a,{...r,bridgeProviders:[...e]})}return Array.from(i.values())}}};export{_ as createTransferManager};
1
+ import{Environment as e,ServiceType as t}from"./constants.js";import{ErrorReason as n,InvalidParamsError as r,ServiceInitializationError as i,ServiceUnavailableError as a}from"./errors.js";import{isEnvironment as o,isServiceInitializer as s}from"./type-guards.js";import{Quoter as c}from"./quoter/quoter.js";import{getAssetId as l}from"./utils/asset-id.js";const u=e=>{if(!o(e))throw new i(n.ENVIRONMENT_NOT_SUPPORTED)},d=e=>{if(e.length===0)throw new i(`No service initializers provided.`);if(e.some(e=>!s(e)))throw new i(`One or more service initializers are invalid.`);let t=new Set;for(let r of e){if(t.has(r.type))throw new i(n.DUPLICATE_SERVICE_INITIALIZATION,`Service type "${r.type}" has been initialized more than once.`);t.add(r.type)}},f=async({environment:r,serviceInitializers:a,fetch:o})=>{let s=new Map,c={},l=(e,t)=>{if(t instanceof i)return t;let r=t instanceof Error?t.message:String(t);return new i(n.UNKNOWN,`Failed to initialize service type "${e}". ${r}`,t)},u=async(e,t)=>{try{let n=await t();s.set(e,n),c[e]={status:`initialized`}}catch(t){c[e]={status:`error`,error:l(e,t)}}};for(let l of a){if(s.has(l.type))throw new i(n.DUPLICATE_SERVICE_INITIALIZATION,`Service type "${l.type}" has been initialized more than once.`);switch(l.type){case t.AVALANCHE_EVM:await u(t.AVALANCHE_EVM,async()=>{let{createAvalancheEvmService:e}=await import(`./transfer-service/avalanche-evm/avalanche-evm-service.js`);return await e({environment:r,evmSigner:l.evmSigner,fetch:o})});break;case t.LOMBARD_BTCB_TO_BTC:await u(t.LOMBARD_BTCB_TO_BTC,async()=>{let{createBtcbToBtcService:e}=await import(`./transfer-service/lombard/btcb-to-btc-service.js`);return await e({bitcoinFunctions:l.btcFunctions,environment:r,evmSigner:l.evmSigner,fetch:o})});break;case t.LOMBARD_BTC_TO_BTCB:await u(t.LOMBARD_BTC_TO_BTCB,async()=>{let{createBtcToBtcbService:e}=await import(`./transfer-service/lombard/btc-to-btcb-service.js`);return await e({bitcoinFunctions:l.btcFunctions,btcSigner:l.btcSigner,environment:r,evmSigner:l.evmSigner,fetch:o})});break;case t.MARKR:if(r!==e.PROD){c[t.MARKR]={status:`unsupported-environment`,message:`Service type "${t.MARKR}" is only supported in production environment.`};break}await u(t.MARKR,async()=>{let{createMarkrService:e}=await import(`./transfer-service/markr/markr-service.js`);return await e({apiBaseUrl:l.markrApiUrl,apiToken:l.markrApiToken,appId:l.markrAppId,disableCrossChainSwaps:l.disableCrossChainSwaps,fetch:o,environment:r,evmSigner:l.evmSigner,getTargetChainAssets:l.getTargetChainAssets,solanaSigner:l.solanaSigner})});break;case t.WRAP_UNWRAP:await u(t.WRAP_UNWRAP,async()=>{let{createWrapUnwrapService:e}=await import(`./transfer-service/wrap-unwrap/wrap-unwrap-service.js`);return await e({environment:r,evmSigner:l.evmSigner,fetch:o})});break;default:break}}return{services:s,status:{environment:r,services:c}}},p=async({environment:e,fetch:t,serviceInitializers:i})=>{u(e),d(i);let{services:o,status:s}=await f({environment:e,serviceInitializers:i,fetch:t});return{id:crypto.randomUUID(),estimateNativeFee:async(e,t)=>{let i=Math.floor(Date.now()/1e3);if(e.expiresAt<=i){let t=i-e.expiresAt;throw new r(n.QUOTE_EXPIRED,`Quote expired ${t} seconds ago.`)}let s=o.get(e.serviceType);if(!s)throw new a(n.SERVICE_TYPE_NOT_CONFIGURED);return await s.estimateNativeFee(e,t)},getBridgeableAssets:async({sourceAsset:e,sourceChainId:t,targetChainId:n})=>{let r=await Promise.allSettled(Array.from(o.values()).map(r=>r.getBridgeableAssets({sourceAsset:e,sourceChainId:t,targetChainId:n}))),i=new Map;for(let e of r)if(e.status===`fulfilled`)for(let t of e.value){let{bridgeProviders:e,...r}=t,a=l(n,r),o=i.get(a);if(o){let t=[...new Set([...o.bridgeProviders,...e])];i.set(a,{...o,bridgeProviders:t})}else i.set(a,{...r,bridgeProviders:[...e]})}return Array.from(i.values())},getMinimumTransferAmount:async e=>{let t={};for(let n of o.values())if(n.analyzeSupport(e)){let r=await n.getMinimumTransferAmount(e);t[n.type]=r}return Object.keys(t).length>0?t:null},getSupportedChains:async()=>{let e=new Map,t=await Promise.all(Array.from(o.values()).map(e=>e.getSupportedChains()));for(let n of t)for(let[t,r]of n.entries()){let n=e.get(t);n||(n=new Set,e.set(t,n));for(let e of r)n.add(e)}return e},getQuoter:(e,t)=>new c(e,Array.from(o.values()),t),status:()=>s,trackTransfer:e=>{let{transfer:t}=e,r=o.get(t.type);if(!r)throw new a(n.SERVICE_TYPE_NOT_CONFIGURED);return r.trackTransfer(e)},transferAsset:async e=>{let{quote:t}=e,r=o.get(t.serviceType);if(!r)throw new a(n.SERVICE_TYPE_NOT_CONFIGURED);return await r.transferAsset(e)}}};export{p as createTransferManager};
2
2
  //# sourceMappingURL=transfer-manager.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"transfer-manager.js","names":[],"sources":["../src/transfer-manager.ts"],"sourcesContent":["import { Environment, ServiceType, TokenType } from './constants';\nimport { ErrorReason, InvalidParamsError, ServiceInitializationError, ServiceUnavailableError } from './errors';\nimport type { Asset, BridgeableUiAsset, ChainAssetMap } from './types/asset';\nimport { isEnvironment, isServiceInitializer } from './type-guards';\nimport type { MutableGetSupportedChainsResult, ServiceInitializer, TransferService } from './types/service';\nimport type {\n CreateTransferManagerOptions,\n TransferManager,\n TransferManagerStatus,\n TransferManagerStatusServicesRecord,\n} from './types/transfer-manager';\nimport { Quoter } from './quoter/quoter';\nimport { mergeChainAssetMaps } from './_utils/merge-assets';\nimport { getAssetId } from './utils/asset-id';\nimport { isCaip2ChainId } from './utils/caip';\nimport type { Caip2ChainId } from './types/caip';\nimport type { Fetch } from './types/utility-types';\n\n/**\n * Validates the provided \"environment\" option.\n *\n * @throws {ServiceInitializationError} If the environment is invalid.\n */\nconst validateEnvironment = (environment: Environment): void => {\n if (!isEnvironment(environment)) {\n throw new ServiceInitializationError(ErrorReason.ENVIRONMENT_NOT_SUPPORTED);\n }\n};\n\n/**\n * Validates the provided \"serviceInitializers\" option.\n *\n * Checks for the following:\n * - At least one service initializer is provided.\n * - All service initializers are valid.\n * - No duplicate service types are initialized.\n *\n * @throws {ServiceInitializationError} If the service initializers are invalid.\n */\nconst validateServiceInitializers = (serviceInitializers: readonly ServiceInitializer[]): void => {\n if (serviceInitializers.length === 0) {\n throw new ServiceInitializationError('No service initializers provided.');\n }\n\n if (serviceInitializers.some((serviceInitializer) => !isServiceInitializer(serviceInitializer))) {\n throw new ServiceInitializationError('One or more service initializers are invalid.');\n }\n\n const serviceInitializerTypes = new Set<ServiceType>();\n for (const initializer of serviceInitializers) {\n if (serviceInitializerTypes.has(initializer.type)) {\n throw new ServiceInitializationError(\n ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,\n `Service type \"${initializer.type}\" has been initialized more than once.`,\n );\n }\n serviceInitializerTypes.add(initializer.type);\n }\n};\n\nconst initializeServices = async ({\n environment,\n serviceInitializers,\n fetch: customFetch,\n}: {\n environment: Environment;\n serviceInitializers: readonly ServiceInitializer[];\n fetch?: Fetch;\n}): Promise<{\n services: Map<ServiceType, TransferService>;\n status: TransferManagerStatus;\n}> => {\n const initializedServicesMap: Map<ServiceType, TransferService> = new Map();\n const serviceStatuses: TransferManagerStatusServicesRecord = {};\n\n const wrapInitializationError = (serviceType: ServiceType, error: unknown): ServiceInitializationError => {\n if (error instanceof ServiceInitializationError) {\n return error;\n }\n\n const details = error instanceof Error ? error.message : String(error);\n\n return new ServiceInitializationError(\n ErrorReason.UNKNOWN,\n `Failed to initialize service type \"${serviceType}\". ${details}`,\n error,\n );\n };\n\n const initializeService = async (\n serviceType: ServiceType,\n initializer: () => Promise<TransferService>,\n ): Promise<void> => {\n try {\n const service = await initializer();\n initializedServicesMap.set(serviceType, service);\n serviceStatuses[serviceType] = { status: 'initialized' };\n } catch (error) {\n const wrappedError = wrapInitializationError(serviceType, error);\n\n serviceStatuses[serviceType] = {\n status: 'error',\n error: wrappedError,\n };\n }\n };\n\n for (const initializer of serviceInitializers) {\n // Error on duplicate initialization attempts.\n if (initializedServicesMap.has(initializer.type)) {\n throw new ServiceInitializationError(\n ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,\n `Service type \"${initializer.type}\" has been initialized more than once.`,\n );\n }\n\n switch (initializer.type) {\n case ServiceType.AVALANCHE_EVM: {\n await initializeService(ServiceType.AVALANCHE_EVM, async () => {\n const { createAvalancheEvmService } = await import('./transfer-service/avalanche-evm/avalanche-evm-service');\n\n return await createAvalancheEvmService({\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.LOMBARD_BTCB_TO_BTC: {\n await initializeService(ServiceType.LOMBARD_BTCB_TO_BTC, async () => {\n const { createBtcbToBtcService } = await import('./transfer-service/lombard/btcb-to-btc-service');\n\n return await createBtcbToBtcService({\n bitcoinFunctions: initializer.btcFunctions,\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.LOMBARD_BTC_TO_BTCB: {\n await initializeService(ServiceType.LOMBARD_BTC_TO_BTCB, async () => {\n const { createBtcToBtcbService } = await import('./transfer-service/lombard/btc-to-btcb-service');\n\n return await createBtcToBtcbService({\n bitcoinFunctions: initializer.btcFunctions,\n btcSigner: initializer.btcSigner,\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.MARKR: {\n if (environment !== Environment.PROD) {\n serviceStatuses[ServiceType.MARKR] = {\n status: 'unsupported-environment',\n message: `Service type \"${ServiceType.MARKR}\" is only supported in production environment.`,\n };\n break;\n }\n\n await initializeService(ServiceType.MARKR, async () => {\n const { createMarkrService } = await import('./transfer-service/markr/markr-service');\n\n return await createMarkrService({\n apiBaseUrl: initializer.markrApiUrl,\n apiToken: initializer.markrApiToken,\n appId: initializer.markrAppId,\n disableCrossChainSwaps: initializer.disableCrossChainSwaps,\n fetch: customFetch,\n environment,\n evmSigner: initializer.evmSigner,\n getTargetChainAssets: initializer.getTargetChainAssets,\n solanaSigner: initializer.solanaSigner,\n });\n });\n\n break;\n }\n\n case ServiceType.WRAP_UNWRAP: {\n await initializeService(ServiceType.WRAP_UNWRAP, async () => {\n const { createWrapUnwrapService } = await import('./transfer-service/wrap-unwrap/wrap-unwrap-service');\n\n return await createWrapUnwrapService({\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n default: {\n break;\n }\n }\n }\n\n return {\n services: initializedServicesMap,\n status: {\n environment,\n services: serviceStatuses,\n },\n };\n};\n\nconst _getAssets = async (services: Map<ServiceType, TransferService>): Promise<ChainAssetMap> => {\n const assetMaps: ChainAssetMap[] = [];\n\n for (const service of services.values()) {\n const serviceAssets = await service.getAssets();\n assetMaps.push(serviceAssets);\n }\n\n return mergeChainAssetMaps(assetMaps);\n};\n\n/**\n * Creates a TransferManager instance.\n *\n * @returns {Promise<TransferManager>} The TransferManager instance.\n * @throws {ServiceInitializationError} If the provided options are invalid.\n */\nexport const createTransferManager = async ({\n environment,\n fetch: customFetch,\n serviceInitializers,\n}: CreateTransferManagerOptions): Promise<TransferManager> => {\n // Validate environment.\n validateEnvironment(environment);\n validateServiceInitializers(serviceInitializers);\n\n const { services, status } = await initializeServices({ environment, serviceInitializers, fetch: customFetch });\n\n return {\n id: crypto.randomUUID(),\n estimateNativeFee: async (quote, options) => {\n const now = Math.floor(Date.now() / 1_000);\n\n if (quote.expiresAt <= now) {\n const expiredSecondsAgo = now - quote.expiresAt;\n\n throw new InvalidParamsError(ErrorReason.QUOTE_EXPIRED, `Quote expired ${expiredSecondsAgo} seconds ago.`);\n }\n\n const service = services.get(quote.serviceType);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return await service.estimateNativeFee(quote, options);\n },\n getAssetBridgeMap: async ({ sourceAsset, sourceChainId }) => {\n const assets = await _getAssets(services);\n\n const chainAssets = assets[sourceChainId];\n\n if (!chainAssets) {\n return null;\n }\n\n const chainAsset = chainAssets.find((asset) => {\n if (sourceAsset.type === TokenType.NATIVE) {\n return asset.type === TokenType.NATIVE;\n } else {\n return asset.type === sourceAsset.type && asset.address === sourceAsset.address;\n }\n });\n\n if (!chainAsset || !chainAsset.destinations) {\n return null;\n }\n\n const destinations = chainAsset.destinations;\n\n // map destinations to the required format, lookup bridged asset from assets map\n const result: {\n [chainId: string]: {\n bridgedAsset: Asset;\n bridgeProviders: readonly ServiceType[];\n };\n } = {};\n\n for (const [destChainId, destInfo] of Object.entries(destinations)) {\n if (!isCaip2ChainId(destChainId)) {\n continue;\n }\n\n const destChainAssets = assets[destChainId];\n\n if (!destChainAssets) {\n continue;\n }\n\n // bridgedAsset is the asset from the assets map that matches the destInfo address\n const bridgedAsset = destChainAssets.find((asset) => {\n if (destInfo.address === TokenType.NATIVE) {\n return asset.type === TokenType.NATIVE;\n }\n\n return asset.type !== TokenType.NATIVE && asset.address === destInfo.address;\n });\n\n if (!bridgedAsset) {\n continue;\n }\n\n // Convert the TransferableAsset to Asset by omitting the 'destinations' field\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { destinations: _omit, swapProviders: _omitSwapProviders, ...convertedBridgedAsset } = bridgedAsset;\n\n result[destChainId] = {\n bridgedAsset: convertedBridgedAsset,\n bridgeProviders: destInfo.bridgeProviders,\n };\n }\n\n return Object.keys(result).length > 0 ? result : null;\n },\n getMinimumTransferAmount: async (props) => {\n const serviceMinimums: { [key in ServiceType]?: bigint } = {};\n\n for (const service of services.values()) {\n if (service.analyzeSupport(props)) {\n const serviceMinAmount = await service.getMinimumTransferAmount(props);\n serviceMinimums[service.type] = serviceMinAmount;\n }\n }\n\n return Object.keys(serviceMinimums).length > 0 ? serviceMinimums : null;\n },\n getSupportedChains: async () => {\n const supportedChainsMap: MutableGetSupportedChainsResult = new Map();\n\n // Fetch supported chains from all configured services in parallel.\n const serviceResults = await Promise.all(\n Array.from(services.values()).map((service) => service.getSupportedChains()),\n );\n\n // Merge results: union destination sets for identical source chain IDs.\n for (const result of serviceResults) {\n for (const [sourceChainId, targetChainIds] of result.entries()) {\n let mergedTargets = supportedChainsMap.get(sourceChainId);\n if (!mergedTargets) {\n mergedTargets = new Set<Caip2ChainId>();\n supportedChainsMap.set(sourceChainId, mergedTargets);\n }\n\n for (const targetChainId of targetChainIds) {\n mergedTargets.add(targetChainId);\n }\n }\n }\n\n return supportedChainsMap;\n },\n getQuoter: (props, options) => {\n return new Quoter(props, Array.from(services.values()), options);\n },\n status: () => status,\n trackTransfer: (props) => {\n const { transfer } = props;\n const service = services.get(transfer.type);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return service.trackTransfer(props);\n },\n transferAsset: async (props) => {\n const { quote } = props;\n const service = services.get(quote.serviceType);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return await service.transferAsset(props);\n },\n getBridgeableAssets: async ({ sourceAsset, sourceChainId, targetChainId }) => {\n const settledResults = await Promise.allSettled(\n Array.from(services.values()).map((service) =>\n service.getBridgeableAssets({ sourceAsset, sourceChainId, targetChainId }),\n ),\n );\n\n const merged = new Map<string, BridgeableUiAsset>();\n\n for (const settled of settledResults) {\n if (settled.status !== 'fulfilled') continue;\n for (const result of settled.value) {\n const { bridgeProviders, ...asset } = result;\n const key = getAssetId(targetChainId, asset);\n\n const existing = merged.get(key);\n if (existing) {\n const combined = [...new Set([...existing.bridgeProviders, ...bridgeProviders])];\n merged.set(key, { ...existing, bridgeProviders: combined });\n } else {\n merged.set(key, { ...asset, bridgeProviders: [...bridgeProviders] });\n }\n }\n }\n\n return Array.from(merged.values());\n },\n } satisfies TransferManager;\n};\n"],"mappings":"oeAuBA,MAAM,EAAuB,GAAmC,CAC9D,GAAI,CAAC,EAAc,EAAY,CAC7B,MAAM,IAAI,EAA2B,EAAY,0BAA0B,EAczE,EAA+B,GAA6D,CAChG,GAAI,EAAoB,SAAW,EACjC,MAAM,IAAI,EAA2B,oCAAoC,CAG3E,GAAI,EAAoB,KAAM,GAAuB,CAAC,EAAqB,EAAmB,CAAC,CAC7F,MAAM,IAAI,EAA2B,gDAAgD,CAGvF,IAAM,EAA0B,IAAI,IACpC,IAAK,IAAM,KAAe,EAAqB,CAC7C,GAAI,EAAwB,IAAI,EAAY,KAAK,CAC/C,MAAM,IAAI,EACR,EAAY,iCACZ,iBAAiB,EAAY,KAAK,wCACnC,CAEH,EAAwB,IAAI,EAAY,KAAK,GAI3C,EAAqB,MAAO,CAChC,cACA,sBACA,MAAO,KAQH,CACJ,IAAM,EAA4D,IAAI,IAChE,EAAuD,EAAE,CAEzD,GAA2B,EAA0B,IAA+C,CACxG,GAAI,aAAiB,EACnB,OAAO,EAGT,IAAM,EAAU,a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B,GAAG,EAAgB,CAAC,CAAC,CAChF,EAAO,IAAI,EAAK,CAAE,GAAG,EAAU,gBAAiB,EAAU,CAAC,MAE3D,EAAO,IAAI,EAAK,CAAE,GAAG,EAAO,gBAAiB,CAAC,GAAG,EAAgB,CAAE,CAAC,CAK1E,OAAO,MAAM,KAAK,EAAO,QAAQ,CAAC,EAErC"}
1
+ {"version":3,"file":"transfer-manager.js","names":[],"sources":["../src/transfer-manager.ts"],"sourcesContent":["import { Environment, ServiceType } from './constants';\nimport { ErrorReason, InvalidParamsError, ServiceInitializationError, ServiceUnavailableError } from './errors';\nimport type { BridgeableUiAsset } from './types/asset';\nimport { isEnvironment, isServiceInitializer } from './type-guards';\nimport type { MutableGetSupportedChainsResult, ServiceInitializer, TransferService } from './types/service';\nimport type {\n CreateTransferManagerOptions,\n TransferManager,\n TransferManagerStatus,\n TransferManagerStatusServicesRecord,\n} from './types/transfer-manager';\nimport { Quoter } from './quoter/quoter';\nimport { getAssetId } from './utils/asset-id';\nimport type { Caip2ChainId } from './types/caip';\nimport type { Fetch } from './types/utility-types';\n\n/**\n * Validates the provided \"environment\" option.\n *\n * @throws {ServiceInitializationError} If the environment is invalid.\n */\nconst validateEnvironment = (environment: Environment): void => {\n if (!isEnvironment(environment)) {\n throw new ServiceInitializationError(ErrorReason.ENVIRONMENT_NOT_SUPPORTED);\n }\n};\n\n/**\n * Validates the provided \"serviceInitializers\" option.\n *\n * Checks for the following:\n * - At least one service initializer is provided.\n * - All service initializers are valid.\n * - No duplicate service types are initialized.\n *\n * @throws {ServiceInitializationError} If the service initializers are invalid.\n */\nconst validateServiceInitializers = (serviceInitializers: readonly ServiceInitializer[]): void => {\n if (serviceInitializers.length === 0) {\n throw new ServiceInitializationError('No service initializers provided.');\n }\n\n if (serviceInitializers.some((serviceInitializer) => !isServiceInitializer(serviceInitializer))) {\n throw new ServiceInitializationError('One or more service initializers are invalid.');\n }\n\n const serviceInitializerTypes = new Set<ServiceType>();\n for (const initializer of serviceInitializers) {\n if (serviceInitializerTypes.has(initializer.type)) {\n throw new ServiceInitializationError(\n ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,\n `Service type \"${initializer.type}\" has been initialized more than once.`,\n );\n }\n serviceInitializerTypes.add(initializer.type);\n }\n};\n\nconst initializeServices = async ({\n environment,\n serviceInitializers,\n fetch: customFetch,\n}: {\n environment: Environment;\n serviceInitializers: readonly ServiceInitializer[];\n fetch?: Fetch;\n}): Promise<{\n services: Map<ServiceType, TransferService>;\n status: TransferManagerStatus;\n}> => {\n const initializedServicesMap: Map<ServiceType, TransferService> = new Map();\n const serviceStatuses: TransferManagerStatusServicesRecord = {};\n\n const wrapInitializationError = (serviceType: ServiceType, error: unknown): ServiceInitializationError => {\n if (error instanceof ServiceInitializationError) {\n return error;\n }\n\n const details = error instanceof Error ? error.message : String(error);\n\n return new ServiceInitializationError(\n ErrorReason.UNKNOWN,\n `Failed to initialize service type \"${serviceType}\". ${details}`,\n error,\n );\n };\n\n const initializeService = async (\n serviceType: ServiceType,\n initializer: () => Promise<TransferService>,\n ): Promise<void> => {\n try {\n const service = await initializer();\n initializedServicesMap.set(serviceType, service);\n serviceStatuses[serviceType] = { status: 'initialized' };\n } catch (error) {\n const wrappedError = wrapInitializationError(serviceType, error);\n\n serviceStatuses[serviceType] = {\n status: 'error',\n error: wrappedError,\n };\n }\n };\n\n for (const initializer of serviceInitializers) {\n // Error on duplicate initialization attempts.\n if (initializedServicesMap.has(initializer.type)) {\n throw new ServiceInitializationError(\n ErrorReason.DUPLICATE_SERVICE_INITIALIZATION,\n `Service type \"${initializer.type}\" has been initialized more than once.`,\n );\n }\n\n switch (initializer.type) {\n case ServiceType.AVALANCHE_EVM: {\n await initializeService(ServiceType.AVALANCHE_EVM, async () => {\n const { createAvalancheEvmService } = await import('./transfer-service/avalanche-evm/avalanche-evm-service');\n\n return await createAvalancheEvmService({\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.LOMBARD_BTCB_TO_BTC: {\n await initializeService(ServiceType.LOMBARD_BTCB_TO_BTC, async () => {\n const { createBtcbToBtcService } = await import('./transfer-service/lombard/btcb-to-btc-service');\n\n return await createBtcbToBtcService({\n bitcoinFunctions: initializer.btcFunctions,\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.LOMBARD_BTC_TO_BTCB: {\n await initializeService(ServiceType.LOMBARD_BTC_TO_BTCB, async () => {\n const { createBtcToBtcbService } = await import('./transfer-service/lombard/btc-to-btcb-service');\n\n return await createBtcToBtcbService({\n bitcoinFunctions: initializer.btcFunctions,\n btcSigner: initializer.btcSigner,\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n case ServiceType.MARKR: {\n if (environment !== Environment.PROD) {\n serviceStatuses[ServiceType.MARKR] = {\n status: 'unsupported-environment',\n message: `Service type \"${ServiceType.MARKR}\" is only supported in production environment.`,\n };\n break;\n }\n\n await initializeService(ServiceType.MARKR, async () => {\n const { createMarkrService } = await import('./transfer-service/markr/markr-service');\n\n return await createMarkrService({\n apiBaseUrl: initializer.markrApiUrl,\n apiToken: initializer.markrApiToken,\n appId: initializer.markrAppId,\n disableCrossChainSwaps: initializer.disableCrossChainSwaps,\n fetch: customFetch,\n environment,\n evmSigner: initializer.evmSigner,\n getTargetChainAssets: initializer.getTargetChainAssets,\n solanaSigner: initializer.solanaSigner,\n });\n });\n\n break;\n }\n\n case ServiceType.WRAP_UNWRAP: {\n await initializeService(ServiceType.WRAP_UNWRAP, async () => {\n const { createWrapUnwrapService } = await import('./transfer-service/wrap-unwrap/wrap-unwrap-service');\n\n return await createWrapUnwrapService({\n environment,\n evmSigner: initializer.evmSigner,\n fetch: customFetch,\n });\n });\n\n break;\n }\n\n default: {\n break;\n }\n }\n }\n\n return {\n services: initializedServicesMap,\n status: {\n environment,\n services: serviceStatuses,\n },\n };\n};\n\n/**\n * Creates a TransferManager instance.\n *\n * @returns {Promise<TransferManager>} The TransferManager instance.\n * @throws {ServiceInitializationError} If the provided options are invalid.\n */\nexport const createTransferManager = async ({\n environment,\n fetch: customFetch,\n serviceInitializers,\n}: CreateTransferManagerOptions): Promise<TransferManager> => {\n // Validate environment.\n validateEnvironment(environment);\n validateServiceInitializers(serviceInitializers);\n\n const { services, status } = await initializeServices({ environment, serviceInitializers, fetch: customFetch });\n\n return {\n id: crypto.randomUUID(),\n estimateNativeFee: async (quote, options) => {\n const now = Math.floor(Date.now() / 1_000);\n\n if (quote.expiresAt <= now) {\n const expiredSecondsAgo = now - quote.expiresAt;\n\n throw new InvalidParamsError(ErrorReason.QUOTE_EXPIRED, `Quote expired ${expiredSecondsAgo} seconds ago.`);\n }\n\n const service = services.get(quote.serviceType);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return await service.estimateNativeFee(quote, options);\n },\n getBridgeableAssets: async ({ sourceAsset, sourceChainId, targetChainId }) => {\n const settledResults = await Promise.allSettled(\n Array.from(services.values()).map((service) =>\n service.getBridgeableAssets({ sourceAsset, sourceChainId, targetChainId }),\n ),\n );\n\n const merged = new Map<string, BridgeableUiAsset>();\n\n for (const settled of settledResults) {\n if (settled.status !== 'fulfilled') continue;\n for (const result of settled.value) {\n const { bridgeProviders, ...asset } = result;\n const key = getAssetId(targetChainId, asset);\n\n const existing = merged.get(key);\n if (existing) {\n const combined = [...new Set([...existing.bridgeProviders, ...bridgeProviders])];\n merged.set(key, { ...existing, bridgeProviders: combined });\n } else {\n merged.set(key, { ...asset, bridgeProviders: [...bridgeProviders] });\n }\n }\n }\n\n return Array.from(merged.values());\n },\n getMinimumTransferAmount: async (props) => {\n const serviceMinimums: { [key in ServiceType]?: bigint } = {};\n\n for (const service of services.values()) {\n if (service.analyzeSupport(props)) {\n const serviceMinAmount = await service.getMinimumTransferAmount(props);\n serviceMinimums[service.type] = serviceMinAmount;\n }\n }\n\n return Object.keys(serviceMinimums).length > 0 ? serviceMinimums : null;\n },\n getSupportedChains: async () => {\n const supportedChainsMap: MutableGetSupportedChainsResult = new Map();\n\n // Fetch supported chains from all configured services in parallel.\n const serviceResults = await Promise.all(\n Array.from(services.values()).map((service) => service.getSupportedChains()),\n );\n\n // Merge results: union destination sets for identical source chain IDs.\n for (const result of serviceResults) {\n for (const [sourceChainId, targetChainIds] of result.entries()) {\n let mergedTargets = supportedChainsMap.get(sourceChainId);\n if (!mergedTargets) {\n mergedTargets = new Set<Caip2ChainId>();\n supportedChainsMap.set(sourceChainId, mergedTargets);\n }\n\n for (const targetChainId of targetChainIds) {\n mergedTargets.add(targetChainId);\n }\n }\n }\n\n return supportedChainsMap;\n },\n getQuoter: (props, options) => {\n return new Quoter(props, Array.from(services.values()), options);\n },\n status: () => status,\n trackTransfer: (props) => {\n const { transfer } = props;\n const service = services.get(transfer.type);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return service.trackTransfer(props);\n },\n transferAsset: async (props) => {\n const { quote } = props;\n const service = services.get(quote.serviceType);\n\n if (!service) {\n throw new ServiceUnavailableError(ErrorReason.SERVICE_TYPE_NOT_CONFIGURED);\n }\n\n return await service.transferAsset(props);\n },\n } satisfies TransferManager;\n};\n"],"mappings":"qWAqBA,MAAM,EAAuB,GAAmC,CAC9D,GAAI,CAAC,EAAc,EAAY,CAC7B,MAAM,IAAI,EAA2B,EAAY,0BAA0B,EAczE,EAA+B,GAA6D,CAChG,GAAI,EAAoB,SAAW,EACjC,MAAM,IAAI,EAA2B,oCAAoC,CAG3E,GAAI,EAAoB,KAAM,GAAuB,CAAC,EAAqB,EAAmB,CAAC,CAC7F,MAAM,IAAI,EAA2B,gDAAgD,CAGvF,IAAM,EAA0B,IAAI,IACpC,IAAK,IAAM,KAAe,EAAqB,CAC7C,GAAI,EAAwB,IAAI,EAAY,KAAK,CAC/C,MAAM,IAAI,EACR,EAAY,iCACZ,iBAAi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AAK,GAAM,CAAC,EAAe,KAAmB,EAAO,SAAS,CAAE,CAC9D,IAAI,EAAgB,EAAmB,IAAI,EAAc,CACpD,IACH,EAAgB,IAAI,IACpB,EAAmB,IAAI,EAAe,EAAc,EAGtD,IAAK,IAAM,KAAiB,EAC1B,EAAc,IAAI,EAAc,CAKtC,OAAO,GAET,WAAY,EAAO,IACV,IAAI,EAAO,EAAO,MAAM,KAAK,EAAS,QAAQ,CAAC,CAAE,EAAQ,CAElE,WAAc,EACd,cAAgB,GAAU,CACxB,GAAM,CAAE,YAAa,EACf,EAAU,EAAS,IAAI,EAAS,KAAK,CAE3C,GAAI,CAAC,EACH,MAAM,IAAI,EAAwB,EAAY,4BAA4B,CAG5E,OAAO,EAAQ,cAAc,EAAM,EAErC,cAAe,KAAO,IAAU,CAC9B,GAAM,CAAE,SAAU,EACZ,EAAU,EAAS,IAAI,EAAM,YAAY,CAE/C,GAAI,CAAC,EACH,MAAM,IAAI,EAAwB,EAAY,4BAA4B,CAG5E,OAAO,MAAM,EAAQ,cAAc,EAAM,EAE5C"}
@@ -1,2 +1,2 @@
1
- const e=require(`../../../constants.cjs`),t=require(`../../../errors.cjs`),n=require(`../../../utils/evm-address.cjs`),r=require(`./fee.cjs`),i=require(`../../_warden-config.cjs`);async function a(e){return o(await i.getWardenConfig(e),e)}function o(i,a){let o=i.critical.assets,{ethereum:s,avalanche:c}=i.critical.networks;if(s===void 0||c===void 0)throw new t.ServiceInitializationError(t.ErrorReason.WARDEN_CONFIG_MISSING_NETWORK,`Critical networks info is missing from wardenConfig`);let l=i.critical.walletAddresses.avalanche,u=i.critical.walletAddresses.ethereum;if(!l||!u)throw new t.ServiceInitializationError(t.ErrorReason.CONFIG_NOT_AVAILABLE,`Wallet address is missing from the critical config.`);let d=Object.entries(o).reduce((t,[a,o])=>{let l=n.formatEvmAddress(o.nativeContractAddress),u={type:e.TokenType.ERC20,address:l,name:o.tokenName,symbol:a,decimals:o.denomination},d=i.nonCritical.wrapFeeApproximation[a];return t[l]={chainId:`eip155:${s}`,token:u,target:{chainId:`eip155:${c}`,tokenAddress:n.formatEvmAddress(o.wrappedContractAddress)},wrapFeeApproximation:r.isDynamicFee(d)?d:d?BigInt(d):void 0},t},{}),f=Object.values(d).find(e=>e.token.symbol===`WETH`);if(!f)throw new t.ServiceInitializationError(t.ErrorReason.CONFIG_NOT_AVAILABLE,`WETH info is missing from config`);let p=Object.entries(o).reduce((t,[a,o])=>{let l=n.formatEvmAddress(o.wrappedContractAddress),u={type:e.TokenType.ERC20,address:l,name:o.tokenName,symbol:`${a}.e`,decimals:o.denomination},d=i.nonCritical.unwrapFeeApproximation[a];return t[l]={chainId:`eip155:${c}`,token:u,target:{chainId:`eip155:${s}`,tokenAddress:n.formatEvmAddress(o.nativeContractAddress)},unwrapFeeApproximation:r.isDynamicFee(d)?d:d?BigInt(d):void 0},t},{}),m=p[f.target.tokenAddress];if(!m)throw new t.ServiceInitializationError(t.ErrorReason.CONFIG_NOT_AVAILABLE,`WETH.e info is missing from config`);let h=i.nonCritical.minimumConfirmations.avalanche,g=i.nonCritical.minimumConfirmations.ethereum;if(!h||!g)throw new t.ServiceInitializationError(t.ErrorReason.CONFIG_NOT_AVAILABLE,`Minimum confirmation info is missing`);return{addressBlocklist:i.critical.addressBlocklist,ethereumTokens:d,avalancheTokens:p,minimumConfirmations:{avalanche:h,ethereum:g},environment:a,walletAddresses:{avalanche:l,ethereum:u},nativeTokenConfig:{ethereumToken:f,avalancheToken:m}}}exports.getConfig=a;
1
+ const e=require(`../../../constants.cjs`),t=require(`../../../errors.cjs`),n=require(`./fee.cjs`),r=require(`../../../utils/evm-address.cjs`),i=require(`../../_warden-config.cjs`);async function a(e){return o(await i.getWardenConfig(e),e)}function o(i,a){let o=i.critical.assets,{ethereum:s,avalanche:c}=i.critical.networks;if(s===void 0||c===void 0)throw new t.ServiceInitializationError(t.ErrorReason.WARDEN_CONFIG_MISSING_NETWORK,`Critical networks info is missing from wardenConfig`);let l=i.critical.walletAddresses.avalanche,u=i.critical.walletAddresses.ethereum;if(!l||!u)throw new t.ServiceInitializationError(t.ErrorReason.CONFIG_NOT_AVAILABLE,`Wallet address is missing from the critical config.`);let d=Object.entries(o).reduce((t,[a,o])=>{let l=r.formatEvmAddress(o.nativeContractAddress),u={type:e.TokenType.ERC20,address:l,name:o.tokenName,symbol:a,decimals:o.denomination},d=i.nonCritical.wrapFeeApproximation[a];return t[l]={chainId:`eip155:${s}`,token:u,target:{chainId:`eip155:${c}`,tokenAddress:r.formatEvmAddress(o.wrappedContractAddress)},wrapFeeApproximation:n.isDynamicFee(d)?d:d?BigInt(d):void 0},t},{}),f=Object.values(d).find(e=>e.token.symbol===`WETH`);if(!f)throw new t.ServiceInitializationError(t.ErrorReason.CONFIG_NOT_AVAILABLE,`WETH info is missing from config`);let p=Object.entries(o).reduce((t,[a,o])=>{let l=r.formatEvmAddress(o.wrappedContractAddress),u={type:e.TokenType.ERC20,address:l,name:o.tokenName,symbol:`${a}.e`,decimals:o.denomination},d=i.nonCritical.unwrapFeeApproximation[a];return t[l]={chainId:`eip155:${c}`,token:u,target:{chainId:`eip155:${s}`,tokenAddress:r.formatEvmAddress(o.nativeContractAddress)},unwrapFeeApproximation:n.isDynamicFee(d)?d:d?BigInt(d):void 0},t},{}),m=p[f.target.tokenAddress];if(!m)throw new t.ServiceInitializationError(t.ErrorReason.CONFIG_NOT_AVAILABLE,`WETH.e info is missing from config`);let h=i.nonCritical.minimumConfirmations.avalanche,g=i.nonCritical.minimumConfirmations.ethereum;if(!h||!g)throw new t.ServiceInitializationError(t.ErrorReason.CONFIG_NOT_AVAILABLE,`Minimum confirmation info is missing`);return{addressBlocklist:i.critical.addressBlocklist,ethereumTokens:d,avalancheTokens:p,minimumConfirmations:{avalanche:h,ethereum:g},environment:a,walletAddresses:{avalanche:l,ethereum:u},nativeTokenConfig:{ethereumToken:f,avalancheToken:m}}}exports.getConfig=a;
2
2
  //# sourceMappingURL=get-config.cjs.map
@@ -1,2 +1,2 @@
1
- import{TokenType as e}from"../../../constants.js";import{ErrorReason as t,ServiceInitializationError as n}from"../../../errors.js";import{formatEvmAddress as r}from"../../../utils/evm-address.js";import{isDynamicFee as i}from"./fee.js";import{getWardenConfig as a}from"../../_warden-config.js";async function o(e){return s(await a(e),e)}function s(a,o){let s=a.critical.assets,{ethereum:c,avalanche:l}=a.critical.networks;if(c===void 0||l===void 0)throw new n(t.WARDEN_CONFIG_MISSING_NETWORK,`Critical networks info is missing from wardenConfig`);let u=a.critical.walletAddresses.avalanche,d=a.critical.walletAddresses.ethereum;if(!u||!d)throw new n(t.CONFIG_NOT_AVAILABLE,`Wallet address is missing from the critical config.`);let f=Object.entries(s).reduce((t,[n,o])=>{let s=r(o.nativeContractAddress),u={type:e.ERC20,address:s,name:o.tokenName,symbol:n,decimals:o.denomination},d=a.nonCritical.wrapFeeApproximation[n];return t[s]={chainId:`eip155:${c}`,token:u,target:{chainId:`eip155:${l}`,tokenAddress:r(o.wrappedContractAddress)},wrapFeeApproximation:i(d)?d:d?BigInt(d):void 0},t},{}),p=Object.values(f).find(e=>e.token.symbol===`WETH`);if(!p)throw new n(t.CONFIG_NOT_AVAILABLE,`WETH info is missing from config`);let m=Object.entries(s).reduce((t,[n,o])=>{let s=r(o.wrappedContractAddress),u={type:e.ERC20,address:s,name:o.tokenName,symbol:`${n}.e`,decimals:o.denomination},d=a.nonCritical.unwrapFeeApproximation[n];return t[s]={chainId:`eip155:${l}`,token:u,target:{chainId:`eip155:${c}`,tokenAddress:r(o.nativeContractAddress)},unwrapFeeApproximation:i(d)?d:d?BigInt(d):void 0},t},{}),h=m[p.target.tokenAddress];if(!h)throw new n(t.CONFIG_NOT_AVAILABLE,`WETH.e info is missing from config`);let g=a.nonCritical.minimumConfirmations.avalanche,_=a.nonCritical.minimumConfirmations.ethereum;if(!g||!_)throw new n(t.CONFIG_NOT_AVAILABLE,`Minimum confirmation info is missing`);return{addressBlocklist:a.critical.addressBlocklist,ethereumTokens:f,avalancheTokens:m,minimumConfirmations:{avalanche:g,ethereum:_},environment:o,walletAddresses:{avalanche:u,ethereum:d},nativeTokenConfig:{ethereumToken:p,avalancheToken:h}}}export{o as getConfig};
1
+ import{TokenType as e}from"../../../constants.js";import{ErrorReason as t,ServiceInitializationError as n}from"../../../errors.js";import{isDynamicFee as r}from"./fee.js";import{formatEvmAddress as i}from"../../../utils/evm-address.js";import{getWardenConfig as a}from"../../_warden-config.js";async function o(e){return s(await a(e),e)}function s(a,o){let s=a.critical.assets,{ethereum:c,avalanche:l}=a.critical.networks;if(c===void 0||l===void 0)throw new n(t.WARDEN_CONFIG_MISSING_NETWORK,`Critical networks info is missing from wardenConfig`);let u=a.critical.walletAddresses.avalanche,d=a.critical.walletAddresses.ethereum;if(!u||!d)throw new n(t.CONFIG_NOT_AVAILABLE,`Wallet address is missing from the critical config.`);let f=Object.entries(s).reduce((t,[n,o])=>{let s=i(o.nativeContractAddress),u={type:e.ERC20,address:s,name:o.tokenName,symbol:n,decimals:o.denomination},d=a.nonCritical.wrapFeeApproximation[n];return t[s]={chainId:`eip155:${c}`,token:u,target:{chainId:`eip155:${l}`,tokenAddress:i(o.wrappedContractAddress)},wrapFeeApproximation:r(d)?d:d?BigInt(d):void 0},t},{}),p=Object.values(f).find(e=>e.token.symbol===`WETH`);if(!p)throw new n(t.CONFIG_NOT_AVAILABLE,`WETH info is missing from config`);let m=Object.entries(s).reduce((t,[n,o])=>{let s=i(o.wrappedContractAddress),u={type:e.ERC20,address:s,name:o.tokenName,symbol:`${n}.e`,decimals:o.denomination},d=a.nonCritical.unwrapFeeApproximation[n];return t[s]={chainId:`eip155:${l}`,token:u,target:{chainId:`eip155:${c}`,tokenAddress:i(o.nativeContractAddress)},unwrapFeeApproximation:r(d)?d:d?BigInt(d):void 0},t},{}),h=m[p.target.tokenAddress];if(!h)throw new n(t.CONFIG_NOT_AVAILABLE,`WETH.e info is missing from config`);let g=a.nonCritical.minimumConfirmations.avalanche,_=a.nonCritical.minimumConfirmations.ethereum;if(!g||!_)throw new n(t.CONFIG_NOT_AVAILABLE,`Minimum confirmation info is missing`);return{addressBlocklist:a.critical.addressBlocklist,ethereumTokens:f,avalancheTokens:m,minimumConfirmations:{avalanche:g,ethereum:_},environment:o,walletAddresses:{avalanche:u,ethereum:d},nativeTokenConfig:{ethereumToken:p,avalancheToken:h}}}export{o as getConfig};
2
2
  //# sourceMappingURL=get-config.js.map
@@ -1,2 +1,2 @@
1
- const e=require(`../../../../constants.cjs`),t=require(`../../../../errors.cjs`),n=require(`../../../../utils/evm-address.cjs`),r=require(`../../../../utils/bitcoin-address.cjs`),i=require(`../../../../utils/quote-fees.cjs`),a=require(`./analyze-support.cjs`),o=require(`./get-minimum-transfer-amount.cjs`);function s({config:s}){let c=a.analyzeSupportFactory({config:s});return(a,l)=>{let u=new AbortController,d=()=>{u.abort()};return!c({sourceAsset:a.sourceAsset,sourceChainId:a.sourceChain.chainId,targetAsset:a.targetAsset,targetChainId:a.targetChain.chainId})||!r.isBech32AddressInNetwork(a.fromAddress,s.sourceChain===e.BitcoinChainIds.MAINNET)||!n.isEvmAddress(a.toAddress)?(u.signal.aborted||(l(`error`,new t.InvalidParamsError(t.ErrorReason.INVALID_PARAMS,`Invalid addresses, assets, or chains provided.`)),l(`done`)),{cancel:d}):((async()=>{let n=o.getMinimumTransferAmount();if(a.amount<n){u.signal.aborted||(l(`error`,new t.InvalidParamsError(t.ErrorReason.INVALID_PARAMS,`Transfer amount is below the minimum transfer amount of ${n.toString()}.`)),l(`done`));return}let r={aggregator:{name:`Lombard`,id:`lombard-btc-to-btcb`},amountIn:a.amount,amountOut:a.amount-s.mintingFee,assetIn:a.sourceAsset,assetOut:a.targetAsset,expiresAt:Math.floor(Date.now()/1e3)+60,fees:[{type:`bridge`,name:`Bridge Fee`,amount:s.mintingFee,chainId:a.sourceChain.chainId,token:i.assetToQuoteFeeToken(a.sourceAsset)}],fromAddress:a.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:e.ServiceType.LOMBARD_BTC_TO_BTCB,slippageBps:a.slippageBps??0,sourceChain:a.sourceChain,targetChain:a.targetChain,toAddress:a.toAddress};u.signal.aborted||(l(`quote`,r),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=s;
1
+ const e=require(`../../../../constants.cjs`),t=require(`../../../../errors.cjs`),n=require(`../../../../utils/bitcoin-address.cjs`),r=require(`../../../../utils/quote-fees.cjs`),i=require(`../../../../utils/evm-address.cjs`),a=require(`./analyze-support.cjs`),o=require(`./get-minimum-transfer-amount.cjs`);function s({config:s}){let c=a.analyzeSupportFactory({config:s});return(a,l)=>{let u=new AbortController,d=()=>{u.abort()};return!c({sourceAsset:a.sourceAsset,sourceChainId:a.sourceChain.chainId,targetAsset:a.targetAsset,targetChainId:a.targetChain.chainId})||!n.isBech32AddressInNetwork(a.fromAddress,s.sourceChain===e.BitcoinChainIds.MAINNET)||!i.isEvmAddress(a.toAddress)?(u.signal.aborted||(l(`error`,new t.InvalidParamsError(t.ErrorReason.INVALID_PARAMS,`Invalid addresses, assets, or chains provided.`)),l(`done`)),{cancel:d}):((async()=>{let n=o.getMinimumTransferAmount();if(a.amount<n){u.signal.aborted||(l(`error`,new t.InvalidParamsError(t.ErrorReason.INVALID_PARAMS,`Transfer amount is below the minimum transfer amount of ${n.toString()}.`)),l(`done`));return}let i={aggregator:{name:`Lombard`,id:`lombard-btc-to-btcb`},amountIn:a.amount,amountOut:a.amount-s.mintingFee,assetIn:a.sourceAsset,assetOut:a.targetAsset,expiresAt:Math.floor(Date.now()/1e3)+60,fees:[{type:`bridge`,name:`Bridge Fee`,amount:s.mintingFee,chainId:a.sourceChain.chainId,token:r.assetToQuoteFeeToken(a.sourceAsset)}],fromAddress:a.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:e.ServiceType.LOMBARD_BTC_TO_BTCB,slippageBps:a.slippageBps??0,sourceChain:a.sourceChain,targetChain:a.targetChain,toAddress:a.toAddress};u.signal.aborted||(l(`quote`,i),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=s;
2
2
  //# sourceMappingURL=stream-quotes.cjs.map
@@ -1,2 +1,2 @@
1
- import{BitcoinChainIds as e,ServiceType as t}from"../../../../constants.js";import{ErrorCode as n,ErrorReason as r,InvalidParamsError as i,SdkError as a}from"../../../../errors.js";import{isEvmAddress as o}from"../../../../utils/evm-address.js";import{isBech32AddressInNetwork as s}from"../../../../utils/bitcoin-address.js";import{assetToQuoteFeeToken as c}from"../../../../utils/quote-fees.js";import{analyzeSupportFactory as l}from"./analyze-support.js";import{getMinimumTransferAmount as u}from"./get-minimum-transfer-amount.js";function d({config:d}){let f=l({config:d});return(l,p)=>{let m=new AbortController,h=()=>{m.abort()};return!f({sourceAsset:l.sourceAsset,sourceChainId:l.sourceChain.chainId,targetAsset:l.targetAsset,targetChainId:l.targetChain.chainId})||!s(l.fromAddress,d.sourceChain===e.MAINNET)||!o(l.toAddress)?(m.signal.aborted||(p(`error`,new i(r.INVALID_PARAMS,`Invalid addresses, assets, or chains provided.`)),p(`done`)),{cancel:h}):((async()=>{let e=u();if(l.amount<e){m.signal.aborted||(p(`error`,new i(r.INVALID_PARAMS,`Transfer amount is below the minimum transfer amount of ${e.toString()}.`)),p(`done`));return}let n={aggregator:{name:`Lombard`,id:`lombard-btc-to-btcb`},amountIn:l.amount,amountOut:l.amount-d.mintingFee,assetIn:l.sourceAsset,assetOut:l.targetAsset,expiresAt:Math.floor(Date.now()/1e3)+60,fees:[{type:`bridge`,name:`Bridge Fee`,amount:d.mintingFee,chainId:l.sourceChain.chainId,token:c(l.sourceAsset)}],fromAddress:l.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:t.LOMBARD_BTC_TO_BTCB,slippageBps:l.slippageBps??0,sourceChain:l.sourceChain,targetChain:l.targetChain,toAddress:l.toAddress};m.signal.aborted||(p(`quote`,n),p(`done`))})().catch(e=>{m.signal.aborted||(p(`error`,new a(r.UNKNOWN,n.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),p(`done`))}),{cancel:h})}}export{d as streamQuotesFactory};
1
+ import{BitcoinChainIds as e,ServiceType as t}from"../../../../constants.js";import{ErrorCode as n,ErrorReason as r,InvalidParamsError as i,SdkError as a}from"../../../../errors.js";import{isBech32AddressInNetwork as o}from"../../../../utils/bitcoin-address.js";import{assetToQuoteFeeToken as s}from"../../../../utils/quote-fees.js";import{isEvmAddress as c}from"../../../../utils/evm-address.js";import{analyzeSupportFactory as l}from"./analyze-support.js";import{getMinimumTransferAmount as u}from"./get-minimum-transfer-amount.js";function d({config:d}){let f=l({config:d});return(l,p)=>{let m=new AbortController,h=()=>{m.abort()};return!f({sourceAsset:l.sourceAsset,sourceChainId:l.sourceChain.chainId,targetAsset:l.targetAsset,targetChainId:l.targetChain.chainId})||!o(l.fromAddress,d.sourceChain===e.MAINNET)||!c(l.toAddress)?(m.signal.aborted||(p(`error`,new i(r.INVALID_PARAMS,`Invalid addresses, assets, or chains provided.`)),p(`done`)),{cancel:h}):((async()=>{let e=u();if(l.amount<e){m.signal.aborted||(p(`error`,new i(r.INVALID_PARAMS,`Transfer amount is below the minimum transfer amount of ${e.toString()}.`)),p(`done`));return}let n={aggregator:{name:`Lombard`,id:`lombard-btc-to-btcb`},amountIn:l.amount,amountOut:l.amount-d.mintingFee,assetIn:l.sourceAsset,assetOut:l.targetAsset,expiresAt:Math.floor(Date.now()/1e3)+60,fees:[{type:`bridge`,name:`Bridge Fee`,amount:d.mintingFee,chainId:l.sourceChain.chainId,token:s(l.sourceAsset)}],fromAddress:l.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:t.LOMBARD_BTC_TO_BTCB,slippageBps:l.slippageBps??0,sourceChain:l.sourceChain,targetChain:l.targetChain,toAddress:l.toAddress};m.signal.aborted||(p(`quote`,n),p(`done`))})().catch(e=>{m.signal.aborted||(p(`error`,new a(r.UNKNOWN,n.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),p(`done`))}),{cancel:h})}}export{d as streamQuotesFactory};
2
2
  //# sourceMappingURL=stream-quotes.js.map
@@ -1,2 +1,2 @@
1
- const e=require(`../../../../constants.cjs`),t=require(`../../../../errors.cjs`),n=require(`../../../../utils/evm-address.cjs`),r=require(`../../../../utils/bitcoin-address.cjs`),i=require(`../../../../utils/quote-fees.cjs`),a=require(`./analyze-support.cjs`);function o({config:o}){let s=a.analyzeSupportFactory({config:o});return(a,c)=>{let l=new AbortController,u=()=>{l.abort()};return!s({sourceAsset:a.sourceAsset,sourceChainId:a.sourceChain.chainId,targetAsset:a.targetAsset,targetChainId:a.targetChain.chainId})||!n.isEvmAddress(a.fromAddress)||!r.isBech32AddressInNetwork(a.toAddress,o.targetChain===e.BitcoinChainIds.MAINNET)?(l.signal.aborted||(c(`error`,new t.InvalidParamsError(t.ErrorReason.INVALID_PARAMS,`Invalid addresses, assets, or chains provided.`)),c(`done`)),{cancel:u}):((async()=>{let n=o.minRedeemAmount;if(a.amount<n){l.signal.aborted||(c(`error`,new t.InvalidParamsError(t.ErrorReason.INVALID_PARAMS,`Transfer amount is below the minimum transfer amount of ${n.toString()}.`)),c(`done`));return}let r={aggregator:{name:`Lombard`,id:`lombard-btcb-to-btc`},amountIn:a.amount,amountOut:a.amount-o.redeemFee,assetIn:a.sourceAsset,assetOut:a.targetAsset,expiresAt:Math.floor(Date.now()/1e3)+60,fees:[{type:`bridge`,name:`Bridge Fee`,amount:o.redeemFee,chainId:a.sourceChain.chainId,token:i.assetToQuoteFeeToken(a.sourceAsset)}],fromAddress:a.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:e.ServiceType.LOMBARD_BTCB_TO_BTC,slippageBps:a.slippageBps??0,sourceChain:a.sourceChain,targetChain:a.targetChain,toAddress:a.toAddress};l.signal.aborted||(c(`quote`,r),c(`done`))})().catch(e=>{l.signal.aborted||(c(`error`,new t.SdkError(t.ErrorReason.UNKNOWN,t.ErrorCode.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),c(`done`))}),{cancel:u})}}exports.streamQuotesFactory=o;
1
+ const e=require(`../../../../constants.cjs`),t=require(`../../../../errors.cjs`),n=require(`../../../../utils/bitcoin-address.cjs`),r=require(`../../../../utils/quote-fees.cjs`),i=require(`../../../../utils/evm-address.cjs`),a=require(`./analyze-support.cjs`);function o({config:o}){let s=a.analyzeSupportFactory({config:o});return(a,c)=>{let l=new AbortController,u=()=>{l.abort()};return!s({sourceAsset:a.sourceAsset,sourceChainId:a.sourceChain.chainId,targetAsset:a.targetAsset,targetChainId:a.targetChain.chainId})||!i.isEvmAddress(a.fromAddress)||!n.isBech32AddressInNetwork(a.toAddress,o.targetChain===e.BitcoinChainIds.MAINNET)?(l.signal.aborted||(c(`error`,new t.InvalidParamsError(t.ErrorReason.INVALID_PARAMS,`Invalid addresses, assets, or chains provided.`)),c(`done`)),{cancel:u}):((async()=>{let n=o.minRedeemAmount;if(a.amount<n){l.signal.aborted||(c(`error`,new t.InvalidParamsError(t.ErrorReason.INVALID_PARAMS,`Transfer amount is below the minimum transfer amount of ${n.toString()}.`)),c(`done`));return}let i={aggregator:{name:`Lombard`,id:`lombard-btcb-to-btc`},amountIn:a.amount,amountOut:a.amount-o.redeemFee,assetIn:a.sourceAsset,assetOut:a.targetAsset,expiresAt:Math.floor(Date.now()/1e3)+60,fees:[{type:`bridge`,name:`Bridge Fee`,amount:o.redeemFee,chainId:a.sourceChain.chainId,token:r.assetToQuoteFeeToken(a.sourceAsset)}],fromAddress:a.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:e.ServiceType.LOMBARD_BTCB_TO_BTC,slippageBps:a.slippageBps??0,sourceChain:a.sourceChain,targetChain:a.targetChain,toAddress:a.toAddress};l.signal.aborted||(c(`quote`,i),c(`done`))})().catch(e=>{l.signal.aborted||(c(`error`,new t.SdkError(t.ErrorReason.UNKNOWN,t.ErrorCode.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),c(`done`))}),{cancel:u})}}exports.streamQuotesFactory=o;
2
2
  //# sourceMappingURL=stream-quotes.cjs.map
@@ -1,2 +1,2 @@
1
- import{BitcoinChainIds as e,ServiceType as t}from"../../../../constants.js";import{ErrorCode as n,ErrorReason as r,InvalidParamsError as i,SdkError as a}from"../../../../errors.js";import{isEvmAddress as o}from"../../../../utils/evm-address.js";import{isBech32AddressInNetwork as s}from"../../../../utils/bitcoin-address.js";import{assetToQuoteFeeToken as c}from"../../../../utils/quote-fees.js";import{analyzeSupportFactory as l}from"./analyze-support.js";function u({config:u}){let d=l({config:u});return(l,f)=>{let p=new AbortController,m=()=>{p.abort()};return!d({sourceAsset:l.sourceAsset,sourceChainId:l.sourceChain.chainId,targetAsset:l.targetAsset,targetChainId:l.targetChain.chainId})||!o(l.fromAddress)||!s(l.toAddress,u.targetChain===e.MAINNET)?(p.signal.aborted||(f(`error`,new i(r.INVALID_PARAMS,`Invalid addresses, assets, or chains provided.`)),f(`done`)),{cancel:m}):((async()=>{let e=u.minRedeemAmount;if(l.amount<e){p.signal.aborted||(f(`error`,new i(r.INVALID_PARAMS,`Transfer amount is below the minimum transfer amount of ${e.toString()}.`)),f(`done`));return}let n={aggregator:{name:`Lombard`,id:`lombard-btcb-to-btc`},amountIn:l.amount,amountOut:l.amount-u.redeemFee,assetIn:l.sourceAsset,assetOut:l.targetAsset,expiresAt:Math.floor(Date.now()/1e3)+60,fees:[{type:`bridge`,name:`Bridge Fee`,amount:u.redeemFee,chainId:l.sourceChain.chainId,token:c(l.sourceAsset)}],fromAddress:l.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:t.LOMBARD_BTCB_TO_BTC,slippageBps:l.slippageBps??0,sourceChain:l.sourceChain,targetChain:l.targetChain,toAddress:l.toAddress};p.signal.aborted||(f(`quote`,n),f(`done`))})().catch(e=>{p.signal.aborted||(f(`error`,new a(r.UNKNOWN,n.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),f(`done`))}),{cancel:m})}}export{u as streamQuotesFactory};
1
+ import{BitcoinChainIds as e,ServiceType as t}from"../../../../constants.js";import{ErrorCode as n,ErrorReason as r,InvalidParamsError as i,SdkError as a}from"../../../../errors.js";import{isBech32AddressInNetwork as o}from"../../../../utils/bitcoin-address.js";import{assetToQuoteFeeToken as s}from"../../../../utils/quote-fees.js";import{isEvmAddress as c}from"../../../../utils/evm-address.js";import{analyzeSupportFactory as l}from"./analyze-support.js";function u({config:u}){let d=l({config:u});return(l,f)=>{let p=new AbortController,m=()=>{p.abort()};return!d({sourceAsset:l.sourceAsset,sourceChainId:l.sourceChain.chainId,targetAsset:l.targetAsset,targetChainId:l.targetChain.chainId})||!c(l.fromAddress)||!o(l.toAddress,u.targetChain===e.MAINNET)?(p.signal.aborted||(f(`error`,new i(r.INVALID_PARAMS,`Invalid addresses, assets, or chains provided.`)),f(`done`)),{cancel:m}):((async()=>{let e=u.minRedeemAmount;if(l.amount<e){p.signal.aborted||(f(`error`,new i(r.INVALID_PARAMS,`Transfer amount is below the minimum transfer amount of ${e.toString()}.`)),f(`done`));return}let n={aggregator:{name:`Lombard`,id:`lombard-btcb-to-btc`},amountIn:l.amount,amountOut:l.amount-u.redeemFee,assetIn:l.sourceAsset,assetOut:l.targetAsset,expiresAt:Math.floor(Date.now()/1e3)+60,fees:[{type:`bridge`,name:`Bridge Fee`,amount:u.redeemFee,chainId:l.sourceChain.chainId,token:s(l.sourceAsset)}],fromAddress:l.fromAddress,id:crypto.randomUUID(),partnerFeeBps:null,serviceType:t.LOMBARD_BTCB_TO_BTC,slippageBps:l.slippageBps??0,sourceChain:l.sourceChain,targetChain:l.targetChain,toAddress:l.toAddress};p.signal.aborted||(f(`quote`,n),f(`done`))})().catch(e=>{p.signal.aborted||(f(`error`,new a(r.UNKNOWN,n.UNKNOWN,{cause:e,details:`Failed to stream quotes`})),f(`done`))}),{cancel:m})}}export{u as streamQuotesFactory};
2
2
  //# sourceMappingURL=stream-quotes.js.map
@@ -1,2 +1,2 @@
1
- const e=require(`../../../errors.cjs`),t=require(`../../../utils/caip.cjs`),n=require(`../../../utils/evm-address.cjs`),r=require(`../../../_utils/chain.cjs`),i=require(`../_api.cjs`),a=require(`../../../utils/sol-address.cjs`),o=require(`../_utils.cjs`);function s({apiOptions:e,appId:n,partnerFeeBps:a}){return(s,l)=>{let u=new AbortController,{userEvmAddress:d,userSolanaAddress:f,validationError:p}=c(s);return p?(l(`error`,p),l(`done`),{cancel:()=>{}}):(i.markrStreamQuote(e,{amount:s.amount.toString(),appId:n,chainId:r.isEvmNamespace(s.sourceChain.chainId)?t.caip2ToEip155ChainId(s.sourceChain.chainId):s.sourceChain.chainId,destinationChainId:s.sourceChain.chainId===s.targetChain.chainId?void 0:r.isEvmNamespace(s.targetChain.chainId)?t.caip2ToEip155ChainId(s.targetChain.chainId):s.targetChain.chainId,slippage:s.slippageBps,tokenIn:o.assetToAddressString(s.sourceAsset,s.sourceChain.chainId),tokenInDecimals:s.sourceAsset.decimals,tokenOut:o.assetToAddressString(s.targetAsset,s.targetChain.chainId),tokenOutDecimals:s.targetAsset.decimals,userEvmAddress:d,userSolanaAddress:f},{onDone:()=>{u.signal.aborted||l(`done`)},onError:e=>{u.signal.aborted||(l(`error`,e),l(`done`))},onQuote:e=>{u.signal.aborted||l(`quote`,o.quoteFromMarkrQuoteResponseData(e,s,a))},signal:u.signal}),{cancel:()=>{u.abort()}})}}function c(t){let i=t.sourceChain.chainId!==t.targetChain.chainId,o=r.isEvmNamespace(t.sourceChain.chainId),s=r.isEvmNamespace(t.targetChain.chainId),c=r.isSolanaNamespace(t.sourceChain.chainId),l=r.isSolanaNamespace(t.targetChain.chainId);return o&&!n.isEvmAddress(t.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid fromAddress for EVM source chain.`)}:s&&!n.isEvmAddress(t.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid toAddress for EVM target chain.`)}:c&&!a.isSolAddress(t.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid fromAddress for Solana source chain.`)}:l&&!a.isSolAddress(t.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`Invalid toAddress for Solana target chain.`)}:i&&(o&&s||c&&l)&&t.fromAddress!==t.toAddress?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`fromAddress and toAddress must match for same-namespace cross-chain swaps.`)}:i?{userEvmAddress:o&&n.isEvmAddress(t.fromAddress)?t.fromAddress:s&&n.isEvmAddress(t.toAddress)?t.toAddress:void 0,userSolanaAddress:c&&a.isSolAddress(t.fromAddress)?t.fromAddress:l&&a.isSolAddress(t.toAddress)?t.toAddress:void 0}:t.fromAddress===t.toAddress?{userEvmAddress:void 0,userSolanaAddress:void 0}:{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new e.InvalidParamsError(e.ErrorReason.INVALID_PARAMS,`fromAddress and toAddress must match for same-chain swaps.`)}}exports.streamQuotesFactory=s;
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;
2
2
  //# sourceMappingURL=stream-quotes.cjs.map
@@ -1,2 +1,2 @@
1
- import{ErrorReason as e,InvalidParamsError as t}from"../../../errors.js";import{caip2ToEip155ChainId as n}from"../../../utils/caip.js";import{isEvmAddress as r}from"../../../utils/evm-address.js";import{isEvmNamespace as i,isSolanaNamespace as a}from"../../../_utils/chain.js";import{markrStreamQuote as o}from"../_api.js";import{isSolAddress as s}from"../../../utils/sol-address.js";import{assetToAddressString as c,quoteFromMarkrQuoteResponseData as l}from"../_utils.js";function u({apiOptions:e,appId:t,partnerFeeBps:r}){return(a,s)=>{let u=new AbortController,{userEvmAddress:f,userSolanaAddress:p,validationError:m}=d(a);return m?(s(`error`,m),s(`done`),{cancel:()=>{}}):(o(e,{amount:a.amount.toString(),appId:t,chainId:i(a.sourceChain.chainId)?n(a.sourceChain.chainId):a.sourceChain.chainId,destinationChainId:a.sourceChain.chainId===a.targetChain.chainId?void 0:i(a.targetChain.chainId)?n(a.targetChain.chainId):a.targetChain.chainId,slippage:a.slippageBps,tokenIn:c(a.sourceAsset,a.sourceChain.chainId),tokenInDecimals:a.sourceAsset.decimals,tokenOut:c(a.targetAsset,a.targetChain.chainId),tokenOutDecimals:a.targetAsset.decimals,userEvmAddress:f,userSolanaAddress:p},{onDone:()=>{u.signal.aborted||s(`done`)},onError:e=>{u.signal.aborted||(s(`error`,e),s(`done`))},onQuote:e=>{u.signal.aborted||s(`quote`,l(e,a,r))},signal:u.signal}),{cancel:()=>{u.abort()}})}}function d(n){let o=n.sourceChain.chainId!==n.targetChain.chainId,c=i(n.sourceChain.chainId),l=i(n.targetChain.chainId),u=a(n.sourceChain.chainId),d=a(n.targetChain.chainId);return c&&!r(n.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid fromAddress for EVM source chain.`)}:l&&!r(n.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid toAddress for EVM target chain.`)}:u&&!s(n.fromAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid fromAddress for Solana source chain.`)}:d&&!s(n.toAddress)?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`Invalid toAddress for Solana target chain.`)}:o&&(c&&l||u&&d)&&n.fromAddress!==n.toAddress?{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`fromAddress and toAddress must match for same-namespace cross-chain swaps.`)}:o?{userEvmAddress:c&&r(n.fromAddress)?n.fromAddress:l&&r(n.toAddress)?n.toAddress:void 0,userSolanaAddress:u&&s(n.fromAddress)?n.fromAddress:d&&s(n.toAddress)?n.toAddress:void 0}:n.fromAddress===n.toAddress?{userEvmAddress:void 0,userSolanaAddress:void 0}:{userEvmAddress:void 0,userSolanaAddress:void 0,validationError:new t(e.INVALID_PARAMS,`fromAddress and toAddress must match for same-chain swaps.`)}}export{u as streamQuotesFactory};
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};
2
2
  //# sourceMappingURL=stream-quotes.js.map
@@ -1,2 +1,2 @@
1
- require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../utils/caip.cjs`),t=require(`../service-schemas.cjs`);let n=require(`zod`);const r=n.z.string().refine(t=>e.isCaip2ChainId(t),{message:`Invalid CAIP-2 chain ID`}).transform(e=>e),i=n.z.object({chainId:n.z.union([n.z.number(),n.z.string()]),chainType:n.z.string(),enabled_services:n.z.array(n.z.enum([`cross-chain-swap`,`cross-chain-quote`,`quote`,`swap`,`token-list`])),logo_url:n.z.url(),name:n.z.string(),lanes:n.z.array(n.z.union([n.z.coerce.number().int().nonnegative(),r]))}),a=i.extend({chainId:n.z.coerce.number().int().nonnegative(),chainType:n.z.literal(`evm`),router:t.EvmAddressSchema.optional(),wrapped_token:t.EvmAddressSchema.optional()}),o=i.extend({chainId:n.z.string().refine(t=>e.isCaip2ChainId(t)&&t.startsWith(`solana:`),{error:`Is not a valid Solana CAIP-2 ID`}).transform(e=>e),chainType:n.z.literal(`svm`)}),s=n.z.array(n.z.union([a,o,i.refine(e=>e.chainType!==`evm`&&e.chainType!==`svm`,`Known chain types must match their expected schema`)])),c=n.z.array(n.z.object({address:t.EvmAddressSchema,decimals:n.z.number().int().nonnegative().max(18),logo_url:n.z.url(),name:n.z.string(),symbol:n.z.string()})),l=n.z.union([n.z.object({aggregator:n.z.object({id:n.z.string(),logo_url:n.z.url(),name:n.z.string()}),amountIn:n.z.coerce.bigint().nonnegative(),amountOut:n.z.coerce.bigint().nonnegative(),chainId:n.z.union([n.z.number().int().nonnegative(),r]),expiredAt:n.z.number().int().nonnegative(),fees:n.z.array(n.z.object({type:n.z.enum([`protocol`,`gas`,`bridge`,`slippage`,`swap`,`other`]),name:n.z.string(),amount:n.z.coerce.bigint().nonnegative(),token:n.z.object({chainId:n.z.union([n.z.number().int().nonnegative(),r]),address:n.z.union([t.EvmAddressSchema,t.SolAddressSchema])})})).optional(),gasEstimate:n.z.coerce.bigint().nonnegative().optional(),recommendedSlippage:n.z.number().int().nonnegative(),tokenIn:n.z.union([t.EvmAddressSchema,t.SolAddressSchema]),tokenInDecimals:n.z.number().int().nonnegative().max(18),tokenOut:n.z.union([t.EvmAddressSchema,t.SolAddressSchema]),tokenOutDecimals:n.z.number().int().nonnegative().max(18),uuid:n.z.uuid()}),n.z.object({done:n.z.literal(!0)})]),u=n.z.object({data:t.HexSchema,to:t.EvmAddressSchema,value:n.z.coerce.bigint().nonnegative()}),d=n.z.object({chainType:n.z.literal(`svm`),swapTransaction:n.z.base64()}),f=n.z.union([u,d]),p=n.z.object({fee:n.z.int().nonnegative(),name:n.z.string()}),m=/[zZ]|[+-]\d{2}:?\d{2}$/,h=n.z.iso.datetime({local:!0}).refine(e=>{let t=m.test(e)?e:e+`Z`;return n.z.iso.datetime().safeParse(t).success},{error:`Invalid ISO-8601 datetime (must be valid with timezone, or local assumed UTC)`}).transform(e=>m.test(e)?e:e+`Z`),g=n.z.object({messageId:n.z.string().nullable(),status:n.z.enum([`pending`,`committed`,`pending_execution`,`completed`,`failed`,`unknown`]),description:n.z.string(),sourceChain:n.z.object({name:n.z.string(),transactionHash:n.z.union([t.HashSchema,t.SolSignatureSchema]),timestamp:h,finalized:h.or(n.z.boolean()).nullable()}),destinationChain:n.z.object({name:n.z.string().nullable(),transactionHash:n.z.union([t.HashSchema,t.SolSignatureSchema]).nullable(),bridgeHash:n.z.union([t.HashSchema,t.SolSignatureSchema]).nullable().optional(),timestamp:h.nullable(),finalized:h.nullable()}),progress:n.z.object({committed:n.z.boolean(),commitTimestamp:h.nullable().optional(),executed:n.z.boolean()}),fees:n.z.object({token:n.z.union([t.EvmAddressSchema,t.SolAddressSchema]).nullable(),amount:n.z.coerce.bigint().nonnegative().nullable()}),transferredTokens:n.z.array(n.z.object({token:n.z.union([t.EvmAddressSchema,t.SolAddressSchema]),amount:n.z.coerce.bigint().nonnegative()})),debug:n.z.looseObject({messageId:n.z.string(),status:n.z.string(),destinationChain:n.z.string(),destinationTxHash:n.z.string(),relayTxHash:n.z.string(),retryCount:n.z.number().int().nonnegative(),lastRetryAt:n.z.iso.datetime(),sourceChain:n.z.string(),sourceTxHash:n.z.string(),createdAt:n.z.iso.datetime()}).nullable().optional()}),_=n.z.object({address:t.EvmAddressSchema});exports.CrossChainStatusResponseSchema=g,exports.PartnerInfoResponseSchema=p,exports.QuoteResponseSchema=l,exports.SpenderAddressResponseSchema=_,exports.SupportedChainsResponseSchema=s,exports.SwapResponseSchema=f,exports.TokenListResponseSchema=c;
1
+ require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../utils/caip.cjs`),t=require(`../service-schemas.cjs`);let n=require(`zod`);const r=n.z.string().refine(t=>e.isCaip2ChainId(t),{message:`Invalid CAIP-2 chain ID`}).transform(e=>e),i=n.z.object({chainId:n.z.union([n.z.number(),n.z.string()]),chainType:n.z.string(),enabled_services:n.z.array(n.z.enum([`cross-chain-swap`,`cross-chain-quote`,`quote`,`swap`,`token-list`])),logo_url:n.z.url(),name:n.z.string(),lanes:n.z.array(n.z.union([n.z.coerce.number().int().nonnegative(),r]))}),a=i.extend({chainId:n.z.coerce.number().int().nonnegative(),chainType:n.z.literal(`evm`),router:t.EvmAddressSchema.optional(),wrapped_token:t.EvmAddressSchema.optional()}),o=i.extend({chainId:n.z.string().refine(t=>e.isCaip2ChainId(t)&&t.startsWith(`solana:`),{error:`Is not a valid Solana CAIP-2 ID`}).transform(e=>e),chainType:n.z.literal(`svm`)}),s=n.z.array(n.z.union([a,o,i.refine(e=>e.chainType!==`evm`&&e.chainType!==`svm`,`Known chain types must match their expected schema`)])),c=n.z.array(n.z.object({address:t.EvmAddressSchema,decimals:n.z.number().int().nonnegative().max(18),logo_url:n.z.url(),name:n.z.string(),symbol:n.z.string()})),l=n.z.union([n.z.object({aggregator:n.z.object({id:n.z.string(),logo_url:n.z.url(),name:n.z.string()}),amountIn:n.z.coerce.bigint().nonnegative(),amountOut:n.z.coerce.bigint().nonnegative(),chainId:n.z.union([n.z.number().int().nonnegative(),r]),expiredAt:n.z.number().int().nonnegative(),fees:n.z.array(n.z.object({type:n.z.enum([`protocol`,`gas`,`bridge`,`slippage`,`swap`,`other`]),name:n.z.string(),amount:n.z.coerce.bigint().nonnegative(),token:n.z.object({chainId:n.z.union([n.z.number().int().nonnegative(),r]),address:n.z.union([t.EvmAddressSchema,t.SolAddressSchema])})})).optional(),gasEstimate:n.z.coerce.bigint().nonnegative().optional(),recommendedSlippage:n.z.number().int().nonnegative(),tokenIn:n.z.union([t.EvmAddressSchema,t.SolAddressSchema]),tokenInDecimals:n.z.number().int().nonnegative().max(18),tokenOut:n.z.union([t.EvmAddressSchema,t.SolAddressSchema]),tokenOutDecimals:n.z.number().int().nonnegative().max(18),uuid:n.z.uuid()}),n.z.object({done:n.z.literal(!0)})]),u=n.z.object({data:t.HexSchema,to:t.EvmAddressSchema,value:n.z.coerce.bigint().nonnegative()}),d=n.z.object({chainType:n.z.literal(`svm`),swapTransaction:n.z.base64()}),f=n.z.union([u,d]),p=n.z.object({fee:n.z.int().nonnegative(),name:n.z.string()}),m=/[zZ]|[+-]\d{2}:?\d{2}$/,h=n.z.iso.datetime({local:!0}).refine(e=>{let t=m.test(e)?e:e+`Z`;return n.z.iso.datetime().safeParse(t).success},{error:`Invalid ISO-8601 datetime (must be valid with timezone, or local assumed UTC)`}).transform(e=>m.test(e)?e:e+`Z`),g=n.z.object({messageId:n.z.string().nullable(),status:n.z.enum([`pending`,`committed`,`pending_execution`,`completed`,`failed`,`unknown`]),description:n.z.string(),sourceChain:n.z.object({name:n.z.string(),transactionHash:n.z.union([t.HashSchema,t.SolSignatureSchema]),timestamp:h,finalized:h.or(n.z.boolean()).nullable()}),destinationChain:n.z.object({name:n.z.string().nullable(),transactionHash:n.z.union([t.HashSchema,t.SolSignatureSchema]).nullable(),bridgeHash:n.z.union([t.HashSchema,t.SolSignatureSchema]).nullable().optional(),timestamp:h.nullable(),finalized:h.nullable()}),progress:n.z.object({committed:n.z.boolean(),commitTimestamp:h.nullable().optional(),executed:n.z.boolean()}),fees:n.z.object({token:n.z.union([t.EvmAddressSchema,t.SolAddressSchema]).nullable(),amount:n.z.coerce.bigint().nonnegative().nullable()}),transferredTokens:n.z.array(n.z.object({token:n.z.union([t.EvmAddressSchema,t.SolAddressSchema]),amount:n.z.coerce.bigint().nonnegative()})),debug:n.z.looseObject({messageId:n.z.string(),status:n.z.string(),destinationChain:n.z.string(),destinationTxHash:n.z.string(),relayTxHash:n.z.string(),retryCount:n.z.number().int().nonnegative(),lastRetryAt:n.z.iso.datetime(),sourceChain:n.z.string(),sourceTxHash:n.z.string(),createdAt:n.z.iso.datetime()}).partial().nullable().optional()}),_=n.z.object({address:t.EvmAddressSchema});exports.CrossChainStatusResponseSchema=g,exports.PartnerInfoResponseSchema=p,exports.QuoteResponseSchema=l,exports.SpenderAddressResponseSchema=_,exports.SupportedChainsResponseSchema=s,exports.SwapResponseSchema=f,exports.TokenListResponseSchema=c;
2
2
  //# sourceMappingURL=_schema.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"_schema.cjs","names":["z","isCaip2ChainId","EvmAddressSchema","SolAddressSchema","HexSchema","HashSchema","SolSignatureSchema"],"sources":["../../../src/transfer-service/markr/_schema.ts"],"sourcesContent":["import type { Signature, Address as SolAddress } from '@solana/kit';\nimport { z } from 'zod';\nimport type { Address as EvmAddress, Hash } from 'viem';\nimport { EvmAddressSchema, HashSchema, HexSchema, SolAddressSchema, SolSignatureSchema } from '../service-schemas';\nimport { isCaip2ChainId } from '../../utils/caip';\nimport type { Caip2ChainId } from '../../types/caip';\nimport type { Hex } from '../../types/signer';\n\ninterface SupportedChainsResponseItemBase {\n chainId: number | string;\n chainType: string;\n /** Available services on the chain. Each service has specific functionality */\n enabled_services: Array<'cross-chain-swap' | 'cross-chain-quote' | 'quote' | 'swap' | 'token-list'>;\n /** Chain logo URL */\n logo_url: string;\n /** Chain display name */\n name: string;\n /**\n * List of chain IDs that this chain can swap to via cross-chain aggregators.\n *\n * Empty array means no cross-chain routes available.\n */\n lanes: ReadonlyArray<number | Caip2ChainId>;\n}\n\nexport interface SupportedChainsResponseItemEvm extends SupportedChainsResponseItemBase {\n /** Chain identifier */\n chainId: number;\n /** Chain virtual machine type */\n chainType: 'evm';\n /** Router contract address */\n router?: EvmAddress;\n /** Native token wrapped contract address */\n wrapped_token?: EvmAddress;\n}\n\nexport interface SupportedChainsResponseItemSvm extends SupportedChainsResponseItemBase {\n /** Chain identifier */\n chainId: Caip2ChainId;\n /** Chain virtual machine type */\n chainType: 'svm';\n}\n\nexport type SupportedChainsResponse = Array<\n SupportedChainsResponseItemEvm | SupportedChainsResponseItemSvm | SupportedChainsResponseItemBase\n>;\n\nexport const Caip2ChainIdSchema: z.ZodType<Caip2ChainId> = z\n .string()\n .refine((value) => isCaip2ChainId(value), {\n message: 'Invalid CAIP-2 chain ID',\n })\n .transform((value) => value as Caip2ChainId);\n\nconst SupportedChainsResponseItemBaseSchema = z.object({\n chainId: z.union([z.number(), z.string()]),\n chainType: z.string(),\n enabled_services: z.array(z.enum(['cross-chain-swap', 'cross-chain-quote', 'quote', 'swap', 'token-list'])),\n logo_url: z.url(),\n name: z.string(),\n lanes: z.array(z.union([z.coerce.number().int().nonnegative(), Caip2ChainIdSchema])),\n});\n\nconst SupportedChainsResponseItemEvmSchema: z.ZodType<SupportedChainsResponseItemEvm> =\n SupportedChainsResponseItemBaseSchema.extend({\n chainId: z.coerce.number().int().nonnegative(),\n chainType: z.literal('evm'),\n router: EvmAddressSchema.optional(),\n wrapped_token: EvmAddressSchema.optional(),\n });\n\nconst SupportedChainsResponseItemSvmSchema: z.ZodType<SupportedChainsResponseItemSvm> =\n SupportedChainsResponseItemBaseSchema.extend({\n chainId: z\n .string()\n .refine((value) => isCaip2ChainId(value) && value.startsWith('solana:'), {\n error: 'Is not a valid Solana CAIP-2 ID',\n })\n .transform((value) => value as Caip2ChainId),\n chainType: z.literal('svm'),\n });\n\n/**\n * Schema for the response from Markr's /info/chains endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1info~1chains/get\n */\nexport const SupportedChainsResponseSchema: z.ZodType<SupportedChainsResponse> = z.array(\n z.union([\n SupportedChainsResponseItemEvmSchema,\n SupportedChainsResponseItemSvmSchema,\n SupportedChainsResponseItemBaseSchema.refine(\n (item) => item.chainType !== 'evm' && item.chainType !== 'svm',\n 'Known chain types must match their expected schema',\n ),\n ]),\n);\n\nexport type TokenListResponse = Array<{\n address: EvmAddress;\n decimals: number;\n logo_url: string;\n name: string;\n symbol: string;\n}>;\n\n/**\n * Schema for the response Markr's /tokens/{chainId}/list endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1tokens~1%7BchainId%7D~1list/get\n */\nexport const TokenListResponseSchema: z.ZodType<TokenListResponse> = z.array(\n z.object({\n address: EvmAddressSchema,\n decimals: z.number().int().nonnegative().max(18),\n logo_url: z.url(),\n name: z.string(),\n symbol: z.string(),\n }),\n);\n\nexport interface QuoteResponseData {\n aggregator: {\n id: string;\n logo_url: string;\n name: string;\n };\n amountIn: bigint;\n amountOut: bigint;\n /** Chain identifier (number for EVM chains, CAIP-2 ID for SVM chains) */\n chainId: number | Caip2ChainId;\n expiredAt: number;\n /**\n * Fee breakdown for cross-chain bridge transactions.\n *\n * Only included in quotes from cross-chain aggregators (DeBridge, LiFi).\n */\n fees?: ReadonlyArray<{\n type: 'protocol' | 'gas' | 'bridge' | 'slippage' | 'swap' | 'other';\n /** Human-readable fee name */\n name: string;\n /** Fee amount in token's smallest unit */\n amount: bigint;\n /** Token the fee is deducted from */\n token: {\n /** Chain ID where fee is deducted */\n chainId: number | Caip2ChainId;\n /** Token address (EVM hex or Solana base58) */\n address: EvmAddress | SolAddress;\n };\n }>;\n gasEstimate?: bigint;\n recommendedSlippage: number;\n /** Input token address (EVM hex or Solana base58) */\n tokenIn: EvmAddress | SolAddress;\n tokenInDecimals: number;\n /** Output token address (EVM hex or Solana base58) */\n tokenOut: EvmAddress | SolAddress;\n tokenOutDecimals: number;\n uuid: string;\n}\n\nexport interface QuoteResponseDataDone {\n done: true;\n}\n\nexport type QuoteResponse = QuoteResponseData | QuoteResponseDataDone;\n\n/**\n * Schema for the response from Markr's /quote endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1quote/post\n */\nexport const QuoteResponseSchema: z.ZodType<QuoteResponse> = z.union([\n z.object({\n aggregator: z.object({\n id: z.string(),\n logo_url: z.url(),\n name: z.string(),\n }),\n amountIn: z.coerce.bigint().nonnegative(),\n amountOut: z.coerce.bigint().nonnegative(),\n chainId: z.union([z.number().int().nonnegative(), Caip2ChainIdSchema]),\n /**\n * Unix time in seconds when the quote expires.\n */\n expiredAt: z.number().int().nonnegative(),\n fees: z\n .array(\n z.object({\n type: z.enum(['protocol', 'gas', 'bridge', 'slippage', 'swap', 'other']),\n name: z.string(),\n amount: z.coerce.bigint().nonnegative(),\n token: z.object({\n chainId: z.union([z.number().int().nonnegative(), Caip2ChainIdSchema]),\n address: z.union([EvmAddressSchema, SolAddressSchema]),\n }),\n }),\n )\n .optional(),\n /**\n * Estimated gas for the swap transaction.\n * Markr estimates already include a buffer.\n *\n * The API docs do not specify this field as optional, but in practice it can be missing.\n */\n gasEstimate: z.coerce.bigint().nonnegative().optional(),\n /** Recommended slippage in basis points. */\n recommendedSlippage: z.number().int().nonnegative(),\n tokenIn: z.union([EvmAddressSchema, SolAddressSchema]),\n tokenInDecimals: z.number().int().nonnegative().max(18),\n tokenOut: z.union([EvmAddressSchema, SolAddressSchema]),\n tokenOutDecimals: z.number().int().nonnegative().max(18),\n uuid: z.uuid(),\n }),\n z.object({\n done: z.literal(true),\n }),\n]);\n\n/**\n * Response type for Markr's /swap endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1swap/post\n */\nexport interface WrappedSwapTransactionResponse {\n data: Hex;\n to: EvmAddress;\n value: bigint;\n}\n\nexport const WrappedSwapTransactionResponseSchema: z.ZodType<WrappedSwapTransactionResponse> = z.object({\n data: HexSchema,\n to: EvmAddressSchema,\n value: z.coerce.bigint().nonnegative(),\n});\n\n/**\n * Solana swap transaction (returned for SVM chains).\n */\nexport interface SolanaSwapTransactionResponse {\n /** Chain type identifier */\n chainType: 'svm';\n /** Base64-encoded Solana transaction to be signed and sent by the client */\n swapTransaction: string;\n}\n\nexport const SolanaSwapTransactionResponseSchema: z.ZodType<SolanaSwapTransactionResponse> = z.object({\n chainType: z.literal('svm'),\n swapTransaction: z.base64(),\n});\n\nexport type SwapResponse = WrappedSwapTransactionResponse | SolanaSwapTransactionResponse;\n\nexport const SwapResponseSchema: z.ZodType<SwapResponse> = z.union([\n WrappedSwapTransactionResponseSchema,\n SolanaSwapTransactionResponseSchema,\n]);\n\nexport interface PartnerInfoResponse {\n /**\n * The partner fee in basis points collected on each swap.\n */\n fee: number;\n name: string;\n}\n\nexport const PartnerInfoResponseSchema: z.ZodType<PartnerInfoResponse> = z.object({\n fee: z.int().nonnegative(),\n name: z.string(),\n});\n\n/**\n * If the destination token is USDC, the flow is:\n * - pending -> committed -> completed\n *\n * If the destination token is not USDC, the flow is:\n * - pending -> committed -> pending_execution -> completed\n *\n * If the transaction fails at any point, the status will be 'failed'.\n */\nexport type CrossChainStatus =\n | /** Transaction submitted to CCIP */\n 'pending'\n /** Message committed, awaiting execution on destination chain */\n | 'committed'\n /** Message received on destination, swap pending execution by relayer */\n | 'pending_execution'\n /** Message executed successfully on destination chain */\n | 'completed'\n /** Execution failed */\n | 'failed'\n /** Unknown state */\n | 'unknown';\n\nexport interface CrossChainStatusResponse {\n /** CCIP message ID */\n messageId: string | null;\n /** Current status of the cross-chain transaction. */\n status: CrossChainStatus;\n /** Human-readable status description */\n description: string;\n /** Source chain information */\n sourceChain: {\n /** Source chain network name */\n name: string;\n /** Source chain transaction hash */\n transactionHash: Hash | Signature;\n /** Transaction timestamp on source chain (ISO 8601) */\n timestamp: string;\n /** When the source transaction was finalized (ISO 8601) */\n finalized: string | boolean | null;\n };\n /** Destination chain information */\n destinationChain: {\n /** Destination chain network name */\n name: string | null;\n /**\n * Destination chain tx hash.\n *\n * - For direct transfers (USDC -> USDC): The CCIP bridge transaction hash.\n * - For successful swaps: The actual swap transaction hash from the relayer.\n * - For pending swaps: null (swap not yet executed).\n */\n transactionHash: Hash | Signature | null;\n /**\n * CCIP bridge tx hash (only present for swaps, not direct transfers).\n *\n * This is the transaction that delivered USDC to the destination chain via CCIP.\n * The `transactionHash` field contains the subsequent swap transaction.\n */\n bridgeHash?: Hash | Signature | null;\n /** Transaction timestamp on destination chain (null if not yet executed) (ISO 8601) */\n timestamp: string | null;\n /** When the destination transaction was finalized (null if not yet executed) (ISO 8601) */\n finalized: string | null;\n };\n /** Transaction progress information */\n progress: {\n /** Whether the message has been committed on destination chain */\n committed: boolean;\n /** When the message was committed (null if not committed) (ISO 8601) */\n commitTimestamp?: string | null;\n /** Whether the message has been executed on destination chain */\n executed: boolean;\n };\n /** Fee information */\n fees: {\n /** Fee token address */\n token: EvmAddress | SolAddress | null;\n /** Fee amount in wei */\n amount: bigint | null;\n };\n /** Tokens transferred in this cross-chain transaction */\n transferredTokens: ReadonlyArray<{\n /** Token address */\n token: EvmAddress | SolAddress;\n /** Token amount */\n amount: bigint;\n }>;\n /**\n * Debug information from Markr transaction API (only present for swaps that have been executed).\n *\n * Contains detailed information about the relayer execution, retry attempts, and transaction details.\n */\n debug?: {\n /** CCIP message ID */\n messageId: string;\n /** Execution status from relayer */\n status: string;\n /** Destination chain name */\n destinationChain: string;\n /** Destination swap transaction hash */\n destinationTxHash: string;\n /** Relay transaction hash */\n relayTxHash: string;\n /** Number of retry attempts */\n retryCount: number;\n /** Timestamp of last retry attempt (ISO 8601) */\n lastRetryAt: string;\n /** Source chain name */\n sourceChain: string;\n /** Source transaction hash */\n sourceTxHash: string;\n /** When the record was created (ISO 8601) */\n createdAt: string;\n } | null;\n}\n\nconst ISO_8601_TIMEZONE_DESIGNATOR_REGEX = /[zZ]|[+-]\\d{2}:?\\d{2}$/;\n\n// Markr API returns ISO-8601 datetime strings that are sometimes missing a timezone designator (\"local\" ISO).\n// We assume these are meant to be UTC and append 'Z' if missing, then validate as strict ISO-8601 with timezone.\nconst datetime = z.iso\n .datetime({ local: true })\n .refine(\n (value) => {\n // Accept at least local ISO format\n // If missing timezone, treat as UTC\n const hasTimezone = ISO_8601_TIMEZONE_DESIGNATOR_REGEX.test(value);\n const isoString = hasTimezone ? value : value + 'Z';\n // Validate as strict ISO-8601 with timezone\n return z.iso.datetime().safeParse(isoString).success;\n },\n {\n error: 'Invalid ISO-8601 datetime (must be valid with timezone, or local assumed UTC)',\n },\n )\n .transform((value) => {\n const hasTimezone = ISO_8601_TIMEZONE_DESIGNATOR_REGEX.test(value);\n return hasTimezone ? value : value + 'Z';\n });\n\nexport const CrossChainStatusResponseSchema: z.ZodType<CrossChainStatusResponse> = z.object({\n messageId: z.string().nullable(),\n status: z.enum(['pending', 'committed', 'pending_execution', 'completed', 'failed', 'unknown']),\n description: z.string(),\n sourceChain: z.object({\n name: z.string(),\n transactionHash: z.union([HashSchema, SolSignatureSchema]),\n timestamp: datetime,\n finalized: datetime.or(z.boolean()).nullable(),\n }),\n destinationChain: z.object({\n name: z.string().nullable(),\n transactionHash: z.union([HashSchema, SolSignatureSchema]).nullable(),\n bridgeHash: z.union([HashSchema, SolSignatureSchema]).nullable().optional(),\n timestamp: datetime.nullable(),\n finalized: datetime.nullable(),\n }),\n progress: z.object({\n committed: z.boolean(),\n commitTimestamp: datetime.nullable().optional(),\n executed: z.boolean(),\n }),\n fees: z.object({\n token: z.union([EvmAddressSchema, SolAddressSchema]).nullable(),\n amount: z.coerce.bigint().nonnegative().nullable(),\n }),\n transferredTokens: z.array(\n z.object({\n token: z.union([EvmAddressSchema, SolAddressSchema]),\n amount: z.coerce.bigint().nonnegative(),\n }),\n ),\n debug: z\n .looseObject({\n messageId: z.string(),\n status: z.string(),\n destinationChain: z.string(),\n destinationTxHash: z.string(),\n relayTxHash: z.string(),\n retryCount: z.number().int().nonnegative(),\n lastRetryAt: z.iso.datetime(),\n sourceChain: z.string(),\n sourceTxHash: z.string(),\n createdAt: z.iso.datetime(),\n })\n .nullable()\n .optional(),\n});\n\nexport interface SpenderAddressResponse {\n address: EvmAddress;\n}\n\nexport const SpenderAddressResponseSchema: z.ZodType<SpenderAddressResponse> = z.object({\n address: EvmAddressSchema,\n});\n"],"mappings":"iJA+CA,MAAa,EAA8CA,EAAAA,EACxD,QAAQ,CACR,OAAQ,GAAUC,EAAAA,eAAe,EAAM,CAAE,CACxC,QAAS,0BACV,CAAC,CACD,UAAW,GAAU,EAAsB,CAExC,EAAwCD,EAAAA,EAAE,OAAO,CACrD,QAASA,EAAAA,EAAE,MAAM,CAACA,EAAAA,EAAE,QAAQ,CAAEA,EAAAA,EAAE,QAAQ,CAAC,CAAC,CAC1C,UAAWA,EAAAA,EAAE,QAAQ,CACrB,iBAAkBA,EAAAA,EAAE,MAAMA,EAAAA,EAAE,KAAK,CAAC,mBAAoB,oBAAqB,QAAS,OAAQ,aAAa,CAAC,CAAC,CAC3G,SAAUA,EAAAA,EAAE,KAAK,CACjB,KAAMA,EAAAA,EAAE,QAAQ,CAChB,MAAOA,EAAAA,EAAE,MAAMA,EAAAA,EAAE,MAAM,CAACA,EAAAA,EAAE,OAAO,QAAQ,C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EA,EAAAA,EAAE,OAAO,CACtF,QAASE,EAAAA,iBACV,CAAC"}
1
+ {"version":3,"file":"_schema.cjs","names":["z","isCaip2ChainId","EvmAddressSchema","SolAddressSchema","HexSchema","HashSchema","SolSignatureSchema"],"sources":["../../../src/transfer-service/markr/_schema.ts"],"sourcesContent":["import type { Signature, Address as SolAddress } from '@solana/kit';\nimport { z } from 'zod';\nimport type { Address as EvmAddress, Hash } from 'viem';\nimport { EvmAddressSchema, HashSchema, HexSchema, SolAddressSchema, SolSignatureSchema } from '../service-schemas';\nimport { isCaip2ChainId } from '../../utils/caip';\nimport type { Caip2ChainId } from '../../types/caip';\nimport type { Hex } from '../../types/signer';\n\ninterface SupportedChainsResponseItemBase {\n chainId: number | string;\n chainType: string;\n /** Available services on the chain. Each service has specific functionality */\n enabled_services: Array<'cross-chain-swap' | 'cross-chain-quote' | 'quote' | 'swap' | 'token-list'>;\n /** Chain logo URL */\n logo_url: string;\n /** Chain display name */\n name: string;\n /**\n * List of chain IDs that this chain can swap to via cross-chain aggregators.\n *\n * Empty array means no cross-chain routes available.\n */\n lanes: ReadonlyArray<number | Caip2ChainId>;\n}\n\nexport interface SupportedChainsResponseItemEvm extends SupportedChainsResponseItemBase {\n /** Chain identifier */\n chainId: number;\n /** Chain virtual machine type */\n chainType: 'evm';\n /** Router contract address */\n router?: EvmAddress;\n /** Native token wrapped contract address */\n wrapped_token?: EvmAddress;\n}\n\nexport interface SupportedChainsResponseItemSvm extends SupportedChainsResponseItemBase {\n /** Chain identifier */\n chainId: Caip2ChainId;\n /** Chain virtual machine type */\n chainType: 'svm';\n}\n\nexport type SupportedChainsResponse = Array<\n SupportedChainsResponseItemEvm | SupportedChainsResponseItemSvm | SupportedChainsResponseItemBase\n>;\n\nexport const Caip2ChainIdSchema: z.ZodType<Caip2ChainId> = z\n .string()\n .refine((value) => isCaip2ChainId(value), {\n message: 'Invalid CAIP-2 chain ID',\n })\n .transform((value) => value as Caip2ChainId);\n\nconst SupportedChainsResponseItemBaseSchema = z.object({\n chainId: z.union([z.number(), z.string()]),\n chainType: z.string(),\n enabled_services: z.array(z.enum(['cross-chain-swap', 'cross-chain-quote', 'quote', 'swap', 'token-list'])),\n logo_url: z.url(),\n name: z.string(),\n lanes: z.array(z.union([z.coerce.number().int().nonnegative(), Caip2ChainIdSchema])),\n});\n\nconst SupportedChainsResponseItemEvmSchema: z.ZodType<SupportedChainsResponseItemEvm> =\n SupportedChainsResponseItemBaseSchema.extend({\n chainId: z.coerce.number().int().nonnegative(),\n chainType: z.literal('evm'),\n router: EvmAddressSchema.optional(),\n wrapped_token: EvmAddressSchema.optional(),\n });\n\nconst SupportedChainsResponseItemSvmSchema: z.ZodType<SupportedChainsResponseItemSvm> =\n SupportedChainsResponseItemBaseSchema.extend({\n chainId: z\n .string()\n .refine((value) => isCaip2ChainId(value) && value.startsWith('solana:'), {\n error: 'Is not a valid Solana CAIP-2 ID',\n })\n .transform((value) => value as Caip2ChainId),\n chainType: z.literal('svm'),\n });\n\n/**\n * Schema for the response from Markr's /info/chains endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1info~1chains/get\n */\nexport const SupportedChainsResponseSchema: z.ZodType<SupportedChainsResponse> = z.array(\n z.union([\n SupportedChainsResponseItemEvmSchema,\n SupportedChainsResponseItemSvmSchema,\n SupportedChainsResponseItemBaseSchema.refine(\n (item) => item.chainType !== 'evm' && item.chainType !== 'svm',\n 'Known chain types must match their expected schema',\n ),\n ]),\n);\n\nexport type TokenListResponse = Array<{\n address: EvmAddress;\n decimals: number;\n logo_url: string;\n name: string;\n symbol: string;\n}>;\n\n/**\n * Schema for the response Markr's /tokens/{chainId}/list endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1tokens~1%7BchainId%7D~1list/get\n */\nexport const TokenListResponseSchema: z.ZodType<TokenListResponse> = z.array(\n z.object({\n address: EvmAddressSchema,\n decimals: z.number().int().nonnegative().max(18),\n logo_url: z.url(),\n name: z.string(),\n symbol: z.string(),\n }),\n);\n\nexport interface QuoteResponseData {\n aggregator: {\n id: string;\n logo_url: string;\n name: string;\n };\n amountIn: bigint;\n amountOut: bigint;\n /** Chain identifier (number for EVM chains, CAIP-2 ID for SVM chains) */\n chainId: number | Caip2ChainId;\n expiredAt: number;\n /**\n * Fee breakdown for cross-chain bridge transactions.\n *\n * Only included in quotes from cross-chain aggregators (DeBridge, LiFi).\n */\n fees?: ReadonlyArray<{\n type: 'protocol' | 'gas' | 'bridge' | 'slippage' | 'swap' | 'other';\n /** Human-readable fee name */\n name: string;\n /** Fee amount in token's smallest unit */\n amount: bigint;\n /** Token the fee is deducted from */\n token: {\n /** Chain ID where fee is deducted */\n chainId: number | Caip2ChainId;\n /** Token address (EVM hex or Solana base58) */\n address: EvmAddress | SolAddress;\n };\n }>;\n gasEstimate?: bigint;\n recommendedSlippage: number;\n /** Input token address (EVM hex or Solana base58) */\n tokenIn: EvmAddress | SolAddress;\n tokenInDecimals: number;\n /** Output token address (EVM hex or Solana base58) */\n tokenOut: EvmAddress | SolAddress;\n tokenOutDecimals: number;\n uuid: string;\n}\n\nexport interface QuoteResponseDataDone {\n done: true;\n}\n\nexport type QuoteResponse = QuoteResponseData | QuoteResponseDataDone;\n\n/**\n * Schema for the response from Markr's /quote endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1quote/post\n */\nexport const QuoteResponseSchema: z.ZodType<QuoteResponse> = z.union([\n z.object({\n aggregator: z.object({\n id: z.string(),\n logo_url: z.url(),\n name: z.string(),\n }),\n amountIn: z.coerce.bigint().nonnegative(),\n amountOut: z.coerce.bigint().nonnegative(),\n chainId: z.union([z.number().int().nonnegative(), Caip2ChainIdSchema]),\n /**\n * Unix time in seconds when the quote expires.\n */\n expiredAt: z.number().int().nonnegative(),\n fees: z\n .array(\n z.object({\n type: z.enum(['protocol', 'gas', 'bridge', 'slippage', 'swap', 'other']),\n name: z.string(),\n amount: z.coerce.bigint().nonnegative(),\n token: z.object({\n chainId: z.union([z.number().int().nonnegative(), Caip2ChainIdSchema]),\n address: z.union([EvmAddressSchema, SolAddressSchema]),\n }),\n }),\n )\n .optional(),\n /**\n * Estimated gas for the swap transaction.\n * Markr estimates already include a buffer.\n *\n * The API docs do not specify this field as optional, but in practice it can be missing.\n */\n gasEstimate: z.coerce.bigint().nonnegative().optional(),\n /** Recommended slippage in basis points. */\n recommendedSlippage: z.number().int().nonnegative(),\n tokenIn: z.union([EvmAddressSchema, SolAddressSchema]),\n tokenInDecimals: z.number().int().nonnegative().max(18),\n tokenOut: z.union([EvmAddressSchema, SolAddressSchema]),\n tokenOutDecimals: z.number().int().nonnegative().max(18),\n uuid: z.uuid(),\n }),\n z.object({\n done: z.literal(true),\n }),\n]);\n\n/**\n * Response type for Markr's /swap endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1swap/post\n */\nexport interface WrappedSwapTransactionResponse {\n data: Hex;\n to: EvmAddress;\n value: bigint;\n}\n\nexport const WrappedSwapTransactionResponseSchema: z.ZodType<WrappedSwapTransactionResponse> = z.object({\n data: HexSchema,\n to: EvmAddressSchema,\n value: z.coerce.bigint().nonnegative(),\n});\n\n/**\n * Solana swap transaction (returned for SVM chains).\n */\nexport interface SolanaSwapTransactionResponse {\n /** Chain type identifier */\n chainType: 'svm';\n /** Base64-encoded Solana transaction to be signed and sent by the client */\n swapTransaction: string;\n}\n\nexport const SolanaSwapTransactionResponseSchema: z.ZodType<SolanaSwapTransactionResponse> = z.object({\n chainType: z.literal('svm'),\n swapTransaction: z.base64(),\n});\n\nexport type SwapResponse = WrappedSwapTransactionResponse | SolanaSwapTransactionResponse;\n\nexport const SwapResponseSchema: z.ZodType<SwapResponse> = z.union([\n WrappedSwapTransactionResponseSchema,\n SolanaSwapTransactionResponseSchema,\n]);\n\nexport interface PartnerInfoResponse {\n /**\n * The partner fee in basis points collected on each swap.\n */\n fee: number;\n name: string;\n}\n\nexport const PartnerInfoResponseSchema: z.ZodType<PartnerInfoResponse> = z.object({\n fee: z.int().nonnegative(),\n name: z.string(),\n});\n\n/**\n * If the destination token is USDC, the flow is:\n * - pending -> committed -> completed\n *\n * If the destination token is not USDC, the flow is:\n * - pending -> committed -> pending_execution -> completed\n *\n * If the transaction fails at any point, the status will be 'failed'.\n */\nexport type CrossChainStatus =\n | /** Transaction submitted to CCIP */\n 'pending'\n /** Message committed, awaiting execution on destination chain */\n | 'committed'\n /** Message received on destination, swap pending execution by relayer */\n | 'pending_execution'\n /** Message executed successfully on destination chain */\n | 'completed'\n /** Execution failed */\n | 'failed'\n /** Unknown state */\n | 'unknown';\n\nexport interface CrossChainStatusResponse {\n /** CCIP message ID */\n messageId: string | null;\n /** Current status of the cross-chain transaction. */\n status: CrossChainStatus;\n /** Human-readable status description */\n description: string;\n /** Source chain information */\n sourceChain: {\n /** Source chain network name */\n name: string;\n /** Source chain transaction hash */\n transactionHash: Hash | Signature;\n /** Transaction timestamp on source chain (ISO 8601) */\n timestamp: string;\n /** When the source transaction was finalized (ISO 8601) */\n finalized: string | boolean | null;\n };\n /** Destination chain information */\n destinationChain: {\n /** Destination chain network name */\n name: string | null;\n /**\n * Destination chain tx hash.\n *\n * - For direct transfers (USDC -> USDC): The CCIP bridge transaction hash.\n * - For successful swaps: The actual swap transaction hash from the relayer.\n * - For pending swaps: null (swap not yet executed).\n */\n transactionHash: Hash | Signature | null;\n /**\n * CCIP bridge tx hash (only present for swaps, not direct transfers).\n *\n * This is the transaction that delivered USDC to the destination chain via CCIP.\n * The `transactionHash` field contains the subsequent swap transaction.\n */\n bridgeHash?: Hash | Signature | null;\n /** Transaction timestamp on destination chain (null if not yet executed) (ISO 8601) */\n timestamp: string | null;\n /** When the destination transaction was finalized (null if not yet executed) (ISO 8601) */\n finalized: string | null;\n };\n /** Transaction progress information */\n progress: {\n /** Whether the message has been committed on destination chain */\n committed: boolean;\n /** When the message was committed (null if not committed) (ISO 8601) */\n commitTimestamp?: string | null;\n /** Whether the message has been executed on destination chain */\n executed: boolean;\n };\n /** Fee information */\n fees: {\n /** Fee token address */\n token: EvmAddress | SolAddress | null;\n /** Fee amount in wei */\n amount: bigint | null;\n };\n /** Tokens transferred in this cross-chain transaction */\n transferredTokens: ReadonlyArray<{\n /** Token address */\n token: EvmAddress | SolAddress;\n /** Token amount */\n amount: bigint;\n }>;\n /**\n * Debug information from Markr transaction API (only present for swaps that have been executed).\n *\n * Contains detailed information about the relayer execution, retry attempts, and transaction details.\n */\n debug?: Partial<{\n /** CCIP message ID */\n messageId: string;\n /** Execution status from relayer */\n status: string;\n /** Destination chain name */\n destinationChain: string;\n /** Destination swap transaction hash */\n destinationTxHash: string;\n /** Relay transaction hash */\n relayTxHash: string;\n /** Number of retry attempts */\n retryCount: number;\n /** Timestamp of last retry attempt (ISO 8601) */\n lastRetryAt: string;\n /** Source chain name */\n sourceChain: string;\n /** Source transaction hash */\n sourceTxHash: string;\n /** When the record was created (ISO 8601) */\n createdAt: string;\n }> | null;\n}\n\nconst ISO_8601_TIMEZONE_DESIGNATOR_REGEX = /[zZ]|[+-]\\d{2}:?\\d{2}$/;\n\n// Markr API returns ISO-8601 datetime strings that are sometimes missing a timezone designator (\"local\" ISO).\n// We assume these are meant to be UTC and append 'Z' if missing, then validate as strict ISO-8601 with timezone.\nconst datetime = z.iso\n .datetime({ local: true })\n .refine(\n (value) => {\n // Accept at least local ISO format\n // If missing timezone, treat as UTC\n const hasTimezone = ISO_8601_TIMEZONE_DESIGNATOR_REGEX.test(value);\n const isoString = hasTimezone ? value : value + 'Z';\n // Validate as strict ISO-8601 with timezone\n return z.iso.datetime().safeParse(isoString).success;\n },\n {\n error: 'Invalid ISO-8601 datetime (must be valid with timezone, or local assumed UTC)',\n },\n )\n .transform((value) => {\n const hasTimezone = ISO_8601_TIMEZONE_DESIGNATOR_REGEX.test(value);\n return hasTimezone ? value : value + 'Z';\n });\n\nexport const CrossChainStatusResponseSchema: z.ZodType<CrossChainStatusResponse> = z.object({\n messageId: z.string().nullable(),\n status: z.enum(['pending', 'committed', 'pending_execution', 'completed', 'failed', 'unknown']),\n description: z.string(),\n sourceChain: z.object({\n name: z.string(),\n transactionHash: z.union([HashSchema, SolSignatureSchema]),\n timestamp: datetime,\n finalized: datetime.or(z.boolean()).nullable(),\n }),\n destinationChain: z.object({\n name: z.string().nullable(),\n transactionHash: z.union([HashSchema, SolSignatureSchema]).nullable(),\n bridgeHash: z.union([HashSchema, SolSignatureSchema]).nullable().optional(),\n timestamp: datetime.nullable(),\n finalized: datetime.nullable(),\n }),\n progress: z.object({\n committed: z.boolean(),\n commitTimestamp: datetime.nullable().optional(),\n executed: z.boolean(),\n }),\n fees: z.object({\n token: z.union([EvmAddressSchema, SolAddressSchema]).nullable(),\n amount: z.coerce.bigint().nonnegative().nullable(),\n }),\n transferredTokens: z.array(\n z.object({\n token: z.union([EvmAddressSchema, SolAddressSchema]),\n amount: z.coerce.bigint().nonnegative(),\n }),\n ),\n debug: z\n .looseObject({\n messageId: z.string(),\n status: z.string(),\n destinationChain: z.string(),\n destinationTxHash: z.string(),\n relayTxHash: z.string(),\n retryCount: z.number().int().nonnegative(),\n lastRetryAt: z.iso.datetime(),\n sourceChain: z.string(),\n sourceTxHash: z.string(),\n createdAt: z.iso.datetime(),\n })\n .partial()\n .nullable()\n .optional(),\n});\n\nexport interface SpenderAddressResponse {\n address: EvmAddress;\n}\n\nexport const SpenderAddressResponseSchema: z.ZodType<SpenderAddressResponse> = z.object({\n address: EvmAddressSchema,\n});\n"],"mappings":"iJA+CA,MAAa,EAA8CA,EAAAA,EACxD,QAAQ,CACR,OAAQ,GAAUC,EAAAA,eAAe,EAAM,CAAE,CACxC,QAAS,0BACV,CAAC,CACD,UAAW,GAAU,EAAsB,CAExC,EAAwCD,EAAAA,EAAE,OAAO,CACrD,QAASA,EAAAA,EAAE,MAAM,CAACA,EAAAA,EAAE,QAAQ,CAAEA,EAAAA,EAAE,QAAQ,CAAC,CAAC,CAC1C,UAAWA,EAAAA,EAAE,QAAQ,CACrB,iBAAkBA,EAAAA,EAAE,MAAMA,EAAAA,EAA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,CAAC,aAAa,CAC1C,YAAaA,EAAAA,EAAE,IAAI,UAAU,CAC7B,YAAaA,EAAAA,EAAE,QAAQ,CACvB,aAAcA,EAAAA,EAAE,QAAQ,CACxB,UAAWA,EAAAA,EAAE,IAAI,UAAU,CAC5B,CAAC,CACD,SAAS,CACT,UAAU,CACV,UAAU,CACd,CAAC,CAMW,EAAkEA,EAAAA,EAAE,OAAO,CACtF,QAASE,EAAAA,iBACV,CAAC"}
@@ -1,2 +1,2 @@
1
- import{isCaip2ChainId as e}from"../../utils/caip.js";import{EvmAddressSchema as t,HashSchema as n,HexSchema as r,SolAddressSchema as i,SolSignatureSchema as a}from"../service-schemas.js";import{z as o}from"zod";const s=o.string().refine(t=>e(t),{message:`Invalid CAIP-2 chain ID`}).transform(e=>e),c=o.object({chainId:o.union([o.number(),o.string()]),chainType:o.string(),enabled_services:o.array(o.enum([`cross-chain-swap`,`cross-chain-quote`,`quote`,`swap`,`token-list`])),logo_url:o.url(),name:o.string(),lanes:o.array(o.union([o.coerce.number().int().nonnegative(),s]))}),l=c.extend({chainId:o.coerce.number().int().nonnegative(),chainType:o.literal(`evm`),router:t.optional(),wrapped_token:t.optional()}),u=c.extend({chainId:o.string().refine(t=>e(t)&&t.startsWith(`solana:`),{error:`Is not a valid Solana CAIP-2 ID`}).transform(e=>e),chainType:o.literal(`svm`)}),d=o.array(o.union([l,u,c.refine(e=>e.chainType!==`evm`&&e.chainType!==`svm`,`Known chain types must match their expected schema`)])),f=o.array(o.object({address:t,decimals:o.number().int().nonnegative().max(18),logo_url:o.url(),name:o.string(),symbol:o.string()})),p=o.union([o.object({aggregator:o.object({id:o.string(),logo_url:o.url(),name:o.string()}),amountIn:o.coerce.bigint().nonnegative(),amountOut:o.coerce.bigint().nonnegative(),chainId:o.union([o.number().int().nonnegative(),s]),expiredAt:o.number().int().nonnegative(),fees:o.array(o.object({type:o.enum([`protocol`,`gas`,`bridge`,`slippage`,`swap`,`other`]),name:o.string(),amount:o.coerce.bigint().nonnegative(),token:o.object({chainId:o.union([o.number().int().nonnegative(),s]),address:o.union([t,i])})})).optional(),gasEstimate:o.coerce.bigint().nonnegative().optional(),recommendedSlippage:o.number().int().nonnegative(),tokenIn:o.union([t,i]),tokenInDecimals:o.number().int().nonnegative().max(18),tokenOut:o.union([t,i]),tokenOutDecimals:o.number().int().nonnegative().max(18),uuid:o.uuid()}),o.object({done:o.literal(!0)})]),m=o.object({data:r,to:t,value:o.coerce.bigint().nonnegative()}),h=o.object({chainType:o.literal(`svm`),swapTransaction:o.base64()}),g=o.union([m,h]),_=o.object({fee:o.int().nonnegative(),name:o.string()}),v=/[zZ]|[+-]\d{2}:?\d{2}$/,y=o.iso.datetime({local:!0}).refine(e=>{let t=v.test(e)?e:e+`Z`;return o.iso.datetime().safeParse(t).success},{error:`Invalid ISO-8601 datetime (must be valid with timezone, or local assumed UTC)`}).transform(e=>v.test(e)?e:e+`Z`),b=o.object({messageId:o.string().nullable(),status:o.enum([`pending`,`committed`,`pending_execution`,`completed`,`failed`,`unknown`]),description:o.string(),sourceChain:o.object({name:o.string(),transactionHash:o.union([n,a]),timestamp:y,finalized:y.or(o.boolean()).nullable()}),destinationChain:o.object({name:o.string().nullable(),transactionHash:o.union([n,a]).nullable(),bridgeHash:o.union([n,a]).nullable().optional(),timestamp:y.nullable(),finalized:y.nullable()}),progress:o.object({committed:o.boolean(),commitTimestamp:y.nullable().optional(),executed:o.boolean()}),fees:o.object({token:o.union([t,i]).nullable(),amount:o.coerce.bigint().nonnegative().nullable()}),transferredTokens:o.array(o.object({token:o.union([t,i]),amount:o.coerce.bigint().nonnegative()})),debug:o.looseObject({messageId:o.string(),status:o.string(),destinationChain:o.string(),destinationTxHash:o.string(),relayTxHash:o.string(),retryCount:o.number().int().nonnegative(),lastRetryAt:o.iso.datetime(),sourceChain:o.string(),sourceTxHash:o.string(),createdAt:o.iso.datetime()}).nullable().optional()}),x=o.object({address:t});export{b as CrossChainStatusResponseSchema,_ as PartnerInfoResponseSchema,p as QuoteResponseSchema,x as SpenderAddressResponseSchema,d as SupportedChainsResponseSchema,g as SwapResponseSchema,f as TokenListResponseSchema};
1
+ import{isCaip2ChainId as e}from"../../utils/caip.js";import{EvmAddressSchema as t,HashSchema as n,HexSchema as r,SolAddressSchema as i,SolSignatureSchema as a}from"../service-schemas.js";import{z as o}from"zod";const s=o.string().refine(t=>e(t),{message:`Invalid CAIP-2 chain ID`}).transform(e=>e),c=o.object({chainId:o.union([o.number(),o.string()]),chainType:o.string(),enabled_services:o.array(o.enum([`cross-chain-swap`,`cross-chain-quote`,`quote`,`swap`,`token-list`])),logo_url:o.url(),name:o.string(),lanes:o.array(o.union([o.coerce.number().int().nonnegative(),s]))}),l=c.extend({chainId:o.coerce.number().int().nonnegative(),chainType:o.literal(`evm`),router:t.optional(),wrapped_token:t.optional()}),u=c.extend({chainId:o.string().refine(t=>e(t)&&t.startsWith(`solana:`),{error:`Is not a valid Solana CAIP-2 ID`}).transform(e=>e),chainType:o.literal(`svm`)}),d=o.array(o.union([l,u,c.refine(e=>e.chainType!==`evm`&&e.chainType!==`svm`,`Known chain types must match their expected schema`)])),f=o.array(o.object({address:t,decimals:o.number().int().nonnegative().max(18),logo_url:o.url(),name:o.string(),symbol:o.string()})),p=o.union([o.object({aggregator:o.object({id:o.string(),logo_url:o.url(),name:o.string()}),amountIn:o.coerce.bigint().nonnegative(),amountOut:o.coerce.bigint().nonnegative(),chainId:o.union([o.number().int().nonnegative(),s]),expiredAt:o.number().int().nonnegative(),fees:o.array(o.object({type:o.enum([`protocol`,`gas`,`bridge`,`slippage`,`swap`,`other`]),name:o.string(),amount:o.coerce.bigint().nonnegative(),token:o.object({chainId:o.union([o.number().int().nonnegative(),s]),address:o.union([t,i])})})).optional(),gasEstimate:o.coerce.bigint().nonnegative().optional(),recommendedSlippage:o.number().int().nonnegative(),tokenIn:o.union([t,i]),tokenInDecimals:o.number().int().nonnegative().max(18),tokenOut:o.union([t,i]),tokenOutDecimals:o.number().int().nonnegative().max(18),uuid:o.uuid()}),o.object({done:o.literal(!0)})]),m=o.object({data:r,to:t,value:o.coerce.bigint().nonnegative()}),h=o.object({chainType:o.literal(`svm`),swapTransaction:o.base64()}),g=o.union([m,h]),_=o.object({fee:o.int().nonnegative(),name:o.string()}),v=/[zZ]|[+-]\d{2}:?\d{2}$/,y=o.iso.datetime({local:!0}).refine(e=>{let t=v.test(e)?e:e+`Z`;return o.iso.datetime().safeParse(t).success},{error:`Invalid ISO-8601 datetime (must be valid with timezone, or local assumed UTC)`}).transform(e=>v.test(e)?e:e+`Z`),b=o.object({messageId:o.string().nullable(),status:o.enum([`pending`,`committed`,`pending_execution`,`completed`,`failed`,`unknown`]),description:o.string(),sourceChain:o.object({name:o.string(),transactionHash:o.union([n,a]),timestamp:y,finalized:y.or(o.boolean()).nullable()}),destinationChain:o.object({name:o.string().nullable(),transactionHash:o.union([n,a]).nullable(),bridgeHash:o.union([n,a]).nullable().optional(),timestamp:y.nullable(),finalized:y.nullable()}),progress:o.object({committed:o.boolean(),commitTimestamp:y.nullable().optional(),executed:o.boolean()}),fees:o.object({token:o.union([t,i]).nullable(),amount:o.coerce.bigint().nonnegative().nullable()}),transferredTokens:o.array(o.object({token:o.union([t,i]),amount:o.coerce.bigint().nonnegative()})),debug:o.looseObject({messageId:o.string(),status:o.string(),destinationChain:o.string(),destinationTxHash:o.string(),relayTxHash:o.string(),retryCount:o.number().int().nonnegative(),lastRetryAt:o.iso.datetime(),sourceChain:o.string(),sourceTxHash:o.string(),createdAt:o.iso.datetime()}).partial().nullable().optional()}),x=o.object({address:t});export{b as CrossChainStatusResponseSchema,_ as PartnerInfoResponseSchema,p as QuoteResponseSchema,x as SpenderAddressResponseSchema,d as SupportedChainsResponseSchema,g as SwapResponseSchema,f as TokenListResponseSchema};
2
2
  //# sourceMappingURL=_schema.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_schema.js","names":[],"sources":["../../../src/transfer-service/markr/_schema.ts"],"sourcesContent":["import type { Signature, Address as SolAddress } from '@solana/kit';\nimport { z } from 'zod';\nimport type { Address as EvmAddress, Hash } from 'viem';\nimport { EvmAddressSchema, HashSchema, HexSchema, SolAddressSchema, SolSignatureSchema } from '../service-schemas';\nimport { isCaip2ChainId } from '../../utils/caip';\nimport type { Caip2ChainId } from '../../types/caip';\nimport type { Hex } from '../../types/signer';\n\ninterface SupportedChainsResponseItemBase {\n chainId: number | string;\n chainType: string;\n /** Available services on the chain. Each service has specific functionality */\n enabled_services: Array<'cross-chain-swap' | 'cross-chain-quote' | 'quote' | 'swap' | 'token-list'>;\n /** Chain logo URL */\n logo_url: string;\n /** Chain display name */\n name: string;\n /**\n * List of chain IDs that this chain can swap to via cross-chain aggregators.\n *\n * Empty array means no cross-chain routes available.\n */\n lanes: ReadonlyArray<number | Caip2ChainId>;\n}\n\nexport interface SupportedChainsResponseItemEvm extends SupportedChainsResponseItemBase {\n /** Chain identifier */\n chainId: number;\n /** Chain virtual machine type */\n chainType: 'evm';\n /** Router contract address */\n router?: EvmAddress;\n /** Native token wrapped contract address */\n wrapped_token?: EvmAddress;\n}\n\nexport interface SupportedChainsResponseItemSvm extends SupportedChainsResponseItemBase {\n /** Chain identifier */\n chainId: Caip2ChainId;\n /** Chain virtual machine type */\n chainType: 'svm';\n}\n\nexport type SupportedChainsResponse = Array<\n SupportedChainsResponseItemEvm | SupportedChainsResponseItemSvm | SupportedChainsResponseItemBase\n>;\n\nexport const Caip2ChainIdSchema: z.ZodType<Caip2ChainId> = z\n .string()\n .refine((value) => isCaip2ChainId(value), {\n message: 'Invalid CAIP-2 chain ID',\n })\n .transform((value) => value as Caip2ChainId);\n\nconst SupportedChainsResponseItemBaseSchema = z.object({\n chainId: z.union([z.number(), z.string()]),\n chainType: z.string(),\n enabled_services: z.array(z.enum(['cross-chain-swap', 'cross-chain-quote', 'quote', 'swap', 'token-list'])),\n logo_url: z.url(),\n name: z.string(),\n lanes: z.array(z.union([z.coerce.number().int().nonnegative(), Caip2ChainIdSchema])),\n});\n\nconst SupportedChainsResponseItemEvmSchema: z.ZodType<SupportedChainsResponseItemEvm> =\n SupportedChainsResponseItemBaseSchema.extend({\n chainId: z.coerce.number().int().nonnegative(),\n chainType: z.literal('evm'),\n router: EvmAddressSchema.optional(),\n wrapped_token: EvmAddressSchema.optional(),\n });\n\nconst SupportedChainsResponseItemSvmSchema: z.ZodType<SupportedChainsResponseItemSvm> =\n SupportedChainsResponseItemBaseSchema.extend({\n chainId: z\n .string()\n .refine((value) => isCaip2ChainId(value) && value.startsWith('solana:'), {\n error: 'Is not a valid Solana CAIP-2 ID',\n })\n .transform((value) => value as Caip2ChainId),\n chainType: z.literal('svm'),\n });\n\n/**\n * Schema for the response from Markr's /info/chains endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1info~1chains/get\n */\nexport const SupportedChainsResponseSchema: z.ZodType<SupportedChainsResponse> = z.array(\n z.union([\n SupportedChainsResponseItemEvmSchema,\n SupportedChainsResponseItemSvmSchema,\n SupportedChainsResponseItemBaseSchema.refine(\n (item) => item.chainType !== 'evm' && item.chainType !== 'svm',\n 'Known chain types must match their expected schema',\n ),\n ]),\n);\n\nexport type TokenListResponse = Array<{\n address: EvmAddress;\n decimals: number;\n logo_url: string;\n name: string;\n symbol: string;\n}>;\n\n/**\n * Schema for the response Markr's /tokens/{chainId}/list endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1tokens~1%7BchainId%7D~1list/get\n */\nexport const TokenListResponseSchema: z.ZodType<TokenListResponse> = z.array(\n z.object({\n address: EvmAddressSchema,\n decimals: z.number().int().nonnegative().max(18),\n logo_url: z.url(),\n name: z.string(),\n symbol: z.string(),\n }),\n);\n\nexport interface QuoteResponseData {\n aggregator: {\n id: string;\n logo_url: string;\n name: string;\n };\n amountIn: bigint;\n amountOut: bigint;\n /** Chain identifier (number for EVM chains, CAIP-2 ID for SVM chains) */\n chainId: number | Caip2ChainId;\n expiredAt: number;\n /**\n * Fee breakdown for cross-chain bridge transactions.\n *\n * Only included in quotes from cross-chain aggregators (DeBridge, LiFi).\n */\n fees?: ReadonlyArray<{\n type: 'protocol' | 'gas' | 'bridge' | 'slippage' | 'swap' | 'other';\n /** Human-readable fee name */\n name: string;\n /** Fee amount in token's smallest unit */\n amount: bigint;\n /** Token the fee is deducted from */\n token: {\n /** Chain ID where fee is deducted */\n chainId: number | Caip2ChainId;\n /** Token address (EVM hex or Solana base58) */\n address: EvmAddress | SolAddress;\n };\n }>;\n gasEstimate?: bigint;\n recommendedSlippage: number;\n /** Input token address (EVM hex or Solana base58) */\n tokenIn: EvmAddress | SolAddress;\n tokenInDecimals: number;\n /** Output token address (EVM hex or Solana base58) */\n tokenOut: EvmAddress | SolAddress;\n tokenOutDecimals: number;\n uuid: string;\n}\n\nexport interface QuoteResponseDataDone {\n done: true;\n}\n\nexport type QuoteResponse = QuoteResponseData | QuoteResponseDataDone;\n\n/**\n * Schema for the response from Markr's /quote endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1quote/post\n */\nexport const QuoteResponseSchema: z.ZodType<QuoteResponse> = z.union([\n z.object({\n aggregator: z.object({\n id: z.string(),\n logo_url: z.url(),\n name: z.string(),\n }),\n amountIn: z.coerce.bigint().nonnegative(),\n amountOut: z.coerce.bigint().nonnegative(),\n chainId: z.union([z.number().int().nonnegative(), Caip2ChainIdSchema]),\n /**\n * Unix time in seconds when the quote expires.\n */\n expiredAt: z.number().int().nonnegative(),\n fees: z\n .array(\n z.object({\n type: z.enum(['protocol', 'gas', 'bridge', 'slippage', 'swap', 'other']),\n name: z.string(),\n amount: z.coerce.bigint().nonnegative(),\n token: z.object({\n chainId: z.union([z.number().int().nonnegative(), Caip2ChainIdSchema]),\n address: z.union([EvmAddressSchema, SolAddressSchema]),\n }),\n }),\n )\n .optional(),\n /**\n * Estimated gas for the swap transaction.\n * Markr estimates already include a buffer.\n *\n * The API docs do not specify this field as optional, but in practice it can be missing.\n */\n gasEstimate: z.coerce.bigint().nonnegative().optional(),\n /** Recommended slippage in basis points. */\n recommendedSlippage: z.number().int().nonnegative(),\n tokenIn: z.union([EvmAddressSchema, SolAddressSchema]),\n tokenInDecimals: z.number().int().nonnegative().max(18),\n tokenOut: z.union([EvmAddressSchema, SolAddressSchema]),\n tokenOutDecimals: z.number().int().nonnegative().max(18),\n uuid: z.uuid(),\n }),\n z.object({\n done: z.literal(true),\n }),\n]);\n\n/**\n * Response type for Markr's /swap endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1swap/post\n */\nexport interface WrappedSwapTransactionResponse {\n data: Hex;\n to: EvmAddress;\n value: bigint;\n}\n\nexport const WrappedSwapTransactionResponseSchema: z.ZodType<WrappedSwapTransactionResponse> = z.object({\n data: HexSchema,\n to: EvmAddressSchema,\n value: z.coerce.bigint().nonnegative(),\n});\n\n/**\n * Solana swap transaction (returned for SVM chains).\n */\nexport interface SolanaSwapTransactionResponse {\n /** Chain type identifier */\n chainType: 'svm';\n /** Base64-encoded Solana transaction to be signed and sent by the client */\n swapTransaction: string;\n}\n\nexport const SolanaSwapTransactionResponseSchema: z.ZodType<SolanaSwapTransactionResponse> = z.object({\n chainType: z.literal('svm'),\n swapTransaction: z.base64(),\n});\n\nexport type SwapResponse = WrappedSwapTransactionResponse | SolanaSwapTransactionResponse;\n\nexport const SwapResponseSchema: z.ZodType<SwapResponse> = z.union([\n WrappedSwapTransactionResponseSchema,\n SolanaSwapTransactionResponseSchema,\n]);\n\nexport interface PartnerInfoResponse {\n /**\n * The partner fee in basis points collected on each swap.\n */\n fee: number;\n name: string;\n}\n\nexport const PartnerInfoResponseSchema: z.ZodType<PartnerInfoResponse> = z.object({\n fee: z.int().nonnegative(),\n name: z.string(),\n});\n\n/**\n * If the destination token is USDC, the flow is:\n * - pending -> committed -> completed\n *\n * If the destination token is not USDC, the flow is:\n * - pending -> committed -> pending_execution -> completed\n *\n * If the transaction fails at any point, the status will be 'failed'.\n */\nexport type CrossChainStatus =\n | /** Transaction submitted to CCIP */\n 'pending'\n /** Message committed, awaiting execution on destination chain */\n | 'committed'\n /** Message received on destination, swap pending execution by relayer */\n | 'pending_execution'\n /** Message executed successfully on destination chain */\n | 'completed'\n /** Execution failed */\n | 'failed'\n /** Unknown state */\n | 'unknown';\n\nexport interface CrossChainStatusResponse {\n /** CCIP message ID */\n messageId: string | null;\n /** Current status of the cross-chain transaction. */\n status: CrossChainStatus;\n /** Human-readable status description */\n description: string;\n /** Source chain information */\n sourceChain: {\n /** Source chain network name */\n name: string;\n /** Source chain transaction hash */\n transactionHash: Hash | Signature;\n /** Transaction timestamp on source chain (ISO 8601) */\n timestamp: string;\n /** When the source transaction was finalized (ISO 8601) */\n finalized: string | boolean | null;\n };\n /** Destination chain information */\n destinationChain: {\n /** Destination chain network name */\n name: string | null;\n /**\n * Destination chain tx hash.\n *\n * - For direct transfers (USDC -> USDC): The CCIP bridge transaction hash.\n * - For successful swaps: The actual swap transaction hash from the relayer.\n * - For pending swaps: null (swap not yet executed).\n */\n transactionHash: Hash | Signature | null;\n /**\n * CCIP bridge tx hash (only present for swaps, not direct transfers).\n *\n * This is the transaction that delivered USDC to the destination chain via CCIP.\n * The `transactionHash` field contains the subsequent swap transaction.\n */\n bridgeHash?: Hash | Signature | null;\n /** Transaction timestamp on destination chain (null if not yet executed) (ISO 8601) */\n timestamp: string | null;\n /** When the destination transaction was finalized (null if not yet executed) (ISO 8601) */\n finalized: string | null;\n };\n /** Transaction progress information */\n progress: {\n /** Whether the message has been committed on destination chain */\n committed: boolean;\n /** When the message was committed (null if not committed) (ISO 8601) */\n commitTimestamp?: string | null;\n /** Whether the message has been executed on destination chain */\n executed: boolean;\n };\n /** Fee information */\n fees: {\n /** Fee token address */\n token: EvmAddress | SolAddress | null;\n /** Fee amount in wei */\n amount: bigint | null;\n };\n /** Tokens transferred in this cross-chain transaction */\n transferredTokens: ReadonlyArray<{\n /** Token address */\n token: EvmAddress | SolAddress;\n /** Token amount */\n amount: bigint;\n }>;\n /**\n * Debug information from Markr transaction API (only present for swaps that have been executed).\n *\n * Contains detailed information about the relayer execution, retry attempts, and transaction details.\n */\n debug?: {\n /** CCIP message ID */\n messageId: string;\n /** Execution status from relayer */\n status: string;\n /** Destination chain name */\n destinationChain: string;\n /** Destination swap transaction hash */\n destinationTxHash: string;\n /** Relay transaction hash */\n relayTxHash: string;\n /** Number of retry attempts */\n retryCount: number;\n /** Timestamp of last retry attempt (ISO 8601) */\n lastRetryAt: string;\n /** Source chain name */\n sourceChain: string;\n /** Source transaction hash */\n sourceTxHash: string;\n /** When the record was created (ISO 8601) */\n createdAt: string;\n } | null;\n}\n\nconst ISO_8601_TIMEZONE_DESIGNATOR_REGEX = /[zZ]|[+-]\\d{2}:?\\d{2}$/;\n\n// Markr API returns ISO-8601 datetime strings that are sometimes missing a timezone designator (\"local\" ISO).\n// We assume these are meant to be UTC and append 'Z' if missing, then validate as strict ISO-8601 with timezone.\nconst datetime = z.iso\n .datetime({ local: true })\n .refine(\n (value) => {\n // Accept at least local ISO format\n // If missing timezone, treat as UTC\n const hasTimezone = ISO_8601_TIMEZONE_DESIGNATOR_REGEX.test(value);\n const isoString = hasTimezone ? value : value + 'Z';\n // Validate as strict ISO-8601 with timezone\n return z.iso.datetime().safeParse(isoString).success;\n },\n {\n error: 'Invalid ISO-8601 datetime (must be valid with timezone, or local assumed UTC)',\n },\n )\n .transform((value) => {\n const hasTimezone = ISO_8601_TIMEZONE_DESIGNATOR_REGEX.test(value);\n return hasTimezone ? value : value + 'Z';\n });\n\nexport const CrossChainStatusResponseSchema: z.ZodType<CrossChainStatusResponse> = z.object({\n messageId: z.string().nullable(),\n status: z.enum(['pending', 'committed', 'pending_execution', 'completed', 'failed', 'unknown']),\n description: z.string(),\n sourceChain: z.object({\n name: z.string(),\n transactionHash: z.union([HashSchema, SolSignatureSchema]),\n timestamp: datetime,\n finalized: datetime.or(z.boolean()).nullable(),\n }),\n destinationChain: z.object({\n name: z.string().nullable(),\n transactionHash: z.union([HashSchema, SolSignatureSchema]).nullable(),\n bridgeHash: z.union([HashSchema, SolSignatureSchema]).nullable().optional(),\n timestamp: datetime.nullable(),\n finalized: datetime.nullable(),\n }),\n progress: z.object({\n committed: z.boolean(),\n commitTimestamp: datetime.nullable().optional(),\n executed: z.boolean(),\n }),\n fees: z.object({\n token: z.union([EvmAddressSchema, SolAddressSchema]).nullable(),\n amount: z.coerce.bigint().nonnegative().nullable(),\n }),\n transferredTokens: z.array(\n z.object({\n token: z.union([EvmAddressSchema, SolAddressSchema]),\n amount: z.coerce.bigint().nonnegative(),\n }),\n ),\n debug: z\n .looseObject({\n messageId: z.string(),\n status: z.string(),\n destinationChain: z.string(),\n destinationTxHash: z.string(),\n relayTxHash: z.string(),\n retryCount: z.number().int().nonnegative(),\n lastRetryAt: z.iso.datetime(),\n sourceChain: z.string(),\n sourceTxHash: z.string(),\n createdAt: z.iso.datetime(),\n })\n .nullable()\n .optional(),\n});\n\nexport interface SpenderAddressResponse {\n address: EvmAddress;\n}\n\nexport const SpenderAddressResponseSchema: z.ZodType<SpenderAddressResponse> = z.object({\n address: EvmAddressSchema,\n});\n"],"mappings":"mNA+CA,MAAa,EAA8C,EACxD,QAAQ,CACR,OAAQ,GAAU,EAAe,EAAM,CAAE,CACxC,QAAS,0BACV,CAAC,CACD,UAAW,GAAU,EAAsB,CAExC,EAAwC,EAAE,OAAO,CACrD,QAAS,EAAE,MAAM,CAAC,EAAE,QAAQ,CAAE,EAAE,QAAQ,CAAC,CAAC,CAC1C,UAAW,EAAE,QAAQ,CACrB,iBAAkB,EAAE,MAAM,EAAE,KAAK,CAAC,mBAAoB,oBAAqB,QAAS,OAAQ,aAAa,CAAC,CAAC,CAC3G,SAAU,EAAE,KAAK,CACjB,KAAM,EAAE,QAAQ,CAChB,MAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,QAAQ,CAAC,KAAK,CAAC,aAAa,CAAE,EAAmB,CAAC,CAAC,CACrF,CAAC,CAEI,EACJ,EAAsC,OAAO,CAC3C,QAAS,EAAE,OAAO,QAAQ,CAAC,KA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WAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC1C,YAAa,EAAE,IAAI,UAAU,CAC7B,YAAa,EAAE,QAAQ,CACvB,aAAc,EAAE,QAAQ,CACxB,UAAW,EAAE,IAAI,UAAU,CAC5B,CAAC,CACD,UAAU,CACV,UAAU,CACd,CAAC,CAMW,EAAkE,EAAE,OAAO,CACtF,QAAS,EACV,CAAC"}
1
+ {"version":3,"file":"_schema.js","names":[],"sources":["../../../src/transfer-service/markr/_schema.ts"],"sourcesContent":["import type { Signature, Address as SolAddress } from '@solana/kit';\nimport { z } from 'zod';\nimport type { Address as EvmAddress, Hash } from 'viem';\nimport { EvmAddressSchema, HashSchema, HexSchema, SolAddressSchema, SolSignatureSchema } from '../service-schemas';\nimport { isCaip2ChainId } from '../../utils/caip';\nimport type { Caip2ChainId } from '../../types/caip';\nimport type { Hex } from '../../types/signer';\n\ninterface SupportedChainsResponseItemBase {\n chainId: number | string;\n chainType: string;\n /** Available services on the chain. Each service has specific functionality */\n enabled_services: Array<'cross-chain-swap' | 'cross-chain-quote' | 'quote' | 'swap' | 'token-list'>;\n /** Chain logo URL */\n logo_url: string;\n /** Chain display name */\n name: string;\n /**\n * List of chain IDs that this chain can swap to via cross-chain aggregators.\n *\n * Empty array means no cross-chain routes available.\n */\n lanes: ReadonlyArray<number | Caip2ChainId>;\n}\n\nexport interface SupportedChainsResponseItemEvm extends SupportedChainsResponseItemBase {\n /** Chain identifier */\n chainId: number;\n /** Chain virtual machine type */\n chainType: 'evm';\n /** Router contract address */\n router?: EvmAddress;\n /** Native token wrapped contract address */\n wrapped_token?: EvmAddress;\n}\n\nexport interface SupportedChainsResponseItemSvm extends SupportedChainsResponseItemBase {\n /** Chain identifier */\n chainId: Caip2ChainId;\n /** Chain virtual machine type */\n chainType: 'svm';\n}\n\nexport type SupportedChainsResponse = Array<\n SupportedChainsResponseItemEvm | SupportedChainsResponseItemSvm | SupportedChainsResponseItemBase\n>;\n\nexport const Caip2ChainIdSchema: z.ZodType<Caip2ChainId> = z\n .string()\n .refine((value) => isCaip2ChainId(value), {\n message: 'Invalid CAIP-2 chain ID',\n })\n .transform((value) => value as Caip2ChainId);\n\nconst SupportedChainsResponseItemBaseSchema = z.object({\n chainId: z.union([z.number(), z.string()]),\n chainType: z.string(),\n enabled_services: z.array(z.enum(['cross-chain-swap', 'cross-chain-quote', 'quote', 'swap', 'token-list'])),\n logo_url: z.url(),\n name: z.string(),\n lanes: z.array(z.union([z.coerce.number().int().nonnegative(), Caip2ChainIdSchema])),\n});\n\nconst SupportedChainsResponseItemEvmSchema: z.ZodType<SupportedChainsResponseItemEvm> =\n SupportedChainsResponseItemBaseSchema.extend({\n chainId: z.coerce.number().int().nonnegative(),\n chainType: z.literal('evm'),\n router: EvmAddressSchema.optional(),\n wrapped_token: EvmAddressSchema.optional(),\n });\n\nconst SupportedChainsResponseItemSvmSchema: z.ZodType<SupportedChainsResponseItemSvm> =\n SupportedChainsResponseItemBaseSchema.extend({\n chainId: z\n .string()\n .refine((value) => isCaip2ChainId(value) && value.startsWith('solana:'), {\n error: 'Is not a valid Solana CAIP-2 ID',\n })\n .transform((value) => value as Caip2ChainId),\n chainType: z.literal('svm'),\n });\n\n/**\n * Schema for the response from Markr's /info/chains endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1info~1chains/get\n */\nexport const SupportedChainsResponseSchema: z.ZodType<SupportedChainsResponse> = z.array(\n z.union([\n SupportedChainsResponseItemEvmSchema,\n SupportedChainsResponseItemSvmSchema,\n SupportedChainsResponseItemBaseSchema.refine(\n (item) => item.chainType !== 'evm' && item.chainType !== 'svm',\n 'Known chain types must match their expected schema',\n ),\n ]),\n);\n\nexport type TokenListResponse = Array<{\n address: EvmAddress;\n decimals: number;\n logo_url: string;\n name: string;\n symbol: string;\n}>;\n\n/**\n * Schema for the response Markr's /tokens/{chainId}/list endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1tokens~1%7BchainId%7D~1list/get\n */\nexport const TokenListResponseSchema: z.ZodType<TokenListResponse> = z.array(\n z.object({\n address: EvmAddressSchema,\n decimals: z.number().int().nonnegative().max(18),\n logo_url: z.url(),\n name: z.string(),\n symbol: z.string(),\n }),\n);\n\nexport interface QuoteResponseData {\n aggregator: {\n id: string;\n logo_url: string;\n name: string;\n };\n amountIn: bigint;\n amountOut: bigint;\n /** Chain identifier (number for EVM chains, CAIP-2 ID for SVM chains) */\n chainId: number | Caip2ChainId;\n expiredAt: number;\n /**\n * Fee breakdown for cross-chain bridge transactions.\n *\n * Only included in quotes from cross-chain aggregators (DeBridge, LiFi).\n */\n fees?: ReadonlyArray<{\n type: 'protocol' | 'gas' | 'bridge' | 'slippage' | 'swap' | 'other';\n /** Human-readable fee name */\n name: string;\n /** Fee amount in token's smallest unit */\n amount: bigint;\n /** Token the fee is deducted from */\n token: {\n /** Chain ID where fee is deducted */\n chainId: number | Caip2ChainId;\n /** Token address (EVM hex or Solana base58) */\n address: EvmAddress | SolAddress;\n };\n }>;\n gasEstimate?: bigint;\n recommendedSlippage: number;\n /** Input token address (EVM hex or Solana base58) */\n tokenIn: EvmAddress | SolAddress;\n tokenInDecimals: number;\n /** Output token address (EVM hex or Solana base58) */\n tokenOut: EvmAddress | SolAddress;\n tokenOutDecimals: number;\n uuid: string;\n}\n\nexport interface QuoteResponseDataDone {\n done: true;\n}\n\nexport type QuoteResponse = QuoteResponseData | QuoteResponseDataDone;\n\n/**\n * Schema for the response from Markr's /quote endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1quote/post\n */\nexport const QuoteResponseSchema: z.ZodType<QuoteResponse> = z.union([\n z.object({\n aggregator: z.object({\n id: z.string(),\n logo_url: z.url(),\n name: z.string(),\n }),\n amountIn: z.coerce.bigint().nonnegative(),\n amountOut: z.coerce.bigint().nonnegative(),\n chainId: z.union([z.number().int().nonnegative(), Caip2ChainIdSchema]),\n /**\n * Unix time in seconds when the quote expires.\n */\n expiredAt: z.number().int().nonnegative(),\n fees: z\n .array(\n z.object({\n type: z.enum(['protocol', 'gas', 'bridge', 'slippage', 'swap', 'other']),\n name: z.string(),\n amount: z.coerce.bigint().nonnegative(),\n token: z.object({\n chainId: z.union([z.number().int().nonnegative(), Caip2ChainIdSchema]),\n address: z.union([EvmAddressSchema, SolAddressSchema]),\n }),\n }),\n )\n .optional(),\n /**\n * Estimated gas for the swap transaction.\n * Markr estimates already include a buffer.\n *\n * The API docs do not specify this field as optional, but in practice it can be missing.\n */\n gasEstimate: z.coerce.bigint().nonnegative().optional(),\n /** Recommended slippage in basis points. */\n recommendedSlippage: z.number().int().nonnegative(),\n tokenIn: z.union([EvmAddressSchema, SolAddressSchema]),\n tokenInDecimals: z.number().int().nonnegative().max(18),\n tokenOut: z.union([EvmAddressSchema, SolAddressSchema]),\n tokenOutDecimals: z.number().int().nonnegative().max(18),\n uuid: z.uuid(),\n }),\n z.object({\n done: z.literal(true),\n }),\n]);\n\n/**\n * Response type for Markr's /swap endpoint.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1swap/post\n */\nexport interface WrappedSwapTransactionResponse {\n data: Hex;\n to: EvmAddress;\n value: bigint;\n}\n\nexport const WrappedSwapTransactionResponseSchema: z.ZodType<WrappedSwapTransactionResponse> = z.object({\n data: HexSchema,\n to: EvmAddressSchema,\n value: z.coerce.bigint().nonnegative(),\n});\n\n/**\n * Solana swap transaction (returned for SVM chains).\n */\nexport interface SolanaSwapTransactionResponse {\n /** Chain type identifier */\n chainType: 'svm';\n /** Base64-encoded Solana transaction to be signed and sent by the client */\n swapTransaction: string;\n}\n\nexport const SolanaSwapTransactionResponseSchema: z.ZodType<SolanaSwapTransactionResponse> = z.object({\n chainType: z.literal('svm'),\n swapTransaction: z.base64(),\n});\n\nexport type SwapResponse = WrappedSwapTransactionResponse | SolanaSwapTransactionResponse;\n\nexport const SwapResponseSchema: z.ZodType<SwapResponse> = z.union([\n WrappedSwapTransactionResponseSchema,\n SolanaSwapTransactionResponseSchema,\n]);\n\nexport interface PartnerInfoResponse {\n /**\n * The partner fee in basis points collected on each swap.\n */\n fee: number;\n name: string;\n}\n\nexport const PartnerInfoResponseSchema: z.ZodType<PartnerInfoResponse> = z.object({\n fee: z.int().nonnegative(),\n name: z.string(),\n});\n\n/**\n * If the destination token is USDC, the flow is:\n * - pending -> committed -> completed\n *\n * If the destination token is not USDC, the flow is:\n * - pending -> committed -> pending_execution -> completed\n *\n * If the transaction fails at any point, the status will be 'failed'.\n */\nexport type CrossChainStatus =\n | /** Transaction submitted to CCIP */\n 'pending'\n /** Message committed, awaiting execution on destination chain */\n | 'committed'\n /** Message received on destination, swap pending execution by relayer */\n | 'pending_execution'\n /** Message executed successfully on destination chain */\n | 'completed'\n /** Execution failed */\n | 'failed'\n /** Unknown state */\n | 'unknown';\n\nexport interface CrossChainStatusResponse {\n /** CCIP message ID */\n messageId: string | null;\n /** Current status of the cross-chain transaction. */\n status: CrossChainStatus;\n /** Human-readable status description */\n description: string;\n /** Source chain information */\n sourceChain: {\n /** Source chain network name */\n name: string;\n /** Source chain transaction hash */\n transactionHash: Hash | Signature;\n /** Transaction timestamp on source chain (ISO 8601) */\n timestamp: string;\n /** When the source transaction was finalized (ISO 8601) */\n finalized: string | boolean | null;\n };\n /** Destination chain information */\n destinationChain: {\n /** Destination chain network name */\n name: string | null;\n /**\n * Destination chain tx hash.\n *\n * - For direct transfers (USDC -> USDC): The CCIP bridge transaction hash.\n * - For successful swaps: The actual swap transaction hash from the relayer.\n * - For pending swaps: null (swap not yet executed).\n */\n transactionHash: Hash | Signature | null;\n /**\n * CCIP bridge tx hash (only present for swaps, not direct transfers).\n *\n * This is the transaction that delivered USDC to the destination chain via CCIP.\n * The `transactionHash` field contains the subsequent swap transaction.\n */\n bridgeHash?: Hash | Signature | null;\n /** Transaction timestamp on destination chain (null if not yet executed) (ISO 8601) */\n timestamp: string | null;\n /** When the destination transaction was finalized (null if not yet executed) (ISO 8601) */\n finalized: string | null;\n };\n /** Transaction progress information */\n progress: {\n /** Whether the message has been committed on destination chain */\n committed: boolean;\n /** When the message was committed (null if not committed) (ISO 8601) */\n commitTimestamp?: string | null;\n /** Whether the message has been executed on destination chain */\n executed: boolean;\n };\n /** Fee information */\n fees: {\n /** Fee token address */\n token: EvmAddress | SolAddress | null;\n /** Fee amount in wei */\n amount: bigint | null;\n };\n /** Tokens transferred in this cross-chain transaction */\n transferredTokens: ReadonlyArray<{\n /** Token address */\n token: EvmAddress | SolAddress;\n /** Token amount */\n amount: bigint;\n }>;\n /**\n * Debug information from Markr transaction API (only present for swaps that have been executed).\n *\n * Contains detailed information about the relayer execution, retry attempts, and transaction details.\n */\n debug?: Partial<{\n /** CCIP message ID */\n messageId: string;\n /** Execution status from relayer */\n status: string;\n /** Destination chain name */\n destinationChain: string;\n /** Destination swap transaction hash */\n destinationTxHash: string;\n /** Relay transaction hash */\n relayTxHash: string;\n /** Number of retry attempts */\n retryCount: number;\n /** Timestamp of last retry attempt (ISO 8601) */\n lastRetryAt: string;\n /** Source chain name */\n sourceChain: string;\n /** Source transaction hash */\n sourceTxHash: string;\n /** When the record was created (ISO 8601) */\n createdAt: string;\n }> | null;\n}\n\nconst ISO_8601_TIMEZONE_DESIGNATOR_REGEX = /[zZ]|[+-]\\d{2}:?\\d{2}$/;\n\n// Markr API returns ISO-8601 datetime strings that are sometimes missing a timezone designator (\"local\" ISO).\n// We assume these are meant to be UTC and append 'Z' if missing, then validate as strict ISO-8601 with timezone.\nconst datetime = z.iso\n .datetime({ local: true })\n .refine(\n (value) => {\n // Accept at least local ISO format\n // If missing timezone, treat as UTC\n const hasTimezone = ISO_8601_TIMEZONE_DESIGNATOR_REGEX.test(value);\n const isoString = hasTimezone ? value : value + 'Z';\n // Validate as strict ISO-8601 with timezone\n return z.iso.datetime().safeParse(isoString).success;\n },\n {\n error: 'Invalid ISO-8601 datetime (must be valid with timezone, or local assumed UTC)',\n },\n )\n .transform((value) => {\n const hasTimezone = ISO_8601_TIMEZONE_DESIGNATOR_REGEX.test(value);\n return hasTimezone ? value : value + 'Z';\n });\n\nexport const CrossChainStatusResponseSchema: z.ZodType<CrossChainStatusResponse> = z.object({\n messageId: z.string().nullable(),\n status: z.enum(['pending', 'committed', 'pending_execution', 'completed', 'failed', 'unknown']),\n description: z.string(),\n sourceChain: z.object({\n name: z.string(),\n transactionHash: z.union([HashSchema, SolSignatureSchema]),\n timestamp: datetime,\n finalized: datetime.or(z.boolean()).nullable(),\n }),\n destinationChain: z.object({\n name: z.string().nullable(),\n transactionHash: z.union([HashSchema, SolSignatureSchema]).nullable(),\n bridgeHash: z.union([HashSchema, SolSignatureSchema]).nullable().optional(),\n timestamp: datetime.nullable(),\n finalized: datetime.nullable(),\n }),\n progress: z.object({\n committed: z.boolean(),\n commitTimestamp: datetime.nullable().optional(),\n executed: z.boolean(),\n }),\n fees: z.object({\n token: z.union([EvmAddressSchema, SolAddressSchema]).nullable(),\n amount: z.coerce.bigint().nonnegative().nullable(),\n }),\n transferredTokens: z.array(\n z.object({\n token: z.union([EvmAddressSchema, SolAddressSchema]),\n amount: z.coerce.bigint().nonnegative(),\n }),\n ),\n debug: z\n .looseObject({\n messageId: z.string(),\n status: z.string(),\n destinationChain: z.string(),\n destinationTxHash: z.string(),\n relayTxHash: z.string(),\n retryCount: z.number().int().nonnegative(),\n lastRetryAt: z.iso.datetime(),\n sourceChain: z.string(),\n sourceTxHash: z.string(),\n createdAt: z.iso.datetime(),\n })\n .partial()\n .nullable()\n .optional(),\n});\n\nexport interface SpenderAddressResponse {\n address: EvmAddress;\n}\n\nexport const SpenderAddressResponseSchema: z.ZodType<SpenderAddressResponse> = z.object({\n address: EvmAddressSchema,\n});\n"],"mappings":"mNA+CA,MAAa,EAA8C,EACxD,QAAQ,CACR,OAAQ,GAAU,EAAe,EAAM,CAAE,CACxC,QAAS,0BACV,CAAC,CACD,UAAW,GAAU,EAAsB,CAExC,EAAwC,EAAE,OAAO,CACrD,QAAS,EAAE,MAAM,CAAC,EAAE,QAAQ,CAAE,EAAE,QAAQ,CAAC,CAAC,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AAO,QAAQ,CAAC,aAAa,CAAC,UAAU,CACnD,CAAC,CACF,kBAAmB,EAAE,MACnB,EAAE,OAAO,CACP,MAAO,EAAE,MAAM,CAAC,EAAkB,EAAiB,CAAC,CACpD,OAAQ,EAAE,OAAO,QAAQ,CAAC,aAAa,CACxC,CAAC,CACH,CACD,MAAO,EACJ,YAAY,CACX,UAAW,EAAE,QAAQ,CACrB,OAAQ,EAAE,QAAQ,CAClB,iBAAkB,EAAE,QAAQ,CAC5B,kBAAmB,EAAE,QAAQ,CAC7B,YAAa,EAAE,QAAQ,CACvB,WAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC1C,YAAa,EAAE,IAAI,UAAU,CAC7B,YAAa,EAAE,QAAQ,CACvB,aAAc,EAAE,QAAQ,CACxB,UAAW,EAAE,IAAI,UAAU,CAC5B,CAAC,CACD,SAAS,CACT,UAAU,CACV,UAAU,CACd,CAAC,CAMW,EAAkE,EAAE,OAAO,CACtF,QAAS,EACV,CAAC"}
@@ -1,2 +1,2 @@
1
- require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../constants.cjs`),t=require(`../../errors.cjs`),n=require(`../../utils/caip.cjs`),r=require(`../../utils/evm-address.cjs`),i=require(`../../_utils/chain.cjs`),a=require(`../../_utils/math.cjs`),o=require(`./_api.cjs`),s=require(`../../utils/sol-address.cjs`);let c=require(`viem`);function l(e,t,n){let r=e.get(t),i=e.get(n);return!r||!i?!1:t===n?r.swapEnabled:r.crossChainSwapEnabled&&r.crossChainTargetChainIds.has(n)}async function u(e,r=!1){let i=new Map;try{let t=(await o.markrGetInfoChains(e)).filter(e=>e.chainType===`evm`||e.chainType===`svm`);for(let e of t){let t=typeof e.chainId==`number`?n.eip155ChainIdToCaip2(e.chainId):e.chainId,a=e.enabled_services.includes(`cross-chain-quote`)&&e.enabled_services.includes(`cross-chain-swap`),o=e.enabled_services.includes(`quote`)&&e.enabled_services.includes(`swap`),s=new Set;for(let r of e.lanes){let e=typeof r==`number`?n.eip155ChainIdToCaip2(r):r;e!==t&&s.add(e)}let c=r?!1:a,l=c?s:new Set;!o&&l.size===0||i.set(t,{chainId:e.chainId,crossChainSwapEnabled:c,crossChainTargetChainIds:l,swapEnabled:o,tokenList:e.enabled_services.includes(`token-list`)})}}catch(e){throw new t.SdkError(t.ErrorReason.UNKNOWN,t.ErrorCode.INITIALIZATION_FAILED,{cause:e,details:`Failed to fetch supported chains from Markr API.`})}return i}async function d(e,t){let n=new Map;for(let[r,i]of t.entries())if(typeof i.chainId==`number`&&i.tokenList&&(i.crossChainSwapEnabled||i.swapEnabled))try{let t=o.markrGetTokenList(e,i.chainId);n.set(r,t)}catch{}return n}function f(t){return t===e.ERC_ZERO_ADDRESS||t===e.SOL_MINT_ADDRESS}function p(t,n){return t.type===e.TokenType.NATIVE?i.isSolanaNamespace(n)?e.SOL_MINT_ADDRESS:e.ERC_ZERO_ADDRESS:t.address}function m({amountOut:e,assetOut:t,slippageBps:n}){let r=a.calculateMinimumAmountOut({amountOut:e,assetOut:t,slippageBps:n});return e>0n&&r===0n?1n:r}function h(t,n,r){let i=t.amountOut*BigInt(r)/10000n,a=t.amountOut-i,o=[..._(t.fees),{type:`partner`,name:`Core Fee`,amount:i,chainId:n.targetChain.chainId,token:v(n.targetAsset)}];return{aggregator:{id:t.aggregator.id,logoUrl:t.aggregator.logo_url,name:t.aggregator.name},amountIn:t.amountIn,amountOut:a,assetIn:n.sourceAsset,assetOut:n.targetAsset,expiresAt:t.expiredAt,fees:o,fromAddress:n.fromAddress,gasEstimate:t.gasEstimate,id:t.uuid,partnerFeeBps:r,serviceType:e.ServiceType.MARKR,slippageBps:n.slippageBps??t.recommendedSlippage,sourceChain:n.sourceChain,targetChain:n.targetChain,toAddress:n.toAddress}}async function g(e){try{return(await o.markrGetPartnerInfo(e)).fee}catch(e){throw new t.SdkError(t.ErrorReason.UNKNOWN,t.ErrorCode.INITIALIZATION_FAILED,{cause:e,details:`Failed to fetch partner info from Markr API.`})}}function _(t){if(!t)return[];let i=[];for(let a of t){let t=typeof a.token.chainId==`number`?n.eip155ChainIdToCaip2(a.token.chainId):a.token.chainId,o;f(a.token.address)?o={type:e.TokenType.NATIVE}:r.isEvmAddress(a.token.address)?o={type:e.TokenType.ERC20,address:a.token.address}:s.isSolAddress(a.token.address)&&(o={type:e.TokenType.SPL,address:a.token.address}),o&&i.push({type:a.type,name:a.name,amount:a.amount,chainId:t,token:o})}return i}function v(t){return t.type===e.TokenType.NATIVE?{type:e.TokenType.NATIVE}:t.type===e.TokenType.SPL?{type:e.TokenType.SPL,address:t.address}:{type:e.TokenType.ERC20,address:t.address}}async function y(e){return e?(await Promise.resolve().then(()=>require(`./_abis/cross-chain-swap-wrapper-abi.cjs`))).MARKR_CROSS_CHAIN_SWAP_WRAPPER_ABI:(await Promise.resolve().then(()=>require(`./_abis/swap-wrapper-abi.cjs`))).MARKR_SWAP_WRAPPER_ABI}function b(e){if(e instanceof c.BaseError){let t=e.data;if((0,c.isHex)(t))return t;let n;if(e.walk(e=>{let t=e.data;return!n&&(0,c.isHex)(t)&&(n=t),!1}),n)return n;let r=e.cause?.data;if((0,c.isHex)(r))return r}if(!e||typeof e!=`object`)return;let t=e;if((0,c.isHex)(t.data))return t.data;if((0,c.isHex)(t.error?.data))return t.error.data;if((0,c.isHex)(t.cause?.data))return t.cause.data;if((0,c.isHex)(t.response?.data))return t.response.data;if((0,c.isHex)(t.body?.error?.data))return t.body.error.data}function x(e,t){let n=b(t);if(!n)return null;try{let t=(0,c.decodeErrorResult)({abi:e,data:n}),r=t.args.length>0?`(${t.args.map(String).join(`, `)})`:`()`;return`${t.errorName}${r}`}catch{let t=n.slice(0,10).toLowerCase();for(let n of e)if(n.type===`error`&&(0,c.toFunctionSelector)(`${n.name}(${n.inputs.map(e=>e.type).join(`,`)})`).toLowerCase()===t)return`${n.name}()`}return null}exports.assetToAddressString=p,exports.calculateMarkrMinimumAmountOut=m,exports.decodeMarkrRevertError=x,exports.getMarkrSwapWrapperAbi=y,exports.getPartnerFeeBps=g,exports.getSupportedChains=u,exports.getSupportedTokens=d,exports.isRouteSupported=l,exports.isTokenAddressNative=f,exports.quoteFromMarkrQuoteResponseData=h;
1
+ require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../constants.cjs`),t=require(`../../errors.cjs`),n=require(`../../utils/caip.cjs`),r=require(`../../_utils/chain.cjs`),i=require(`../../utils/evm-address.cjs`),a=require(`../../_utils/math.cjs`),o=require(`./_api.cjs`),s=require(`../../utils/sol-address.cjs`);let c=require(`viem`);function l(e,t,n){let r=e.get(t),i=e.get(n);return!r||!i?!1:t===n?r.swapEnabled:r.crossChainSwapEnabled&&r.crossChainTargetChainIds.has(n)}async function u(e,r=!1){let i=new Map;try{let t=(await o.markrGetInfoChains(e)).filter(e=>e.chainType===`evm`||e.chainType===`svm`);for(let e of t){let t=typeof e.chainId==`number`?n.eip155ChainIdToCaip2(e.chainId):e.chainId,a=e.enabled_services.includes(`cross-chain-quote`)&&e.enabled_services.includes(`cross-chain-swap`),o=e.enabled_services.includes(`quote`)&&e.enabled_services.includes(`swap`),s=new Set;for(let r of e.lanes){let e=typeof r==`number`?n.eip155ChainIdToCaip2(r):r;e!==t&&s.add(e)}let c=r?!1:a,l=c?s:new Set;!o&&l.size===0||i.set(t,{chainId:e.chainId,crossChainSwapEnabled:c,crossChainTargetChainIds:l,swapEnabled:o,tokenList:e.enabled_services.includes(`token-list`)})}}catch(e){throw new t.SdkError(t.ErrorReason.UNKNOWN,t.ErrorCode.INITIALIZATION_FAILED,{cause:e,details:`Failed to fetch supported chains from Markr API.`})}return i}async function d(e,t){let n=new Map;for(let[r,i]of t.entries())if(typeof i.chainId==`number`&&i.tokenList&&(i.crossChainSwapEnabled||i.swapEnabled))try{let t=o.markrGetTokenList(e,i.chainId);n.set(r,t)}catch{}return n}function f(t){return t===e.ERC_ZERO_ADDRESS||t===e.SOL_MINT_ADDRESS}function p(t,n){return t.type===e.TokenType.NATIVE?r.isSolanaNamespace(n)?e.SOL_MINT_ADDRESS:e.ERC_ZERO_ADDRESS:t.address}function m({amountOut:e,assetOut:t,slippageBps:n}){let r=a.calculateMinimumAmountOut({amountOut:e,assetOut:t,slippageBps:n});return e>0n&&r===0n?1n:r}function h(t,n,r){let i=t.amountOut*BigInt(r)/10000n,a=t.amountOut-i,o=[..._(t.fees),{type:`partner`,name:`Core Fee`,amount:i,chainId:n.targetChain.chainId,token:v(n.targetAsset)}];return{aggregator:{id:t.aggregator.id,logoUrl:t.aggregator.logo_url,name:t.aggregator.name},amountIn:t.amountIn,amountOut:a,assetIn:n.sourceAsset,assetOut:n.targetAsset,expiresAt:t.expiredAt,fees:o,fromAddress:n.fromAddress,gasEstimate:t.gasEstimate,id:t.uuid,partnerFeeBps:r,serviceType:e.ServiceType.MARKR,slippageBps:n.slippageBps??t.recommendedSlippage,sourceChain:n.sourceChain,targetChain:n.targetChain,toAddress:n.toAddress}}async function g(e){try{return(await o.markrGetPartnerInfo(e)).fee}catch(e){throw new t.SdkError(t.ErrorReason.UNKNOWN,t.ErrorCode.INITIALIZATION_FAILED,{cause:e,details:`Failed to fetch partner info from Markr API.`})}}function _(t){if(!t)return[];let r=[];for(let a of t){let t=typeof a.token.chainId==`number`?n.eip155ChainIdToCaip2(a.token.chainId):a.token.chainId,o;f(a.token.address)?o={type:e.TokenType.NATIVE}:i.isEvmAddress(a.token.address)?o={type:e.TokenType.ERC20,address:a.token.address}:s.isSolAddress(a.token.address)&&(o={type:e.TokenType.SPL,address:a.token.address}),o&&r.push({type:a.type,name:a.name,amount:a.amount,chainId:t,token:o})}return r}function v(t){return t.type===e.TokenType.NATIVE?{type:e.TokenType.NATIVE}:t.type===e.TokenType.SPL?{type:e.TokenType.SPL,address:t.address}:{type:e.TokenType.ERC20,address:t.address}}async function y(e){return e?(await Promise.resolve().then(()=>require(`./_abis/cross-chain-swap-wrapper-abi.cjs`))).MARKR_CROSS_CHAIN_SWAP_WRAPPER_ABI:(await Promise.resolve().then(()=>require(`./_abis/swap-wrapper-abi.cjs`))).MARKR_SWAP_WRAPPER_ABI}function b(e){if(e instanceof c.BaseError){let t=e.data;if((0,c.isHex)(t))return t;let n;if(e.walk(e=>{let t=e.data;return!n&&(0,c.isHex)(t)&&(n=t),!1}),n)return n;let r=e.cause?.data;if((0,c.isHex)(r))return r}if(!e||typeof e!=`object`)return;let t=e;if((0,c.isHex)(t.data))return t.data;if((0,c.isHex)(t.error?.data))return t.error.data;if((0,c.isHex)(t.cause?.data))return t.cause.data;if((0,c.isHex)(t.response?.data))return t.response.data;if((0,c.isHex)(t.body?.error?.data))return t.body.error.data}function x(e,t){let n=b(t);if(!n)return null;try{let t=(0,c.decodeErrorResult)({abi:e,data:n}),r=t.args.length>0?`(${t.args.map(String).join(`, `)})`:`()`;return`${t.errorName}${r}`}catch{let t=n.slice(0,10).toLowerCase();for(let n of e)if(n.type===`error`&&(0,c.toFunctionSelector)(`${n.name}(${n.inputs.map(e=>e.type).join(`,`)})`).toLowerCase()===t)return`${n.name}()`}return null}exports.assetToAddressString=p,exports.calculateMarkrMinimumAmountOut=m,exports.decodeMarkrRevertError=x,exports.getMarkrSwapWrapperAbi=y,exports.getPartnerFeeBps=g,exports.getSupportedChains=u,exports.getSupportedTokens=d,exports.isRouteSupported=l,exports.isTokenAddressNative=f,exports.quoteFromMarkrQuoteResponseData=h;
2
2
  //# sourceMappingURL=_utils.cjs.map
@@ -1,2 +1,2 @@
1
- import{ERC_ZERO_ADDRESS as e,SOL_MINT_ADDRESS as t,ServiceType as n,TokenType as r}from"../../constants.js";import{ErrorCode as i,ErrorReason as a,SdkError as o}from"../../errors.js";import{eip155ChainIdToCaip2 as s}from"../../utils/caip.js";import{isEvmAddress as c}from"../../utils/evm-address.js";import{isSolanaNamespace as l}from"../../_utils/chain.js";import{calculateMinimumAmountOut as u}from"../../_utils/math.js";import{markrGetInfoChains as d,markrGetPartnerInfo as f,markrGetTokenList as p}from"./_api.js";import{isSolAddress as m}from"../../utils/sol-address.js";import{BaseError as h,decodeErrorResult as g,isHex as _,toFunctionSelector as v}from"viem";function y(e,t,n){let r=e.get(t),i=e.get(n);return!r||!i?!1:t===n?r.swapEnabled:r.crossChainSwapEnabled&&r.crossChainTargetChainIds.has(n)}async function b(e,t=!1){let n=new Map;try{let r=(await d(e)).filter(e=>e.chainType===`evm`||e.chainType===`svm`);for(let e of r){let r=typeof e.chainId==`number`?s(e.chainId):e.chainId,i=e.enabled_services.includes(`cross-chain-quote`)&&e.enabled_services.includes(`cross-chain-swap`),a=e.enabled_services.includes(`quote`)&&e.enabled_services.includes(`swap`),o=new Set;for(let t of e.lanes){let e=typeof t==`number`?s(t):t;e!==r&&o.add(e)}let c=t?!1:i,l=c?o:new Set;!a&&l.size===0||n.set(r,{chainId:e.chainId,crossChainSwapEnabled:c,crossChainTargetChainIds:l,swapEnabled:a,tokenList:e.enabled_services.includes(`token-list`)})}}catch(e){throw new o(a.UNKNOWN,i.INITIALIZATION_FAILED,{cause:e,details:`Failed to fetch supported chains from Markr API.`})}return n}async function x(e,t){let n=new Map;for(let[r,i]of t.entries())if(typeof i.chainId==`number`&&i.tokenList&&(i.crossChainSwapEnabled||i.swapEnabled))try{let t=p(e,i.chainId);n.set(r,t)}catch{}return n}function S(n){return n===e||n===t}function C(n,i){return n.type===r.NATIVE?l(i)?t:e:n.address}function w({amountOut:e,assetOut:t,slippageBps:n}){let r=u({amountOut:e,assetOut:t,slippageBps:n});return e>0n&&r===0n?1n:r}function T(e,t,r){let i=e.amountOut*BigInt(r)/10000n,a=e.amountOut-i,o=[...D(e.fees),{type:`partner`,name:`Core Fee`,amount:i,chainId:t.targetChain.chainId,token:O(t.targetAsset)}];return{aggregator:{id:e.aggregator.id,logoUrl:e.aggregator.logo_url,name:e.aggregator.name},amountIn:e.amountIn,amountOut:a,assetIn:t.sourceAsset,assetOut:t.targetAsset,expiresAt:e.expiredAt,fees:o,fromAddress:t.fromAddress,gasEstimate:e.gasEstimate,id:e.uuid,partnerFeeBps:r,serviceType:n.MARKR,slippageBps:t.slippageBps??e.recommendedSlippage,sourceChain:t.sourceChain,targetChain:t.targetChain,toAddress:t.toAddress}}async function E(e){try{return(await f(e)).fee}catch(e){throw new o(a.UNKNOWN,i.INITIALIZATION_FAILED,{cause:e,details:`Failed to fetch partner info from Markr API.`})}}function D(e){if(!e)return[];let t=[];for(let n of e){let e=typeof n.token.chainId==`number`?s(n.token.chainId):n.token.chainId,i;S(n.token.address)?i={type:r.NATIVE}:c(n.token.address)?i={type:r.ERC20,address:n.token.address}:m(n.token.address)&&(i={type:r.SPL,address:n.token.address}),i&&t.push({type:n.type,name:n.name,amount:n.amount,chainId:e,token:i})}return t}function O(e){return e.type===r.NATIVE?{type:r.NATIVE}:e.type===r.SPL?{type:r.SPL,address:e.address}:{type:r.ERC20,address:e.address}}async function k(e){return e?(await import(`./_abis/cross-chain-swap-wrapper-abi.js`)).MARKR_CROSS_CHAIN_SWAP_WRAPPER_ABI:(await import(`./_abis/swap-wrapper-abi.js`)).MARKR_SWAP_WRAPPER_ABI}function A(e){if(e instanceof h){let t=e.data;if(_(t))return t;let n;if(e.walk(e=>{let t=e.data;return!n&&_(t)&&(n=t),!1}),n)return n;let r=e.cause?.data;if(_(r))return r}if(!e||typeof e!=`object`)return;let t=e;if(_(t.data))return t.data;if(_(t.error?.data))return t.error.data;if(_(t.cause?.data))return t.cause.data;if(_(t.response?.data))return t.response.data;if(_(t.body?.error?.data))return t.body.error.data}function j(e,t){let n=A(t);if(!n)return null;try{let t=g({abi:e,data:n}),r=t.args.length>0?`(${t.args.map(String).join(`, `)})`:`()`;return`${t.errorName}${r}`}catch{let t=n.slice(0,10).toLowerCase();for(let n of e)if(n.type===`error`&&v(`${n.name}(${n.inputs.map(e=>e.type).join(`,`)})`).toLowerCase()===t)return`${n.name}()`}return null}export{C as assetToAddressString,w as calculateMarkrMinimumAmountOut,j as decodeMarkrRevertError,k as getMarkrSwapWrapperAbi,E as getPartnerFeeBps,b as getSupportedChains,x as getSupportedTokens,y as isRouteSupported,S as isTokenAddressNative,T as quoteFromMarkrQuoteResponseData};
1
+ import{ERC_ZERO_ADDRESS as e,SOL_MINT_ADDRESS as t,ServiceType as n,TokenType as r}from"../../constants.js";import{ErrorCode as i,ErrorReason as a,SdkError as o}from"../../errors.js";import{eip155ChainIdToCaip2 as s}from"../../utils/caip.js";import{isSolanaNamespace as c}from"../../_utils/chain.js";import{isEvmAddress as l}from"../../utils/evm-address.js";import{calculateMinimumAmountOut as u}from"../../_utils/math.js";import{markrGetInfoChains as d,markrGetPartnerInfo as f,markrGetTokenList as p}from"./_api.js";import{isSolAddress as m}from"../../utils/sol-address.js";import{BaseError as h,decodeErrorResult as g,isHex as _,toFunctionSelector as v}from"viem";function y(e,t,n){let r=e.get(t),i=e.get(n);return!r||!i?!1:t===n?r.swapEnabled:r.crossChainSwapEnabled&&r.crossChainTargetChainIds.has(n)}async function b(e,t=!1){let n=new Map;try{let r=(await d(e)).filter(e=>e.chainType===`evm`||e.chainType===`svm`);for(let e of r){let r=typeof e.chainId==`number`?s(e.chainId):e.chainId,i=e.enabled_services.includes(`cross-chain-quote`)&&e.enabled_services.includes(`cross-chain-swap`),a=e.enabled_services.includes(`quote`)&&e.enabled_services.includes(`swap`),o=new Set;for(let t of e.lanes){let e=typeof t==`number`?s(t):t;e!==r&&o.add(e)}let c=t?!1:i,l=c?o:new Set;!a&&l.size===0||n.set(r,{chainId:e.chainId,crossChainSwapEnabled:c,crossChainTargetChainIds:l,swapEnabled:a,tokenList:e.enabled_services.includes(`token-list`)})}}catch(e){throw new o(a.UNKNOWN,i.INITIALIZATION_FAILED,{cause:e,details:`Failed to fetch supported chains from Markr API.`})}return n}async function x(e,t){let n=new Map;for(let[r,i]of t.entries())if(typeof i.chainId==`number`&&i.tokenList&&(i.crossChainSwapEnabled||i.swapEnabled))try{let t=p(e,i.chainId);n.set(r,t)}catch{}return n}function S(n){return n===e||n===t}function C(n,i){return n.type===r.NATIVE?c(i)?t:e:n.address}function w({amountOut:e,assetOut:t,slippageBps:n}){let r=u({amountOut:e,assetOut:t,slippageBps:n});return e>0n&&r===0n?1n:r}function T(e,t,r){let i=e.amountOut*BigInt(r)/10000n,a=e.amountOut-i,o=[...D(e.fees),{type:`partner`,name:`Core Fee`,amount:i,chainId:t.targetChain.chainId,token:O(t.targetAsset)}];return{aggregator:{id:e.aggregator.id,logoUrl:e.aggregator.logo_url,name:e.aggregator.name},amountIn:e.amountIn,amountOut:a,assetIn:t.sourceAsset,assetOut:t.targetAsset,expiresAt:e.expiredAt,fees:o,fromAddress:t.fromAddress,gasEstimate:e.gasEstimate,id:e.uuid,partnerFeeBps:r,serviceType:n.MARKR,slippageBps:t.slippageBps??e.recommendedSlippage,sourceChain:t.sourceChain,targetChain:t.targetChain,toAddress:t.toAddress}}async function E(e){try{return(await f(e)).fee}catch(e){throw new o(a.UNKNOWN,i.INITIALIZATION_FAILED,{cause:e,details:`Failed to fetch partner info from Markr API.`})}}function D(e){if(!e)return[];let t=[];for(let n of e){let e=typeof n.token.chainId==`number`?s(n.token.chainId):n.token.chainId,i;S(n.token.address)?i={type:r.NATIVE}:l(n.token.address)?i={type:r.ERC20,address:n.token.address}:m(n.token.address)&&(i={type:r.SPL,address:n.token.address}),i&&t.push({type:n.type,name:n.name,amount:n.amount,chainId:e,token:i})}return t}function O(e){return e.type===r.NATIVE?{type:r.NATIVE}:e.type===r.SPL?{type:r.SPL,address:e.address}:{type:r.ERC20,address:e.address}}async function k(e){return e?(await import(`./_abis/cross-chain-swap-wrapper-abi.js`)).MARKR_CROSS_CHAIN_SWAP_WRAPPER_ABI:(await import(`./_abis/swap-wrapper-abi.js`)).MARKR_SWAP_WRAPPER_ABI}function A(e){if(e instanceof h){let t=e.data;if(_(t))return t;let n;if(e.walk(e=>{let t=e.data;return!n&&_(t)&&(n=t),!1}),n)return n;let r=e.cause?.data;if(_(r))return r}if(!e||typeof e!=`object`)return;let t=e;if(_(t.data))return t.data;if(_(t.error?.data))return t.error.data;if(_(t.cause?.data))return t.cause.data;if(_(t.response?.data))return t.response.data;if(_(t.body?.error?.data))return t.body.error.data}function j(e,t){let n=A(t);if(!n)return null;try{let t=g({abi:e,data:n}),r=t.args.length>0?`(${t.args.map(String).join(`, `)})`:`()`;return`${t.errorName}${r}`}catch{let t=n.slice(0,10).toLowerCase();for(let n of e)if(n.type===`error`&&v(`${n.name}(${n.inputs.map(e=>e.type).join(`,`)})`).toLowerCase()===t)return`${n.name}()`}return null}export{C as assetToAddressString,w as calculateMarkrMinimumAmountOut,j as decodeMarkrRevertError,k as getMarkrSwapWrapperAbi,E as getPartnerFeeBps,b as getSupportedChains,x as getSupportedTokens,y as isRouteSupported,S as isTokenAddressNative,T as quoteFromMarkrQuoteResponseData};
2
2
  //# sourceMappingURL=_utils.js.map
@@ -55,18 +55,6 @@ interface TransferManager {
55
55
  /** Estimate the native fee for executing the provided quote. */
56
56
  estimateNativeFee(quote: Quote, options?: EstimateNativeFeeOptions): Promise<NativeFeeEstimate>;
57
57
  /**
58
- * Given a source asset and chain, provides a mapping of supported destination chains to their
59
- * corresponding bridged asset via the underlying services.
60
- *
61
- * If there is no supported bridge for the given source asset and chain, returns null.
62
- *
63
- * @deprecated Use `getBridgeableAssets` instead.
64
- */
65
- getAssetBridgeMap(props: {
66
- sourceAsset: Asset;
67
- sourceChainId: Caip2ChainId;
68
- }): Promise<AssetBridgeMap | null>;
69
- /**
70
58
  * Returns all assets possibly receivable on targetChainId for the given source asset,
71
59
  * across all configured bridge and swap providers. Assets are enriched with logoUri
72
60
  * where available.
@@ -55,18 +55,6 @@ interface TransferManager {
55
55
  /** Estimate the native fee for executing the provided quote. */
56
56
  estimateNativeFee(quote: Quote, options?: EstimateNativeFeeOptions): Promise<NativeFeeEstimate>;
57
57
  /**
58
- * Given a source asset and chain, provides a mapping of supported destination chains to their
59
- * corresponding bridged asset via the underlying services.
60
- *
61
- * If there is no supported bridge for the given source asset and chain, returns null.
62
- *
63
- * @deprecated Use `getBridgeableAssets` instead.
64
- */
65
- getAssetBridgeMap(props: {
66
- sourceAsset: Asset;
67
- sourceChainId: Caip2ChainId;
68
- }): Promise<AssetBridgeMap | null>;
69
- /**
70
58
  * Returns all assets possibly receivable on targetChainId for the given source asset,
71
59
  * across all configured bridge and swap providers. Assets are enriched with logoUri
72
60
  * where available.
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.7.0",
4
+ "version": "0.8.0",
5
5
  "type": "module",
6
6
  "main": "./dist/mod.cjs",
7
7
  "module": "./dist/mod.js",
@@ -1,2 +0,0 @@
1
- require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../constants.cjs`),t=require(`../errors.cjs`),n=require(`../utils/caip.cjs`),r=require(`../utils/evm-address.cjs`);let i=require(`viem`),a=require(`es-toolkit`);function o(e){return{destinations:Object.fromEntries(Object.entries(e.destinations).map(([e,t])=>[e,{address:t.address,bridgeProviders:[...t.bridgeProviders]}])),swapProviders:[...e.swapProviders]}}function s(e,t){for(let[r,i]of Object.entries(t)){if(!n.isCaip2ChainId(r))continue;let t=e[r];if(t){let n=new Set(t.bridgeProviders);for(let e of i.bridgeProviders)n.add(e);e[r]={address:t.address??i.address,bridgeProviders:Array.from(n)}}else e[r]={address:i.address,bridgeProviders:[...i.bridgeProviders]}}}function c(e,t){let n=new Set(e);for(let e of t)n.add(e);return Array.from(n)}function l(t,n){let r=t[e.TokenType.NATIVE];if(!r){t[e.TokenType.NATIVE]={...n,...o(n)};return}s(r.destinations,n.destinations),r.swapProviders=c(r.swapProviders,n.swapProviders)}function u(e,t){if(!e)return[{...t,...o(t),address:r.formatEvmAddress(t.address)}];let n=e.find(e=>(0,i.isAddressEqual)(e.address,t.address));return n?(s(n.destinations,t.destinations),n.swapProviders=c(n.swapProviders,t.swapProviders),e):(e.push({...t,...o(t)}),e)}function d(e,t){if(!e)return[{...t,...o(t)}];let n=e.find(e=>e.address===t.address);return n?(s(n.destinations,t.destinations),n.swapProviders=c(n.swapProviders,t.swapProviders),e):(e.push({...t,...o(t)}),e)}function f(r){let i={};for(let a of r)for(let[r,o]of Object.entries(a))if(n.isCaip2ChainId(r)){i[r]||(i[r]={});for(let n of o)switch(n.type){case e.TokenType.NATIVE:l(i[r],n);break;case e.TokenType.ERC20:i[r][e.TokenType.ERC20]=u(i[r][e.TokenType.ERC20],n);break;case e.TokenType.SPL:i[r][e.TokenType.SPL]=d(i[r][e.TokenType.SPL],n);break;default:throw new t.SdkError(`Unsupported asset type encountered during merge.`,t.ErrorCode.UNKNOWN,{details:JSON.stringify({asset:n})})}}let o={};for(let t of Object.keys(i)){if(!n.isCaip2ChainId(t))continue;let r=i[t];o[t]=[],r?.[e.TokenType.NATIVE]&&o[t].push(r[e.TokenType.NATIVE]),r?.[e.TokenType.ERC20]&&o[t].push(...(0,a.sortBy)(r[e.TokenType.ERC20],[`symbol`,`name`,`address`])),r?.[e.TokenType.SPL]&&o[t].push(...(0,a.sortBy)(r[e.TokenType.SPL],[`symbol`,`name`,`address`]))}return o}exports.mergeChainAssetMaps=f;
2
- //# sourceMappingURL=merge-assets.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"merge-assets.cjs","names":["isCaip2ChainId","TokenType","formatEvmAddress","SdkError","ErrorCode"],"sources":["../../src/_utils/merge-assets.ts"],"sourcesContent":["import { sortBy } from 'es-toolkit';\nimport { TokenType, type ServiceType } from '../constants';\nimport { ErrorCode, SdkError } from '../errors';\nimport type { ChainAssetMap, Erc20Asset, NativeAsset, SplAsset } from '../types/asset';\nimport type { Caip2ChainId } from '../types/caip';\nimport type { DeepMutable } from '../types/utility-types';\nimport { isCaip2ChainId } from '../utils/caip';\nimport { isAddressEqual } from 'viem';\nimport { formatEvmAddress } from '../utils/evm-address';\n\n/** @internal */\nexport interface TransferableData {\n destinations: { [chainId: Caip2ChainId]: { address: string; bridgeProviders: ServiceType[] } };\n swapProviders: ServiceType[];\n}\n\n/** @internal */\nexport interface ReadonlyTransferableData {\n destinations: {\n readonly [chainId: Caip2ChainId]: { readonly address: string; readonly bridgeProviders: readonly ServiceType[] };\n };\n swapProviders: readonly ServiceType[];\n}\n\ninterface ChainAssets {\n [TokenType.NATIVE]?: NativeAsset & TransferableData;\n [TokenType.ERC20]?: (Erc20Asset & TransferableData)[];\n [TokenType.SPL]?: (SplAsset & TransferableData)[];\n}\n\ninterface OrganizedChainAssetMap {\n [chainId: Caip2ChainId]: ChainAssets;\n}\n\nfunction cloneTransferableData(data: ReadonlyTransferableData): TransferableData {\n return {\n destinations: Object.fromEntries(\n Object.entries(data.destinations).map(([chainId, info]) => [\n chainId,\n { address: info.address, bridgeProviders: [...info.bridgeProviders] },\n ]),\n ),\n swapProviders: [...data.swapProviders],\n };\n}\n\nfunction mergeDestinations(\n target: TransferableData['destinations'],\n source: ReadonlyTransferableData['destinations'],\n): void {\n for (const [destChainId, info] of Object.entries(source)) {\n if (!isCaip2ChainId(destChainId)) {\n continue;\n }\n\n const existingInfo = target[destChainId];\n if (existingInfo) {\n const merged = new Set(existingInfo.bridgeProviders);\n for (const service of info.bridgeProviders) {\n merged.add(service);\n }\n // Keep existing address; if none, set from source\n const address = existingInfo.address ?? info.address;\n target[destChainId] = { address, bridgeProviders: Array.from(merged) };\n } else {\n target[destChainId] = { address: info.address, bridgeProviders: [...info.bridgeProviders] };\n }\n }\n}\n\nfunction mergeSwapProviders(target: ServiceType[], source: readonly ServiceType[]): ServiceType[] {\n const merged = new Set(target);\n for (const provider of source) {\n merged.add(provider);\n }\n return Array.from(merged);\n}\n\nfunction mergeNative(chainAssets: ChainAssets, asset: NativeAsset & ReadonlyTransferableData): void {\n const existingAsset = chainAssets[TokenType.NATIVE];\n if (!existingAsset) {\n chainAssets[TokenType.NATIVE] = {\n ...asset,\n ...cloneTransferableData(asset),\n };\n return;\n }\n\n mergeDestinations(existingAsset.destinations, asset.destinations);\n existingAsset.swapProviders = mergeSwapProviders(existingAsset.swapProviders, asset.swapProviders);\n}\n\nfunction upsertErc20(\n list: (Erc20Asset & TransferableData)[] | undefined,\n asset: Erc20Asset & ReadonlyTransferableData,\n): (Erc20Asset & TransferableData)[] {\n if (!list) {\n return [\n {\n ...asset,\n ...cloneTransferableData(asset),\n // format address to lowercase for consistency\n address: formatEvmAddress(asset.address),\n },\n ];\n }\n const matchingAsset = list.find((a) => isAddressEqual(a.address, asset.address));\n if (matchingAsset) {\n mergeDestinations(matchingAsset.destinations, asset.destinations);\n matchingAsset.swapProviders = mergeSwapProviders(matchingAsset.swapProviders, asset.swapProviders);\n return list;\n }\n list.push({ ...asset, ...cloneTransferableData(asset) });\n return list;\n}\n\nfunction upsertSpl(\n list: (SplAsset & TransferableData)[] | undefined,\n asset: SplAsset & ReadonlyTransferableData,\n): (SplAsset & TransferableData)[] {\n if (!list) {\n return [{ ...asset, ...cloneTransferableData(asset) }];\n }\n const matchingAsset = list.find((a) => a.address === asset.address);\n if (matchingAsset) {\n mergeDestinations(matchingAsset.destinations, asset.destinations);\n matchingAsset.swapProviders = mergeSwapProviders(matchingAsset.swapProviders, asset.swapProviders);\n return list;\n }\n list.push({ ...asset, ...cloneTransferableData(asset) });\n return list;\n}\n\nexport function mergeChainAssetMaps(chainAssetMaps: readonly ChainAssetMap[]): ChainAssetMap {\n const organizedMap: OrganizedChainAssetMap = {};\n\n for (const assetMap of chainAssetMaps) {\n for (const [chainId, assets] of Object.entries(assetMap)) {\n if (!isCaip2ChainId(chainId)) {\n continue;\n }\n\n if (!organizedMap[chainId]) {\n organizedMap[chainId] = {};\n }\n\n for (const asset of assets) {\n switch (asset.type) {\n case TokenType.NATIVE: {\n mergeNative(organizedMap[chainId], asset);\n break;\n }\n\n case TokenType.ERC20: {\n organizedMap[chainId][TokenType.ERC20] = upsertErc20(organizedMap[chainId][TokenType.ERC20], asset);\n break;\n }\n\n case TokenType.SPL: {\n organizedMap[chainId][TokenType.SPL] = upsertSpl(organizedMap[chainId][TokenType.SPL], asset);\n break;\n }\n\n default: {\n throw new SdkError('Unsupported asset type encountered during merge.', ErrorCode.UNKNOWN, {\n details: JSON.stringify({ asset }),\n });\n }\n }\n }\n }\n }\n\n // Convert organized map back to ChainAssetMap format\n const mergedAssetMap: DeepMutable<ChainAssetMap> = {};\n\n for (const chainId of Object.keys(organizedMap)) {\n if (!isCaip2ChainId(chainId)) {\n continue;\n }\n\n const assetsByType = organizedMap[chainId];\n\n mergedAssetMap[chainId] = [];\n\n // Add native asset if exists\n if (assetsByType?.[TokenType.NATIVE]) {\n mergedAssetMap[chainId].push(assetsByType[TokenType.NATIVE]);\n }\n\n // Add ERC20 assets if exist\n if (assetsByType?.[TokenType.ERC20]) {\n mergedAssetMap[chainId].push(...sortBy(assetsByType[TokenType.ERC20], ['symbol', 'name', 'address']));\n }\n\n // Add SPL assets if exist\n if (assetsByType?.[TokenType.SPL]) {\n mergedAssetMap[chainId].push(...sortBy(assetsByType[TokenType.SPL], ['symbol', 'name', 'address']));\n }\n }\n\n return mergedAssetMap as ChainAssetMap;\n}\n"],"mappings":"+NAkCA,SAAS,EAAsB,EAAkD,CAC/E,MAAO,CACL,aAAc,OAAO,YACnB,OAAO,QAAQ,EAAK,aAAa,CAAC,KAAK,CAAC,EAAS,KAAU,CACzD,EACA,CAAE,QAAS,EAAK,QAAS,gBAAiB,CAAC,GAAG,EAAK,gBAAgB,CAAE,CACtE,CAAC,CACH,CACD,cAAe,CAAC,GAAG,EAAK,cAAc,CACvC,CAGH,SAAS,EACP,EACA,EACM,CACN,IAAK,GAAM,CAAC,EAAa,KAAS,OAAO,QAAQ,EAAO,CAAE,CACxD,GAAI,CAACA,EAAAA,eAAe,EAAY,CAC9B,SAGF,IAAM,EAAe,EAAO,GAC5B,GAAI,EAAc,CAChB,IAAM,EAAS,IAAI,IAAI,EAAa,gBAAgB,CACpD,IAAK,IAAM,KAAW,EAAK,gBACzB,EAAO,IAAI,EAAQ,CAIrB,EAAO,GAAe,CAAE,QADR,EAAa,SAAW,EAAK,QACZ,gBAAiB,MAAM,KAAK,EAAO,CAAE,MAE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,CAIvG,OAAO"}
@@ -1,2 +0,0 @@
1
- import{TokenType as e}from"../constants.js";import{ErrorCode as t,SdkError as n}from"../errors.js";import{isCaip2ChainId as r}from"../utils/caip.js";import{formatEvmAddress as i}from"../utils/evm-address.js";import{isAddressEqual as a}from"viem";import{sortBy as o}from"es-toolkit";function s(e){return{destinations:Object.fromEntries(Object.entries(e.destinations).map(([e,t])=>[e,{address:t.address,bridgeProviders:[...t.bridgeProviders]}])),swapProviders:[...e.swapProviders]}}function c(e,t){for(let[n,i]of Object.entries(t)){if(!r(n))continue;let t=e[n];if(t){let r=new Set(t.bridgeProviders);for(let e of i.bridgeProviders)r.add(e);e[n]={address:t.address??i.address,bridgeProviders:Array.from(r)}}else e[n]={address:i.address,bridgeProviders:[...i.bridgeProviders]}}}function l(e,t){let n=new Set(e);for(let e of t)n.add(e);return Array.from(n)}function u(t,n){let r=t[e.NATIVE];if(!r){t[e.NATIVE]={...n,...s(n)};return}c(r.destinations,n.destinations),r.swapProviders=l(r.swapProviders,n.swapProviders)}function d(e,t){if(!e)return[{...t,...s(t),address:i(t.address)}];let n=e.find(e=>a(e.address,t.address));return n?(c(n.destinations,t.destinations),n.swapProviders=l(n.swapProviders,t.swapProviders),e):(e.push({...t,...s(t)}),e)}function f(e,t){if(!e)return[{...t,...s(t)}];let n=e.find(e=>e.address===t.address);return n?(c(n.destinations,t.destinations),n.swapProviders=l(n.swapProviders,t.swapProviders),e):(e.push({...t,...s(t)}),e)}function p(i){let a={};for(let o of i)for(let[i,s]of Object.entries(o))if(r(i)){a[i]||(a[i]={});for(let r of s)switch(r.type){case e.NATIVE:u(a[i],r);break;case e.ERC20:a[i][e.ERC20]=d(a[i][e.ERC20],r);break;case e.SPL:a[i][e.SPL]=f(a[i][e.SPL],r);break;default:throw new n(`Unsupported asset type encountered during merge.`,t.UNKNOWN,{details:JSON.stringify({asset:r})})}}let s={};for(let t of Object.keys(a)){if(!r(t))continue;let n=a[t];s[t]=[],n?.[e.NATIVE]&&s[t].push(n[e.NATIVE]),n?.[e.ERC20]&&s[t].push(...o(n[e.ERC20],[`symbol`,`name`,`address`])),n?.[e.SPL]&&s[t].push(...o(n[e.SPL],[`symbol`,`name`,`address`]))}return s}export{p as mergeChainAssetMaps};
2
- //# sourceMappingURL=merge-assets.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"merge-assets.js","names":[],"sources":["../../src/_utils/merge-assets.ts"],"sourcesContent":["import { sortBy } from 'es-toolkit';\nimport { TokenType, type ServiceType } from '../constants';\nimport { ErrorCode, SdkError } from '../errors';\nimport type { ChainAssetMap, Erc20Asset, NativeAsset, SplAsset } from '../types/asset';\nimport type { Caip2ChainId } from '../types/caip';\nimport type { DeepMutable } from '../types/utility-types';\nimport { isCaip2ChainId } from '../utils/caip';\nimport { isAddressEqual } from 'viem';\nimport { formatEvmAddress } from '../utils/evm-address';\n\n/** @internal */\nexport interface TransferableData {\n destinations: { [chainId: Caip2ChainId]: { address: string; bridgeProviders: ServiceType[] } };\n swapProviders: ServiceType[];\n}\n\n/** @internal */\nexport interface ReadonlyTransferableData {\n destinations: {\n readonly [chainId: Caip2ChainId]: { readonly address: string; readonly bridgeProviders: readonly ServiceType[] };\n };\n swapProviders: readonly ServiceType[];\n}\n\ninterface ChainAssets {\n [TokenType.NATIVE]?: NativeAsset & TransferableData;\n [TokenType.ERC20]?: (Erc20Asset & TransferableData)[];\n [TokenType.SPL]?: (SplAsset & TransferableData)[];\n}\n\ninterface OrganizedChainAssetMap {\n [chainId: Caip2ChainId]: ChainAssets;\n}\n\nfunction cloneTransferableData(data: ReadonlyTransferableData): TransferableData {\n return {\n destinations: Object.fromEntries(\n Object.entries(data.destinations).map(([chainId, info]) => [\n chainId,\n { address: info.address, bridgeProviders: [...info.bridgeProviders] },\n ]),\n ),\n swapProviders: [...data.swapProviders],\n };\n}\n\nfunction mergeDestinations(\n target: TransferableData['destinations'],\n source: ReadonlyTransferableData['destinations'],\n): void {\n for (const [destChainId, info] of Object.entries(source)) {\n if (!isCaip2ChainId(destChainId)) {\n continue;\n }\n\n const existingInfo = target[destChainId];\n if (existingInfo) {\n const merged = new Set(existingInfo.bridgeProviders);\n for (const service of info.bridgeProviders) {\n merged.add(service);\n }\n // Keep existing address; if none, set from source\n const address = existingInfo.address ?? info.address;\n target[destChainId] = { address, bridgeProviders: Array.from(merged) };\n } else {\n target[destChainId] = { address: info.address, bridgeProviders: [...info.bridgeProviders] };\n }\n }\n}\n\nfunction mergeSwapProviders(target: ServiceType[], source: readonly ServiceType[]): ServiceType[] {\n const merged = new Set(target);\n for (const provider of source) {\n merged.add(provider);\n }\n return Array.from(merged);\n}\n\nfunction mergeNative(chainAssets: ChainAssets, asset: NativeAsset & ReadonlyTransferableData): void {\n const existingAsset = chainAssets[TokenType.NATIVE];\n if (!existingAsset) {\n chainAssets[TokenType.NATIVE] = {\n ...asset,\n ...cloneTransferableData(asset),\n };\n return;\n }\n\n mergeDestinations(existingAsset.destinations, asset.destinations);\n existingAsset.swapProviders = mergeSwapProviders(existingAsset.swapProviders, asset.swapProviders);\n}\n\nfunction upsertErc20(\n list: (Erc20Asset & TransferableData)[] | undefined,\n asset: Erc20Asset & ReadonlyTransferableData,\n): (Erc20Asset & TransferableData)[] {\n if (!list) {\n return [\n {\n ...asset,\n ...cloneTransferableData(asset),\n // format address to lowercase for consistency\n address: formatEvmAddress(asset.address),\n },\n ];\n }\n const matchingAsset = list.find((a) => isAddressEqual(a.address, asset.address));\n if (matchingAsset) {\n mergeDestinations(matchingAsset.destinations, asset.destinations);\n matchingAsset.swapProviders = mergeSwapProviders(matchingAsset.swapProviders, asset.swapProviders);\n return list;\n }\n list.push({ ...asset, ...cloneTransferableData(asset) });\n return list;\n}\n\nfunction upsertSpl(\n list: (SplAsset & TransferableData)[] | undefined,\n asset: SplAsset & ReadonlyTransferableData,\n): (SplAsset & TransferableData)[] {\n if (!list) {\n return [{ ...asset, ...cloneTransferableData(asset) }];\n }\n const matchingAsset = list.find((a) => a.address === asset.address);\n if (matchingAsset) {\n mergeDestinations(matchingAsset.destinations, asset.destinations);\n matchingAsset.swapProviders = mergeSwapProviders(matchingAsset.swapProviders, asset.swapProviders);\n return list;\n }\n list.push({ ...asset, ...cloneTransferableData(asset) });\n return list;\n}\n\nexport function mergeChainAssetMaps(chainAssetMaps: readonly ChainAssetMap[]): ChainAssetMap {\n const organizedMap: OrganizedChainAssetMap = {};\n\n for (const assetMap of chainAssetMaps) {\n for (const [chainId, assets] of Object.entries(assetMap)) {\n if (!isCaip2ChainId(chainId)) {\n continue;\n }\n\n if (!organizedMap[chainId]) {\n organizedMap[chainId] = {};\n }\n\n for (const asset of assets) {\n switch (asset.type) {\n case TokenType.NATIVE: {\n mergeNative(organizedMap[chainId], asset);\n break;\n }\n\n case TokenType.ERC20: {\n organizedMap[chainId][TokenType.ERC20] = upsertErc20(organizedMap[chainId][TokenType.ERC20], asset);\n break;\n }\n\n case TokenType.SPL: {\n organizedMap[chainId][TokenType.SPL] = upsertSpl(organizedMap[chainId][TokenType.SPL], asset);\n break;\n }\n\n default: {\n throw new SdkError('Unsupported asset type encountered during merge.', ErrorCode.UNKNOWN, {\n details: JSON.stringify({ asset }),\n });\n }\n }\n }\n }\n }\n\n // Convert organized map back to ChainAssetMap format\n const mergedAssetMap: DeepMutable<ChainAssetMap> = {};\n\n for (const chainId of Object.keys(organizedMap)) {\n if (!isCaip2ChainId(chainId)) {\n continue;\n }\n\n const assetsByType = organizedMap[chainId];\n\n mergedAssetMap[chainId] = [];\n\n // Add native asset if exists\n if (assetsByType?.[TokenType.NATIVE]) {\n mergedAssetMap[chainId].push(assetsByType[TokenType.NATIVE]);\n }\n\n // Add ERC20 assets if exist\n if (assetsByType?.[TokenType.ERC20]) {\n mergedAssetMap[chainId].push(...sortBy(assetsByType[TokenType.ERC20], ['symbol', 'name', 'address']));\n }\n\n // Add SPL assets if exist\n if (assetsByType?.[TokenType.SPL]) {\n mergedAssetMap[chainId].push(...sortBy(assetsByType[TokenType.SPL], ['symbol', 'name', 'address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