@avalabs/bridge-unified
Advanced tools
Comparing version 0.0.0-feat-unified-api-interface-20231204170641 to 0.0.0-feat-unified-api-interface-20231213160746
# @avalabs/unified-bridge | ||
## 0.0.0-feat-unified-api-interface-20231204170641 | ||
## 0.0.0-feat-unified-api-interface-20231213160746 | ||
@@ -5,0 +5,0 @@ ### Major Changes |
@@ -139,5 +139,6 @@ import { Address, TransactionRequest, Hex } from 'viem'; | ||
declare const createUnifiedBridgeService: ({ environment, disabledBridgeTypes }: BridgeServiceConfig) => { | ||
environment: Environment; | ||
bridges: Map<BridgeType, BridgeService>; | ||
init: () => Promise<void>; | ||
updateConfigs: () => Promise<void[]>; | ||
updateConfigs: () => Promise<void>; | ||
getAssets: () => Promise<ChainAssetMap>; | ||
@@ -144,0 +145,0 @@ getFees: (params: FeeParams) => Promise<AssetFeeMap>; |
@@ -1,8 +0,8 @@ | ||
import { merge } from 'lodash'; | ||
import { custom, http, createWalletClient, publicActions, encodeFunctionData, decodeEventLog } from 'viem'; | ||
import { mergeWith, isArray } from 'lodash'; | ||
var R=(r=>(r.NATIVE="native",r.ERC20="erc20",r))(R||{});var k=(t=>(t.CCTP="cctp",t))(k||{});var S=(r=>(r.PROD="production",r.TEST="test",r))(S||{});var W={test:"https://raw.githubusercontent.com/ava-labs/avalanche-bridge-resources/main/cctp/cctp_config.test.json",production:"https://raw.githubusercontent.com/ava-labs/avalanche-bridge-resources/main/cctp/cctp_config.json"},D=async e=>{try{return await(await fetch(W[e])).json()}catch(t){throw new Error(`Error while fetching CCTP config: ${t.message}`)}},F=e=>{switch(e){case 43114:case 43113:return 1e3;default:return 2e4}};async function _(e){await e.ensureHasConfig();let t=e.config.map(r=>r.chainId);return e.config.reduce((r,a)=>(r[a.chainId]=a.tokens.map(p=>({...p,type:"erc20",destinations:t.reduce((n,o)=>(a.chainId!==o&&(n[o]||(n[o]=[]),n[o]?.push("cctp")),n),{})})),r),{})}var Z=e=>({id:e.chainId,name:e.chainName,nativeCurrency:{decimals:e.networkToken.decimals,symbol:e.networkToken.symbol,name:e.networkToken.name},network:e.chainName,rpcUrls:{default:{http:[e.rpcUrl]},public:{http:[e.rpcUrl]}},...e.utilityAddresses.multicall&&{contracts:{multicall3:{address:e.utilityAddresses.multicall}}}}),T=({chain:e,provider:t})=>{let r=Z(e),a=t?custom(t):http(e.rpcUrl,{batch:!0,retryCount:0});return createWalletClient({chain:r,transport:a}).extend(publicActions)};var h=[{inputs:[{internalType:"address",name:"circleTokenMessenger_",type:"address"},{internalType:"address",name:"burnToken_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AlreadyAdmin",type:"error"},{inputs:[],name:"AlreadyFeeCollector",type:"error"},{inputs:[],name:"AlreadySupportedBurnToken",type:"error"},{inputs:[],name:"AmountLessThanFee",type:"error"},{inputs:[],name:"BalanceNotIncreased",type:"error"},{inputs:[],name:"CannotRemoveLastAdmin",type:"error"},{inputs:[],name:"FeePercentageGreaterThanMax",type:"error"},{inputs:[],name:"InvalidAdminAddress",type:"error"},{inputs:[],name:"InvalidFeeCollector",type:"error"},{inputs:[],name:"InvalidMintRecipientAddress",type:"error"},{inputs:[],name:"InvalidTokenAddress",type:"error"},{inputs:[],name:"InvalidTokenMessengerAddress",type:"error"},{inputs:[],name:"MaxFeeLessThanMinFee",type:"error"},{inputs:[],name:"NotAdmin",type:"error"},{inputs:[],name:"NotFeeCollector",type:"error"},{inputs:[],name:"UnSupportedBurnToken",type:"error"},{inputs:[],name:"UnsupportedDomain",type:"error"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"admin",type:"address"}],name:"AdminAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"admin",type:"address"}],name:"AdminRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"BurnTokenAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"BurnTokenRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"feeCollector",type:"address"}],name:"FeeCollectorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"feeCollector",type:"address"}],name:"FeeCollectorRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint32",name:"domain",type:"uint32"},{components:[{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint32",name:"feePercentage",type:"uint32"},{internalType:"uint256",name:"txnFee",type:"uint256"},{internalType:"bool",name:"supported",type:"bool"}],indexed:!1,internalType:"struct FeeCalculator.FeeConfiguration",name:"feeConfiguration",type:"tuple"}],name:"FeeConfigurationUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"nonce",type:"uint64"},{indexed:!1,internalType:"address",name:"burnToken",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"address",name:"depositor",type:"address"},{indexed:!1,internalType:"address",name:"mintRecipient",type:"address"},{indexed:!1,internalType:"uint32",name:"destinationDomain",type:"uint32"},{indexed:!1,internalType:"uint256",name:"totalFee",type:"uint256"}],name:"TransferTokens",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"addAdmin",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"feeCollector",type:"address"}],name:"addFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"addSupportedBurnToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint32",name:"destinationDomain",type:"uint32"}],name:"calculateFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"circleTokenMessenger",outputs:[{internalType:"contract ICircleTokenMessenger",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"circleTokenMessengerAddress",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"collectFees",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"getFeeAmounts",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getFeeConfiguration",outputs:[{components:[{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint32",name:"feePercentage",type:"uint32"},{internalType:"uint256",name:"txnFee",type:"uint256"},{internalType:"bool",name:"supported",type:"bool"}],internalType:"struct FeeCalculator.FeeConfiguration",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getFeePercentage",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getMaxFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getMinFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getTxnFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isAdmin",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isFeeCollector",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"isSupportedBurnToken",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"isSupportedDomain",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"removeAdmin",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"feeCollector",type:"address"}],name:"removeFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"removeSupportedBurnToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"},{components:[{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint32",name:"feePercentage",type:"uint32"},{internalType:"uint256",name:"txnFee",type:"uint256"},{internalType:"bool",name:"supported",type:"bool"}],internalType:"struct FeeCalculator.FeeConfiguration",name:"feeConfiguration",type:"tuple"}],name:"setFeeConfiguration",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"supportedBurnTokens",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint32",name:"destinationDomain",type:"uint32"},{internalType:"address",name:"mintRecipient",type:"address"},{internalType:"address",name:"burnToken",type:"address"}],name:"transferTokens",outputs:[{internalType:"uint64",name:"nonce",type:"uint64"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"}];var x=({sourceChain:e,targetChain:t,amount:r,asset:a},p)=>{if(e.chainId===t.chainId)throw new Error("Source and target chains are the same");if(r<=0n)throw new Error("Amount must be greater than zero");let n=p.find(i=>i.chainId===e.chainId);if(!n)throw new Error(`Not supported on source chain "${e.chainId}"`);let o=p.find(i=>i.chainId===t.chainId);if(!o)throw new Error(`Not supported on target chain "${t.chainId}"`);let u=n.tokens.find(i=>i.symbol===a.symbol),c=o.tokens.find(i=>i.symbol===a.symbol);if(!u||!c)throw new Error(`Not supported asset "${a.symbol}"`);return {sourceChainData:n,targetChainData:o,burnToken:u,mintToken:c}};async function H(e,t){await e.ensureHasConfig();let{sourceChain:r,targetChain:a,asset:p,amount:n,provider:o}=t,{sourceChainData:u,targetChainData:c,burnToken:i}=x({sourceChain:r,targetChain:a,asset:p,amount:n},e.config),d=await T({chain:r,provider:o}).readContract({address:u.tokenRouterAddress,abi:h,functionName:"calculateFee",args:[n,c.domain]});return {[i.address]:d}}var B=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}];var ee=async(e,t)=>{let{sourceChain:r,targetChain:a,asset:p,amount:n,addressC:o,sourceProvider:u}=t,{sourceChainData:c,targetChainData:i,burnToken:s}=x({sourceChain:r,targetChain:a,asset:p,amount:n},e.config),d=T({chain:r,provider:u});if(await d.readContract({address:s.address,abi:B,functionName:"allowance",args:[o,c.tokenRouterAddress]})<n)if(u.sign){let m=encodeFunctionData({abi:B,functionName:"approve",args:[c.tokenRouterAddress,n]}),l=await u.sign({from:o,to:s.address,data:m}),g=await d.sendRawTransaction({serializedTransaction:l});await d.waitForTransactionReceipt({hash:g,pollingInterval:1e3});}else {let{request:m}=await d.simulateContract({account:o,address:s.address,abi:B,functionName:"approve",args:[c.tokenRouterAddress,n]}),l=await d.writeContract(m);await d.waitForTransactionReceipt({hash:l,pollingInterval:1e3});}if(u.sign){let m=encodeFunctionData({abi:h,functionName:"transferTokens",args:[n,i.domain,o,s.address]}),l=await u.sign({from:o,to:c.tokenRouterAddress,data:m});return d.sendRawTransaction({serializedTransaction:l})}else {let{request:m}=await d.simulateContract({account:o,address:c.tokenRouterAddress,abi:h,functionName:"transferTokens",args:[n,i.domain,o,s.address]});return d.writeContract(m)}},te=async e=>{try{return await e.getBlockNumber()}catch{return}};async function L(e,t,r){await e.ensureHasConfig();let{minimumConfirmations:a}=e.config.find(d=>d.chainId===t.sourceChain.chainId)??{},{minimumConfirmations:p}=e.config.find(d=>d.chainId===t.targetChain.chainId)??{};if(!a||!p)throw new Error("BridgeTransfer: unable to determine required confirmation counts for the given chains.");let n=await e.getFees({...t,provider:t.sourceProvider}),o=(t.asset.address&&n[t.asset.address])??0n,u=await ee(e,t),c=Date.now(),i=T({chain:t.targetChain,provider:t.targetProvider}),s=await te(i);return {type:e.type,environment:r,addressC:t.addressC,addressBtc:t.addressBtc,amount:t.amount,symbol:t.asset.symbol,bridgeFee:o,sourceChain:t.sourceChain,sourceStartedAt:c,sourceTxHash:u,sourceConfirmationCount:0,requiredSourceConfirmationCount:a,targetChain:t.targetChain,targetConfirmationCount:0,requiredTargetConfirmationCount:p,startBlockNumber:s}}async function U(e){if(!e.config&&(await e.updateConfig(),!e.config))throw new Error("Config is not available")}var P=(e,t)=>e.gasPrice&&BigInt(e.gasPrice*t.gasUsed);var M=async e=>new Promise(t=>{setTimeout(t,e);});var I=({promise:e,delay:t,startAfter:r})=>{let a=!1,p=!1,n=0,o,u,c=d=>{o&&a&&(a=!1,o(d));},i=()=>{p=!0,u&&a&&(a=!1,u("cancelled"));};return {result:new Promise((d,y)=>{a=!0,o=d,u=y;let m=async()=>{if(!(!a||p)){try{if(await e(c),!a||p)return;await M(t);}catch(l){console.error(l.message),n+=1,await M(2**n*t);}await m();}};r?setTimeout(m,r):m();}),cancel:i}};var j=1e3*60*60*3,q=1024n,K=5e3,f=(e,t,r)=>{Object.assign(e,Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0))),r({...e});},ne=async(e,t)=>{let{sourceProvider:r,targetProvider:a,updateListener:p,bridgeTransfer:n}=t,o=T({chain:n.sourceChain,provider:r}),u=e.find(y=>y.chainId===n.sourceChain.chainId),c=T({chain:n.targetChain,provider:a}),i=e.find(y=>y.chainId===n.targetChain.chainId),s={...n};if(!u)throw new Error(`BridgeTransfer: unknown source chain "${n.sourceChain.chainId}"`);if(!i)throw new Error(`BridgeTransfer: unknown target chain "${n.targetChain.chainId}"`);return I({promise:async y=>{if(s.completedAt||s.metadata?.nonce)return y(s);if(s.sourceStartedAt+j<=Date.now())return f(s,{completedAt:Date.now(),error:"timeout"},p),y(s);let m=await o.getTransactionReceipt({hash:s.sourceTxHash});if(!s.sourceNetworkFee){let b=await o.getTransaction({hash:s.sourceTxHash}),A=P(b,m);A&&f(s,{sourceNetworkFee:A},p);}if(m.status==="reverted")return f(s,{completedAt:Date.now(),error:`source transaction "${s.sourceTxHash}" reverted`},p),y(s);let l=await o.getTransactionConfirmations({hash:s.sourceTxHash}),g=l>s.sourceConfirmationCount,v=l>=s.requiredSourceConfirmationCount;if(g){let b={};b.sourceConfirmationCount=Number(l),v||(b.startBlockNumber=await c.getBlockNumber()),f(s,b,p);}if(!v)return;s.startBlockNumber||f(s,{startBlockNumber:await c.getBlockNumber()},p);let C=m.logs.find(b=>b.address===u.tokenRouterAddress?decodeEventLog({abi:h,...b}).eventName==="TransferTokens":!1);if(!C)throw new Error(`BridgeTransfer: can't find a TransferTokens event in source transaction "${s.sourceTxHash}"`);let w=decodeEventLog({abi:h,eventName:"TransferTokens",...C}).args.nonce;return f(s,{targetStartedAt:Date.now(),metadata:{nonce:w}},p),y(s)},delay:F(u.chainId),startAfter:K})},re=async(e,t)=>{let{targetProvider:r,updateListener:a,bridgeTransfer:p}=t,n={...p};if(!p.completedAt&&!p.metadata?.nonce)throw new Error("BridgeTransfer: nonce is missing");if(!p.startBlockNumber)throw new Error("BridgeTransfer: startBlockNumber is missing");let o=T({chain:p.targetChain,provider:r}),u=e.find(i=>i.chainId===p.targetChain.chainId);if(!u)throw new Error(`BridgeTransfer: unknown target chain "${p.targetChain.chainId}"`);return I({promise:async i=>{if(n.completedAt)return i(n);if(n.sourceStartedAt+j<=Date.now())return f(n,{completedAt:Date.now(),error:"timeout"},a),i(n);if(!n.targetTxHash){let l=await o.getBlockNumber(),g=(n.startBlockNumber??0n)-q,v=g>=0n?g:"earliest",C=(n.startBlockNumber??0n)+q,E=C<l?C:"latest",w=await o.getLogs({address:u.messageTransmitterAddress,event:{name:"MessageReceived",type:"event",inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint32",name:"sourceDomain",type:"uint32"},{indexed:!0,internalType:"uint64",name:"nonce",type:"uint64"},{indexed:!1,internalType:"bytes32",name:"sender",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"messageBody",type:"bytes"}]},args:{nonce:n.metadata.nonce},fromBlock:v,toBlock:E});if(w[0]?.transactionHash)f(n,{targetTxHash:w[0].transactionHash},a);else return}let s=await o.getTransactionReceipt({hash:n.targetTxHash});if(!n.targetNetworkFee){let l=await o.getTransaction({hash:n.targetTxHash}),g=P(l,s);g&&f(n,{targetNetworkFee:g},a);}if(s.status==="reverted")return f(n,{completedAt:Date.now(),error:`target transaction "${n.targetTxHash}" reverted`},a),i(n);let d=await o.getTransactionConfirmations({hash:n.targetTxHash}),y=d>n.targetConfirmationCount,m=d>=n.requiredTargetConfirmationCount;if(y&&f(n,{targetConfirmationCount:Number(d)},a),!!m)return f(n,{completedAt:Date.now()},a),i(n)},delay:F(u.chainId),startAfter:K})};function z(e,t){let r,a=()=>{r?.();};return {result:(async()=>{await e.ensureHasConfig();let{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:c}=t,{result:i,cancel:s}=await ne(e.config,{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:c});r=s;let d=await i,{result:y,cancel:m}=await re(e.config,{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:d});return r=m,y})(),cancel:a}}var G=e=>({type:"cctp",config:null,updateConfig:async function(){this.config=await D(e);},ensureHasConfig:async function(){return U(this)},getAssets:async function(){return _(this)},getFees:async function(t){return H(this,t)},transferAsset:async function(t){return L(this,t,e)},trackTransfer:function(t){return z(this,t)}});var ae=new Map([["cctp",G]]),V=(e,t)=>new Map([...ae].filter(([r])=>!t?.includes(r)).map(([r,a])=>[r,a(e)])),N=(e,t,r)=>{let a=t.destinations[r]?.find(p=>e.has(p));if(!a)throw new Error(`No enabled implementation found for transfering ${t.symbol} to ${r}`);return {type:a,bridge:e.get(a)}};var mt=({environment:e,disabledBridgeTypes:t})=>{let r=V(e,t),a=async()=>Promise.all(Array.from(r).map(([,i])=>i.updateConfig()));return {bridges:r,init:async()=>{await a();},updateConfigs:a,getAssets:async()=>(await Promise.all(Array.from(r).map(([,s])=>s.getAssets()))).flat().reduce(merge),getFees:async i=>{let{bridge:s}=N(r,i.asset,i.targetChain.chainId);return s.getFees(i)},transferAsset:async i=>{let{bridge:s}=N(r,i.asset,i.targetChain.chainId);return s.transferAsset(i)},trackTransfer:i=>{let s=r.get(i.bridgeTransfer.type);if(!s)throw new Error(`No enabled implementation found for tracking ${i.bridgeTransfer.type} transactions.`);return s.trackTransfer(i)}}}; | ||
var R=(r=>(r.NATIVE="native",r.ERC20="erc20",r))(R||{});var x=(t=>(t.CCTP="cctp",t))(x||{});var S=(r=>(r.PROD="production",r.TEST="test",r))(S||{});var W={test:"https://raw.githubusercontent.com/ava-labs/avalanche-bridge-resources/main/cctp/cctp_config.test.json",production:"https://raw.githubusercontent.com/ava-labs/avalanche-bridge-resources/main/cctp/cctp_config.json"},D=async e=>{try{return await(await fetch(W[e])).json()}catch(t){throw new Error(`Error while fetching CCTP config: ${t.message}`)}},P=e=>{switch(e){case 43114:case 43113:return 1e3;default:return 2e4}};async function _(e){await e.ensureHasConfig();let t=e.config.map(r=>r.chainId);return e.config.reduce((r,s)=>(r[s.chainId]=s.tokens.map(p=>({...p,type:"erc20",destinations:t.reduce((n,o)=>(s.chainId!==o&&(n[o]||(n[o]=[]),n[o]?.push("cctp")),n),{})})),r),{})}var Z=e=>({id:e.chainId,name:e.chainName,nativeCurrency:{decimals:e.networkToken.decimals,symbol:e.networkToken.symbol,name:e.networkToken.name},network:e.chainName,rpcUrls:{default:{http:[e.rpcUrl]},public:{http:[e.rpcUrl]}},...e.utilityAddresses.multicall&&{contracts:{multicall3:{address:e.utilityAddresses.multicall}}}}),T=({chain:e,provider:t})=>{let r=Z(e),s=t?custom(t):http(e.rpcUrl,{batch:!0,retryCount:0});return createWalletClient({chain:r,transport:s}).extend(publicActions)};var w=[{inputs:[{internalType:"address",name:"circleTokenMessenger_",type:"address"},{internalType:"address",name:"burnToken_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AlreadyAdmin",type:"error"},{inputs:[],name:"AlreadyFeeCollector",type:"error"},{inputs:[],name:"AlreadySupportedBurnToken",type:"error"},{inputs:[],name:"AmountLessThanFee",type:"error"},{inputs:[],name:"BalanceNotIncreased",type:"error"},{inputs:[],name:"CannotRemoveLastAdmin",type:"error"},{inputs:[],name:"FeePercentageGreaterThanMax",type:"error"},{inputs:[],name:"InvalidAdminAddress",type:"error"},{inputs:[],name:"InvalidFeeCollector",type:"error"},{inputs:[],name:"InvalidMintRecipientAddress",type:"error"},{inputs:[],name:"InvalidTokenAddress",type:"error"},{inputs:[],name:"InvalidTokenMessengerAddress",type:"error"},{inputs:[],name:"MaxFeeLessThanMinFee",type:"error"},{inputs:[],name:"NotAdmin",type:"error"},{inputs:[],name:"NotFeeCollector",type:"error"},{inputs:[],name:"UnSupportedBurnToken",type:"error"},{inputs:[],name:"UnsupportedDomain",type:"error"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"admin",type:"address"}],name:"AdminAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"admin",type:"address"}],name:"AdminRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"BurnTokenAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"BurnTokenRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"feeCollector",type:"address"}],name:"FeeCollectorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"feeCollector",type:"address"}],name:"FeeCollectorRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint32",name:"domain",type:"uint32"},{components:[{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint32",name:"feePercentage",type:"uint32"},{internalType:"uint256",name:"txnFee",type:"uint256"},{internalType:"bool",name:"supported",type:"bool"}],indexed:!1,internalType:"struct FeeCalculator.FeeConfiguration",name:"feeConfiguration",type:"tuple"}],name:"FeeConfigurationUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"nonce",type:"uint64"},{indexed:!1,internalType:"address",name:"burnToken",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"address",name:"depositor",type:"address"},{indexed:!1,internalType:"address",name:"mintRecipient",type:"address"},{indexed:!1,internalType:"uint32",name:"destinationDomain",type:"uint32"},{indexed:!1,internalType:"uint256",name:"totalFee",type:"uint256"}],name:"TransferTokens",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"addAdmin",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"feeCollector",type:"address"}],name:"addFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"addSupportedBurnToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint32",name:"destinationDomain",type:"uint32"}],name:"calculateFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"circleTokenMessenger",outputs:[{internalType:"contract ICircleTokenMessenger",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"circleTokenMessengerAddress",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"collectFees",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"getFeeAmounts",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getFeeConfiguration",outputs:[{components:[{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint32",name:"feePercentage",type:"uint32"},{internalType:"uint256",name:"txnFee",type:"uint256"},{internalType:"bool",name:"supported",type:"bool"}],internalType:"struct FeeCalculator.FeeConfiguration",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getFeePercentage",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getMaxFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getMinFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"getTxnFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isAdmin",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isFeeCollector",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"isSupportedBurnToken",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"}],name:"isSupportedDomain",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"removeAdmin",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"feeCollector",type:"address"}],name:"removeFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"removeSupportedBurnToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint32",name:"domain",type:"uint32"},{components:[{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint32",name:"feePercentage",type:"uint32"},{internalType:"uint256",name:"txnFee",type:"uint256"},{internalType:"bool",name:"supported",type:"bool"}],internalType:"struct FeeCalculator.FeeConfiguration",name:"feeConfiguration",type:"tuple"}],name:"setFeeConfiguration",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"supportedBurnTokens",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint32",name:"destinationDomain",type:"uint32"},{internalType:"address",name:"mintRecipient",type:"address"},{internalType:"address",name:"burnToken",type:"address"}],name:"transferTokens",outputs:[{internalType:"uint64",name:"nonce",type:"uint64"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"}];var A=({sourceChain:e,targetChain:t,amount:r,asset:s},p)=>{if(e.chainId===t.chainId)throw new Error("Source and target chains are the same");if(r<=0n)throw new Error("Amount must be greater than zero");let n=p.find(i=>i.chainId===e.chainId);if(!n)throw new Error(`Not supported on source chain "${e.chainId}"`);let o=p.find(i=>i.chainId===t.chainId);if(!o)throw new Error(`Not supported on target chain "${t.chainId}"`);let u=n.tokens.find(i=>i.symbol===s.symbol),m=o.tokens.find(i=>i.symbol===s.symbol);if(!u||!m)throw new Error(`Not supported asset "${s.symbol}"`);return {sourceChainData:n,targetChainData:o,burnToken:u,mintToken:m}};async function H(e,t){await e.ensureHasConfig();let{sourceChain:r,targetChain:s,asset:p,amount:n,provider:o}=t,{sourceChainData:u,targetChainData:m,burnToken:i}=A({sourceChain:r,targetChain:s,asset:p,amount:n},e.config),d=await T({chain:r,provider:o}).readContract({address:u.tokenRouterAddress,abi:w,functionName:"calculateFee",args:[n,m.domain]});return {[i.address]:d}}var B=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}];var ee=async(e,t)=>{let{sourceChain:r,targetChain:s,asset:p,amount:n,addressC:o,sourceProvider:u}=t,{sourceChainData:m,targetChainData:i,burnToken:a}=A({sourceChain:r,targetChain:s,asset:p,amount:n},e.config),d=T({chain:r,provider:u});if(await d.readContract({address:a.address,abi:B,functionName:"allowance",args:[o,m.tokenRouterAddress]})<n)if(u.sign){let c=encodeFunctionData({abi:B,functionName:"approve",args:[m.tokenRouterAddress,n]}),y=await u.sign({from:o,to:a.address,data:c}),f=await d.sendRawTransaction({serializedTransaction:y});await d.waitForTransactionReceipt({hash:f,pollingInterval:1e3});}else {let{request:c}=await d.simulateContract({account:o,address:a.address,abi:B,functionName:"approve",args:[m.tokenRouterAddress,n]}),y=await d.writeContract(c);await d.waitForTransactionReceipt({hash:y,pollingInterval:1e3});}if(u.sign){let c=encodeFunctionData({abi:w,functionName:"transferTokens",args:[n,i.domain,o,a.address]}),y=await u.sign({from:o,to:m.tokenRouterAddress,data:c});return d.sendRawTransaction({serializedTransaction:y})}else {let{request:c}=await d.simulateContract({account:o,address:m.tokenRouterAddress,abi:w,functionName:"transferTokens",args:[n,i.domain,o,a.address]});return d.writeContract(c)}},te=async e=>{try{return await e.getBlockNumber()}catch{return}};async function L(e,t,r){await e.ensureHasConfig();let{minimumConfirmations:s}=e.config.find(d=>d.chainId===t.sourceChain.chainId)??{},{minimumConfirmations:p}=e.config.find(d=>d.chainId===t.targetChain.chainId)??{};if(!s||!p)throw new Error("BridgeTransfer: unable to determine required confirmation counts for the given chains.");let n=await e.getFees({...t,provider:t.sourceProvider}),o=(t.asset.address&&n[t.asset.address])??0n,u=await ee(e,t),m=Date.now(),i=T({chain:t.targetChain,provider:t.targetProvider}),a=await te(i);return {type:e.type,environment:r,addressC:t.addressC,addressBtc:t.addressBtc,amount:t.amount,symbol:t.asset.symbol,bridgeFee:o,sourceChain:t.sourceChain,sourceStartedAt:m,sourceTxHash:u,sourceConfirmationCount:0,requiredSourceConfirmationCount:s,targetChain:t.targetChain,targetConfirmationCount:0,requiredTargetConfirmationCount:p,startBlockNumber:a}}async function U(e){if(!e.config&&(await e.updateConfig(),!e.config))throw new Error("Config is not available")}var M=(e,t)=>e.gasPrice&&BigInt(e.gasPrice*t.gasUsed);var I=async e=>new Promise(t=>{setTimeout(t,e);});var N=({promise:e,delay:t,startAfter:r})=>{let s=!1,p=!1,n=0,o,u,m=d=>{o&&s&&(s=!1,o(d));},i=()=>{p=!0,u&&s&&(s=!1,u("cancelled"));};return {result:new Promise((d,l)=>{s=!0,o=d,u=l;let c=async()=>{if(!(!s||p)){try{if(await e(m),!s||p)return;await I(t);}catch(y){console.error(y.message),n+=1,await I(2**n*t);}await c();}};r?setTimeout(c,r):c();}),cancel:i}};var j=1e3*60*60*3,q=1024n,K=5e3,g=(e,t,r)=>{Object.assign(e,Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0))),r({...e});},ne=async(e,t)=>{let{sourceProvider:r,targetProvider:s,updateListener:p,bridgeTransfer:n}=t,o=T({chain:n.sourceChain,provider:r}),u=e.find(l=>l.chainId===n.sourceChain.chainId),m=T({chain:n.targetChain,provider:s}),i=e.find(l=>l.chainId===n.targetChain.chainId),a={...n};if(!u)throw new Error(`BridgeTransfer: unknown source chain "${n.sourceChain.chainId}"`);if(!i)throw new Error(`BridgeTransfer: unknown target chain "${n.targetChain.chainId}"`);return N({promise:async l=>{if(a.completedAt||a.metadata?.nonce)return l(a);if(a.sourceStartedAt+j<=Date.now())return g(a,{completedAt:Date.now(),error:"timeout"},p),l(a);let c=await o.getTransactionReceipt({hash:a.sourceTxHash});if(!a.sourceNetworkFee){let C=await o.getTransaction({hash:a.sourceTxHash}),F=M(C,c);F&&g(a,{sourceNetworkFee:F},p);}if(c.status==="reverted")return g(a,{completedAt:Date.now(),error:`source transaction "${a.sourceTxHash}" reverted`},p),l(a);let y=await o.getTransactionConfirmations({hash:a.sourceTxHash}),f=y>a.sourceConfirmationCount,b=y>=a.requiredSourceConfirmationCount;if(f){let C={};C.sourceConfirmationCount=Number(y),b||(C.startBlockNumber=await m.getBlockNumber()),g(a,C,p);}if(!b)return;a.startBlockNumber||g(a,{startBlockNumber:await m.getBlockNumber()},p);let h=c.logs.find(C=>C.address===u.tokenRouterAddress?decodeEventLog({abi:w,...C}).eventName==="TransferTokens":!1);if(!h)throw new Error(`BridgeTransfer: can't find a TransferTokens event in source transaction "${a.sourceTxHash}"`);let k=decodeEventLog({abi:w,eventName:"TransferTokens",...h}).args.nonce;return g(a,{targetStartedAt:Date.now(),metadata:{nonce:k}},p),l(a)},delay:P(u.chainId),startAfter:K})},re=async(e,t)=>{let{targetProvider:r,updateListener:s,bridgeTransfer:p}=t,n={...p};if(!p.completedAt&&!p.metadata?.nonce)throw new Error("BridgeTransfer: nonce is missing");if(!p.startBlockNumber)throw new Error("BridgeTransfer: startBlockNumber is missing");let o=T({chain:p.targetChain,provider:r}),u=e.find(i=>i.chainId===p.targetChain.chainId);if(!u)throw new Error(`BridgeTransfer: unknown target chain "${p.targetChain.chainId}"`);return N({promise:async i=>{if(n.completedAt)return i(n);if(n.sourceStartedAt+j<=Date.now())return g(n,{completedAt:Date.now(),error:"timeout"},s),i(n);if(!n.targetTxHash){let y=await o.getBlockNumber(),f=(n.startBlockNumber??0n)-q,b=f>=0n?f:"earliest",h=(n.startBlockNumber??0n)+q,v=h<y?h:"latest",k=await o.getLogs({address:u.messageTransmitterAddress,event:{name:"MessageReceived",type:"event",inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint32",name:"sourceDomain",type:"uint32"},{indexed:!0,internalType:"uint64",name:"nonce",type:"uint64"},{indexed:!1,internalType:"bytes32",name:"sender",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"messageBody",type:"bytes"}]},args:{nonce:n.metadata.nonce},fromBlock:b,toBlock:v});if(k[0]?.transactionHash)g(n,{targetTxHash:k[0].transactionHash},s);else return}let a=await o.getTransactionReceipt({hash:n.targetTxHash});if(!n.targetNetworkFee){let y=await o.getTransaction({hash:n.targetTxHash}),f=M(y,a);f&&g(n,{targetNetworkFee:f},s);}if(a.status==="reverted")return g(n,{completedAt:Date.now(),error:`target transaction "${n.targetTxHash}" reverted`},s),i(n);let d=await o.getTransactionConfirmations({hash:n.targetTxHash}),l=d>n.targetConfirmationCount,c=d>=n.requiredTargetConfirmationCount;if(l&&g(n,{targetConfirmationCount:Number(d)},s),!!c)return g(n,{completedAt:Date.now()},s),i(n)},delay:P(u.chainId),startAfter:K})};function z(e,t){let r,s=()=>{r?.();};return {result:(async()=>{await e.ensureHasConfig();let{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:m}=t,{result:i,cancel:a}=await ne(e.config,{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:m});r=a;let d=await i,{result:l,cancel:c}=await re(e.config,{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:d});return r=c,l})(),cancel:s}}var G=e=>({type:"cctp",config:null,updateConfig:async function(){this.config=await D(e);},ensureHasConfig:async function(){return U(this)},getAssets:async function(){return _(this)},getFees:async function(t){return H(this,t)},transferAsset:async function(t){return L(this,t,e)},trackTransfer:function(t){return z(this,t)}});var ae=new Map([["cctp",G]]),V=(e,t)=>new Map([...ae].filter(([r])=>!t?.includes(r)).map(([r,s])=>[r,s(e)])),E=(e,t,r)=>{let s=t.destinations[r]?.find(p=>e.has(p));if(!s)throw new Error(`No enabled implementation found for transfering ${t.symbol} to ${r}`);return {type:s,bridge:e.get(s)}};var yt=({environment:e,disabledBridgeTypes:t})=>{let r=V(e,t),s=async()=>{await Promise.allSettled(Array.from(r).map(([,i])=>i.updateConfig()));};return {environment:e,bridges:r,init:async()=>{await s();},updateConfigs:s,getAssets:async()=>(await Promise.all(Array.from(r).map(([,a])=>a.getAssets()))).reduce((a,d)=>{for(let[l,c]of Object.entries(d)){let y=Number(l),f=a[y];if(f)for(let b of c){let h=f.findIndex(({symbol:v})=>v===b.symbol);h===-1?f.push(b):mergeWith(f[h],b,(v,k)=>{if(isArray(v))return [...new Set(v.concat(k))]});}else a[y]=c;}return a},{}),getFees:async i=>{let{bridge:a}=E(r,i.asset,i.targetChain.chainId);return a.getFees(i)},transferAsset:async i=>{let{bridge:a}=E(r,i.asset,i.targetChain.chainId);return a.transferAsset(i)},trackTransfer:i=>{let a=r.get(i.bridgeTransfer.type);if(!a)throw new Error(`No enabled implementation found for tracking ${i.bridgeTransfer.type} transactions.`);return a.trackTransfer(i)}}}; | ||
export { k as BridgeType, S as Environment, R as TokenType, mt as createUnifiedBridgeService }; | ||
export { x as BridgeType, S as Environment, R as TokenType, yt as createUnifiedBridgeService }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@avalabs/bridge-unified", | ||
"version": "0.0.0-feat-unified-api-interface-20231204170641", | ||
"version": "0.0.0-feat-unified-api-interface-20231213160746", | ||
"main": "dist/index.js", | ||
@@ -18,3 +18,3 @@ "type": "module", | ||
"@internal/tsup-config": "0.0.1", | ||
"eslint-config-custom": "0.0.0-feat-unified-api-interface-20231204170641" | ||
"eslint-config-custom": "0.0.0-feat-unified-api-interface-20231213160746" | ||
}, | ||
@@ -21,0 +21,0 @@ "scripts": { |
@@ -1,5 +0,6 @@ | ||
import { merge } from 'lodash'; | ||
import type { FeeParams, TrackingParams, TransferParams } from './types/bridge'; | ||
import type { BridgeServiceConfig } from './types/config'; | ||
import { getBridgeForTransfer, getEnabledBridgeServices } from './utils'; | ||
import type { ChainAssetMap } from './types'; | ||
import { isArray, mergeWith } from 'lodash'; | ||
@@ -10,3 +11,5 @@ export const createUnifiedBridgeService = ({ environment, disabledBridgeTypes }: BridgeServiceConfig) => { | ||
const updateConfigs = async () => { | ||
return Promise.all(Array.from(enabledBridgeServices).map(([, bridgeService]) => bridgeService.updateConfig())); | ||
await Promise.allSettled( | ||
Array.from(enabledBridgeServices).map(([, bridgeService]) => bridgeService.updateConfig()), | ||
); | ||
}; | ||
@@ -20,3 +23,28 @@ | ||
const assets = await Promise.all(Array.from(enabledBridgeServices).map(([, bridge]) => bridge.getAssets())); | ||
return assets.flat().reduce(merge); | ||
return assets.reduce<ChainAssetMap>((aggregatedAssets, chainAssetMap) => { | ||
for (const [key, bridgeAssets] of Object.entries(chainAssetMap)) { | ||
const chainId = Number(key); | ||
const existingAssets = aggregatedAssets[chainId]; | ||
if (existingAssets) { | ||
for (const bridgeAsset of bridgeAssets) { | ||
const index = existingAssets.findIndex(({ symbol }) => symbol === bridgeAsset.symbol); | ||
if (index === -1) { | ||
existingAssets.push(bridgeAsset); | ||
} else { | ||
mergeWith(existingAssets[index], bridgeAsset, (objValue, srcValue) => { | ||
if (isArray(objValue)) { | ||
return [...new Set(objValue.concat(srcValue))]; | ||
} | ||
}); | ||
} | ||
} | ||
} else { | ||
aggregatedAssets[chainId] = bridgeAssets; | ||
} | ||
} | ||
return aggregatedAssets; | ||
}, {}); | ||
}; | ||
@@ -45,2 +73,3 @@ | ||
return { | ||
environment, | ||
bridges: enabledBridgeServices, | ||
@@ -47,0 +76,0 @@ init, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
334606
60
4147