@galacticcouncil/sdk-next 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 Ut=Object.defineProperty;var J=(u,t)=>{for(var e in t)Ut(u,e,{get:t[e],enumerable:!0})};import Wt from"buffer";typeof window<"u"&&(window.Buffer=Wt.Buffer);import{calculate_in_given_out as vi,calculate_out_given_in as Ii,calculate_linear_weights as Oi,calculate_pool_trade_fee as Ai,get_spot_price as Bi}from"@galacticcouncil/math-lbp";import{big as Zi,RUNTIME_DECIMALS as ta}from"@galacticcouncil/common";var H={};J(H,{withTimeout:()=>$t});function $t(u,t,e="timeout"){return new Promise((i,s)=>{let a=setTimeout(()=>s(new Error(e)),t);u.then(n=>{clearTimeout(a),i(n)},n=>{clearTimeout(a),s(n)})})}var b={};J(b,{divSpot:()=>Yt,getFraction:()=>Kt,mulScaled:()=>dt,mulSpot:()=>Xt});import{RUNTIME_DECIMALS as mt}from"@galacticcouncil/common";function dt(u,t,e,i,s){let a=e+i-s,n=u*t;return a>0?n/BigInt(10)**BigInt(a):a<0?n*BigInt(10)**BigInt(-a):n}function Xt(u,t,e,i){return dt(u,t,e,mt,i)}function Yt(u,t,e,i){if(t===0n)return 0n;let s=BigInt(10)**BigInt(mt+i-e);return u*s/t}function Kt(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let i=BigInt(10)**BigInt(e),s=BigInt(Math.round(t*Number(i)));return u*s/(BigInt(100)*i)}var p={};J(p,{FeeUtils:()=>Z,shiftNeg:()=>Qt});import jt from"big.js";var Z=class u{static toPct(t){let[e,i]=t;return u.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return u.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let s=10**i;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Qt(u,t){let e=jt(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import Ui from"big.js";import{TLRUCache as Xi}from"@thi.ng/cache";var{FeeUtils:ma}=p;import{CompatibilityLevel as xn}from"polkadot-api";import{Subscription as In,distinctUntilChanged as On,filter as An,map as Bn}from"rxjs";import{memoize1 as Rs}from"@thi.ng/memoize";import{TLRUCache as ks}from"@thi.ng/cache";import{ReplaySubject as Ls,Subscription as qs,combineLatest as Ns,defer as Hs,from as Gs,interval as Vs,merge as Us,of as Ws,EMPTY as $s}from"rxjs";import{bufferCount as Ys,bufferTime as Ks,catchError as zs,filter as js,finalize as Qs,map as Js,pairwise as Zs,repeat as tn,skip as en,share as an,startWith as sn,switchMap as nn,tap as rn,throttleTime as on}from"rxjs/operators";import{hydration as ge,hydrationNext as he,hydrationIce as be}from"@galacticcouncil/descriptors";import{log as ce}from"@galacticcouncil/common";import{map as ue,shareReplay as pe,tap as me}from"rxjs";import{defer as Zt,from as te,of as ht,timer as ee}from"rxjs";import{catchError as ie,distinctUntilChanged as ae,expand as se,map as et,shareReplay as ne,skip as re,switchMap as oe,timeout as le}from"rxjs/operators";function bt(u,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>Zt(()=>te(u._request("system_health",[]))).pipe(le({first:e}),et(()=>"online"),ie(()=>ht("offline")));return ht({state:"offline",delayMs:0}).pipe(se(a=>ee(a.delayMs).pipe(oe(i),et(n=>({state:n,delayMs:t})))),re(1),et(a=>a.state),ae(),ne({bufferSize:1,refCount:!0}))}var{logger:de}=ce,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(ue(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",bt(t))}static getInstance(t){return this.instance||(this.instance=new u(t)),this.instance}watched(t,e){return e.pipe(me({error:i=>de.error(t,i)}),pe({bufferSize:1,refCount:!0}))}};var S=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(ge),this.apiNext=this.client.getTypedApi(he),this.apiIce=this.client.getTypedApi(be),this.watcher=G.getInstance(this.client),this.at=e??"best"}};import{getWsProvider as Ra}from"polkadot-api/ws";import{withLogsRecorder as ka}from"polkadot-api/logs-provider";import{Binary as Ka}from"polkadot-api";import{log as ye}from"@galacticcouncil/common";import{combineLatest as fe,concat as Pe,defer as q,from as yt}from"rxjs";import{bufferCount as ft,distinctUntilChanged as Pt,debounceTime as Te,map as E,retry as Se,startWith as Tt,switchMap as St,tap as N,take as we,skip as xe,connect as ve}from"rxjs/operators";var{logger:R}=ye,k=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:i}=await e.getValue(t,{at:this.at});return this.getBreakdown(i)}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 q(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return fe([e,i,s]).pipe(ve(a=>Pe(a.pipe(we(1)),a.pipe(xe(1),Te(250)))))}).pipe(E(e=>e.flat()),Tt([]),ft(2,1),E(([e,i],s)=>s===0?i:this.getDeltas(e,i))).pipe(N({subscribe:()=>R.debug("balance: subscribe",t),error:e=>R.error("balance",e)}),Se({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return q(()=>e.watchValue(t,{at:"best"})).pipe(E(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),N({error:i=>R.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return q(()=>i.watchValue(t,e,{at:"best"})).pipe(E(({value:s})=>({id:e,balance:this.getBreakdown(s)})),N({error:s=>R.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return q(()=>e.watchEntries(t,{at:"best"})).pipe(Pt((i,s)=>!s.deltas),E(({deltas:i})=>{let s=[];return i?.deleted.forEach(a=>{let[n,r]=a.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(a=>{let[n,r]=a.args;s.push({id:r,balance:this.getBreakdown(a.value)})}),s}),N({error:i=>R.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},s=async a=>(await Promise.all(a.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,o])=>({id:r,balance:o}));return q(()=>yt(e?Promise.resolve(e):i()).pipe(St(a=>this.watcher.bestBlock$.pipe(St(()=>yt(s(a))))),Tt([]),ft(2,1),E(([a,n],r)=>r===0?n.filter(o=>o.balance.total>0n):this.getDeltas(a,n)),Pt((a,n)=>n.length===0),N({error:a=>R.error("balance(erc20)",a)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(a,n)=>a!==void 0&&n!==void 0&&a.transferable===n.transferable&&a.total===n.total,s=t.reduce((a,n)=>(a.set(n.id,n.balance),a),new Map);return e.filter(a=>!i(a.balance,s.get(a.id)))}};import{BehaviorSubject as fs}from"rxjs";import{log as Ie}from"@galacticcouncil/common";var vs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM",UniswapV3:"UNIV3"},{logger:Is}=Ie;var{withTimeout:Pn}=H;import{calculate_in_given_out as $n,calculate_lrna_in_given_out as Xn,calculate_out_given_in as Yn,calculate_out_given_lrna_in as Kn,calculate_spot_price as zn,calculate_lrna_spot_price as jn,calculate_shares as Qn,calculate_liquidity_out as Jn,calculate_liquidity_lrna_out as Zn,verify_asset_cap as tr,calculate_liquidity_hub_in as er,is_sell_allowed as ir,is_buy_allowed as ar,is_add_liquidity_allowed as sr,is_remove_liquidity_allowed as nr,recalculate_asset_fee as rr,recalculate_protocol_fee as or}from"@galacticcouncil/math-omnipool";import cr from"big.js";import{big as dr}from"@galacticcouncil/common";var{FeeUtils:Ir}=p;import{AccountId as Nr,Binary as xt,CompatibilityLevel as Hr,Enum as Ee}from"polkadot-api";import{toHex as Ur}from"@polkadot-api/utils";import{Subscription as $r,distinctUntilChanged as Xr,filter as Yr,finalize as Kr,map as zr,merge as jr,tap as Qr}from"rxjs";import{HYDRATION_SS58_PREFIX as Zr}from"@galacticcouncil/common";var{FeeUtils:Rr}=p;var{FeeUtils:lo}=p,co=xt.toHex(xt.fromText("omnipool")),uo=Ee("Short");import{calculate_in_given_out as xo,calculate_out_given_in as vo,calculate_amplification as Io,calculate_add_one_asset as Oo,calculate_liquidity_out_one_asset as Ao,calculate_shares as Bo,calculate_shares_for_amount as _o,calculate_spot_price_with_fee as Eo,pool_account_name as Ro,recalculate_peg as Fo}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as Do,big as Lo}from"@galacticcouncil/common";var{FeeUtils:Jo}=p;import{AccountId as ql,CompatibilityLevel as Nl}from"polkadot-api";import{toHex as Gl}from"@polkadot-api/utils";import{blake2b as Ul}from"@noble/hashes/blake2b";import{Subscription as $l,distinctUntilChanged as Xl,filter as Yl,map as Kl,merge as zl,tap as jl}from"rxjs";import{HYDRATION_SS58_PREFIX as Jl,RUNTIME_DECIMALS as Zl}from"@galacticcouncil/common";import{Binary as rl}from"polkadot-api";import{decodeEventLog as ll}from"viem";var{FeeUtils:_l}=p;var{FeeUtils:gc}=p;import{calculate_in_given_out as wc,calculate_out_given_in as xc,calculate_pool_trade_fee as vc,get_spot_price as Ic,calculate_liquidity_in as Oc,calculate_shares as Ac,calculate_spot_price as Bc,calculate_spot_price_with_fee as _c,calculate_liquidity_out_asset_a as Ec,calculate_liquidity_out_asset_b as Rc}from"@galacticcouncil/math-xyk";import{big as Lc}from"@galacticcouncil/common";var{FeeUtils:zc}=p;import{CompatibilityLevel as Zc}from"polkadot-api";import{Subscription as eu}from"rxjs";import{big as Pu,RUNTIME_DECIMALS as Tu}from"@galacticcouncil/common";import{AccountId as hp}from"polkadot-api";import{toHex as yp}from"@polkadot-api/utils";import{Subscription as Pp,filter as Tp,map as Sp,mergeMap as wp}from"rxjs";import{erc20 as Ge,HYDRATION_SS58_PREFIX as vp}from"@galacticcouncil/common";var it=[{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 at=[{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 It="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",st="0x112b087b60C1a166130d59266363C45F8aa99db0",nt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ot=1000000n;var Nu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var V=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:at,address:st,args:[nt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:at,address:st,args:[nt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:it,address:It,args:[t],functionName:"getUserAccountData"})}};import{Binary as Yu}from"polkadot-api";import{decodeEventLog as zu}from"viem";import g from"big.js";import{big as B,erc20 as Le,h160 as qe}from"@galacticcouncil/common";var{ERC20:M}=Le,{H160:rt}=qe,Ne=1.01,He=31536000n,At=4,U=-1,W=10n**27n,$=class{client;constructor(t){this.client=new V(t)}async getSummary(t){let e=rt.fromAny(t),[i,s,a,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=i,[o,c]=s,[l,d,h,v,P,T]=a,w=B.toDecimal(T,18),I=[];for(let x of o){let A=x.underlyingAsset.toLowerCase(),y=r.find(({underlyingAsset:Vt})=>Vt.toLowerCase()===A);if(!y)throw new Error("Missing pool reserve for "+A);let Q=x.scaledATokenBalance,D=y.liquidityIndex,Ft=y.liquidityRate,kt=y.availableLiquidity,Ct=y.priceInMarketReferenceCurrency,Mt=n+6,Dt=this.calculateLinearInterest(Ft,y.lastUpdateTimestamp,Mt),Lt=D*Dt/W,qt=Q*Lt/W,Nt=Number(c!==0&&c===y.eModeCategoryId?y.eModeLiquidationThreshold:y.reserveLiquidationThreshold)/1e4,Ht=y.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,Gt=M.toAssetId(A);I.push({aTokenBalance:qt,availableLiquidity:kt,decimals:Number(y.decimals),isCollateral:Ht,priceInRef:Ct,reserveId:Gt,reserveAsset:A,reserveLiquidationThreshold:Nt})}return{healthFactor:Number(w),currentLiquidationThreshold:Number(B.toDecimal(v,At)),totalCollateral:l,totalDebt:d,reserves:I}}async hasBorrowPositions(t){let e=rt.fromAny(t),i=await this.client.getUserAccountData(e),[s,a]=i;return a>0n}async getHealthFactor(t){let e=rt.fromAny(t),i=await this.client.getUserAccountData(e),[s,a,n,r,o,c]=i;return this.calculateHealthFactorFromBalances(a,s,r)}async getHealthFactorAfterWithdraw(t,e,i){let{totalCollateral:s,totalDebt:a,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(a===0n)return U;let o=M.fromAssetId(e),c=n.find(A=>A.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:d,priceInRef:h,reserveLiquidationThreshold:v}=c,P=B.toBigInt(i,l),T=d?P*h/10n**BigInt(l):0n,w=s-T;if(w<=0n)return 0;let I=g(s.toString()).mul(r).minus(g(T.toString()).mul(v)).div(w.toString()),x=g(w.toString()).mul(I).div(a.toString()).toFixed(6,g.roundDown);return Number(x)}async getHealthFactorAfterSupply(t,e,i){let{totalCollateral:s,totalDebt:a,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(a===0n)return U;let o=M.fromAssetId(e),c=n.find(x=>x.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:d,reserveLiquidationThreshold:h}=c,P=B.toBigInt(i,l)*d/10n**BigInt(l),T=s+P;if(T<=0n)return 0;let w=g(s.toString()).mul(r).plus(g(P.toString()).mul(h)).div(T.toString()),I=g(T.toString()).mul(w).div(a.toString()).toFixed(6,g.roundDown);return Number(I)}async getHealthFactorAfterSwap(t,e,i,s,a){let{totalDebt:n,reserves:r,healthFactor:o}=await this.getSummary(t);if(n===0n)return U;let c=M.fromAssetId(i),l=M.fromAssetId(a),d=r.find(D=>D.reserveAsset===c),h=r.find(D=>D.reserveAsset===l);if(!d)throw new Error(`Missing reserve ctx for ${c}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let v=B.toBigInt(e,d.decimals),P=B.toBigInt(s,h.decimals),T=v*d.priceInRef/10n**BigInt(d.decimals),w=P*h.priceInRef/10n**BigInt(h.decimals),I=d.isCollateral?g(T.toString()).mul(d.reserveLiquidationThreshold):g(0),y=(h.isCollateral?g(w.toString()).mul(h.reserveLiquidationThreshold):g(0)).minus(I).div(n.toString()),Q=g(o).plus(y).toFixed(6,g.roundDown);return Number(Q)}async getMaxWithdraw(t,e){let{totalDebt:i,reserves:s,healthFactor:a}=await this.getSummary(t),n=M.fromAssetId(e),r=s.find(o=>o.reserveAsset===n);if(!r)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(r,i,a)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:i,healthFactor:s}=await this.getSummary(t),a={};for(let n of i){let r=this.calculateWithdrawMax(n,e,s);n.reserveId&&(a[n.reserveId]=r)}return a}calculateWithdrawMax(t,e,i){let{aTokenBalance:s,availableLiquidity:a,decimals:n,priceInRef:r,reserveLiquidationThreshold:o,isCollateral:c}=t,l=s;if(c&&e>0n){let h=i-Ne;if(h>0){let v=g(h).mul(e.toString()).div(o).toFixed(0,g.roundDown),P=g(v).div(r.toString()).mul(10**n).toFixed(0,g.roundDown);l=s<BigInt(P)?s:BigInt(P)}else l=0n}return{amount:l<a?l:a,decimals:n}}calculateLinearInterest(t,e,i){let s=i-e;if(s<=0)return W;let a=t*BigInt(s)/He;return W+a}calculateHealthFactorFromBalances(t,e,i){if(t===0n)return U;let s=e*i/t,a=B.toDecimal(s,At);return Number(a)}};var{ERC20:Fp}=Ge;import{calculate_collateral_in_given_hollar_out as Np,calculate_collateral_out_given_hollar_in as Hp,calculate_hollar_in_given_collateral_out as Gp,calculate_hollar_out_given_collateral_in as Vp,calculate_imbalance as Up,calculate_max_price as Wp,calculate_buyback_limit as $p,calculate_buyback_price_with_fee as Xp}from"@galacticcouncil/math-hsm";import{big as Qp,RUNTIME_DECIMALS as Jp}from"@galacticcouncil/common";var{FeeUtils:cm}=p;import{AccountId as Cm,CompatibilityLevel as Mm}from"polkadot-api";import{toHex as qm}from"@polkadot-api/utils";import{Subscription as Gm,combineLatest as Vm,filter as Um,map as Wm,mergeMap as $m,pairwise as Xm}from"rxjs";import{h160 as $e,HYDRATION_SS58_PREFIX as Km}from"@galacticcouncil/common";import{Binary as hm}from"polkadot-api";import{decodeEventLog as ym}from"viem";var{FeeUtils:id}=p,{H160:ad}=$e;import ot from"jsbi";import{LiquidityMath as bd,SwapMath as yd,Tick as fd,TickList as Pd,TickMath as Td}from"@uniswap/v3-sdk";var Sd=ot.BigInt(0),wd=ot.BigInt(1),xd=ot.BigInt(-1);import{RUNTIME_DECIMALS as Ye}from"@galacticcouncil/common";var Ld=10n**BigInt(Ye);import{Subscription as Xd,filter as Yd,map as Kd,mergeMap as zd}from"rxjs";import{erc20 as Qe}from"@galacticcouncil/common";import{TICK_SPACINGS as Zd,TickMath as tg,nearestUsableTick as eg}from"@uniswap/v3-sdk";import{parseAbi as lt}from"viem";var Ke=lt(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)"]),ze=lt(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickBitmap(int16 wordPosition) view returns (uint256)","function ticks(int24 tick) view returns (uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized)"]),je=lt(["function balanceOf(address account) view returns (uint256)"]);var{ERC20:cg}=Qe;import{log as ei}from"@galacticcouncil/common";import{Subject as Qg,Subscription as Jg,takeUntil as Zg}from"rxjs";var{logger:yh}=ei;import{big as Sb,RUNTIME_DECIMALS as wb}from"@galacticcouncil/common";var{FeeUtils:Lb}=p;import{big as ay}from"@galacticcouncil/common";import{Enum as ct}from"polkadot-api";var O=class{static build(t){return t.map(({assetIn:e,assetOut:i,pool:s,poolId:a,fee:n})=>s==="Stableswap"?{pool:ct("Stableswap",a),asset_in:e,asset_out:i}:s==="UniswapV3"?{pool:ct("UniswapV3",n),asset_in:e,asset_out:i}:{pool:ct(s),asset_in:e,asset_out:i})}};import{Enum as Et}from"polkadot-api";function _t(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,i){super(t,i),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new k(t,i),this.aaveUtils=new $(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:i=>this.dryRun(i,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Ot})}async dryRun(t,e){let i=Et("Signed",t),s=Et("system",i),n=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall,4,{at:this.at}),r=n.success&&!n.value.execution_result.success?n.value.execution_result.value.error:null;if(r){let o=r.type==="Module"?_t(r.value):r.type;throw new Error("Dry run execution error!",{cause:o})}return n}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var X=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:i}=this.trade;if(i==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],a=await this.balance.getBalance(this.beneficiary,s);return t>=a.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,s=i[0],a=i[i.length-1],n=b.getFraction(t,this.slippagePct),r=s.assetIn,o=a.assetOut,c=t+n,l;return this.isDirectOmnipoolTrade(i)?l=this.api.tx.Omnipool.buy({asset_in:r,asset_out:o,amount:e,max_sell_amount:c}):l=this.api.tx.Router.buy({asset_in:r,asset_out:o,amount_out:e,max_amount_in:c,route:O.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterBuy",l)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,s=i[0],a=i[i.length-1],n=b.getFraction(e,this.slippagePct),r=s.assetIn,o=a.assetOut,c=e-n,l;return this.isDirectOmnipoolTrade(i)?l=this.api.tx.Omnipool.sell({asset_in:r,asset_out:o,amount:t,min_buy_amount:c}):l=this.api.tx.Router.sell({asset_in:r,asset_out:o,amount_in:t,min_amount_out:c,route:O.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSell",l)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,i=e[0],s=e[e.length-1],a=b.getFraction(t,this.slippagePct),n=i.assetIn,r=s.assetOut,o=t-a,c=this.api.tx.Router.sell_all({asset_in:n,asset_out:r,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 ut}from"polkadot-api";var Y=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:i,tradeAmountIn:s,tradePeriod:a,tradeRoute:n}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ut("Sell",{asset_in:e,asset_out:i,amount_in:s,min_amount_out:0n,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(r=await this.dispatchWithExtraGas(r)),this.wrapTx("DcaSchedule",r)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:n,tradeRoute:r}=this.order,o=b.getFraction(a,this.slippagePct),c=a-o,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ut("Sell",{asset_in:e,asset_out:i,amount_in:s,min_amount_out:c,route:r})},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:i,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:n,tradeRoute:r}=this.order,o=b.getFraction(s,this.slippagePct),c=s+o,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ut("Buy",{asset_in:e,asset_out:i,amount_out:a,max_amount_in:c,route:r})},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 ci}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:i}=this.trade,s=i[0],a=i[i.length-1],n=s.assetIn,r=a.assetOut,o=b.getFraction(e,this.slippagePct),c=e-o,l=ci("Swap",{asset_in:n,asset_out:r,amount_in:t,amount_out:c,partial:!1}),d=this.apiIce.tx.Intent.submit_intent({intent:{data:l}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(d=await this.dispatchWithExtraGas(d)),this.wrapTx("IntentSwap",d)}};import{Enum as ui}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:i}=this.trade,s=i[0],a=i[i.length-1],n=s.assetIn,r=a.assetOut,o=ui("Swap",{asset_in:n,asset_out:r,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 Rt}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:i,assetOutEd:s,tradeAmountIn:a,tradePeriod:n}=this.order,r=Rt("Dca",{asset_in:e,asset_out:i,amount_in:a,amount_out:s,slippage:this.slippagePct*1e4,budget:t,period:n}),o=this.apiIce.tx.Intent.submit_intent({intent:{data:r}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("IntentDcaSchedule",o)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:n}=this.order,r=b.getFraction(a,this.slippagePct),o=a-r,c=Rt("Dca",{asset_in:e,asset_out:i,amount_in:s,amount_out:o,slippage:this.slippagePct*1e4,budget:t,period:n}),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 pt=class{client;evmClient;at;constructor(t,e,i){this.client=t,this.evmClient=e,this.at=i}trade(t){return new X(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new Y(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{pt as TxBuilderFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk-next",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Galactic next gen sdk (papi)",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {
@@ -101,6 +101,9 @@
101
101
  "@galacticcouncil/math-xyk": "^1.3.0",
102
102
  "@noble/hashes": "^1.6.1",
103
103
  "@thi.ng/cache": "^2.1.35",
104
+ "@uniswap/sdk-core": "^7.17.0",
105
+ "@uniswap/v3-sdk": "^3.30.4",
106
+ "jsbi": "^3.2.5",
104
107
  "@thi.ng/memoize": "^4.0.2",
105
108
  "big.js": "^6.2.1"
106
109
  },