@avalabs/bridge-unified
Advanced tools
Comparing version 0.0.0-feat-unified-api-interface-20240105153058 to 0.0.0-feat-unified-api-interface-20240105191038
# @avalabs/unified-bridge | ||
## 0.0.0-feat-unified-api-interface-20240105153058 | ||
## 0.0.0-feat-unified-api-interface-20240105191038 | ||
@@ -5,0 +5,0 @@ ### Major Changes |
import { custom, http, createWalletClient, publicActions, isAddress, encodeFunctionData, decodeEventLog } from 'viem'; | ||
import { mergeWith, isArray } from 'lodash'; | ||
var U=(r=>(r.NATIVE="native",r.ERC20="erc20",r))(U||{});var R=(t=>(t.CCTP="cctp",t))(R||{});var H=(r=>(r.PROD="production",r.TEST="test",r))(H||{});var B=(n=>(n[n.BRIDGE_NOT_AVAILABLE=5001]="BRIDGE_NOT_AVAILABLE",n[n.INITIALIZATION_FAILED=5002]="INITIALIZATION_FAILED",n[n.INVALID_PARAMS=5003]="INVALID_PARAMS",n[n.TIMEOUT=5004]="TIMEOUT",n[n.TRANSACTION_REVERTED=5005]="TRANSACTION_REVERTED",n))(B||{}),w=(i=>(i.UNKNOWN="UNKNOWN",i.CONFIG_NOT_AVAILABLE="CONFIG_NOT_AVAILABLE",i.INVALID_PARAMS="INVALID_PARAMS",i.IDENTICAL_CHAINS_PROVIDED="IDENTICAL_CHAINS_PROVIDED",i.INCORRECT_AMOUNT_PROVIDED="INCORRECT_AMOUNT_PROVIDED",i.INCORRECT_ADDRESS_PROVIDED="INCORRECT_ADDRESS_PROVIDED",i.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",i.ASSET_NOT_SUPPORTED="ASSET_NOT_SUPPORTED",i.CONFIRMATION_COUNT_UNKNOWN="CONFIRMATION_COUNT_UNKNOWN",i))(w||{});var I=class extends Error{constructor(r,s,p){super(r);this.code=s;this.details=p;}};var x=class extends I{constructor(t="UNKNOWN",r){super(t,5001,r),this.name="BridgeUnavailableError";}};var P=class extends I{constructor(t="UNKNOWN",r){super(t,5002,r),this.name="BridgeInitializationError";}};var f=class extends I{constructor(t="INVALID_PARAMS",r){super(t,5003,r),this.name="InvalidParamsError";}};var te={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"},V=async e=>{try{return await(await fetch(te[e])).json()}catch(t){throw new P("CONFIG_NOT_AVAILABLE",`Error while fetching CCTP config: ${t.message}`)}},D=e=>{switch(e){case 43114:case 43113:return 1e3;default:return 2e4}};async function K(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 ie=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}}}}),v=({chain:e,provider:t})=>{let r=ie(e),s=t?custom(t):http(e.rpcUrl,{batch:!0,retryCount:0});return createWalletClient({chain:r,transport:s}).extend(publicActions)};var N=[{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 _=({sourceChain:e,targetChain:t,amount:r,asset:s},p)=>{if(e.chainId===t.chainId)throw new f("IDENTICAL_CHAINS_PROVIDED");if(r<=0n)throw new f("INCORRECT_AMOUNT_PROVIDED","Amount must be greater than zero");let n=p.find(i=>i.chainId===e.chainId);if(!n)throw new f("CHAIN_NOT_SUPPORTED",`Not supported on source chain "${e.chainId}"`);let o=p.find(i=>i.chainId===t.chainId);if(!o)throw new f("CHAIN_NOT_SUPPORTED",`Not supported on target chain "${t.chainId}"`);let d=n.tokens.find(i=>i.symbol===s.symbol),y=o.tokens.find(i=>i.symbol===s.symbol);if(!d||!y)throw new f("ASSET_NOT_SUPPORTED");return {sourceChainData:n,targetChainData:o,burnToken:d,mintToken:y}};async function G(e,t){await e.ensureHasConfig();let{sourceChain:r,targetChain:s,asset:p,amount:n,provider:o}=t,{sourceChainData:d,targetChainData:y,burnToken:i}=_({sourceChain:r,targetChain:s,asset:p,amount:n},e.config),u=await v({chain:r,provider:o}).readContract({address:d.tokenRouterAddress,abi:N,functionName:"calculateFee",args:[n,y.domain]});return {[i.address]:u}}var E=[{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 oe=async(e,t)=>{let{sourceChain:r,targetChain:s,asset:p,amount:n,fromAddress:o,toAddress:d,sourceProvider:y}=t,i=d??o;if(!isAddress(o)||!isAddress(i))throw new f("INCORRECT_ADDRESS_PROVIDED");let{sourceChainData:a,targetChainData:u,burnToken:m}=_({sourceChain:r,targetChain:s,asset:p,amount:n},e.config),c=v({chain:r,provider:y});if(await c.readContract({address:m.address,abi:E,functionName:"allowance",args:[o,a.tokenRouterAddress]})<n)if(y.sign){let l=encodeFunctionData({abi:E,functionName:"approve",args:[a.tokenRouterAddress,n]}),T=await y.sign({from:o,to:m.address,data:l}),C=await c.sendRawTransaction({serializedTransaction:T});await c.waitForTransactionReceipt({hash:C,pollingInterval:1e3});}else {let{request:l}=await c.simulateContract({account:o,address:m.address,abi:E,functionName:"approve",args:[a.tokenRouterAddress,n]}),T=await c.writeContract(l);await c.waitForTransactionReceipt({hash:T,pollingInterval:1e3});}if(y.sign){let l=encodeFunctionData({abi:N,functionName:"transferTokens",args:[n,u.domain,i,m.address]}),T=await y.sign({from:o,to:a.tokenRouterAddress,data:l});return c.sendRawTransaction({serializedTransaction:T})}else {let{request:l}=await c.simulateContract({account:o,address:a.tokenRouterAddress,abi:N,functionName:"transferTokens",args:[n,u.domain,i,m.address]});return c.writeContract(l)}},pe=async e=>{try{return await e.getBlockNumber()}catch{return}};async function j(e,t,r){await e.ensureHasConfig();let{minimumConfirmations:s}=e.config.find(u=>u.chainId===t.sourceChain.chainId)??{},{minimumConfirmations:p}=e.config.find(u=>u.chainId===t.targetChain.chainId)??{};if(!s||!p)throw new f("CONFIRMATION_COUNT_UNKNOWN");let n=await e.getFees({...t,provider:t.sourceProvider}),o=(t.asset.address&&n[t.asset.address])??0n,d=await oe(e,t),y=Date.now(),i=v({chain:t.targetChain,provider:t.targetProvider}),a=await pe(i);return {type:e.type,environment:r,fromAddress:t.fromAddress,toAddress:t.toAddress??t.fromAddress,amount:t.amount,symbol:t.asset.symbol,bridgeFee:o,sourceChain:t.sourceChain,sourceStartedAt:y,sourceTxHash:d,sourceConfirmationCount:0,requiredSourceConfirmationCount:s,targetChain:t.targetChain,targetConfirmationCount:0,requiredTargetConfirmationCount:p,startBlockNumber:a}}async function z(e){if(!e.config&&(await e.updateConfig(),!e.config))throw new P("CONFIG_NOT_AVAILABLE")}var O=(e,t)=>e.gasPrice&&BigInt(e.gasPrice*t.gasUsed);var S=async e=>new Promise(t=>{setTimeout(t,e);});var L=({promise:e,delay:t,startAfter:r})=>{let s=!1,p=!1,n=0,o,d,y=u=>{o&&s&&(s=!1,o(u));},i=()=>{p=!0,d&&s&&(s=!1,d("cancelled"));};return {result:new Promise((u,m)=>{s=!0,o=u,d=m;let c=async()=>{if(!(!s||p)){try{if(await e(y),!s||p)return;await S(t);}catch(g){console.error(g.message),n+=1,await S(2**n*t);}await c();}};r?setTimeout(c,r):c();}),cancel:i}};var Z=1e3*60*60*3,J=1024n,X=5e3,A=(e,t,r)=>{Object.assign(e,Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0))),r({...e});},ue=async(e,t)=>{let{sourceProvider:r,targetProvider:s,updateListener:p,bridgeTransfer:n}=t,o=v({chain:n.sourceChain,provider:r}),d=e.find(m=>m.chainId===n.sourceChain.chainId),y=v({chain:n.targetChain,provider:s}),i=e.find(m=>m.chainId===n.targetChain.chainId),a={...n};if(!d||!i)throw new f("CHAIN_NOT_SUPPORTED");return L({promise:async m=>{if(a.completedAt||a.metadata?.nonce)return m(a);if(a.sourceStartedAt+Z<=Date.now())return A(a,{completedAt:Date.now(),errorCode:5004},p),m(a);let c=await o.getTransactionReceipt({hash:a.sourceTxHash});if(!a.sourceNetworkFee){let b=await o.getTransaction({hash:a.sourceTxHash}),M=O(b,c);M&&A(a,{sourceNetworkFee:M},p);}if(c.status==="reverted")return A(a,{completedAt:Date.now(),errorCode:5005},p),m(a);let g=await o.getTransactionConfirmations({hash:a.sourceTxHash}),l=g>a.sourceConfirmationCount,T=g>=a.requiredSourceConfirmationCount;if(l){let b={};b.sourceConfirmationCount=Number(g),T||(b.startBlockNumber=await y.getBlockNumber()),A(a,b,p);}if(!T)return;a.startBlockNumber||A(a,{startBlockNumber:await y.getBlockNumber()},p);let C=c.logs.find(b=>b.address===d.tokenRouterAddress?decodeEventLog({abi:N,...b}).eventName==="TransferTokens":!1);if(!C)throw new f("INVALID_PARAMS",`unable to find a TransferTokens event in source transaction "${a.sourceTxHash}"`);let h=decodeEventLog({abi:N,eventName:"TransferTokens",...C}).args.nonce;return A(a,{targetStartedAt:Date.now(),metadata:{nonce:h}},p),m(a)},delay:D(d.chainId),startAfter:X})},de=async(e,t)=>{let{targetProvider:r,updateListener:s,bridgeTransfer:p}=t,n={...p};if(!p.completedAt&&!p.metadata?.nonce)throw new f("INVALID_PARAMS","nonce is missing");if(!p.startBlockNumber)throw new f("INVALID_PARAMS","startBlockNumber is missing");let o=v({chain:p.targetChain,provider:r}),d=e.find(i=>i.chainId===p.targetChain.chainId);if(!d)throw new f("INVALID_PARAMS",`unknown target chain "${p.targetChain.chainId}"`);return L({promise:async i=>{if(n.completedAt)return i(n);if(n.sourceStartedAt+Z<=Date.now())return A(n,{completedAt:Date.now(),errorCode:5004},s),i(n);if(!n.targetTxHash){let g=await o.getBlockNumber(),l=(n.startBlockNumber??0n)-J,T=l>=0n?l:"earliest",C=(n.startBlockNumber??0n)+J,k=C<g?C:"latest",h=await o.getLogs({address:d.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:T,toBlock:k});if(h[0]?.transactionHash)A(n,{targetTxHash:h[0].transactionHash},s);else return}let a=await o.getTransactionReceipt({hash:n.targetTxHash});if(!n.targetNetworkFee){let g=await o.getTransaction({hash:n.targetTxHash}),l=O(g,a);l&&A(n,{targetNetworkFee:l},s);}if(a.status==="reverted")return A(n,{completedAt:Date.now(),errorCode:5005},s),i(n);let u=await o.getTransactionConfirmations({hash:n.targetTxHash}),m=u>n.targetConfirmationCount,c=u>=n.requiredTargetConfirmationCount;if(m&&A(n,{targetConfirmationCount:Number(u)},s),!!c)return A(n,{completedAt:Date.now()},s),i(n)},delay:D(d.chainId),startAfter:X})};function Y(e,t){let r,s=()=>{r?.();};return {result:(async()=>{await e.ensureHasConfig();let{sourceProvider:n,targetProvider:o,updateListener:d,bridgeTransfer:y}=t,{result:i,cancel:a}=await ue(e.config,{sourceProvider:n,targetProvider:o,updateListener:d,bridgeTransfer:y});r=a;let u=await i,{result:m,cancel:c}=await de(e.config,{sourceProvider:n,targetProvider:o,updateListener:d,bridgeTransfer:u});return r=c,m})(),cancel:s}}var Q=e=>({type:"cctp",config:null,updateConfig:async function(){this.config=await V(e);},ensureHasConfig:async function(){return z(this)},getAssets:async function(){return K(this)},getFees:async function(t){return G(this,t)},transferAsset:async function(t){return j(this,t,e)},trackTransfer:function(t){return Y(this,t)}});var ce=new Map([["cctp",Q]]),ee=(e,t)=>new Map([...ce].filter(([r])=>!t?.includes(r)).map(([r,s])=>[r,s(e)])),F=(e,t,r)=>{let s=t.destinations[r]?.find(p=>e.has(p));if(!s)throw new x;return {type:s,bridge:e.get(s)}};var Yt=({environment:e,disabledBridgeTypes:t})=>{let r=ee(e,t),s=async()=>{await Promise.allSettled(Array.from(r).map(([,a])=>a.updateConfig()));};return {environment:e,bridges:r,init:async()=>{await s();},updateConfigs:s,getAssets:async()=>(await Promise.all(Array.from(r).map(([,u])=>u.getAssets()))).reduce((u,m)=>{for(let[c,g]of Object.entries(m)){let l=Number(c),T=u[l];if(T)for(let C of g){let k=T.findIndex(({symbol:h})=>h===C.symbol);k===-1?T.push(C):mergeWith(T[k],C,(h,b)=>{if(isArray(h))return [...new Set(h.concat(b))]});}else u[l]=g;}return u},{}),getFees:async a=>{let{bridge:u}=F(r,a.asset,a.targetChain.chainId);return u.getFees(a)},canTransferAsset:(a,u)=>{try{return F(r,a,u),!0}catch{return !1}},transferAsset:async a=>{let{bridge:u}=F(r,a.asset,a.targetChain.chainId);return u.transferAsset(a)},trackTransfer:a=>{let u=r.get(a.bridgeTransfer.type);if(!u)throw new x;return u.trackTransfer(a)}}}; | ||
var U=(r=>(r.NATIVE="native",r.ERC20="erc20",r))(U||{});var R=(t=>(t.CCTP="cctp",t))(R||{});var H=(r=>(r.PROD="production",r.TEST="test",r))(H||{});var B=(n=>(n[n.BRIDGE_NOT_AVAILABLE=5001]="BRIDGE_NOT_AVAILABLE",n[n.INITIALIZATION_FAILED=5002]="INITIALIZATION_FAILED",n[n.INVALID_PARAMS=5003]="INVALID_PARAMS",n[n.TIMEOUT=5004]="TIMEOUT",n[n.TRANSACTION_REVERTED=5005]="TRANSACTION_REVERTED",n))(B||{}),w=(i=>(i.UNKNOWN="UNKNOWN",i.CONFIG_NOT_AVAILABLE="CONFIG_NOT_AVAILABLE",i.INVALID_PARAMS="INVALID_PARAMS",i.IDENTICAL_CHAINS_PROVIDED="IDENTICAL_CHAINS_PROVIDED",i.INCORRECT_AMOUNT_PROVIDED="INCORRECT_AMOUNT_PROVIDED",i.INCORRECT_ADDRESS_PROVIDED="INCORRECT_ADDRESS_PROVIDED",i.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",i.ASSET_NOT_SUPPORTED="ASSET_NOT_SUPPORTED",i.CONFIRMATION_COUNT_UNKNOWN="CONFIRMATION_COUNT_UNKNOWN",i))(w||{});var I=class extends Error{constructor(r,s,p){super(r);this.code=s;this.details=p;}};var x=class extends I{constructor(t="UNKNOWN",r){super(t,5001,r),this.name="BridgeUnavailableError";}};var P=class extends I{constructor(t="UNKNOWN",r){super(t,5002,r),this.name="BridgeInitializationError";}};var f=class extends I{constructor(t="INVALID_PARAMS",r){super(t,5003,r),this.name="InvalidParamsError";}};var te={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"},V=async e=>{try{return await(await fetch(te[e])).json()}catch(t){throw new P("CONFIG_NOT_AVAILABLE",`Error while fetching CCTP config: ${t.message}`)}},O=e=>{switch(e){case 43114:case 43113:return 1e3;default:return 2e4}};async function K(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 ie=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}}}}),v=({chain:e,provider:t})=>{let r=ie(e),s=t?custom(t):http(e.rpcUrl,{batch:!0,retryCount:0});return createWalletClient({chain:r,transport:s}).extend(publicActions)};var N=[{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 E=({sourceChain:e,targetChain:t,amount:r,asset:s},p)=>{if(e.chainId===t.chainId)throw new f("IDENTICAL_CHAINS_PROVIDED");if(r<=0n)throw new f("INCORRECT_AMOUNT_PROVIDED","Amount must be greater than zero");let n=p.find(i=>i.chainId===e.chainId);if(!n)throw new f("CHAIN_NOT_SUPPORTED",`Not supported on source chain "${e.chainId}"`);let o=p.find(i=>i.chainId===t.chainId);if(!o)throw new f("CHAIN_NOT_SUPPORTED",`Not supported on target chain "${t.chainId}"`);let d=n.tokens.find(i=>i.symbol===s.symbol),y=o.tokens.find(i=>i.symbol===s.symbol);if(!d||!y)throw new f("ASSET_NOT_SUPPORTED");return {sourceChainData:n,targetChainData:o,burnToken:d,mintToken:y}};async function $(e,t){await e.ensureHasConfig();let{sourceChain:r,targetChain:s,asset:p,amount:n,provider:o}=t,{sourceChainData:d,targetChainData:y,burnToken:i}=E({sourceChain:r,targetChain:s,asset:p,amount:n},e.config),u=await v({chain:r,provider:o}).readContract({address:d.tokenRouterAddress,abi:N,functionName:"calculateFee",args:[n,y.domain]});return {[i.address]:u}}var _=[{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 oe=async(e,t)=>{let{sourceChain:r,targetChain:s,asset:p,amount:n,fromAddress:o,toAddress:d,sourceProvider:y}=t,i=d??o;if(!isAddress(o)||!isAddress(i))throw new f("INCORRECT_ADDRESS_PROVIDED");let{sourceChainData:a,targetChainData:u,burnToken:m}=E({sourceChain:r,targetChain:s,asset:p,amount:n},e.config),c=v({chain:r,provider:y});if(await c.readContract({address:m.address,abi:_,functionName:"allowance",args:[o,a.tokenRouterAddress]})<n)if(y.sign){let l=encodeFunctionData({abi:_,functionName:"approve",args:[a.tokenRouterAddress,n]}),T=await y.sign({from:o,to:m.address,data:l}),A=await c.sendRawTransaction({serializedTransaction:T});await c.waitForTransactionReceipt({hash:A,pollingInterval:1e3});}else {let{request:l}=await c.simulateContract({account:o,address:m.address,abi:_,functionName:"approve",args:[a.tokenRouterAddress,n]}),T=await c.writeContract(l);await c.waitForTransactionReceipt({hash:T,pollingInterval:1e3});}if(y.sign){let l=encodeFunctionData({abi:N,functionName:"transferTokens",args:[n,u.domain,i,m.address]}),T=await y.sign({from:o,to:a.tokenRouterAddress,data:l});return c.sendRawTransaction({serializedTransaction:T})}else {let{request:l}=await c.simulateContract({account:o,address:a.tokenRouterAddress,abi:N,functionName:"transferTokens",args:[n,u.domain,i,m.address]});return c.writeContract(l)}},pe=async e=>{try{return await e.getBlockNumber()}catch{return}};async function q(e,t,r){await e.ensureHasConfig();let{minimumConfirmations:s}=e.config.find(u=>u.chainId===t.sourceChain.chainId)??{},{minimumConfirmations:p}=e.config.find(u=>u.chainId===t.targetChain.chainId)??{};if(!s||!p)throw new f("CONFIRMATION_COUNT_UNKNOWN");let n=await e.getFees({...t,provider:t.sourceProvider}),o=(t.asset.address&&n[t.asset.address])??0n,d=await oe(e,t),y=Date.now(),i=v({chain:t.targetChain,provider:t.targetProvider}),a=await pe(i);return {type:e.type,environment:r,fromAddress:t.fromAddress,toAddress:t.toAddress??t.fromAddress,amount:t.amount,symbol:t.asset.symbol,bridgeFee:o,sourceChain:t.sourceChain,sourceStartedAt:y,sourceTxHash:d,sourceConfirmationCount:0,requiredSourceConfirmationCount:s,targetChain:t.targetChain,targetConfirmationCount:0,requiredTargetConfirmationCount:p,startBlockNumber:a}}async function j(e){if(!e.config&&(await e.updateConfig(),!e.config))throw new P("CONFIG_NOT_AVAILABLE")}var D=(e,t)=>e.gasPrice&&BigInt(e.gasPrice*t.gasUsed);var S=async e=>new Promise(t=>{setTimeout(t,e);});var L=({promise:e,delay:t,startAfter:r})=>{let s=!1,p=!1,n=0,o,d,y=u=>{o&&s&&(s=!1,o(u));},i=()=>{p=!0,d&&s&&(s=!1,d("cancelled"));};return {result:new Promise((u,m)=>{s=!0,o=u,d=m;let c=async()=>{if(!(!s||p)){try{if(await e(y),!s||p)return;await S(t);}catch(g){console.error(g.message),n+=1,await S(2**n*t);}await c();}};r?setTimeout(c,r):c();}),cancel:i}};var Z=1e3*60*60*3,J=1024n,X=5e3,C=(e,t,r)=>{Object.assign(e,Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0))),r({...e});},ue=async(e,t)=>{let{sourceProvider:r,targetProvider:s,updateListener:p,bridgeTransfer:n}=t,o=v({chain:n.sourceChain,provider:r}),d=e.find(m=>m.chainId===n.sourceChain.chainId),y=v({chain:n.targetChain,provider:s}),i=e.find(m=>m.chainId===n.targetChain.chainId),a={...n};if(!d||!i)throw new f("CHAIN_NOT_SUPPORTED");return L({promise:async m=>{if(a.completedAt||a.metadata?.nonce)return m(a);if(a.sourceStartedAt+Z<=Date.now())return C(a,{completedAt:Date.now(),errorCode:5004},p),m(a);let c=await o.getTransactionReceipt({hash:a.sourceTxHash});if(!a.sourceNetworkFee){let b=await o.getTransaction({hash:a.sourceTxHash}),M=D(b,c);M&&C(a,{sourceNetworkFee:M},p);}if(c.status==="reverted")return C(a,{completedAt:Date.now(),errorCode:5005},p),m(a);let g=await o.getTransactionConfirmations({hash:a.sourceTxHash}),l=g>a.sourceConfirmationCount,T=g>=a.requiredSourceConfirmationCount;if(l){let b={};b.sourceConfirmationCount=Number(g),T||(b.startBlockNumber=await y.getBlockNumber()),C(a,b,p);}if(!T)return;a.startBlockNumber||C(a,{startBlockNumber:await y.getBlockNumber()},p);let A=c.logs.find(b=>b.address===d.tokenRouterAddress?decodeEventLog({abi:N,...b}).eventName==="TransferTokens":!1);if(!A)throw new f("INVALID_PARAMS",`unable to find a TransferTokens event in source transaction "${a.sourceTxHash}"`);let h=decodeEventLog({abi:N,eventName:"TransferTokens",...A}).args.nonce;return C(a,{targetStartedAt:Date.now(),metadata:{nonce:h}},p),m(a)},delay:O(d.chainId),startAfter:X})},de=async(e,t)=>{let{targetProvider:r,updateListener:s,bridgeTransfer:p}=t,n={...p};if(!p.completedAt&&!p.metadata?.nonce)throw new f("INVALID_PARAMS","nonce is missing");if(!p.startBlockNumber)throw new f("INVALID_PARAMS","startBlockNumber is missing");let o=v({chain:p.targetChain,provider:r}),d=e.find(i=>i.chainId===p.targetChain.chainId);if(!d)throw new f("INVALID_PARAMS",`unknown target chain "${p.targetChain.chainId}"`);return L({promise:async i=>{if(n.completedAt)return i(n);if(n.sourceStartedAt+Z<=Date.now())return C(n,{completedAt:Date.now(),errorCode:5004},s),i(n);if(!n.targetTxHash){let g=await o.getBlockNumber(),l=(n.startBlockNumber??0n)-J,T=l>=0n?l:"earliest",A=(n.startBlockNumber??0n)+J,k=A<g?A:"latest",h=await o.getLogs({address:d.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:T,toBlock:k});if(h[0]?.transactionHash)C(n,{targetTxHash:h[0].transactionHash},s);else return}let a=await o.getTransactionReceipt({hash:n.targetTxHash});if(!n.targetNetworkFee){let g=await o.getTransaction({hash:n.targetTxHash}),l=D(g,a);l&&C(n,{targetNetworkFee:l},s);}if(a.status==="reverted")return C(n,{completedAt:Date.now(),errorCode:5005},s),i(n);let u=await o.getTransactionConfirmations({hash:n.targetTxHash}),m=u>n.targetConfirmationCount,c=u>=n.requiredTargetConfirmationCount;if(m&&C(n,{targetConfirmationCount:Number(u)},s),!!c)return C(n,{completedAt:Date.now()},s),i(n)},delay:O(d.chainId),startAfter:X})};function Y(e,t){let r,s=()=>{r?.();};return {result:(async()=>{await e.ensureHasConfig();let{sourceProvider:n,targetProvider:o,updateListener:d,bridgeTransfer:y}=t,{result:i,cancel:a}=await ue(e.config,{sourceProvider:n,targetProvider:o,updateListener:d,bridgeTransfer:y});r=a;let u=await i,{result:m,cancel:c}=await de(e.config,{sourceProvider:n,targetProvider:o,updateListener:d,bridgeTransfer:u});return r=c,m})(),cancel:s}}var Q=e=>({type:"cctp",config:null,updateConfig:async function(){this.config=await V(e);},ensureHasConfig:async function(){return j(this)},getAssets:async function(){return K(this)},getFees:async function(t){return $(this,t)},transferAsset:async function(t){return q(this,t,e)},trackTransfer:function(t){return Y(this,t)}});var ce=new Map([["cctp",Q]]),ee=(e,t)=>new Map([...ce].filter(([r])=>!t?.includes(r)).map(([r,s])=>[r,s(e)])),F=(e,t,r)=>{let s=t.destinations[r]?.find(p=>e.has(p));if(!s)throw new x;return {type:s,bridge:e.get(s)}};var en=({environment:e,disabledBridgeTypes:t})=>{let r=ee(e,t),s=async()=>{await Promise.allSettled(Array.from(r).map(([,a])=>a.updateConfig()));};return {environment:e,bridges:r,init:async()=>{await s();},updateConfigs:s,getAssets:async()=>(await Promise.all(Array.from(r).map(([,u])=>u.getAssets()))).reduce((u,m)=>{for(let[c,g]of Object.entries(m)){let l=Number(c),T=u[l];if(T)for(let A of g){let k=T.findIndex(({symbol:h})=>h===A.symbol);k===-1?T.push(A):mergeWith(T[k],A,(h,b)=>{if(isArray(h))return [...new Set(h.concat(b))]});}else u[l]=g;}return u},{}),getFees:async a=>{let{bridge:u}=F(r,a.asset,a.targetChain.chainId);return u.getFees(a)},canTransferAsset:(a,u)=>{try{return F(r,a,u),!0}catch{return !1}},transferAsset:async a=>{let{bridge:u}=F(r,a.asset,a.targetChain.chainId);return u.transferAsset(a)},trackTransfer:a=>{let u=r.get(a.bridgeTransfer.type);if(!u)throw new x;return u.trackTransfer(a)}}}; | ||
export { R as BridgeType, H as Environment, B as ErrorCode, w as ErrorReason, U as TokenType, Yt as createUnifiedBridgeService }; | ||
export { R as BridgeType, H as Environment, B as ErrorCode, w as ErrorReason, U as TokenType, en as createUnifiedBridgeService }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@avalabs/bridge-unified", | ||
"version": "0.0.0-feat-unified-api-interface-20240105153058", | ||
"version": "0.0.0-feat-unified-api-interface-20240105191038", | ||
"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-20240105153058" | ||
"eslint-config-custom": "0.0.0-feat-unified-api-interface-20240105191038" | ||
}, | ||
@@ -21,0 +21,0 @@ "scripts": { |
export * from './bridge-types'; | ||
export * from './caip2'; |
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
366558
72
4560
1