@galacticcouncil/sdk-next 1.5.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";var be=Object.create;var Z=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var tt=(o,t)=>{for(var e in t)Z(o,e,{get:t[e],enumerable:!0})},Ct=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fe(t))!Te.call(o,i)&&i!==e&&Z(o,i,{get:()=>t[i],enumerable:!(a=ye(t,i))||a.enumerable});return o};var et=(o,t,e)=>(e=o!=null?be(Pe(o)):{},Ct(t||!o||!o.__esModule?Z(e,"default",{value:o,enumerable:!0}):e,o)),Se=o=>Ct(Z({},"__esModule",{value:!0}),o);var Ia={};tt(Ia,{TxBuilderFactory:()=>yt});module.exports=Se(Ia);var j=require("@galacticcouncil/math-lbp");var Lt=require("@galacticcouncil/common");var at={};tt(at,{withTimeout:()=>we});function we(o,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);o.then(r=>{clearTimeout(s),a(r)},r=>{clearTimeout(s),i(r)})})}var P={};tt(P,{divSpot:()=>xe,getFraction:()=>Ie,mulScaled:()=>kt,mulSpot:()=>ve});var Pt=require("@galacticcouncil/common");function kt(o,t,e,a,i){let s=e+a-i,r=o*t;return s>0?r/BigInt(10)**BigInt(s):s<0?r*BigInt(10)**BigInt(-s):r}function ve(o,t,e,a){return kt(o,t,e,Pt.RUNTIME_DECIMALS,a)}function xe(o,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(Pt.RUNTIME_DECIMALS+a-e);return o*i/t}function Ie(o,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),i=BigInt(Math.round(t*Number(a)));return o*i/(BigInt(100)*a)}var m={};tt(m,{FeeUtils:()=>Tt,shiftNeg:()=>Ae});var Mt=et(require("big.js"));var Tt=class o{static toPct(t){let[e,a]=t;return o.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return o.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let i=10**a;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ae(o,t){let e=(0,Mt.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Be=et(require("big.js"));var{FeeUtils:Ja}=m;var Me=require("polkadot-api"),rt=require("rxjs");var C=require("rxjs"),T=require("rxjs/operators");var U=require("@galacticcouncil/descriptors");var Ht=require("@galacticcouncil/common"),G=require("rxjs");var F=require("rxjs"),b=require("rxjs/operators");function Nt(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,F.defer)(()=>(0,F.from)(o._request("system_health",[]))).pipe((0,b.timeout)({first:e}),(0,b.map)(()=>"online"),(0,b.catchError)(()=>(0,F.of)("offline")));return(0,F.of)({state:"offline",delayMs:0}).pipe((0,b.expand)(s=>(0,F.timer)(s.delayMs).pipe((0,b.switchMap)(a),(0,b.map)(r=>({state:r,delayMs:t})))),(0,b.skip)(1),(0,b.map)(s=>s.state),(0,b.distinctUntilChanged)(),(0,b.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Ee}=Ht.log,it=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,G.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Nt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,G.tap)({error:a=>Ee.error(t,a)}),(0,G.shareReplay)({bufferSize:1,refCount:!0}))}};var A=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(U.hydration),this.apiNext=this.client.getTypedApi(U.hydrationNext),this.apiIce=this.client.getTypedApi(U.hydrationIce),this.watcher=it.getInstance(this.client),this.at=e??"best"}};var Re=require("polkadot-api/ws"),Fe=require("polkadot-api/logs-provider");var Ce=require("polkadot-api");var qt=require("@galacticcouncil/common"),w=require("rxjs"),p=require("rxjs/operators");var{logger:V}=qt.log,$=class extends A{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,w.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),i=this.watchErc20Balance(t);return(0,w.combineLatest)([e,a,i]).pipe((0,p.connect)(s=>(0,w.concat)(s.pipe((0,p.take)(1)),s.pipe((0,p.skip)(1),(0,p.debounceTime)(250)))))}).pipe((0,p.map)(e=>e.flat()),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([e,a],i)=>i===0?a:this.getDeltas(e,a))).pipe((0,p.tap)({subscribe:()=>V.debug("balance: subscribe",t),error:e=>V.error("balance",e)}),(0,p.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,w.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,p.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,p.tap)({error:a=>V.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,p.map)(({value:i})=>({id:e,balance:this.getBreakdown(i)})),(0,p.tap)({error:i=>V.error("balance(token)",i)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,p.distinctUntilChanged)((a,i)=>!i.deltas),(0,p.map)(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown(s.value)})}),i}),(0,p.tap)({error:a=>V.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[n]=r;return n}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async n=>[n,await this.getBalanceData(t,n)]))).map(([n,l])=>({id:n,balance:l}));return(0,w.defer)(()=>(0,w.from)(e?Promise.resolve(e):a()).pipe((0,p.switchMap)(s=>this.watcher.bestBlock$.pipe((0,p.switchMap)(()=>(0,w.from)(i(s))))),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([s,r],n)=>n===0?r.filter(l=>l.balance.total>0n):this.getDeltas(s,r)),(0,p.distinctUntilChanged)((s,r)=>r.length===0),(0,p.tap)({error:s=>V.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(s,r)=>s!==void 0&&r!==void 0&&s.transferable===r.transferable&&s.total===r.total,i=t.reduce((s,r)=>(s.set(r.id,r.balance),s),new Map);return e.filter(s=>!a(s.balance,i.get(s.id)))}};var ke=require("rxjs");var Gt=require("@galacticcouncil/common");var ks={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ms}=Gt.log;var{withTimeout:Js}=at;var y=require("@galacticcouncil/math-omnipool"),Le=et(require("big.js"));var Ne=require("@galacticcouncil/common");var{FeeUtils:xi}=m;var H=require("polkadot-api"),Ue=require("@polkadot-api/utils"),q=require("rxjs"),Ve=require("@galacticcouncil/common");var{FeeUtils:_i}=m;var{FeeUtils:Vi}=m,Wi=H.Binary.toHex(H.Binary.fromText("omnipool")),$i=(0,H.Enum)("Short");var B=require("@galacticcouncil/math-stableswap");var Wt=require("@galacticcouncil/common");var{FeeUtils:gr}=m;var $t=require("polkadot-api"),je=require("@polkadot-api/utils"),Qe=require("@noble/hashes/blake2b"),Y=require("rxjs"),Yt=require("@galacticcouncil/common");var Ye=require("polkadot-api"),Xe=require("viem");var{FeeUtils:kr}=m;var{FeeUtils:en}=m;var _=require("@galacticcouncil/math-xyk");var Ze=require("@galacticcouncil/common");var{FeeUtils:Sn}=m;var ta=require("polkadot-api"),ea=require("rxjs");var Xt=require("@galacticcouncil/common");var oa=require("polkadot-api"),la=require("@polkadot-api/utils"),ut=require("rxjs"),At=require("@galacticcouncil/common");var wt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var vt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",xt="0x112b087b60C1a166130d59266363C45F8aa99db0",It="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",zt=1000000n;var jn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var nt=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:vt,address:xt,args:[It],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:vt,address:xt,args:[It,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:wt,address:Kt,args:[t],functionName:"getUserAccountData"})}};var sa=require("polkadot-api"),ia=require("viem");var h=et(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:X}=v.erc20,{H160:Ot}=v.h160,ra=1.01,na=31536000n,jt=4,ot=-1,lt=10n**27n,ct=class{client;constructor(t){this.client=new nt(t)}async getSummary(t){let e=Ot.fromAny(t),[a,i,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[n]=a,[l,u]=i,[c,d,f,k,I,O]=s,E=v.big.toDecimal(O,18),M=[];for(let R of l){let N=R.underlyingAsset.toLowerCase(),S=n.find(({underlyingAsset:he})=>he.toLowerCase()===N);if(!S)throw new Error("Missing pool reserve for "+N);let ft=R.scaledATokenBalance,z=S.liquidityIndex,re=S.liquidityRate,ne=S.availableLiquidity,oe=S.priceInMarketReferenceCurrency,le=r+6,ce=this.calculateLinearInterest(re,S.lastUpdateTimestamp,le),ue=z*ce/lt,pe=ft*ue/lt,me=Number(u!==0&&u===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,de=S.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,ge=X.toAssetId(N);M.push({aTokenBalance:pe,availableLiquidity:ne,decimals:Number(S.decimals),isCollateral:de,priceInRef:oe,reserveId:ge,reserveAsset:N,reserveLiquidationThreshold:me})}return{healthFactor:Number(E),currentLiquidationThreshold:Number(v.big.toDecimal(k,jt)),totalCollateral:c,totalDebt:d,reserves:M}}async hasBorrowPositions(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[i,s]=a;return s>0n}async getHealthFactor(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[i,s,r,n,l,u]=a;return this.calculateHealthFactorFromBalances(s,i,n)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return ot;let l=X.fromAssetId(e),u=r.find(N=>N.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,isCollateral:d,priceInRef:f,reserveLiquidationThreshold:k}=u,I=v.big.toBigInt(a,c),O=d?I*f/10n**BigInt(c):0n,E=i-O;if(E<=0n)return 0;let M=(0,h.default)(i.toString()).mul(n).minus((0,h.default)(O.toString()).mul(k)).div(E.toString()),R=(0,h.default)(E.toString()).mul(M).div(s.toString()).toFixed(6,h.default.roundDown);return Number(R)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return ot;let l=X.fromAssetId(e),u=r.find(R=>R.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,priceInRef:d,reserveLiquidationThreshold:f}=u,I=v.big.toBigInt(a,c)*d/10n**BigInt(c),O=i+I;if(O<=0n)return 0;let E=(0,h.default)(i.toString()).mul(n).plus((0,h.default)(I.toString()).mul(f)).div(O.toString()),M=(0,h.default)(O.toString()).mul(E).div(s.toString()).toFixed(6,h.default.roundDown);return Number(M)}async getHealthFactorAfterSwap(t,e,a,i,s){let{totalDebt:r,reserves:n,healthFactor:l}=await this.getSummary(t);if(r===0n)return ot;let u=X.fromAssetId(a),c=X.fromAssetId(s),d=n.find(z=>z.reserveAsset===u),f=n.find(z=>z.reserveAsset===c);if(!d)throw new Error(`Missing reserve ctx for ${u}`);if(!f)throw new Error(`Missing reserve ctx for ${f}`);let k=v.big.toBigInt(e,d.decimals),I=v.big.toBigInt(i,f.decimals),O=k*d.priceInRef/10n**BigInt(d.decimals),E=I*f.priceInRef/10n**BigInt(f.decimals),M=d.isCollateral?(0,h.default)(O.toString()).mul(d.reserveLiquidationThreshold):(0,h.default)(0),S=(f.isCollateral?(0,h.default)(E.toString()).mul(f.reserveLiquidationThreshold):(0,h.default)(0)).minus(M).div(r.toString()),ft=(0,h.default)(l).plus(S).toFixed(6,h.default.roundDown);return Number(ft)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:i,healthFactor:s}=await this.getSummary(t),r=X.fromAssetId(e),n=i.find(l=>l.reserveAsset===r);if(!n)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(n,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:i}=await this.getSummary(t),s={};for(let r of a){let n=this.calculateWithdrawMax(r,e,i);r.reserveId&&(s[r.reserveId]=n)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:i,availableLiquidity:s,decimals:r,priceInRef:n,reserveLiquidationThreshold:l,isCollateral:u}=t,c=i;if(u&&e>0n){let f=a-ra;if(f>0){let k=(0,h.default)(f).mul(e.toString()).div(l).toFixed(0,h.default.roundDown),I=(0,h.default)(k).div(n.toString()).mul(10**r).toFixed(0,h.default.roundDown);c=i<BigInt(I)?i:BigInt(I)}else c=0n}return{amount:c<s?c:s,decimals:r}}calculateLinearInterest(t,e,a){let i=a-e;if(i<=0)return lt;let s=t*BigInt(i)/na;return lt+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return ot;let i=e*a/t,s=v.big.toDecimal(i,jt);return Number(s)}};var{ERC20:So}=At.erc20;var D=require("@galacticcouncil/math-hsm");var Qt=require("@galacticcouncil/common");var{FeeUtils:Lo}=m;var Jt=require("polkadot-api"),ga=require("@polkadot-api/utils"),K=require("rxjs"),Bt=require("@galacticcouncil/common");var ma=require("polkadot-api"),da=require("viem");var{FeeUtils:nl}=m,{H160:ol}=Bt.h160;var Zt=require("@galacticcouncil/common"),_t=require("rxjs");var{logger:tc}=Zt.log;var te=require("@galacticcouncil/common");var{FeeUtils:cu}=m;var xa=require("@galacticcouncil/common");var Et=require("polkadot-api");var L=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s})=>i==="Stableswap"?{pool:(0,Et.Enum)("Stableswap",s),asset_in:e,asset_out:a}:{pool:(0,Et.Enum)(i),asset_in:e,asset_out:a})}};var Rt=require("polkadot-api");function ae(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var x=class extends A{evm;evmClient;balance;aaveUtils;constructor(t,e,a){super(t,a),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new $(t,a),this.aaveUtils=new ct(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:zt})}async dryRun(t,e){let a=(0,Rt.Enum)("Signed",t),i=(0,Rt.Enum)("system",a),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4,{at:this.at}),n=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(n){let l=n.type==="Module"?ae(n.value):n.type;throw new Error("Dry run execution error!",{cause:l})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends x{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],s=await this.balance.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=P.getFraction(t,this.slippagePct),n=i.assetIn,l=s.assetOut,u=t+r,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.buy({asset_in:n,asset_out:l,amount:e,max_sell_amount:u}):c=this.api.tx.Router.buy({asset_in:n,asset_out:l,amount_out:e,max_amount_in:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=P.getFraction(e,this.slippagePct),n=i.assetIn,l=s.assetOut,u=e-r,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.sell({asset_in:n,asset_out:l,amount:t,min_buy_amount:u}):c=this.api.tx.Router.sell({asset_in:n,asset_out:l,amount_in:t,min_amount_out:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],i=e[e.length-1],s=P.getFraction(t,this.slippagePct),r=a.assetIn,n=i.assetOut,l=t-s,u=this.api.tx.Router.sell_all({asset_in:r,asset_out:n,min_amount_out:l,route:L.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};var mt=require("polkadot-api");var dt=class extends x{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradePeriod:s,tradeRoute:r}=this.order,n=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:0n,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(n=await this.dispatchWithExtraGas(n)),this.wrapTx("DcaSchedule",n)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,l=P.getFraction(s,this.slippagePct),u=s-l,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:u,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapSell",c)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,l=P.getFraction(i,this.slippagePct),u=i+l,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Buy",{asset_in:e,asset_out:a,amount_out:s,max_amount_in:u,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapBuy",c)}};var se=require("polkadot-api");var gt=class extends x{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,l=P.getFraction(e,this.slippagePct),u=e-l,c=(0,se.Enum)("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:u,partial:!1}),d=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(d=await this.dispatchWithExtraGas(d)),this.wrapTx("IntentSwap",d)}};var ie=require("polkadot-api");var ht=class extends x{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,l=(0,ie.Enum)("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentLimitOrder",u)}};var Ft=require("polkadot-api");var bt=class extends x{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:i,tradeAmountIn:s,tradePeriod:r}=this.order,n=(0,Ft.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:i,slippage:this.slippagePct*1e4,budget:t,period:r}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:n}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule",l)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r}=this.order,n=P.getFraction(s,this.slippagePct),l=s-n,u=(0,Ft.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:i,amount_out:l,slippage:this.slippagePct*1e4,budget:t,period:r}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentDcaSchedule.twap",c)}};var yt=class{client;evmClient;at;constructor(t,e,a){this.client=t,this.evmClient=e,this.at=a}trade(t){return new pt(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new dt(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new gt(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new ht(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new bt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
1
+ "use strict";var be=Object.create;var Z=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var tt=(o,t)=>{for(var e in t)Z(o,e,{get:t[e],enumerable:!0})},Ct=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fe(t))!Te.call(o,i)&&i!==e&&Z(o,i,{get:()=>t[i],enumerable:!(a=ye(t,i))||a.enumerable});return o};var et=(o,t,e)=>(e=o!=null?be(Pe(o)):{},Ct(t||!o||!o.__esModule?Z(e,"default",{value:o,enumerable:!0}):e,o)),Se=o=>Ct(Z({},"__esModule",{value:!0}),o);var Ia={};tt(Ia,{TxBuilderFactory:()=>yt});module.exports=Se(Ia);var z=require("@galacticcouncil/math-lbp");var Lt=require("@galacticcouncil/common");var at={};tt(at,{withTimeout:()=>we});function we(o,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);o.then(r=>{clearTimeout(s),a(r)},r=>{clearTimeout(s),i(r)})})}var P={};tt(P,{divSpot:()=>xe,getFraction:()=>Ie,mulScaled:()=>kt,mulSpot:()=>ve});var Pt=require("@galacticcouncil/common");function kt(o,t,e,a,i){let s=e+a-i,r=o*t;return s>0?r/BigInt(10)**BigInt(s):s<0?r*BigInt(10)**BigInt(-s):r}function ve(o,t,e,a){return kt(o,t,e,Pt.RUNTIME_DECIMALS,a)}function xe(o,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(Pt.RUNTIME_DECIMALS+a-e);return o*i/t}function Ie(o,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),i=BigInt(Math.round(t*Number(a)));return o*i/(BigInt(100)*a)}var m={};tt(m,{FeeUtils:()=>Tt,shiftNeg:()=>Ae});var Mt=et(require("big.js"));var Tt=class o{static toPct(t){let[e,a]=t;return o.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return o.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let i=10**a;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ae(o,t){let e=(0,Mt.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Be=et(require("big.js"));var{FeeUtils:Ja}=m;var Me=require("polkadot-api"),rt=require("rxjs");var C=require("rxjs"),T=require("rxjs/operators");var G=require("@galacticcouncil/descriptors");var Ht=require("@galacticcouncil/common"),q=require("rxjs");var F=require("rxjs"),b=require("rxjs/operators");function Nt(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,F.defer)(()=>(0,F.from)(o._request("system_health",[]))).pipe((0,b.timeout)({first:e}),(0,b.map)(()=>"online"),(0,b.catchError)(()=>(0,F.of)("offline")));return(0,F.of)({state:"offline",delayMs:0}).pipe((0,b.expand)(s=>(0,F.timer)(s.delayMs).pipe((0,b.switchMap)(a),(0,b.map)(r=>({state:r,delayMs:t})))),(0,b.skip)(1),(0,b.map)(s=>s.state),(0,b.distinctUntilChanged)(),(0,b.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Ee}=Ht.log,it=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,q.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Nt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,q.tap)({error:a=>Ee.error(t,a)}),(0,q.shareReplay)({bufferSize:1,refCount:!0}))}};var A=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(G.hydration),this.apiNext=this.client.getTypedApi(G.hydrationNext),this.apiIce=this.client.getTypedApi(G.hydrationIce),this.watcher=it.getInstance(this.client),this.at=e??"best"}};var Re=require("polkadot-api/ws"),Fe=require("polkadot-api/logs-provider");var Ce=require("polkadot-api");var qt=require("@galacticcouncil/common"),w=require("rxjs"),p=require("rxjs/operators");var{logger:U}=qt.log,W=class extends A{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,w.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),i=this.watchErc20Balance(t);return(0,w.combineLatest)([e,a,i]).pipe((0,p.connect)(s=>(0,w.concat)(s.pipe((0,p.take)(1)),s.pipe((0,p.skip)(1),(0,p.debounceTime)(250)))))}).pipe((0,p.map)(e=>e.flat()),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([e,a],i)=>i===0?a:this.getDeltas(e,a))).pipe((0,p.tap)({subscribe:()=>U.debug("balance: subscribe",t),error:e=>U.error("balance",e)}),(0,p.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,w.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,p.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,p.tap)({error:a=>U.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,p.map)(({value:i})=>({id:e,balance:this.getBreakdown(i)})),(0,p.tap)({error:i=>U.error("balance(token)",i)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,p.distinctUntilChanged)((a,i)=>!i.deltas),(0,p.map)(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown(s.value)})}),i}),(0,p.tap)({error:a=>U.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[n]=r;return n}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async n=>[n,await this.getBalanceData(t,n)]))).map(([n,l])=>({id:n,balance:l}));return(0,w.defer)(()=>(0,w.from)(e?Promise.resolve(e):a()).pipe((0,p.switchMap)(s=>this.watcher.bestBlock$.pipe((0,p.switchMap)(()=>(0,w.from)(i(s))))),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([s,r],n)=>n===0?r.filter(l=>l.balance.total>0n):this.getDeltas(s,r)),(0,p.distinctUntilChanged)((s,r)=>r.length===0),(0,p.tap)({error:s=>U.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.frozen-t.reserved,a=e>0n?e:0n,i=t.free>=a?t.free-a:0n,s=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:s,transferable:i}}getDeltas(t,e){let a=(s,r)=>s!==void 0&&r!==void 0&&s.transferable===r.transferable&&s.total===r.total,i=t.reduce((s,r)=>(s.set(r.id,r.balance),s),new Map);return e.filter(s=>!a(s.balance,i.get(s.id)))}};var ke=require("rxjs");var Gt=require("@galacticcouncil/common");var ks={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ms}=Gt.log;var{withTimeout:Js}=at;var y=require("@galacticcouncil/math-omnipool"),Le=et(require("big.js"));var Ne=require("@galacticcouncil/common");var{FeeUtils:xi}=m;var H=require("polkadot-api"),Ue=require("@polkadot-api/utils"),J=require("rxjs"),Ve=require("@galacticcouncil/common");var{FeeUtils:_i}=m;var{FeeUtils:Vi}=m,Wi=H.Binary.toHex(H.Binary.fromText("omnipool")),$i=(0,H.Enum)("Short");var B=require("@galacticcouncil/math-stableswap");var Wt=require("@galacticcouncil/common");var{FeeUtils:gr}=m;var $t=require("polkadot-api"),je=require("@polkadot-api/utils"),Qe=require("@noble/hashes/blake2b"),$=require("rxjs"),Yt=require("@galacticcouncil/common");var Ye=require("polkadot-api"),Xe=require("viem");var{FeeUtils:kr}=m;var{FeeUtils:en}=m;var _=require("@galacticcouncil/math-xyk");var Ze=require("@galacticcouncil/common");var{FeeUtils:Sn}=m;var ta=require("polkadot-api"),ea=require("rxjs");var Xt=require("@galacticcouncil/common");var oa=require("polkadot-api"),la=require("@polkadot-api/utils"),ut=require("rxjs"),At=require("@galacticcouncil/common");var wt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var vt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",xt="0x112b087b60C1a166130d59266363C45F8aa99db0",It="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",zt=1000000n;var jn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var nt=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:vt,address:xt,args:[It],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:vt,address:xt,args:[It,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:wt,address:Kt,args:[t],functionName:"getUserAccountData"})}};var sa=require("polkadot-api"),ia=require("viem");var h=et(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:Y}=v.erc20,{H160:Ot}=v.h160,ra=1.01,na=31536000n,jt=4,ot=-1,lt=10n**27n,ct=class{client;constructor(t){this.client=new nt(t)}async getSummary(t){let e=Ot.fromAny(t),[a,i,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[n]=a,[l,u]=i,[c,d,f,k,I,O]=s,E=v.big.toDecimal(O,18),M=[];for(let R of l){let N=R.underlyingAsset.toLowerCase(),S=n.find(({underlyingAsset:he})=>he.toLowerCase()===N);if(!S)throw new Error("Missing pool reserve for "+N);let ft=R.scaledATokenBalance,K=S.liquidityIndex,re=S.liquidityRate,ne=S.availableLiquidity,oe=S.priceInMarketReferenceCurrency,le=r+6,ce=this.calculateLinearInterest(re,S.lastUpdateTimestamp,le),ue=K*ce/lt,pe=ft*ue/lt,me=Number(u!==0&&u===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,de=S.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,ge=Y.toAssetId(N);M.push({aTokenBalance:pe,availableLiquidity:ne,decimals:Number(S.decimals),isCollateral:de,priceInRef:oe,reserveId:ge,reserveAsset:N,reserveLiquidationThreshold:me})}return{healthFactor:Number(E),currentLiquidationThreshold:Number(v.big.toDecimal(k,jt)),totalCollateral:c,totalDebt:d,reserves:M}}async hasBorrowPositions(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[i,s]=a;return s>0n}async getHealthFactor(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[i,s,r,n,l,u]=a;return this.calculateHealthFactorFromBalances(s,i,n)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return ot;let l=Y.fromAssetId(e),u=r.find(N=>N.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,isCollateral:d,priceInRef:f,reserveLiquidationThreshold:k}=u,I=v.big.toBigInt(a,c),O=d?I*f/10n**BigInt(c):0n,E=i-O;if(E<=0n)return 0;let M=(0,h.default)(i.toString()).mul(n).minus((0,h.default)(O.toString()).mul(k)).div(E.toString()),R=(0,h.default)(E.toString()).mul(M).div(s.toString()).toFixed(6,h.default.roundDown);return Number(R)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return ot;let l=Y.fromAssetId(e),u=r.find(R=>R.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,priceInRef:d,reserveLiquidationThreshold:f}=u,I=v.big.toBigInt(a,c)*d/10n**BigInt(c),O=i+I;if(O<=0n)return 0;let E=(0,h.default)(i.toString()).mul(n).plus((0,h.default)(I.toString()).mul(f)).div(O.toString()),M=(0,h.default)(O.toString()).mul(E).div(s.toString()).toFixed(6,h.default.roundDown);return Number(M)}async getHealthFactorAfterSwap(t,e,a,i,s){let{totalDebt:r,reserves:n,healthFactor:l}=await this.getSummary(t);if(r===0n)return ot;let u=Y.fromAssetId(a),c=Y.fromAssetId(s),d=n.find(K=>K.reserveAsset===u),f=n.find(K=>K.reserveAsset===c);if(!d)throw new Error(`Missing reserve ctx for ${u}`);if(!f)throw new Error(`Missing reserve ctx for ${f}`);let k=v.big.toBigInt(e,d.decimals),I=v.big.toBigInt(i,f.decimals),O=k*d.priceInRef/10n**BigInt(d.decimals),E=I*f.priceInRef/10n**BigInt(f.decimals),M=d.isCollateral?(0,h.default)(O.toString()).mul(d.reserveLiquidationThreshold):(0,h.default)(0),S=(f.isCollateral?(0,h.default)(E.toString()).mul(f.reserveLiquidationThreshold):(0,h.default)(0)).minus(M).div(r.toString()),ft=(0,h.default)(l).plus(S).toFixed(6,h.default.roundDown);return Number(ft)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:i,healthFactor:s}=await this.getSummary(t),r=Y.fromAssetId(e),n=i.find(l=>l.reserveAsset===r);if(!n)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(n,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:i}=await this.getSummary(t),s={};for(let r of a){let n=this.calculateWithdrawMax(r,e,i);r.reserveId&&(s[r.reserveId]=n)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:i,availableLiquidity:s,decimals:r,priceInRef:n,reserveLiquidationThreshold:l,isCollateral:u}=t,c=i;if(u&&e>0n){let f=a-ra;if(f>0){let k=(0,h.default)(f).mul(e.toString()).div(l).toFixed(0,h.default.roundDown),I=(0,h.default)(k).div(n.toString()).mul(10**r).toFixed(0,h.default.roundDown);c=i<BigInt(I)?i:BigInt(I)}else c=0n}return{amount:c<s?c:s,decimals:r}}calculateLinearInterest(t,e,a){let i=a-e;if(i<=0)return lt;let s=t*BigInt(i)/na;return lt+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return ot;let i=e*a/t,s=v.big.toDecimal(i,jt);return Number(s)}};var{ERC20:So}=At.erc20;var D=require("@galacticcouncil/math-hsm");var Qt=require("@galacticcouncil/common");var{FeeUtils:Lo}=m;var Jt=require("polkadot-api"),ga=require("@polkadot-api/utils"),X=require("rxjs"),Bt=require("@galacticcouncil/common");var ma=require("polkadot-api"),da=require("viem");var{FeeUtils:nl}=m,{H160:ol}=Bt.h160;var Zt=require("@galacticcouncil/common"),_t=require("rxjs");var{logger:tc}=Zt.log;var te=require("@galacticcouncil/common");var{FeeUtils:cu}=m;var xa=require("@galacticcouncil/common");var Et=require("polkadot-api");var L=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s})=>i==="Stableswap"?{pool:(0,Et.Enum)("Stableswap",s),asset_in:e,asset_out:a}:{pool:(0,Et.Enum)(i),asset_in:e,asset_out:a})}};var Rt=require("polkadot-api");function ae(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var x=class extends A{evm;evmClient;balance;aaveUtils;constructor(t,e,a){super(t,a),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new W(t,a),this.aaveUtils=new ct(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:zt})}async dryRun(t,e){let a=(0,Rt.Enum)("Signed",t),i=(0,Rt.Enum)("system",a),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4,{at:this.at}),n=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(n){let l=n.type==="Module"?ae(n.value):n.type;throw new Error("Dry run execution error!",{cause:l})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends x{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],s=await this.balance.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=P.getFraction(t,this.slippagePct),n=i.assetIn,l=s.assetOut,u=t+r,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.buy({asset_in:n,asset_out:l,amount:e,max_sell_amount:u}):c=this.api.tx.Router.buy({asset_in:n,asset_out:l,amount_out:e,max_amount_in:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=P.getFraction(e,this.slippagePct),n=i.assetIn,l=s.assetOut,u=e-r,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.sell({asset_in:n,asset_out:l,amount:t,min_buy_amount:u}):c=this.api.tx.Router.sell({asset_in:n,asset_out:l,amount_in:t,min_amount_out:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],i=e[e.length-1],s=P.getFraction(t,this.slippagePct),r=a.assetIn,n=i.assetOut,l=t-s,u=this.api.tx.Router.sell_all({asset_in:r,asset_out:n,min_amount_out:l,route:L.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};var mt=require("polkadot-api");var dt=class extends x{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradePeriod:s,tradeRoute:r}=this.order,n=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:0n,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(n=await this.dispatchWithExtraGas(n)),this.wrapTx("DcaSchedule",n)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,l=P.getFraction(s,this.slippagePct),u=s-l,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:u,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapSell",c)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,l=P.getFraction(i,this.slippagePct),u=i+l,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Buy",{asset_in:e,asset_out:a,amount_out:s,max_amount_in:u,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapBuy",c)}};var se=require("polkadot-api");var gt=class extends x{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,l=P.getFraction(e,this.slippagePct),u=e-l,c=(0,se.Enum)("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:u,partial:!1}),d=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(d=await this.dispatchWithExtraGas(d)),this.wrapTx("IntentSwap",d)}};var ie=require("polkadot-api");var ht=class extends x{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,l=(0,ie.Enum)("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentLimitOrder",u)}};var Ft=require("polkadot-api");var bt=class extends x{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:i,tradeAmountIn:s,tradePeriod:r}=this.order,n=(0,Ft.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:i,slippage:this.slippagePct*1e4,budget:t,period:r}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:n}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule",l)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r}=this.order,n=P.getFraction(s,this.slippagePct),l=s-n,u=(0,Ft.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:i,amount_out:l,slippage:this.slippagePct*1e4,budget:t,period:r}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentDcaSchedule.twap",c)}};var yt=class{client;evmClient;at;constructor(t,e,a){this.client=t,this.evmClient=e,this.at=a}trade(t){return new pt(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new dt(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new gt(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new ht(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new bt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
@@ -1 +1 @@
1
- var Gt=Object.defineProperty;var J=(u,t)=>{for(var e in t)Gt(u,e,{get:t[e],enumerable:!0})};import Ut from"buffer";typeof window<"u"&&(window.Buffer=Ut.Buffer);import{calculate_in_given_out as ha,calculate_out_given_in as ba,calculate_linear_weights as ya,calculate_pool_trade_fee as fa,get_spot_price as Pa}from"@galacticcouncil/math-lbp";import{big as Wa,RUNTIME_DECIMALS as $a}from"@galacticcouncil/common";var N={};J(N,{withTimeout:()=>Vt});function Vt(u,t,e="timeout"){return new Promise((a,s)=>{let i=setTimeout(()=>s(new Error(e)),t);u.then(r=>{clearTimeout(i),a(r)},r=>{clearTimeout(i),s(r)})})}var b={};J(b,{divSpot:()=>$t,getFraction:()=>Yt,mulScaled:()=>ut,mulSpot:()=>Wt});import{RUNTIME_DECIMALS as ct}from"@galacticcouncil/common";function ut(u,t,e,a,s){let i=e+a-s,r=u*t;return i>0?r/BigInt(10)**BigInt(i):i<0?r*BigInt(10)**BigInt(-i):r}function Wt(u,t,e,a){return ut(u,t,e,ct,a)}function $t(u,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(ct+a-e);return u*s/t}function Yt(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),s=BigInt(Math.round(t*Number(a)));return u*s/(BigInt(100)*a)}var p={};J(p,{FeeUtils:()=>Z,shiftNeg:()=>zt});import Kt from"big.js";var Z=class u{static toPct(t){let[e,a]=t;return u.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return u.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let s=10**a;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function zt(u,t){let e=Kt(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import ka from"big.js";import{TLRUCache as La}from"@thi.ng/cache";var{FeeUtils:ii}=p;import{CompatibilityLevel as dr}from"polkadot-api";import{Subscription as hr,distinctUntilChanged as br,filter as yr,map as fr}from"rxjs";import{memoize1 as ws}from"@thi.ng/memoize";import{TLRUCache as xs}from"@thi.ng/cache";import{ReplaySubject as Bs,Subscription as _s,combineLatest as Es,defer as Rs,from as Fs,interval as Cs,merge as ks,of as Ds,EMPTY as Ms}from"rxjs";import{bufferCount as Hs,bufferTime as Ns,catchError as qs,filter as Gs,finalize as Us,map as Vs,pairwise as Ws,repeat as $s,skip as Ys,share as Xs,startWith as Ks,switchMap as zs,tap as js,throttleTime as Qs}from"rxjs/operators";import{hydration as me,hydrationNext as de,hydrationIce as ge}from"@galacticcouncil/descriptors";import{log as oe}from"@galacticcouncil/common";import{map as le,shareReplay as ce,tap as ue}from"rxjs";import{defer as Qt,from as Jt,of as mt,timer as Zt}from"rxjs";import{catchError as te,distinctUntilChanged as ee,expand as ae,map as et,shareReplay as ie,skip as se,switchMap as re,timeout as ne}from"rxjs/operators";function dt(u,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>Qt(()=>Jt(u._request("system_health",[]))).pipe(ne({first:e}),et(()=>"online"),te(()=>mt("offline")));return mt({state:"offline",delayMs:0}).pipe(ae(i=>Zt(i.delayMs).pipe(re(a),et(r=>({state:r,delayMs:t})))),se(1),et(i=>i.state),ee(),ie({bufferSize:1,refCount:!0}))}var{logger:pe}=oe,G=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(le(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",dt(t))}static getInstance(t){return this.instance||(this.instance=new u(t)),this.instance}watched(t,e){return e.pipe(ue({error:a=>pe.error(t,a)}),ce({bufferSize:1,refCount:!0}))}};var S=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(me),this.apiNext=this.client.getTypedApi(de),this.apiIce=this.client.getTypedApi(ge),this.watcher=G.getInstance(this.client),this.at=e??"best"}};import{getWsProvider as wi}from"polkadot-api/ws";import{withLogsRecorder as xi}from"polkadot-api/logs-provider";import{Binary as Ni}from"polkadot-api";import{log as he}from"@galacticcouncil/common";import{combineLatest as be,concat as ye,defer as M,from as gt}from"rxjs";import{bufferCount as ht,distinctUntilChanged as bt,debounceTime as fe,map as _,retry as Pe,startWith as yt,switchMap as ft,tap as L,take as Te,skip as Se,connect as we}from"rxjs/operators";var{logger:E}=he,F=class extends S{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return M(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return be([e,a,s]).pipe(we(i=>ye(i.pipe(Te(1)),i.pipe(Se(1),fe(250)))))}).pipe(_(e=>e.flat()),yt([]),ht(2,1),_(([e,a],s)=>s===0?a:this.getDeltas(e,a))).pipe(L({subscribe:()=>E.debug("balance: subscribe",t),error:e=>E.error("balance",e)}),Pe({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return M(()=>e.watchValue(t,{at:"best"})).pipe(_(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),L({error:a=>E.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return M(()=>a.watchValue(t,e,{at:"best"})).pipe(_(({value:s})=>({id:e,balance:this.getBreakdown(s)})),L({error:s=>E.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return M(()=>e.watchEntries(t,{at:"best"})).pipe(bt((a,s)=>!s.deltas),_(({deltas:a})=>{let s=[];return a?.deleted.forEach(i=>{let[r,n]=i.args;s.push({id:n,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(i=>{let[r,n]=i.args;s.push({id:n,balance:this.getBreakdown(i.value)})}),s}),L({error:a=>E.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let i=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=i.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[n]=r;return n}),this.erc20Ids},s=async i=>(await Promise.all(i.map(async n=>[n,await this.getBalanceData(t,n)]))).map(([n,o])=>({id:n,balance:o}));return M(()=>gt(e?Promise.resolve(e):a()).pipe(ft(i=>this.watcher.bestBlock$.pipe(ft(()=>gt(s(i))))),yt([]),ht(2,1),_(([i,r],n)=>n===0?r.filter(o=>o.balance.total>0n):this.getDeltas(i,r)),bt((i,r)=>r.length===0),L({error:i=>E.error("balance(erc20)",i)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(i,r)=>i!==void 0&&r!==void 0&&i.transferable===r.transferable&&i.total===r.total,s=t.reduce((i,r)=>(i.set(r.id,r.balance),i),new Map);return e.filter(i=>!a(i.balance,s.get(i.id)))}};import{BehaviorSubject as cs}from"rxjs";import{log as ve}from"@galacticcouncil/common";var hs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:bs}=ve;var{withTimeout:cr}=N;import{calculate_in_given_out as Dr,calculate_lrna_in_given_out as Mr,calculate_out_given_in as Lr,calculate_out_given_lrna_in as Hr,calculate_spot_price as Nr,calculate_lrna_spot_price as qr,calculate_shares as Gr,calculate_liquidity_out as Ur,calculate_liquidity_lrna_out as Vr,verify_asset_cap as Wr,calculate_liquidity_hub_in as $r,is_sell_allowed as Yr,is_buy_allowed as Xr,is_add_liquidity_allowed as Kr,is_remove_liquidity_allowed as zr,recalculate_asset_fee as jr,recalculate_protocol_fee as Qr}from"@galacticcouncil/math-omnipool";import Zr from"big.js";import{big as sn}from"@galacticcouncil/common";var{FeeUtils:bn}=p;import{AccountId as En,Binary as Tt,CompatibilityLevel as Rn,Enum as Be}from"polkadot-api";import{toHex as kn}from"@polkadot-api/utils";import{Subscription as Mn,distinctUntilChanged as Ln,filter as Hn,finalize as Nn,map as qn,merge as Gn,tap as Un}from"rxjs";import{HYDRATION_SS58_PREFIX as Wn}from"@galacticcouncil/common";var{FeeUtils:wn}=p;var{FeeUtils:Zn}=p,to=Tt.toHex(Tt.fromText("omnipool")),eo=Be("Short");import{calculate_in_given_out as go,calculate_out_given_in as ho,calculate_amplification as bo,calculate_add_one_asset as yo,calculate_liquidity_out_one_asset as fo,calculate_shares as Po,calculate_shares_for_amount as To,calculate_spot_price_with_fee as So,pool_account_name as wo,recalculate_peg as vo}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as Ao,big as Bo}from"@galacticcouncil/common";var{FeeUtils:Vo}=p;import{AccountId as _l,CompatibilityLevel as El}from"polkadot-api";import{toHex as Fl}from"@polkadot-api/utils";import{blake2b as kl}from"@noble/hashes/blake2b";import{Subscription as Ml,distinctUntilChanged as Ll,filter as Hl,map as Nl,merge as ql,tap as Gl}from"rxjs";import{HYDRATION_SS58_PREFIX as Vl,RUNTIME_DECIMALS as Wl}from"@galacticcouncil/common";import{Binary as Qo}from"polkadot-api";import{decodeEventLog as Zo}from"viem";var{FeeUtils:Tl}=p;var{FeeUtils:rc}=p;import{calculate_in_given_out as dc,calculate_out_given_in as gc,calculate_pool_trade_fee as hc,get_spot_price as bc,calculate_liquidity_in as yc,calculate_shares as fc,calculate_spot_price as Pc,calculate_spot_price_with_fee as Tc,calculate_liquidity_out_asset_a as Sc,calculate_liquidity_out_asset_b as wc}from"@galacticcouncil/math-xyk";import{big as Bc}from"@galacticcouncil/common";var{FeeUtils:qc}=p;import{CompatibilityLevel as Wc}from"polkadot-api";import{Subscription as Yc}from"rxjs";import{big as uu,RUNTIME_DECIMALS as pu}from"@galacticcouncil/common";import{AccountId as np}from"polkadot-api";import{toHex as lp}from"@polkadot-api/utils";import{Subscription as up,filter as pp,map as mp,mergeMap as dp}from"rxjs";import{erc20 as Ne,HYDRATION_SS58_PREFIX as hp}from"@galacticcouncil/common";var at=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var it=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var wt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",st="0x112b087b60C1a166130d59266363C45F8aa99db0",rt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",vt=1000000n;var Eu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var U=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:it,address:st,args:[rt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:it,address:st,args:[rt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:at,address:wt,args:[t],functionName:"getUserAccountData"})}};import{Binary as Hu}from"polkadot-api";import{decodeEventLog as qu}from"viem";import g from"big.js";import{big as B,erc20 as De,h160 as Me}from"@galacticcouncil/common";var{ERC20:C}=De,{H160:nt}=Me,Le=1.01,He=31536000n,xt=4,V=-1,W=10n**27n,$=class{client;constructor(t){this.client=new U(t)}async getSummary(t){let e=nt.fromAny(t),[a,s,i,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[n]=a,[o,c]=s,[l,m,h,x,P,T]=i,w=B.toDecimal(T,18),I=[];for(let v of o){let A=v.underlyingAsset.toLowerCase(),y=n.find(({underlyingAsset:qt})=>qt.toLowerCase()===A);if(!y)throw new Error("Missing pool reserve for "+A);let Q=v.scaledATokenBalance,k=y.liquidityIndex,Et=y.liquidityRate,Rt=y.availableLiquidity,Ft=y.priceInMarketReferenceCurrency,Ct=r+6,kt=this.calculateLinearInterest(Et,y.lastUpdateTimestamp,Ct),Dt=k*kt/W,Mt=Q*Dt/W,Lt=Number(c!==0&&c===y.eModeCategoryId?y.eModeLiquidationThreshold:y.reserveLiquidationThreshold)/1e4,Ht=y.usageAsCollateralEnabled&&v.usageAsCollateralEnabledOnUser&&v.scaledATokenBalance>0n,Nt=C.toAssetId(A);I.push({aTokenBalance:Mt,availableLiquidity:Rt,decimals:Number(y.decimals),isCollateral:Ht,priceInRef:Ft,reserveId:Nt,reserveAsset:A,reserveLiquidationThreshold:Lt})}return{healthFactor:Number(w),currentLiquidationThreshold:Number(B.toDecimal(x,xt)),totalCollateral:l,totalDebt:m,reserves:I}}async hasBorrowPositions(t){let e=nt.fromAny(t),a=await this.client.getUserAccountData(e),[s,i]=a;return i>0n}async getHealthFactor(t){let e=nt.fromAny(t),a=await this.client.getUserAccountData(e),[s,i,r,n,o,c]=a;return this.calculateHealthFactorFromBalances(i,s,n)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:s,totalDebt:i,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(i===0n)return V;let o=C.fromAssetId(e),c=r.find(A=>A.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:m,priceInRef:h,reserveLiquidationThreshold:x}=c,P=B.toBigInt(a,l),T=m?P*h/10n**BigInt(l):0n,w=s-T;if(w<=0n)return 0;let I=g(s.toString()).mul(n).minus(g(T.toString()).mul(x)).div(w.toString()),v=g(w.toString()).mul(I).div(i.toString()).toFixed(6,g.roundDown);return Number(v)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:s,totalDebt:i,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(i===0n)return V;let o=C.fromAssetId(e),c=r.find(v=>v.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:m,reserveLiquidationThreshold:h}=c,P=B.toBigInt(a,l)*m/10n**BigInt(l),T=s+P;if(T<=0n)return 0;let w=g(s.toString()).mul(n).plus(g(P.toString()).mul(h)).div(T.toString()),I=g(T.toString()).mul(w).div(i.toString()).toFixed(6,g.roundDown);return Number(I)}async getHealthFactorAfterSwap(t,e,a,s,i){let{totalDebt:r,reserves:n,healthFactor:o}=await this.getSummary(t);if(r===0n)return V;let c=C.fromAssetId(a),l=C.fromAssetId(i),m=n.find(k=>k.reserveAsset===c),h=n.find(k=>k.reserveAsset===l);if(!m)throw new Error(`Missing reserve ctx for ${c}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let x=B.toBigInt(e,m.decimals),P=B.toBigInt(s,h.decimals),T=x*m.priceInRef/10n**BigInt(m.decimals),w=P*h.priceInRef/10n**BigInt(h.decimals),I=m.isCollateral?g(T.toString()).mul(m.reserveLiquidationThreshold):g(0),y=(h.isCollateral?g(w.toString()).mul(h.reserveLiquidationThreshold):g(0)).minus(I).div(r.toString()),Q=g(o).plus(y).toFixed(6,g.roundDown);return Number(Q)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:s,healthFactor:i}=await this.getSummary(t),r=C.fromAssetId(e),n=s.find(o=>o.reserveAsset===r);if(!n)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(n,a,i)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:s}=await this.getSummary(t),i={};for(let r of a){let n=this.calculateWithdrawMax(r,e,s);r.reserveId&&(i[r.reserveId]=n)}return i}calculateWithdrawMax(t,e,a){let{aTokenBalance:s,availableLiquidity:i,decimals:r,priceInRef:n,reserveLiquidationThreshold:o,isCollateral:c}=t,l=s;if(c&&e>0n){let h=a-Le;if(h>0){let x=g(h).mul(e.toString()).div(o).toFixed(0,g.roundDown),P=g(x).div(n.toString()).mul(10**r).toFixed(0,g.roundDown);l=s<BigInt(P)?s:BigInt(P)}else l=0n}return{amount:l<i?l:i,decimals:r}}calculateLinearInterest(t,e,a){let s=a-e;if(s<=0)return W;let i=t*BigInt(s)/He;return W+i}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let s=e*a/t,i=B.toDecimal(s,xt);return Number(i)}};var{ERC20:vp}=Ne;import{calculate_collateral_in_given_hollar_out as Ep,calculate_collateral_out_given_hollar_in as Rp,calculate_hollar_in_given_collateral_out as Fp,calculate_hollar_out_given_collateral_in as Cp,calculate_imbalance as kp,calculate_max_price as Dp,calculate_buyback_limit as Mp,calculate_buyback_price_with_fee as Lp}from"@galacticcouncil/math-hsm";import{big as Up,RUNTIME_DECIMALS as Vp}from"@galacticcouncil/common";var{FeeUtils:tm}=p;import{AccountId as Im,CompatibilityLevel as Om}from"polkadot-api";import{toHex as _m}from"@polkadot-api/utils";import{Subscription as Fm,combineLatest as Cm,filter as km,map as Dm,mergeMap as Mm,pairwise as Lm}from"rxjs";import{h160 as Ve,HYDRATION_SS58_PREFIX as Nm}from"@galacticcouncil/common";import{Binary as nm}from"polkadot-api";import{decodeEventLog as lm}from"viem";var{FeeUtils:Xm}=p,{H160:Km}=Ve;import{log as Ye}from"@galacticcouncil/common";import{Subject as Rd,Subscription as Fd,takeUntil as Cd}from"rxjs";var{logger:jd}=Ye;import{big as Zg,RUNTIME_DECIMALS as th}from"@galacticcouncil/common";var{FeeUtils:hh}=p;import{big as Dh}from"@galacticcouncil/common";import{Enum as It}from"polkadot-api";var O=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:i})=>s==="Stableswap"?{pool:It("Stableswap",i),asset_in:e,asset_out:a}:{pool:It(s),asset_in:e,asset_out:a})}};import{Enum as Bt}from"polkadot-api";function At(u){let t=[],e=u;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var f=class extends S{evm;evmClient;balance;aaveUtils;constructor(t,e,a){super(t,a),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new F(t,a),this.aaveUtils=new $(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:vt})}async dryRun(t,e){let a=Bt("Signed",t),s=Bt("system",a),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall,4,{at:this.at}),n=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(n){let o=n.type==="Module"?At(n.value):n.type;throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Y=class extends f{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],i=await this.balance.getBalance(this.beneficiary,s);return t>=i.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],i=a[a.length-1],r=b.getFraction(t,this.slippagePct),n=s.assetIn,o=i.assetOut,c=t+r,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.buy({asset_in:n,asset_out:o,amount:e,max_sell_amount:c}):l=this.api.tx.Router.buy({asset_in:n,asset_out:o,amount_out:e,max_amount_in:c,route:O.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterBuy",l)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],i=a[a.length-1],r=b.getFraction(e,this.slippagePct),n=s.assetIn,o=i.assetOut,c=e-r,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.sell({asset_in:n,asset_out:o,amount:t,min_buy_amount:c}):l=this.api.tx.Router.sell({asset_in:n,asset_out:o,amount_in:t,min_amount_out:c,route:O.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSell",l)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],s=e[e.length-1],i=b.getFraction(t,this.slippagePct),r=a.assetIn,n=s.assetOut,o=t-i,c=this.api.tx.Router.sell_all({asset_in:r,asset_out:n,min_amount_out:o,route:O.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSellAll",c)}};import{Enum as ot}from"polkadot-api";var X=class extends f{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradePeriod:i,tradeRoute:r}=this.order,n=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:0n,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(n=await this.dispatchWithExtraGas(n)),this.wrapTx("DcaSchedule",n)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:r,tradeRoute:n}=this.order,o=b.getFraction(i,this.slippagePct),c=i-o,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:c,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapSell",l)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:r,tradeRoute:n}=this.order,o=b.getFraction(s,this.slippagePct),c=s+o,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Buy",{asset_in:e,asset_out:a,amount_out:i,max_amount_in:c,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapBuy",l)}};import{Enum as ta}from"polkadot-api";var K=class extends f{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],i=a[a.length-1],r=s.assetIn,n=i.assetOut,o=b.getFraction(e,this.slippagePct),c=e-o,l=ta("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:c,partial:!1}),m=this.apiIce.tx.Intent.submit_intent({intent:{data:l}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(m=await this.dispatchWithExtraGas(m)),this.wrapTx("IntentSwap",m)}};import{Enum as ea}from"polkadot-api";var z=class extends f{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],i=a[a.length-1],r=s.assetIn,n=i.assetOut,o=ea("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:o,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentLimitOrder",c)}};import{Enum as _t}from"polkadot-api";var j=class extends f{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:s,tradeAmountIn:i,tradePeriod:r}=this.order,n=_t("Dca",{asset_in:e,asset_out:a,amount_in:i,amount_out:s,slippage:this.slippagePct*1e4,budget:t,period:r}),o=this.apiIce.tx.Intent.submit_intent({intent:{data:n}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("IntentDcaSchedule",o)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:r}=this.order,n=b.getFraction(i,this.slippagePct),o=i-n,c=_t("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:o,slippage:this.slippagePct*1e4,budget:t,period:r}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule.twap",l)}};var lt=class{client;evmClient;at;constructor(t,e,a){this.client=t,this.evmClient=e,this.at=a}trade(t){return new Y(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new X(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new K(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new z(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new j(this.client,this.evmClient).setOrder(t)}};export{lt as TxBuilderFactory};
1
+ var Gt=Object.defineProperty;var J=(u,t)=>{for(var e in t)Gt(u,e,{get:t[e],enumerable:!0})};import Ut from"buffer";typeof window<"u"&&(window.Buffer=Ut.Buffer);import{calculate_in_given_out as ha,calculate_out_given_in as ba,calculate_linear_weights as ya,calculate_pool_trade_fee as fa,get_spot_price as Pa}from"@galacticcouncil/math-lbp";import{big as Wa,RUNTIME_DECIMALS as $a}from"@galacticcouncil/common";var N={};J(N,{withTimeout:()=>Vt});function Vt(u,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);u.then(r=>{clearTimeout(s),a(r)},r=>{clearTimeout(s),i(r)})})}var b={};J(b,{divSpot:()=>$t,getFraction:()=>Yt,mulScaled:()=>ut,mulSpot:()=>Wt});import{RUNTIME_DECIMALS as ct}from"@galacticcouncil/common";function ut(u,t,e,a,i){let s=e+a-i,r=u*t;return s>0?r/BigInt(10)**BigInt(s):s<0?r*BigInt(10)**BigInt(-s):r}function Wt(u,t,e,a){return ut(u,t,e,ct,a)}function $t(u,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(ct+a-e);return u*i/t}function Yt(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),i=BigInt(Math.round(t*Number(a)));return u*i/(BigInt(100)*a)}var p={};J(p,{FeeUtils:()=>Z,shiftNeg:()=>zt});import Kt from"big.js";var Z=class u{static toPct(t){let[e,a]=t;return u.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return u.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let i=10**a;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function zt(u,t){let e=Kt(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import ka from"big.js";import{TLRUCache as La}from"@thi.ng/cache";var{FeeUtils:ss}=p;import{CompatibilityLevel as dr}from"polkadot-api";import{Subscription as hr,distinctUntilChanged as br,filter as yr,map as fr}from"rxjs";import{memoize1 as wi}from"@thi.ng/memoize";import{TLRUCache as xi}from"@thi.ng/cache";import{ReplaySubject as Bi,Subscription as _i,combineLatest as Ei,defer as Ri,from as Fi,interval as Ci,merge as ki,of as Di,EMPTY as Mi}from"rxjs";import{bufferCount as Hi,bufferTime as Ni,catchError as qi,filter as Gi,finalize as Ui,map as Vi,pairwise as Wi,repeat as $i,skip as Yi,share as Xi,startWith as Ki,switchMap as zi,tap as ji,throttleTime as Qi}from"rxjs/operators";import{hydration as me,hydrationNext as de,hydrationIce as ge}from"@galacticcouncil/descriptors";import{log as oe}from"@galacticcouncil/common";import{map as le,shareReplay as ce,tap as ue}from"rxjs";import{defer as Qt,from as Jt,of as mt,timer as Zt}from"rxjs";import{catchError as te,distinctUntilChanged as ee,expand as ae,map as et,shareReplay as se,skip as ie,switchMap as re,timeout as ne}from"rxjs/operators";function dt(u,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>Qt(()=>Jt(u._request("system_health",[]))).pipe(ne({first:e}),et(()=>"online"),te(()=>mt("offline")));return mt({state:"offline",delayMs:0}).pipe(ae(s=>Zt(s.delayMs).pipe(re(a),et(r=>({state:r,delayMs:t})))),ie(1),et(s=>s.state),ee(),se({bufferSize:1,refCount:!0}))}var{logger:pe}=oe,G=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(le(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",dt(t))}static getInstance(t){return this.instance||(this.instance=new u(t)),this.instance}watched(t,e){return e.pipe(ue({error:a=>pe.error(t,a)}),ce({bufferSize:1,refCount:!0}))}};var S=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(me),this.apiNext=this.client.getTypedApi(de),this.apiIce=this.client.getTypedApi(ge),this.watcher=G.getInstance(this.client),this.at=e??"best"}};import{getWsProvider as ws}from"polkadot-api/ws";import{withLogsRecorder as xs}from"polkadot-api/logs-provider";import{Binary as Ns}from"polkadot-api";import{log as he}from"@galacticcouncil/common";import{combineLatest as be,concat as ye,defer as M,from as gt}from"rxjs";import{bufferCount as ht,distinctUntilChanged as bt,debounceTime as fe,map as _,retry as Pe,startWith as yt,switchMap as ft,tap as L,take as Te,skip as Se,connect as we}from"rxjs/operators";var{logger:E}=he,F=class extends S{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return M(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),i=this.watchErc20Balance(t);return be([e,a,i]).pipe(we(s=>ye(s.pipe(Te(1)),s.pipe(Se(1),fe(250)))))}).pipe(_(e=>e.flat()),yt([]),ht(2,1),_(([e,a],i)=>i===0?a:this.getDeltas(e,a))).pipe(L({subscribe:()=>E.debug("balance: subscribe",t),error:e=>E.error("balance",e)}),Pe({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return M(()=>e.watchValue(t,{at:"best"})).pipe(_(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),L({error:a=>E.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return M(()=>a.watchValue(t,e,{at:"best"})).pipe(_(({value:i})=>({id:e,balance:this.getBreakdown(i)})),L({error:i=>E.error("balance(token)",i)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return M(()=>e.watchEntries(t,{at:"best"})).pipe(bt((a,i)=>!i.deltas),_(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown(s.value)})}),i}),L({error:a=>E.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[n]=r;return n}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async n=>[n,await this.getBalanceData(t,n)]))).map(([n,o])=>({id:n,balance:o}));return M(()=>gt(e?Promise.resolve(e):a()).pipe(ft(s=>this.watcher.bestBlock$.pipe(ft(()=>gt(i(s))))),yt([]),ht(2,1),_(([s,r],n)=>n===0?r.filter(o=>o.balance.total>0n):this.getDeltas(s,r)),bt((s,r)=>r.length===0),L({error:s=>E.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.frozen-t.reserved,a=e>0n?e:0n,i=t.free>=a?t.free-a:0n,s=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:s,transferable:i}}getDeltas(t,e){let a=(s,r)=>s!==void 0&&r!==void 0&&s.transferable===r.transferable&&s.total===r.total,i=t.reduce((s,r)=>(s.set(r.id,r.balance),s),new Map);return e.filter(s=>!a(s.balance,i.get(s.id)))}};import{BehaviorSubject as ci}from"rxjs";import{log as ve}from"@galacticcouncil/common";var hi={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:bi}=ve;var{withTimeout:cr}=N;import{calculate_in_given_out as Dr,calculate_lrna_in_given_out as Mr,calculate_out_given_in as Lr,calculate_out_given_lrna_in as Hr,calculate_spot_price as Nr,calculate_lrna_spot_price as qr,calculate_shares as Gr,calculate_liquidity_out as Ur,calculate_liquidity_lrna_out as Vr,verify_asset_cap as Wr,calculate_liquidity_hub_in as $r,is_sell_allowed as Yr,is_buy_allowed as Xr,is_add_liquidity_allowed as Kr,is_remove_liquidity_allowed as zr,recalculate_asset_fee as jr,recalculate_protocol_fee as Qr}from"@galacticcouncil/math-omnipool";import Zr from"big.js";import{big as sn}from"@galacticcouncil/common";var{FeeUtils:bn}=p;import{AccountId as En,Binary as Tt,CompatibilityLevel as Rn,Enum as Be}from"polkadot-api";import{toHex as kn}from"@polkadot-api/utils";import{Subscription as Mn,distinctUntilChanged as Ln,finalize as Hn,map as Nn,tap as qn}from"rxjs";import{HYDRATION_SS58_PREFIX as Un}from"@galacticcouncil/common";var{FeeUtils:wn}=p;var{FeeUtils:Qn}=p,Jn=Tt.toHex(Tt.fromText("omnipool")),Zn=Be("Short");import{calculate_in_given_out as po,calculate_out_given_in as mo,calculate_amplification as go,calculate_add_one_asset as ho,calculate_liquidity_out_one_asset as bo,calculate_shares as yo,calculate_shares_for_amount as fo,calculate_spot_price_with_fee as Po,pool_account_name as To,recalculate_peg as So}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as Io,big as Oo}from"@galacticcouncil/common";var{FeeUtils:Go}=p;import{AccountId as Al,CompatibilityLevel as Bl}from"polkadot-api";import{toHex as El}from"@polkadot-api/utils";import{blake2b as Fl}from"@noble/hashes/blake2b";import{Subscription as kl,distinctUntilChanged as Dl,filter as Ml,map as Ll,merge as Hl,tap as Nl}from"rxjs";import{HYDRATION_SS58_PREFIX as Gl,RUNTIME_DECIMALS as Ul}from"@galacticcouncil/common";import{Binary as zo}from"polkadot-api";import{decodeEventLog as Qo}from"viem";var{FeeUtils:fl}=p;var{FeeUtils:sc}=p;import{calculate_in_given_out as pc,calculate_out_given_in as mc,calculate_pool_trade_fee as dc,get_spot_price as gc,calculate_liquidity_in as hc,calculate_shares as bc,calculate_spot_price as yc,calculate_spot_price_with_fee as fc,calculate_liquidity_out_asset_a as Pc,calculate_liquidity_out_asset_b as Tc}from"@galacticcouncil/math-xyk";import{big as Oc}from"@galacticcouncil/common";var{FeeUtils:Hc}=p;import{CompatibilityLevel as Uc}from"polkadot-api";import{Subscription as Wc}from"rxjs";import{big as lu,RUNTIME_DECIMALS as cu}from"@galacticcouncil/common";import{AccountId as ip}from"polkadot-api";import{toHex as np}from"@polkadot-api/utils";import{Subscription as lp,filter as cp,map as up,mergeMap as pp}from"rxjs";import{erc20 as Ne,HYDRATION_SS58_PREFIX as dp}from"@galacticcouncil/common";var at=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var st=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var wt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",it="0x112b087b60C1a166130d59266363C45F8aa99db0",rt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",vt=1000000n;var Bu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var U=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:st,address:it,args:[rt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:st,address:it,args:[rt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:at,address:wt,args:[t],functionName:"getUserAccountData"})}};import{Binary as Mu}from"polkadot-api";import{decodeEventLog as Hu}from"viem";import g from"big.js";import{big as B,erc20 as De,h160 as Me}from"@galacticcouncil/common";var{ERC20:C}=De,{H160:nt}=Me,Le=1.01,He=31536000n,xt=4,V=-1,W=10n**27n,$=class{client;constructor(t){this.client=new U(t)}async getSummary(t){let e=nt.fromAny(t),[a,i,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[n]=a,[o,c]=i,[l,m,h,x,P,T]=s,w=B.toDecimal(T,18),I=[];for(let v of o){let A=v.underlyingAsset.toLowerCase(),y=n.find(({underlyingAsset:qt})=>qt.toLowerCase()===A);if(!y)throw new Error("Missing pool reserve for "+A);let Q=v.scaledATokenBalance,k=y.liquidityIndex,Et=y.liquidityRate,Rt=y.availableLiquidity,Ft=y.priceInMarketReferenceCurrency,Ct=r+6,kt=this.calculateLinearInterest(Et,y.lastUpdateTimestamp,Ct),Dt=k*kt/W,Mt=Q*Dt/W,Lt=Number(c!==0&&c===y.eModeCategoryId?y.eModeLiquidationThreshold:y.reserveLiquidationThreshold)/1e4,Ht=y.usageAsCollateralEnabled&&v.usageAsCollateralEnabledOnUser&&v.scaledATokenBalance>0n,Nt=C.toAssetId(A);I.push({aTokenBalance:Mt,availableLiquidity:Rt,decimals:Number(y.decimals),isCollateral:Ht,priceInRef:Ft,reserveId:Nt,reserveAsset:A,reserveLiquidationThreshold:Lt})}return{healthFactor:Number(w),currentLiquidationThreshold:Number(B.toDecimal(x,xt)),totalCollateral:l,totalDebt:m,reserves:I}}async hasBorrowPositions(t){let e=nt.fromAny(t),a=await this.client.getUserAccountData(e),[i,s]=a;return s>0n}async getHealthFactor(t){let e=nt.fromAny(t),a=await this.client.getUserAccountData(e),[i,s,r,n,o,c]=a;return this.calculateHealthFactorFromBalances(s,i,n)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return V;let o=C.fromAssetId(e),c=r.find(A=>A.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:m,priceInRef:h,reserveLiquidationThreshold:x}=c,P=B.toBigInt(a,l),T=m?P*h/10n**BigInt(l):0n,w=i-T;if(w<=0n)return 0;let I=g(i.toString()).mul(n).minus(g(T.toString()).mul(x)).div(w.toString()),v=g(w.toString()).mul(I).div(s.toString()).toFixed(6,g.roundDown);return Number(v)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return V;let o=C.fromAssetId(e),c=r.find(v=>v.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:m,reserveLiquidationThreshold:h}=c,P=B.toBigInt(a,l)*m/10n**BigInt(l),T=i+P;if(T<=0n)return 0;let w=g(i.toString()).mul(n).plus(g(P.toString()).mul(h)).div(T.toString()),I=g(T.toString()).mul(w).div(s.toString()).toFixed(6,g.roundDown);return Number(I)}async getHealthFactorAfterSwap(t,e,a,i,s){let{totalDebt:r,reserves:n,healthFactor:o}=await this.getSummary(t);if(r===0n)return V;let c=C.fromAssetId(a),l=C.fromAssetId(s),m=n.find(k=>k.reserveAsset===c),h=n.find(k=>k.reserveAsset===l);if(!m)throw new Error(`Missing reserve ctx for ${c}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let x=B.toBigInt(e,m.decimals),P=B.toBigInt(i,h.decimals),T=x*m.priceInRef/10n**BigInt(m.decimals),w=P*h.priceInRef/10n**BigInt(h.decimals),I=m.isCollateral?g(T.toString()).mul(m.reserveLiquidationThreshold):g(0),y=(h.isCollateral?g(w.toString()).mul(h.reserveLiquidationThreshold):g(0)).minus(I).div(r.toString()),Q=g(o).plus(y).toFixed(6,g.roundDown);return Number(Q)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:i,healthFactor:s}=await this.getSummary(t),r=C.fromAssetId(e),n=i.find(o=>o.reserveAsset===r);if(!n)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(n,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:i}=await this.getSummary(t),s={};for(let r of a){let n=this.calculateWithdrawMax(r,e,i);r.reserveId&&(s[r.reserveId]=n)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:i,availableLiquidity:s,decimals:r,priceInRef:n,reserveLiquidationThreshold:o,isCollateral:c}=t,l=i;if(c&&e>0n){let h=a-Le;if(h>0){let x=g(h).mul(e.toString()).div(o).toFixed(0,g.roundDown),P=g(x).div(n.toString()).mul(10**r).toFixed(0,g.roundDown);l=i<BigInt(P)?i:BigInt(P)}else l=0n}return{amount:l<s?l:s,decimals:r}}calculateLinearInterest(t,e,a){let i=a-e;if(i<=0)return W;let s=t*BigInt(i)/He;return W+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let i=e*a/t,s=B.toDecimal(i,xt);return Number(s)}};var{ERC20:Sp}=Ne;import{calculate_collateral_in_given_hollar_out as Bp,calculate_collateral_out_given_hollar_in as _p,calculate_hollar_in_given_collateral_out as Ep,calculate_hollar_out_given_collateral_in as Rp,calculate_imbalance as Fp,calculate_max_price as Cp,calculate_buyback_limit as kp,calculate_buyback_price_with_fee as Dp}from"@galacticcouncil/math-hsm";import{big as qp,RUNTIME_DECIMALS as Gp}from"@galacticcouncil/common";var{FeeUtils:Jp}=p;import{AccountId as vm,CompatibilityLevel as xm}from"polkadot-api";import{toHex as Am}from"@polkadot-api/utils";import{Subscription as Em,combineLatest as Rm,filter as Fm,map as Cm,mergeMap as km,pairwise as Dm}from"rxjs";import{h160 as Ve,HYDRATION_SS58_PREFIX as Lm}from"@galacticcouncil/common";import{Binary as im}from"polkadot-api";import{decodeEventLog as nm}from"viem";var{FeeUtils:$m}=p,{H160:Ym}=Ve;import{log as Ye}from"@galacticcouncil/common";import{Subject as _d,Subscription as Ed,takeUntil as Rd}from"rxjs";var{logger:Kd}=Ye;import{big as Qg,RUNTIME_DECIMALS as Jg}from"@galacticcouncil/common";var{FeeUtils:dh}=p;import{big as Ch}from"@galacticcouncil/common";import{Enum as It}from"polkadot-api";var O=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s})=>i==="Stableswap"?{pool:It("Stableswap",s),asset_in:e,asset_out:a}:{pool:It(i),asset_in:e,asset_out:a})}};import{Enum as Bt}from"polkadot-api";function At(u){let t=[],e=u;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var f=class extends S{evm;evmClient;balance;aaveUtils;constructor(t,e,a){super(t,a),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new F(t,a),this.aaveUtils=new $(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:vt})}async dryRun(t,e){let a=Bt("Signed",t),i=Bt("system",a),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4,{at:this.at}),n=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(n){let o=n.type==="Module"?At(n.value):n.type;throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Y=class extends f{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],s=await this.balance.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=b.getFraction(t,this.slippagePct),n=i.assetIn,o=s.assetOut,c=t+r,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.buy({asset_in:n,asset_out:o,amount:e,max_sell_amount:c}):l=this.api.tx.Router.buy({asset_in:n,asset_out:o,amount_out:e,max_amount_in:c,route:O.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterBuy",l)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=b.getFraction(e,this.slippagePct),n=i.assetIn,o=s.assetOut,c=e-r,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.sell({asset_in:n,asset_out:o,amount:t,min_buy_amount:c}):l=this.api.tx.Router.sell({asset_in:n,asset_out:o,amount_in:t,min_amount_out:c,route:O.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSell",l)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],i=e[e.length-1],s=b.getFraction(t,this.slippagePct),r=a.assetIn,n=i.assetOut,o=t-s,c=this.api.tx.Router.sell_all({asset_in:r,asset_out:n,min_amount_out:o,route:O.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSellAll",c)}};import{Enum as ot}from"polkadot-api";var X=class extends f{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradePeriod:s,tradeRoute:r}=this.order,n=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:0n,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(n=await this.dispatchWithExtraGas(n)),this.wrapTx("DcaSchedule",n)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,o=b.getFraction(s,this.slippagePct),c=s-o,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:c,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapSell",l)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,o=b.getFraction(i,this.slippagePct),c=i+o,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Buy",{asset_in:e,asset_out:a,amount_out:s,max_amount_in:c,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapBuy",l)}};import{Enum as ta}from"polkadot-api";var K=class extends f{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,o=b.getFraction(e,this.slippagePct),c=e-o,l=ta("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:c,partial:!1}),m=this.apiIce.tx.Intent.submit_intent({intent:{data:l}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(m=await this.dispatchWithExtraGas(m)),this.wrapTx("IntentSwap",m)}};import{Enum as ea}from"polkadot-api";var z=class extends f{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,o=ea("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:o,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentLimitOrder",c)}};import{Enum as _t}from"polkadot-api";var j=class extends f{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:i,tradeAmountIn:s,tradePeriod:r}=this.order,n=_t("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:i,slippage:this.slippagePct*1e4,budget:t,period:r}),o=this.apiIce.tx.Intent.submit_intent({intent:{data:n}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("IntentDcaSchedule",o)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r}=this.order,n=b.getFraction(s,this.slippagePct),o=s-n,c=_t("Dca",{asset_in:e,asset_out:a,amount_in:i,amount_out:o,slippage:this.slippagePct*1e4,budget:t,period:r}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule.twap",l)}};var lt=class{client;evmClient;at;constructor(t,e,a){this.client=t,this.evmClient=e,this.at=a}trade(t){return new Y(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new X(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new K(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new z(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new j(this.client,this.evmClient).setOrder(t)}};export{lt as TxBuilderFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk-next",
3
- "version": "1.5.0",
3
+ "version": "1.5.1",
4
4
  "description": "Galactic next gen sdk (papi)",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {