@avalabs/bridge-unified
Advanced tools
Comparing version 0.0.0-feat-unified-api-interface-20231129000537 to 0.0.0-feat-unified-api-interface-20231129133228
# @avalabs/unified-bridge | ||
## 0.0.0-feat-unified-api-interface-20231129000537 | ||
## 0.0.0-feat-unified-api-interface-20231129133228 | ||
@@ -5,0 +5,0 @@ ### Major Changes |
import { merge } from 'lodash'; | ||
import { custom, http, createWalletClient, publicActions, encodeFunctionData, decodeEventLog } from 'viem'; | ||
var I=(a=>(a.NATIVE="native",a.ERC20="erc20",a))(I||{});var C=(n=>(n.CCTP="cctp",n))(C||{});var E=(a=>(a.PROD="production",a.TEST="test",a))(E||{});var z={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"},N=async e=>{try{return await(await fetch(z[e])).json()}catch(n){throw new Error(`Error while fetching CCTP config: ${n.message}`)}},k=e=>{switch(e){case 43114:case 43113:return 1e3;default:return 2e4}};async function R(e){await e.ensureHasConfig();let n=e.config.map(a=>a.chainId);return e.config.reduce((a,s)=>(a[s.chainId]=s.tokens.map(p=>({...p,type:"erc20",destinations:n.reduce((t,o)=>(s.chainId!==o&&(t[o]||(t[o]=[]),t[o]?.push("cctp")),t),{})})),a),{})}var J=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}}}}),f=({chain:e,provider:n})=>{let a=J(e),s=n?custom(n):http(e.rpcUrl,{batch:!0,retryCount:0});return createWalletClient({chain:a,transport:s}).extend(publicActions)};var g=[{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 h=({sourceChain:e,targetChain:n,amount:a,asset:s},p)=>{if(e.chainId===n.chainId)throw new Error("Source and target chains are the same");if(a<=0n)throw new Error("Amount must be greater than zero");let t=p.find(i=>i.chainId===e.chainId);if(!t)throw new Error(`Not supported on source chain "${e.chainId}"`);let o=p.find(i=>i.chainId===n.chainId);if(!o)throw new Error(`Not supported on target chain "${n.chainId}"`);let u=t.tokens.find(i=>i.symbol===s.symbol),c=o.tokens.find(i=>i.symbol===s.symbol);if(!u||!c)throw new Error(`Not supported asset "${s.symbol}"`);return {sourceChainData:t,targetChainData:o,burnToken:u,mintToken:c}};async function S(e,n){await e.ensureHasConfig();let{sourceChain:a,targetChain:s,asset:p,amount:t,provider:o}=n,{sourceChainData:u,targetChainData:c,burnToken:i}=h({sourceChain:a,targetChain:s,asset:p,amount:t},e.config),d=await f({chain:a,provider:o}).readContract({address:u.tokenRouterAddress,abi:g,functionName:"calculateFee",args:[t,c.domain]});return {[i.address]:d}}var v=[{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 Q=async(e,n)=>{let{sourceChain:a,targetChain:s,asset:p,amount:t,addressC:o,sourceProvider:u}=n,{sourceChainData:c,targetChainData:i,burnToken:r}=h({sourceChain:a,targetChain:s,asset:p,amount:t},e.config),d=f({chain:a,provider:u});if(await d.readContract({address:r.address,abi:v,functionName:"allowance",args:[o,c.tokenRouterAddress]})<t)if(u.sign){let m=encodeFunctionData({abi:v,functionName:"approve",args:[c.tokenRouterAddress,t]}),l=await u.sign({from:o,to:r.address,data:m}),T=await d.sendRawTransaction({serializedTransaction:l});await d.waitForTransactionReceipt({hash:T,pollingInterval:1e3});}else {let{request:m}=await d.simulateContract({account:o,address:r.address,abi:v,functionName:"approve",args:[c.tokenRouterAddress,t]}),l=await d.writeContract(m);await d.waitForTransactionReceipt({hash:l,pollingInterval:1e3});}if(u.sign){let m=encodeFunctionData({abi:g,functionName:"transferTokens",args:[t,i.domain,o,r.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:g,functionName:"transferTokens",args:[t,i.domain,o,r.address]});return d.writeContract(m)}},Y=async e=>{try{return await e.getBlockNumber()}catch{return}};async function _(e,n,a){await e.ensureHasConfig();let{minimumConfirmations:s}=e.config.find(d=>d.chainId===n.sourceChain.chainId)??{},{minimumConfirmations:p}=e.config.find(d=>d.chainId===n.targetChain.chainId)??{};if(!s||!p)throw new Error("BridgeTransfer: unable to determine required confirmation counts for the given chains.");let t=await e.getFees({...n,provider:n.sourceProvider}),o=(n.asset.address&&t[n.asset.address])??0n,u=await Q(e,n),c=Date.now(),i=f({chain:n.targetChain,provider:n.targetProvider}),r=await Y(i);return {type:e.type,environment:a,addressC:n.addressC,addressBtc:n.addressBtc,amount:n.amount,symbol:n.asset.symbol,bridgeFee:o,sourceChain:n.sourceChain,sourceStartedAt:c,sourceTxHash:u,sourceConfirmationCount:0,requiredSourceConfirmationCount:s,targetChain:n.targetChain,targetConfirmationCount:0,requiredTargetConfirmationCount:p,startBlockNumber:r}}async function H(e){if(!e.config&&(await e.updateConfig(),!e.config))throw new Error("Config is not available")}var x=(e,n)=>e.gasPrice&&BigInt(e.gasPrice*n.gasUsed);var A=async e=>new Promise(n=>{setTimeout(n,e);});var B=({promise:e,delay:n})=>{let a=!1,s=!1,p=0,t,o,u=r=>{t&&a&&(a=!1,t(r));},c=()=>{s=!0,o&&a&&(a=!1,o("cancelled"));};return {result:new Promise((r,d)=>{a=!0,t=r,o=d;let y=async()=>{if(!(!a||s)){try{await e(u),await A(n);}catch(m){console.error(m.message),p+=1,await A(2**p*n);}await y();}};y();}),cancel:c}};var L=1e3*60*60*3,U=1024n,Z=async(e,n)=>{let{sourceProvider:a,targetProvider:s,updateListener:p,bridgeTransfer:t}=n,o=f({chain:t.sourceChain,provider:a}),u=e.find(y=>y.chainId===t.sourceChain.chainId),c=f({chain:t.targetChain,provider:s}),i=e.find(y=>y.chainId===t.targetChain.chainId),r={...t};if(!u)throw new Error(`BridgeTransfer: unknown source chain "${t.sourceChain.chainId}"`);if(!i)throw new Error(`BridgeTransfer: unknown target chain "${t.targetChain.chainId}"`);return B({promise:async y=>{if(r.completedAt||r.metadata?.nonce)return y(r);if(r.sourceStartedAt+L<=Date.now())return r.completedAt=Date.now(),r.error="timeout",y(r);let m=await o.getTransactionReceipt({hash:r.sourceTxHash});if(!r.sourceNetworkFee){let b=await o.getTransaction({hash:r.sourceTxHash}),w=x(b,m);w&&(r.sourceNetworkFee=w,p(r));}if(m.status==="reverted")return r.completedAt=Date.now(),r.error=`source transaction "${r.sourceTxHash}" reverted`,y(r);let l=await o.getTransactionConfirmations({hash:r.sourceTxHash}),T=l>r.sourceConfirmationCount,P=l>=r.requiredSourceConfirmationCount;if(T&&(r.sourceConfirmationCount=Number(l),P||(r.startBlockNumber=await c.getBlockNumber()),p(r)),!P)return;r.startBlockNumber||(r.startBlockNumber=await c.getBlockNumber(),p(r));let M=m.logs.find(b=>b.address===u.tokenRouterAddress?decodeEventLog({abi:g,...b}).eventName==="TransferTokens":!1);if(!M)throw new Error(`BridgeTransfer: can't find a TransferTokens event in source transaction "${r.sourceTxHash}"`);let j=decodeEventLog({abi:g,eventName:"TransferTokens",...M}).args.nonce;return r.targetStartedAt=Date.now(),r.metadata={nonce:j},p(r),y(r)},delay:k(u.chainId)})},ee=async(e,n)=>{let{targetProvider:a,updateListener:s,bridgeTransfer:p}=n,t={...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=f({chain:p.targetChain,provider:a}),u=e.find(i=>i.chainId===p.targetChain.chainId);if(!u)throw new Error(`BridgeTransfer: unknown target chain "${p.targetChain.chainId}"`);return B({promise:async i=>{if(t.completedAt)return i(t);if(t.sourceStartedAt+L<=Date.now())return t.completedAt=Date.now(),t.error="timeout",i(t);if(!t.targetTxHash){let l=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:t.metadata.nonce},fromBlock:t.startBlockNumber-U,toBlock:t.startBlockNumber+U});if(l[0]?.transactionHash)t.targetTxHash=l[0].transactionHash,s(t);else return}let r=await o.getTransactionReceipt({hash:t.targetTxHash});if(!t.targetNetworkFee){let l=await o.getTransaction({hash:t.targetTxHash}),T=x(l,r);T&&(t.targetNetworkFee=T,s(t));}if(r.status==="reverted")return t.completedAt=Date.now(),t.error=`target transaction "${t.targetTxHash}" reverted`,s(t),i(t);let d=await o.getTransactionConfirmations({hash:t.targetTxHash}),y=d>t.targetConfirmationCount,m=d>=t.requiredTargetConfirmationCount;if(y&&(t.targetConfirmationCount=Number(d),s(t)),!!m)return t.completedAt=Date.now(),s(t),i(t)},delay:k(u.chainId)})};function $(e,n){let a,s=()=>{a?.();};return {result:(async()=>{await e.ensureHasConfig();let{sourceProvider:t,targetProvider:o,updateListener:u,bridgeTransfer:c}=n,{result:i,cancel:r}=await Z(e.config,{sourceProvider:t,targetProvider:o,updateListener:u,bridgeTransfer:c});a=r;let d=await i,{result:y,cancel:m}=await ee(e.config,{sourceProvider:t,targetProvider:o,updateListener:u,bridgeTransfer:d});return a=m,y})(),cancel:s}}var q=e=>({type:"cctp",config:null,updateConfig:async function(){this.config=await N(e);},ensureHasConfig:async function(){return H(this)},getAssets:async function(){return R(this)},getFees:async function(n){return S(this,n)},transferAsset:async function(n){return _(this,n,e)},trackTransfer:function(n){return $(this,n)}});var te=new Map([["cctp",q]]),K=(e,n)=>new Map([...te].filter(([a])=>!n?.includes(a)).map(([a,s])=>[a,s(e)])),F=(e,n,a)=>{let s=n.destinations[a]?.find(p=>e.has(p));if(!s)throw new Error(`No enabled implementation found for transfering ${n.symbol} to ${a}`);return {type:s,bridge:e.get(s)}};var dt=({environment:e,disabledBridgeTypes:n})=>{let a=K(e,n),s=async()=>Promise.all(Array.from(a).map(([,i])=>i.updateConfig()));return {bridges:a,init:async()=>{await s();},updateConfigs:s,getAssets:async()=>(await Promise.all(Array.from(a).map(([,r])=>r.getAssets()))).flat().reduce(merge),getFees:async i=>{let{bridge:r}=F(a,i.asset,i.targetChain.chainId);return r.getFees(i)},transferAsset:async i=>{let{bridge:r}=F(a,i.asset,i.targetChain.chainId);return r.transferAsset(i)},trackTransfer:i=>{let r=a.get(i.bridgeTransfer.type);if(!r)throw new Error(`No enabled implementation found for tracking ${i.bridgeTransfer.type} transactions.`);return r.trackTransfer(i)}}}; | ||
var E=(r=>(r.NATIVE="native",r.ERC20="erc20",r))(E||{});var C=(t=>(t.CCTP="cctp",t))(C||{});var N=(r=>(r.PROD="production",r.TEST="test",r))(N||{});var G={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"},R=async e=>{try{return await(await fetch(G[e])).json()}catch(t){throw new Error(`Error while fetching CCTP config: ${t.message}`)}},x=e=>{switch(e){case 43114:case 43113:return 1e3;default:return 2e4}};async function S(e){await e.ensureHasConfig();let t=e.config.map(r=>r.chainId);return e.config.reduce((r,i)=>(r[i.chainId]=i.tokens.map(p=>({...p,type:"erc20",destinations:t.reduce((n,o)=>(i.chainId!==o&&(n[o]||(n[o]=[]),n[o]?.push("cctp")),n),{})})),r),{})}var Q=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}}}}),g=({chain:e,provider:t})=>{let r=Q(e),i=t?custom(t):http(e.rpcUrl,{batch:!0,retryCount:0});return createWalletClient({chain:r,transport:i}).extend(publicActions)};var b=[{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 v=({sourceChain:e,targetChain:t,amount:r,asset:i},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(s=>s.chainId===e.chainId);if(!n)throw new Error(`Not supported on source chain "${e.chainId}"`);let o=p.find(s=>s.chainId===t.chainId);if(!o)throw new Error(`Not supported on target chain "${t.chainId}"`);let u=n.tokens.find(s=>s.symbol===i.symbol),c=o.tokens.find(s=>s.symbol===i.symbol);if(!u||!c)throw new Error(`Not supported asset "${i.symbol}"`);return {sourceChainData:n,targetChainData:o,burnToken:u,mintToken:c}};async function D(e,t){await e.ensureHasConfig();let{sourceChain:r,targetChain:i,asset:p,amount:n,provider:o}=t,{sourceChainData:u,targetChainData:c,burnToken:s}=v({sourceChain:r,targetChain:i,asset:p,amount:n},e.config),d=await g({chain:r,provider:o}).readContract({address:u.tokenRouterAddress,abi:b,functionName:"calculateFee",args:[n,c.domain]});return {[s.address]:d}}var w=[{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 Y=async(e,t)=>{let{sourceChain:r,targetChain:i,asset:p,amount:n,addressC:o,sourceProvider:u}=t,{sourceChainData:c,targetChainData:s,burnToken:a}=v({sourceChain:r,targetChain:i,asset:p,amount:n},e.config),d=g({chain:r,provider:u});if(await d.readContract({address:a.address,abi:w,functionName:"allowance",args:[o,c.tokenRouterAddress]})<n)if(u.sign){let m=encodeFunctionData({abi:w,functionName:"approve",args:[c.tokenRouterAddress,n]}),l=await u.sign({from:o,to:a.address,data:m}),h=await d.sendRawTransaction({serializedTransaction:l});await d.waitForTransactionReceipt({hash:h,pollingInterval:1e3});}else {let{request:m}=await d.simulateContract({account:o,address:a.address,abi:w,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:b,functionName:"transferTokens",args:[n,s.domain,o,a.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:b,functionName:"transferTokens",args:[n,s.domain,o,a.address]});return d.writeContract(m)}},Z=async e=>{try{return await e.getBlockNumber()}catch{return}};async function H(e,t,r){await e.ensureHasConfig();let{minimumConfirmations:i}=e.config.find(d=>d.chainId===t.sourceChain.chainId)??{},{minimumConfirmations:p}=e.config.find(d=>d.chainId===t.targetChain.chainId)??{};if(!i||!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 Y(e,t),c=Date.now(),s=g({chain:t.targetChain,provider:t.targetProvider}),a=await Z(s);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:i,targetChain:t.targetChain,targetConfirmationCount:0,requiredTargetConfirmationCount:p,startBlockNumber:a}}async function O(e){if(!e.config&&(await e.updateConfig(),!e.config))throw new Error("Config is not available")}var B=(e,t)=>e.gasPrice&&BigInt(e.gasPrice*t.gasUsed);var A=async e=>new Promise(t=>{setTimeout(t,e);});var F=({promise:e,delay:t})=>{let r=!1,i=!1,p=0,n,o,u=a=>{n&&r&&(r=!1,n(a));},c=()=>{i=!0,o&&r&&(r=!1,o("cancelled"));};return {result:new Promise((a,d)=>{r=!0,n=a,o=d;let y=async()=>{if(!(!r||i)){try{await e(u),await A(t);}catch(m){console.error(m.message),p+=1,await A(2**p*t);}await y();}};y();}),cancel:c}};var $=1e3*60*60*3,U=1024n,f=(e,t,r)=>{Object.assign(e,Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))),r({...e});},ee=async(e,t)=>{let{sourceProvider:r,targetProvider:i,updateListener:p,bridgeTransfer:n}=t,o=g({chain:n.sourceChain,provider:r}),u=e.find(y=>y.chainId===n.sourceChain.chainId),c=g({chain:n.targetChain,provider:i}),s=e.find(y=>y.chainId===n.targetChain.chainId),a={...n};if(!u)throw new Error(`BridgeTransfer: unknown source chain "${n.sourceChain.chainId}"`);if(!s)throw new Error(`BridgeTransfer: unknown target chain "${n.targetChain.chainId}"`);return F({promise:async y=>{if(a.completedAt||a.metadata?.nonce)return y(a);if(a.sourceStartedAt+$<=Date.now())return f(a,{completedAt:Date.now(),error:"timeout"},p),y(a);let m=await o.getTransactionReceipt({hash:a.sourceTxHash});if(!a.sourceNetworkFee){let T=await o.getTransaction({hash:a.sourceTxHash}),k=B(T,m);k&&f(a,{sourceNetworkFee:k},p);}if(m.status==="reverted")return f(a,{completedAt:Date.now(),error:`source transaction "${a.sourceTxHash}" reverted`},p),y(a);let l=await o.getTransactionConfirmations({hash:a.sourceTxHash}),h=l>a.sourceConfirmationCount,M=l>=a.requiredSourceConfirmationCount;if(h){let T={};T.sourceConfirmationCount=Number(l),M||(T.startBlockNumber=await c.getBlockNumber()),f(a,T,p);}if(!M)return;a.startBlockNumber||f(a,{startBlockNumber:await c.getBlockNumber()},p);let I=m.logs.find(T=>T.address===u.tokenRouterAddress?decodeEventLog({abi:b,...T}).eventName==="TransferTokens":!1);if(!I)throw new Error(`BridgeTransfer: can't find a TransferTokens event in source transaction "${a.sourceTxHash}"`);let z=decodeEventLog({abi:b,eventName:"TransferTokens",...I}).args.nonce;return f(a,{targetStartedAt:Date.now(),metadata:{nonce:z}},p),y(a)},delay:x(u.chainId)})},te=async(e,t)=>{let{targetProvider:r,updateListener:i,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=g({chain:p.targetChain,provider:r}),u=e.find(s=>s.chainId===p.targetChain.chainId);if(!u)throw new Error(`BridgeTransfer: unknown target chain "${p.targetChain.chainId}"`);return F({promise:async s=>{if(n.completedAt)return s(n);if(n.sourceStartedAt+$<=Date.now())return f(n,{completedAt:Date.now(),error:"timeout"},i),s(n);if(!n.targetTxHash){let l=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:n.startBlockNumber-U,toBlock:n.startBlockNumber+U});if(l[0]?.transactionHash)f(n,{targetTxHash:l[0].transactionHash},i);else return}let a=await o.getTransactionReceipt({hash:n.targetTxHash});if(!n.targetNetworkFee){let l=await o.getTransaction({hash:n.targetTxHash}),h=B(l,a);h&&f(n,{targetNetworkFee:h},i);}if(a.status==="reverted")return f(n,{completedAt:Date.now(),error:`target transaction "${n.targetTxHash}" reverted`},i),s(n);let d=await o.getTransactionConfirmations({hash:n.targetTxHash}),y=d>n.targetConfirmationCount,m=d>=n.requiredTargetConfirmationCount;if(y&&f(n,{targetConfirmationCount:Number(d)},i),!!m)return f(n,{completedAt:Date.now()},i),s(n)},delay:x(u.chainId)})};function q(e,t){let r,i=()=>{r?.();};return {result:(async()=>{await e.ensureHasConfig();let{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:c}=t,{result:s,cancel:a}=await ee(e.config,{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:c});r=a;let d=await s,{result:y,cancel:m}=await te(e.config,{sourceProvider:n,targetProvider:o,updateListener:u,bridgeTransfer:d});return r=m,y})(),cancel:i}}var j=e=>({type:"cctp",config:null,updateConfig:async function(){this.config=await R(e);},ensureHasConfig:async function(){return O(this)},getAssets:async function(){return S(this)},getFees:async function(t){return D(this,t)},transferAsset:async function(t){return H(this,t,e)},trackTransfer:function(t){return q(this,t)}});var ne=new Map([["cctp",j]]),K=(e,t)=>new Map([...ne].filter(([r])=>!t?.includes(r)).map(([r,i])=>[r,i(e)])),P=(e,t,r)=>{let i=t.destinations[r]?.find(p=>e.has(p));if(!i)throw new Error(`No enabled implementation found for transfering ${t.symbol} to ${r}`);return {type:i,bridge:e.get(i)}};var ct=({environment:e,disabledBridgeTypes:t})=>{let r=K(e,t),i=async()=>Promise.all(Array.from(r).map(([,s])=>s.updateConfig()));return {bridges:r,init:async()=>{await i();},updateConfigs:i,getAssets:async()=>(await Promise.all(Array.from(r).map(([,a])=>a.getAssets()))).flat().reduce(merge),getFees:async s=>{let{bridge:a}=P(r,s.asset,s.targetChain.chainId);return a.getFees(s)},transferAsset:async s=>{let{bridge:a}=P(r,s.asset,s.targetChain.chainId);return a.transferAsset(s)},trackTransfer:s=>{let a=r.get(s.bridgeTransfer.type);if(!a)throw new Error(`No enabled implementation found for tracking ${s.bridgeTransfer.type} transactions.`);return a.trackTransfer(s)}}}; | ||
export { C as BridgeType, E as Environment, I as TokenType, dt as createUnifiedBridgeService }; | ||
export { C as BridgeType, N as Environment, E as TokenType, ct as createUnifiedBridgeService }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@avalabs/bridge-unified", | ||
"version": "0.0.0-feat-unified-api-interface-20231129000537", | ||
"version": "0.0.0-feat-unified-api-interface-20231129133228", | ||
"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-20231129000537" | ||
"eslint-config-custom": "0.0.0-feat-unified-api-interface-20231129133228" | ||
}, | ||
@@ -21,0 +21,0 @@ "scripts": { |
@@ -180,3 +180,4 @@ import { decodeEventLog } from 'viem'; | ||
expect(doneMock).toHaveBeenCalledWith(expectedResult); | ||
expect(updateListenerWithoutReference).not.toHaveBeenCalled(); | ||
expect(updateListenerWithoutReference).toHaveBeenCalledTimes(1); | ||
expect(updateListenerWithoutReference).toHaveBeenCalledWith(expectedResult); | ||
@@ -210,7 +211,8 @@ expect(getTrackingDelayByChainId).toHaveBeenCalledWith(SOURCE_CHAIN.chainId); | ||
expect(doneMock).toHaveBeenCalledWith(expectedResult); | ||
expect(updateListenerWithoutReference).toHaveBeenCalledTimes(1); | ||
expect(updateListenerWithoutReference).toHaveBeenCalledWith({ | ||
expect(updateListenerWithoutReference).toHaveBeenCalledTimes(2); | ||
expect(updateListenerWithoutReference).toHaveBeenNthCalledWith(1, { | ||
...params.bridgeTransfer, | ||
sourceNetworkFee: networkFee, | ||
}); | ||
expect(updateListenerWithoutReference).toHaveBeenNthCalledWith(2, expectedResult); | ||
@@ -467,3 +469,4 @@ expect(sourceClientMock.getTransactionReceipt).toHaveBeenCalledWith({ | ||
expect(doneMock).toHaveBeenCalledWith(expectedResult); | ||
expect(updateListenerWithoutReference).not.toHaveBeenCalled(); | ||
expect(updateListenerWithoutReference).toHaveBeenCalledTimes(1); | ||
expect(updateListenerWithoutReference).toHaveBeenCalledWith(expectedResult); | ||
@@ -470,0 +473,0 @@ expect(getTrackingDelayByChainId).toHaveBeenCalledWith(TARGET_CHAIN.chainId); |
@@ -15,2 +15,15 @@ import { decodeEventLog, type Address } from 'viem'; | ||
/** | ||
* Mutates the `initial` transfer by merging it with the `updated` properties if they are not undefined | ||
* Invokes the `updateListener` with a copy of the updated `initial` transfer | ||
*/ | ||
const updateTransfer = ( | ||
initial: BridgeTransfer, | ||
updated: Partial<BridgeTransfer>, | ||
updateListener: TrackingParams['updateListener'], | ||
) => { | ||
Object.assign(initial, Object.fromEntries(Object.entries(updated).filter(([, value]) => value !== undefined))); | ||
updateListener({ ...initial }); | ||
}; | ||
/** | ||
* Polls the source network until it's able to get the CCTP message's `nonce` from the source transaction's logs | ||
@@ -49,4 +62,3 @@ * Updates the provided `BridgeTransfer` and broadcasts the changes via `updateListener` | ||
if (updateableTransfer.sourceStartedAt + TRACKING_LIMIT_MS <= Date.now()) { | ||
updateableTransfer.completedAt = Date.now(); | ||
updateableTransfer.error = 'timeout'; | ||
updateTransfer(updateableTransfer, { completedAt: Date.now(), error: 'timeout' }, updateListener); | ||
return done(updateableTransfer); | ||
@@ -71,4 +83,3 @@ } | ||
if (networkFee) { | ||
updateableTransfer.sourceNetworkFee = networkFee; | ||
updateListener(updateableTransfer); | ||
updateTransfer(updateableTransfer, { sourceNetworkFee: networkFee }, updateListener); | ||
} | ||
@@ -81,4 +92,7 @@ } | ||
if (txReceipt.status === 'reverted') { | ||
updateableTransfer.completedAt = Date.now(); | ||
updateableTransfer.error = `source transaction "${updateableTransfer.sourceTxHash}" reverted`; | ||
updateTransfer( | ||
updateableTransfer, | ||
{ completedAt: Date.now(), error: `source transaction "${updateableTransfer.sourceTxHash}" reverted` }, | ||
updateListener, | ||
); | ||
return done(updateableTransfer); | ||
@@ -100,9 +114,10 @@ } | ||
if (hasMoreConfirmations) { | ||
updateableTransfer.sourceConfirmationCount = Number(confirmationCount); | ||
const changes = {} as Partial<BridgeTransfer>; | ||
changes.sourceConfirmationCount = Number(confirmationCount); | ||
if (!hasRequiredConfirmations) { | ||
updateableTransfer.startBlockNumber = await targetClient.getBlockNumber(); | ||
changes.startBlockNumber = await targetClient.getBlockNumber(); | ||
} | ||
updateListener(updateableTransfer); | ||
updateTransfer(updateableTransfer, changes, updateListener); | ||
} | ||
@@ -115,4 +130,3 @@ | ||
if (!updateableTransfer.startBlockNumber) { | ||
updateableTransfer.startBlockNumber = await targetClient.getBlockNumber(); | ||
updateListener(updateableTransfer); | ||
updateTransfer(updateableTransfer, { startBlockNumber: await targetClient.getBlockNumber() }, updateListener); | ||
} | ||
@@ -154,5 +168,3 @@ | ||
const nonce = transferEvent.args.nonce; | ||
updateableTransfer.targetStartedAt = Date.now(); | ||
updateableTransfer.metadata = { nonce }; | ||
updateListener(updateableTransfer); | ||
updateTransfer(updateableTransfer, { targetStartedAt: Date.now(), metadata: { nonce } }, updateListener); | ||
return done(updateableTransfer); | ||
@@ -203,4 +215,3 @@ }; | ||
if (updateableTransfer.sourceStartedAt + TRACKING_LIMIT_MS <= Date.now()) { | ||
updateableTransfer.completedAt = Date.now(); | ||
updateableTransfer.error = 'timeout'; | ||
updateTransfer(updateableTransfer, { completedAt: Date.now(), error: 'timeout' }, updateListener); | ||
return done(updateableTransfer); | ||
@@ -229,4 +240,3 @@ } | ||
if (targetLogs[0]?.transactionHash) { | ||
updateableTransfer.targetTxHash = targetLogs[0].transactionHash; | ||
updateListener(updateableTransfer); | ||
updateTransfer(updateableTransfer, { targetTxHash: targetLogs[0].transactionHash }, updateListener); | ||
} else { | ||
@@ -253,4 +263,3 @@ return; | ||
if (networkFee) { | ||
updateableTransfer.targetNetworkFee = networkFee; | ||
updateListener(updateableTransfer); | ||
updateTransfer(updateableTransfer, { targetNetworkFee: networkFee }, updateListener); | ||
} | ||
@@ -263,5 +272,7 @@ } | ||
if (txReceipt.status === 'reverted') { | ||
updateableTransfer.completedAt = Date.now(); | ||
updateableTransfer.error = `target transaction "${updateableTransfer.targetTxHash}" reverted`; | ||
updateListener(updateableTransfer); | ||
updateTransfer( | ||
updateableTransfer, | ||
{ completedAt: Date.now(), error: `target transaction "${updateableTransfer.targetTxHash}" reverted` }, | ||
updateListener, | ||
); | ||
return done(updateableTransfer); | ||
@@ -282,4 +293,3 @@ } | ||
if (hasMoreConfirmations) { | ||
updateableTransfer.targetConfirmationCount = Number(confirmationCount); | ||
updateListener(updateableTransfer); | ||
updateTransfer(updateableTransfer, { targetConfirmationCount: Number(confirmationCount) }, updateListener); | ||
} | ||
@@ -291,4 +301,3 @@ | ||
updateableTransfer.completedAt = Date.now(); | ||
updateListener(updateableTransfer); | ||
updateTransfer(updateableTransfer, { completedAt: Date.now() }, updateListener); | ||
return done(updateableTransfer); | ||
@@ -295,0 +304,0 @@ }; |
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
310692
3671