@galacticcouncil/sdk-next 1.0.0 → 1.0.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
- var Mt=Object.defineProperty;var K=(l,t)=>{for(var e in t)Mt(l,e,{get:t[e],enumerable:!0})};import Lt from"buffer";typeof window<"u"&&(window.Buffer=Lt.Buffer);import{calculate_in_given_out as sa,calculate_out_given_in as na,calculate_linear_weights as ia,calculate_pool_trade_fee as ra,get_spot_price as oa}from"@galacticcouncil/math-lbp";import{big as Ea,RUNTIME_DECIMALS as Ca}from"@galacticcouncil/common";var N={};K(N,{withTimeout:()=>Ht});function Ht(l,t,e="timeout"){return new Promise((a,n)=>{let s=setTimeout(()=>n(new Error(e)),t);l.then(i=>{clearTimeout(s),a(i)},i=>{clearTimeout(s),n(i)})})}var y={};K(y,{divSpot:()=>qt,getFraction:()=>Gt,mulScaled:()=>it,mulSpot:()=>Nt});import{RUNTIME_DECIMALS as nt}from"@galacticcouncil/common";function it(l,t,e,a,n){let s=e+a-n,i=l*t;return s>0?i/BigInt(10)**BigInt(s):s<0?i*BigInt(10)**BigInt(-s):i}function Nt(l,t,e,a){return it(l,t,e,nt,a)}function qt(l,t,e,a){if(t===0n)return 0n;let n=BigInt(10)**BigInt(nt+a-e);return l*n/t}function Gt(l,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),n=BigInt(Math.round(t*Number(a)));return l*n/(BigInt(100)*a)}var p={};K(p,{FeeUtils:()=>j,shiftNeg:()=>Wt});import Vt from"big.js";var j=class l{static toPct(t){let[e,a]=t;return l.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return l.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 n=10**a;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Wt(l,t){let e=Vt(typeof l=="bigint"?l.toString():l);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import va from"big.js";import{TLRUCache as Ia}from"@thi.ng/cache";var{FeeUtils:$a}=p;import{CompatibilityLevel as ai}from"polkadot-api";import{Subscription as ni,distinctUntilChanged as ii,filter as ri,map as oi}from"rxjs";import{memoize1 as mn}from"@thi.ng/memoize";import{TLRUCache as gn}from"@thi.ng/cache";import{ReplaySubject as Pn,Subscription as fn,combineLatest as Tn,defer as Sn,from as vn,interval as wn,merge as xn,of as In,EMPTY as On}from"rxjs";import{bufferCount as Bn,bufferTime as _n,catchError as Rn,filter as Fn,finalize as En,map as Cn,pairwise as kn,repeat as Dn,skip as Mn,share as Ln,startWith as Hn,switchMap as Nn,tap as qn,throttleTime as Gn}from"rxjs/operators";import{hydration as oe,hydrationNext as le}from"@galacticcouncil/descriptors";import{log as ae}from"@galacticcouncil/common";import{map as se,shareReplay as ne,tap as ie}from"rxjs";import{defer as Xt,from as Yt,of as lt,timer as zt}from"rxjs";import{catchError as Kt,distinctUntilChanged as jt,expand as Qt,map as Q,shareReplay as Jt,skip as Zt,switchMap as te,timeout as ee}from"rxjs/operators";function ct(l,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>Xt(()=>Yt(l._request("system_health",[]))).pipe(ee({first:e}),Q(()=>"online"),Kt(()=>lt("offline")));return lt({state:"offline",delayMs:0}).pipe(Qt(s=>zt(s.delayMs).pipe(te(a),Q(i=>({state:i,delayMs:t})))),Zt(1),Q(s=>s.state),jt(),Jt({bufferSize:1,refCount:!0}))}var{logger:re}=ae,G=class l{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(se(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ct(t))}static getInstance(t){return this.instance||(this.instance=new l(t)),this.instance}watched(t,e){return e.pipe(ie({error:a=>re.error(t,a)}),ne({bufferSize:1,refCount:!0}))}};var T=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(oe),this.apiNext=this.client.getTypedApi(le),this.watcher=G.getInstance(this.client)}};import{getWsProvider as us}from"polkadot-api/ws";import{withLogsRecorder as ms}from"polkadot-api/logs-provider";import{getSmProvider as bs}from"polkadot-api/sm-provider";import{Binary as _s}from"polkadot-api";import{log as ce}from"@galacticcouncil/common";import{combineLatest as ue,concat as pe,defer as D,from as ut}from"rxjs";import{bufferCount as pt,distinctUntilChanged as mt,debounceTime as me,map as B,retry as de,startWith as dt,switchMap as gt,tap as M,take as ge,skip as he,connect as be}from"rxjs/operators";var{logger:_}=ce,R=class extends T{erc20Ids=null;constructor(t){super(t)}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:"best"});return this.getBreakdown(a)}async getTokenBalance(t,e){let n=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(n)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return D(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),n=this.watchErc20Balance(t);return ue([e,a,n]).pipe(be(s=>pe(s.pipe(ge(1)),s.pipe(he(1),me(250)))))}).pipe(B(e=>e.flat()),dt([]),pt(2,1),B(([e,a],n)=>n===0?a:this.getDeltas(e,a))).pipe(M({subscribe:()=>_.debug("balance: subscribe",t),error:e=>_.error("balance",e)}),de({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return D(()=>e.watchValue(t,{at:"best"})).pipe(B(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),M({error:a=>_.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return D(()=>a.watchValue(t,e,{at:"best"})).pipe(B(({value:n})=>({id:e,balance:this.getBreakdown(n)})),M({error:n=>_.error("balance(token)",n)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return D(()=>e.watchEntries(t,{at:"best"})).pipe(mt((a,n)=>!n.deltas),B(({deltas:a})=>{let n=[];return a?.deleted.forEach(s=>{let[i,r]=s.args;n.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[i,r]=s.args;n.push({id:r,balance:this.getBreakdown(s.value)})}),n}),M({error:a=>_.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:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},n=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,c])=>({id:r,balance:c}));return D(()=>ut(e?Promise.resolve(e):a()).pipe(gt(s=>this.watcher.bestBlock$.pipe(gt(()=>ut(n(s))))),dt([]),pt(2,1),B(([s,i],r)=>r===0?i.filter(c=>c.balance.total>0n):this.getDeltas(s,i)),mt((s,i)=>i.length===0),M({error:s=>_.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});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,i)=>s!==void 0&&i!==void 0&&s.transferable===i.transferable&&s.total===i.total,n=t.reduce((s,i)=>(s.set(i.id,i.balance),s),new Map);return e.filter(s=>!a(s.balance,n.get(s.id)))}};import{BehaviorSubject as Js}from"rxjs";import{log as ye}from"@galacticcouncil/common";var nn={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:rn}=ye;var{withTimeout:Jn}=N;import{calculate_in_given_out as vi,calculate_lrna_in_given_out as wi,calculate_out_given_in as xi,calculate_out_given_lrna_in as Ii,calculate_spot_price as Oi,calculate_lrna_spot_price as Ai,calculate_shares as Bi,calculate_liquidity_out as _i,calculate_liquidity_lrna_out as Ri,verify_asset_cap as Fi,calculate_liquidity_hub_in as Ei,is_sell_allowed as Ci,is_buy_allowed as ki,is_add_liquidity_allowed as Di,is_remove_liquidity_allowed as Mi,recalculate_asset_fee as Li,recalculate_protocol_fee as Hi}from"@galacticcouncil/math-omnipool";import qi from"big.js";import{big as Wi}from"@galacticcouncil/common";var{FeeUtils:ar}=p;import{AccountId as lr,Binary as bt,CompatibilityLevel as cr,Enum as fe}from"polkadot-api";import{toHex as mr}from"@polkadot-api/utils";import{Subscription as gr,distinctUntilChanged as hr,filter as br,finalize as yr,map as Pr,merge as fr,tap as Tr}from"rxjs";import{HYDRATION_SS58_PREFIX as vr}from"@galacticcouncil/common";var{FeeUtils:Fr}=p,Er=bt.toHex(bt.fromText("omnipool")),Cr=fe("Short");import{calculate_in_given_out as Gr,calculate_out_given_in as Ur,calculate_amplification as Vr,calculate_add_one_asset as Wr,calculate_liquidity_out_one_asset as $r,calculate_shares as Xr,calculate_shares_for_amount as Yr,calculate_spot_price_with_fee as zr,pool_account_name as Kr,recalculate_peg as jr}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as to,big as eo}from"@galacticcouncil/common";var{FeeUtils:yo}=p;import{AccountId as So,CompatibilityLevel as vo}from"polkadot-api";import{toHex as xo}from"@polkadot-api/utils";import{blake2b as Oo}from"@noble/hashes/blake2b";import{Subscription as Bo,distinctUntilChanged as _o,map as Ro,merge as Fo,tap as Eo}from"rxjs";import{HYDRATION_SS58_PREFIX as ko,RUNTIME_DECIMALS as Do}from"@galacticcouncil/common";var{FeeUtils:Xo}=p;import{calculate_in_given_out as tl,calculate_out_given_in as el,calculate_pool_trade_fee as al,get_spot_price as sl,calculate_liquidity_in as nl,calculate_shares as il,calculate_spot_price as rl,calculate_spot_price_with_fee as ol,calculate_liquidity_out_asset_a as ll,calculate_liquidity_out_asset_b as cl}from"@galacticcouncil/math-xyk";import{big as hl}from"@galacticcouncil/common";var{FeeUtils:Al}=p;import{CompatibilityLevel as Fl}from"polkadot-api";import{Subscription as Cl}from"rxjs";import{big as Kl,RUNTIME_DECIMALS as jl}from"@galacticcouncil/common";import{AccountId as pc,Binary as mc}from"polkadot-api";import{toHex as gc}from"@polkadot-api/utils";import{Subscription as bc,filter as yc,map as Pc,mergeMap as fc}from"rxjs";import{decodeEventLog as Sc}from"viem";import{erc20 as Ie,HYDRATION_SS58_PREFIX as wc}from"@galacticcouncil/common";var{ERC20:Rc}=Ie;import{calculate_collateral_in_given_hollar_out as Lc,calculate_collateral_out_given_hollar_in as Hc,calculate_hollar_in_given_collateral_out as Nc,calculate_hollar_out_given_collateral_in as qc,calculate_imbalance as Gc,calculate_max_price as Uc,calculate_buyback_limit as Vc,calculate_buyback_price_with_fee as Wc}from"@galacticcouncil/math-hsm";import{big as Kc,RUNTIME_DECIMALS as jc}from"@galacticcouncil/common";var{FeeUtils:ou}=p;import{AccountId as Tu,Binary as Su,CompatibilityLevel as vu}from"polkadot-api";import{toHex as Iu}from"@polkadot-api/utils";import{Subscription as Bu,combineLatest as _u,filter as Ru,map as Fu,mergeMap as Eu,pairwise as Cu}from"rxjs";import{decodeEventLog as Du}from"viem";import{h160 as _e,HYDRATION_SS58_PREFIX as Lu}from"@galacticcouncil/common";var{FeeUtils:Wu}=p,{H160:$u}=_e;import{log as Fe}from"@galacticcouncil/common";import{Subject as _p,Subscription as Rp,takeUntil as Fp}from"rxjs";var{logger:Yp}=Fe;import{big as km,RUNTIME_DECIMALS as Dm}from"@galacticcouncil/common";var{FeeUtils:jm}=p;import{big as bd}from"@galacticcouncil/common";import{Enum as Pt}from"polkadot-api";var I=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:n,poolId:s})=>n==="Stableswap"?{pool:Pt("Stableswap",s),asset_in:e,asset_out:a}:{pool:Pt(n),asset_in:e,asset_out:a})}};import{Enum as xt}from"polkadot-api";var ft=[{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 J=[{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 Tt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Z="0x112b087b60C1a166130d59266363C45F8aa99db0",tt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",St=1000000n;var Xd=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:J,address:Z,args:[tt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:J,address:Z,args:[tt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:ft,address:Tt,args:[t],functionName:"getUserAccountData"})}};import d from"big.js";import{big as A,erc20 as qe,h160 as Ge}from"@galacticcouncil/common";var{ERC20:F}=qe,{H160:et}=Ge,Ue=1.01,Ve=31536000n,vt=4,V=-1,W=10n**27n,$=class{client;constructor(t){this.client=new U(t)}async getSummary(t){let e=et.fromAny(t),[a,n,s,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[c,u]=n,[o,g,h,w,P,f]=s,S=A.toDecimal(f,18),x=[];for(let v of c){let O=v.underlyingAsset.toLowerCase(),b=r.find(({underlyingAsset:Dt})=>Dt.toLowerCase()===O);if(!b)throw new Error("Missing pool reserve for "+O);let z=v.scaledATokenBalance,C=b.liquidityIndex,It=b.liquidityRate,Ot=b.availableLiquidity,At=b.priceInMarketReferenceCurrency,Bt=i+6,_t=this.calculateLinearInterest(It,b.lastUpdateTimestamp,Bt),Rt=C*_t/W,Ft=z*Rt/W,Et=Number(u!==0&&u===b.eModeCategoryId?b.eModeLiquidationThreshold:b.reserveLiquidationThreshold)/1e4,Ct=b.usageAsCollateralEnabled&&v.usageAsCollateralEnabledOnUser&&v.scaledATokenBalance>0n,kt=F.toAssetId(O);x.push({aTokenBalance:Ft,availableLiquidity:Ot,decimals:Number(b.decimals),isCollateral:Ct,priceInRef:At,reserveId:kt,reserveAsset:O,reserveLiquidationThreshold:Et})}return{healthFactor:Number(S),currentLiquidationThreshold:Number(A.toDecimal(w,vt)),totalCollateral:o,totalDebt:g,reserves:x}}async hasBorrowPositions(t){let e=et.fromAny(t),a=await this.client.getUserAccountData(e),[n,s]=a;return s>0n}async getHealthFactor(t){let e=et.fromAny(t),a=await this.client.getUserAccountData(e),[n,s,i,r,c,u]=a;return this.calculateHealthFactorFromBalances(s,n,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:n,totalDebt:s,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return V;let c=F.fromAssetId(e),u=i.find(O=>O.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,isCollateral:g,priceInRef:h,reserveLiquidationThreshold:w}=u,P=A.toBigInt(a,o),f=g?P*h/10n**BigInt(o):0n,S=n-f;if(S<=0n)return 0;let x=d(n.toString()).mul(r).minus(d(f.toString()).mul(w)).div(S.toString()),v=d(S.toString()).mul(x).div(s.toString()).toFixed(6,d.roundDown);return Number(v)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:n,totalDebt:s,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return V;let c=F.fromAssetId(e),u=i.find(v=>v.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,priceInRef:g,reserveLiquidationThreshold:h}=u,P=A.toBigInt(a,o)*g/10n**BigInt(o),f=n+P;if(f<=0n)return 0;let S=d(n.toString()).mul(r).plus(d(P.toString()).mul(h)).div(f.toString()),x=d(f.toString()).mul(S).div(s.toString()).toFixed(6,d.roundDown);return Number(x)}async getHealthFactorAfterSwap(t,e,a,n,s){let{totalDebt:i,reserves:r,healthFactor:c}=await this.getSummary(t);if(i===0n)return V;let u=F.fromAssetId(a),o=F.fromAssetId(s),g=r.find(C=>C.reserveAsset===u),h=r.find(C=>C.reserveAsset===o);if(!g)throw new Error(`Missing reserve ctx for ${u}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let w=A.toBigInt(e,g.decimals),P=A.toBigInt(n,h.decimals),f=w*g.priceInRef/10n**BigInt(g.decimals),S=P*h.priceInRef/10n**BigInt(h.decimals),x=g.isCollateral?d(f.toString()).mul(g.reserveLiquidationThreshold):d(0),b=(h.isCollateral?d(S.toString()).mul(h.reserveLiquidationThreshold):d(0)).minus(x).div(i.toString()),z=d(c).plus(b).toFixed(6,d.roundDown);return Number(z)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:n,healthFactor:s}=await this.getSummary(t),i=F.fromAssetId(e),r=n.find(c=>c.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:n}=await this.getSummary(t),s={};for(let i of a){let r=this.calculateWithdrawMax(i,e,n);i.reserveId&&(s[i.reserveId]=r)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:n,availableLiquidity:s,decimals:i,priceInRef:r,reserveLiquidationThreshold:c,isCollateral:u}=t,o=n;if(u&&e>0n){let h=a-Ue;if(h>0){let w=d(h).mul(e.toString()).div(c).toFixed(0,d.roundDown),P=d(w).div(r.toString()).mul(10**i).toFixed(0,d.roundDown);o=n<BigInt(P)?n:BigInt(P)}else o=0n}return{amount:o<s?o:s,decimals:i}}calculateLinearInterest(t,e,a){let n=a-e;if(n<=0)return W;let s=t*BigInt(n)/Ve;return W+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let n=e*a/t,s=A.toDecimal(n,vt);return Number(s)}};function wt(l){let t=[],e=l;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var E=class extends T{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new R(t),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:St})}async dryRun(t,e){let a=xt("Signed",t),n=xt("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(n,e.decodedCall,4),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let c=r.type==="Module"?wt(r.value):r.type;throw new Error("Dry run execution error!",{cause:c})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var X=class extends E{_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:n}=e[0],s=await this.balance.getBalance(this.beneficiary,n);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,n=a[0],s=a[a.length-1],i=y.getFraction(t,this.slippagePct),r=n.assetIn,c=s.assetOut,u=t+i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.buy({asset_in:r,asset_out:c,amount:e,max_sell_amount:u}):o=this.api.tx.Router.buy({asset_in:r,asset_out:c,amount_out:e,max_amount_in:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterBuy",o)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,n=a[0],s=a[a.length-1],i=y.getFraction(e,this.slippagePct),r=n.assetIn,c=s.assetOut,u=e-i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.sell({asset_in:r,asset_out:c,amount:t,min_buy_amount:u}):o=this.api.tx.Router.sell({asset_in:r,asset_out:c,amount_in:t,min_amount_out:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterSell",o)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],n=e[e.length-1],s=y.getFraction(t,this.slippagePct),i=a.assetIn,r=n.assetOut,c=t-s,u=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:c,route:I.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};import{Enum as at}from"polkadot-api";var Y=class extends E{_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:n,tradePeriod:s,tradeRoute:i}=this.order,r=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:at("Sell",{asset_in:e,asset_out:a,amount_in:n,min_amount_out:0n,route:i})},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:a,tradeAmountIn:n,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(s,this.slippagePct),u=s-c,o=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:at("Sell",{asset_in:e,asset_out:a,amount_in:n,min_amount_out:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapSell",o)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:n,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(n,this.slippagePct),u=n+c,o=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:at("Buy",{asset_in:e,asset_out:a,amount_out:s,max_amount_in:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapBuy",o)}};var st=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new X(this.client,this.evmClient).setTrade(t)}order(t){return new Y(this.client,this.evmClient).setOrder(t)}};export{st as TxBuilderFactory};
1
+ var Mt=Object.defineProperty;var K=(l,t)=>{for(var e in t)Mt(l,e,{get:t[e],enumerable:!0})};import Lt from"buffer";typeof window<"u"&&(window.Buffer=Lt.Buffer);import{calculate_in_given_out as sa,calculate_out_given_in as na,calculate_linear_weights as ia,calculate_pool_trade_fee as ra,get_spot_price as oa}from"@galacticcouncil/math-lbp";import{big as Ea,RUNTIME_DECIMALS as Ca}from"@galacticcouncil/common";var N={};K(N,{withTimeout:()=>Ht});function Ht(l,t,e="timeout"){return new Promise((a,n)=>{let s=setTimeout(()=>n(new Error(e)),t);l.then(i=>{clearTimeout(s),a(i)},i=>{clearTimeout(s),n(i)})})}var y={};K(y,{divSpot:()=>qt,getFraction:()=>Gt,mulScaled:()=>it,mulSpot:()=>Nt});import{RUNTIME_DECIMALS as nt}from"@galacticcouncil/common";function it(l,t,e,a,n){let s=e+a-n,i=l*t;return s>0?i/BigInt(10)**BigInt(s):s<0?i*BigInt(10)**BigInt(-s):i}function Nt(l,t,e,a){return it(l,t,e,nt,a)}function qt(l,t,e,a){if(t===0n)return 0n;let n=BigInt(10)**BigInt(nt+a-e);return l*n/t}function Gt(l,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),n=BigInt(Math.round(t*Number(a)));return l*n/(BigInt(100)*a)}var p={};K(p,{FeeUtils:()=>j,shiftNeg:()=>Wt});import Vt from"big.js";var j=class l{static toPct(t){let[e,a]=t;return l.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return l.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 n=10**a;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Wt(l,t){let e=Vt(typeof l=="bigint"?l.toString():l);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import wa from"big.js";import{TLRUCache as Ia}from"@thi.ng/cache";var{FeeUtils:$a}=p;import{CompatibilityLevel as ti}from"polkadot-api";import{Subscription as ai,distinctUntilChanged as si,filter as ni,map as ii}from"rxjs";import{memoize1 as un}from"@thi.ng/memoize";import{TLRUCache as mn}from"@thi.ng/cache";import{ReplaySubject as bn,Subscription as yn,combineLatest as Pn,defer as fn,from as Tn,interval as Sn,merge as wn,of as vn,EMPTY as xn}from"rxjs";import{bufferCount as On,bufferTime as An,catchError as Bn,filter as _n,finalize as Rn,map as Fn,pairwise as En,repeat as Cn,skip as kn,share as Dn,startWith as Mn,switchMap as Ln,tap as Hn,throttleTime as Nn}from"rxjs/operators";import{hydration as oe,hydrationNext as le}from"@galacticcouncil/descriptors";import{log as ae}from"@galacticcouncil/common";import{map as se,shareReplay as ne,tap as ie}from"rxjs";import{defer as Xt,from as Yt,of as lt,timer as zt}from"rxjs";import{catchError as Kt,distinctUntilChanged as jt,expand as Qt,map as Q,shareReplay as Jt,skip as Zt,switchMap as te,timeout as ee}from"rxjs/operators";function ct(l,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>Xt(()=>Yt(l._request("system_health",[]))).pipe(ee({first:e}),Q(()=>"online"),Kt(()=>lt("offline")));return lt({state:"offline",delayMs:0}).pipe(Qt(s=>zt(s.delayMs).pipe(te(a),Q(i=>({state:i,delayMs:t})))),Zt(1),Q(s=>s.state),jt(),Jt({bufferSize:1,refCount:!0}))}var{logger:re}=ae,G=class l{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(se(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ct(t))}static getInstance(t){return this.instance||(this.instance=new l(t)),this.instance}watched(t,e){return e.pipe(ie({error:a=>re.error(t,a)}),ne({bufferSize:1,refCount:!0}))}};var T=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(oe),this.apiNext=this.client.getTypedApi(le),this.watcher=G.getInstance(this.client)}};import{getWsProvider as us}from"polkadot-api/ws";import{withLogsRecorder as ms}from"polkadot-api/logs-provider";import{Binary as As}from"polkadot-api";import{log as ce}from"@galacticcouncil/common";import{combineLatest as ue,concat as pe,defer as D,from as ut}from"rxjs";import{bufferCount as pt,distinctUntilChanged as mt,debounceTime as me,map as B,retry as de,startWith as dt,switchMap as gt,tap as M,take as ge,skip as he,connect as be}from"rxjs/operators";var{logger:_}=ce,R=class extends T{erc20Ids=null;constructor(t){super(t)}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:"best"});return this.getBreakdown(a)}async getTokenBalance(t,e){let n=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(n)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return D(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),n=this.watchErc20Balance(t);return ue([e,a,n]).pipe(be(s=>pe(s.pipe(ge(1)),s.pipe(he(1),me(250)))))}).pipe(B(e=>e.flat()),dt([]),pt(2,1),B(([e,a],n)=>n===0?a:this.getDeltas(e,a))).pipe(M({subscribe:()=>_.debug("balance: subscribe",t),error:e=>_.error("balance",e)}),de({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return D(()=>e.watchValue(t,{at:"best"})).pipe(B(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),M({error:a=>_.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return D(()=>a.watchValue(t,e,{at:"best"})).pipe(B(({value:n})=>({id:e,balance:this.getBreakdown(n)})),M({error:n=>_.error("balance(token)",n)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return D(()=>e.watchEntries(t,{at:"best"})).pipe(mt((a,n)=>!n.deltas),B(({deltas:a})=>{let n=[];return a?.deleted.forEach(s=>{let[i,r]=s.args;n.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[i,r]=s.args;n.push({id:r,balance:this.getBreakdown(s.value)})}),n}),M({error:a=>_.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:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},n=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,c])=>({id:r,balance:c}));return D(()=>ut(e?Promise.resolve(e):a()).pipe(gt(s=>this.watcher.bestBlock$.pipe(gt(()=>ut(n(s))))),dt([]),pt(2,1),B(([s,i],r)=>r===0?i.filter(c=>c.balance.total>0n):this.getDeltas(s,i)),mt((s,i)=>i.length===0),M({error:s=>_.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});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,i)=>s!==void 0&&i!==void 0&&s.transferable===i.transferable&&s.total===i.total,n=t.reduce((s,i)=>(s.set(i.id,i.balance),s),new Map);return e.filter(s=>!a(s.balance,n.get(s.id)))}};import{BehaviorSubject as js}from"rxjs";import{log as ye}from"@galacticcouncil/common";var an={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:sn}=ye;var{withTimeout:jn}=N;import{calculate_in_given_out as Ti,calculate_lrna_in_given_out as Si,calculate_out_given_in as wi,calculate_out_given_lrna_in as vi,calculate_spot_price as xi,calculate_lrna_spot_price as Ii,calculate_shares as Oi,calculate_liquidity_out as Ai,calculate_liquidity_lrna_out as Bi,verify_asset_cap as _i,calculate_liquidity_hub_in as Ri,is_sell_allowed as Fi,is_buy_allowed as Ei,is_add_liquidity_allowed as Ci,is_remove_liquidity_allowed as ki,recalculate_asset_fee as Di,recalculate_protocol_fee as Mi}from"@galacticcouncil/math-omnipool";import Hi from"big.js";import{big as Ui}from"@galacticcouncil/common";var{FeeUtils:tr}=p;import{AccountId as rr,Binary as bt,CompatibilityLevel as or,Enum as fe}from"polkadot-api";import{toHex as ur}from"@polkadot-api/utils";import{Subscription as mr,distinctUntilChanged as dr,filter as gr,finalize as hr,map as br,merge as yr,tap as Pr}from"rxjs";import{HYDRATION_SS58_PREFIX as Tr}from"@galacticcouncil/common";var{FeeUtils:_r}=p,Rr=bt.toHex(bt.fromText("omnipool")),Fr=fe("Short");import{calculate_in_given_out as Nr,calculate_out_given_in as qr,calculate_amplification as Gr,calculate_add_one_asset as Ur,calculate_liquidity_out_one_asset as Vr,calculate_shares as Wr,calculate_shares_for_amount as $r,calculate_spot_price_with_fee as Xr,pool_account_name as Yr,recalculate_peg as zr}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as Jr,big as Zr}from"@galacticcouncil/common";var{FeeUtils:ho}=p;import{AccountId as fo,CompatibilityLevel as To}from"polkadot-api";import{toHex as wo}from"@polkadot-api/utils";import{blake2b as xo}from"@noble/hashes/blake2b";import{Subscription as Oo,distinctUntilChanged as Ao,map as Bo,merge as _o,tap as Ro}from"rxjs";import{HYDRATION_SS58_PREFIX as Eo,RUNTIME_DECIMALS as Co}from"@galacticcouncil/common";var{FeeUtils:Wo}=p;import{calculate_in_given_out as Jo,calculate_out_given_in as Zo,calculate_pool_trade_fee as tl,get_spot_price as el,calculate_liquidity_in as al,calculate_shares as sl,calculate_spot_price as nl,calculate_spot_price_with_fee as il,calculate_liquidity_out_asset_a as rl,calculate_liquidity_out_asset_b as ol}from"@galacticcouncil/math-xyk";import{big as dl}from"@galacticcouncil/common";var{FeeUtils:Il}=p;import{CompatibilityLevel as _l}from"polkadot-api";import{Subscription as Fl}from"rxjs";import{big as Yl,RUNTIME_DECIMALS as zl}from"@galacticcouncil/common";import{AccountId as cc,Binary as uc}from"polkadot-api";import{toHex as mc}from"@polkadot-api/utils";import{Subscription as gc,filter as hc,map as bc,mergeMap as yc}from"rxjs";import{decodeEventLog as fc}from"viem";import{erc20 as Ie,HYDRATION_SS58_PREFIX as Sc}from"@galacticcouncil/common";var{ERC20:Bc}=Ie;import{calculate_collateral_in_given_hollar_out as Dc,calculate_collateral_out_given_hollar_in as Mc,calculate_hollar_in_given_collateral_out as Lc,calculate_hollar_out_given_collateral_in as Hc,calculate_imbalance as Nc,calculate_max_price as qc,calculate_buyback_limit as Gc,calculate_buyback_price_with_fee as Uc}from"@galacticcouncil/math-hsm";import{big as Yc,RUNTIME_DECIMALS as zc}from"@galacticcouncil/common";var{FeeUtils:iu}=p;import{AccountId as Pu,Binary as fu,CompatibilityLevel as Tu}from"polkadot-api";import{toHex as vu}from"@polkadot-api/utils";import{Subscription as Ou,combineLatest as Au,filter as Bu,map as _u,mergeMap as Ru,pairwise as Fu}from"rxjs";import{decodeEventLog as Cu}from"viem";import{h160 as _e,HYDRATION_SS58_PREFIX as Du}from"@galacticcouncil/common";var{FeeUtils:Uu}=p,{H160:Vu}=_e;import{log as Fe}from"@galacticcouncil/common";import{Subject as Ap,Subscription as Bp,takeUntil as _p}from"rxjs";var{logger:$p}=Fe;import{big as Em,RUNTIME_DECIMALS as Cm}from"@galacticcouncil/common";var{FeeUtils:zm}=p;import{big as gd}from"@galacticcouncil/common";import{Enum as Pt}from"polkadot-api";var I=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:n,poolId:s})=>n==="Stableswap"?{pool:Pt("Stableswap",s),asset_in:e,asset_out:a}:{pool:Pt(n),asset_in:e,asset_out:a})}};import{Enum as xt}from"polkadot-api";var ft=[{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 J=[{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 Tt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Z="0x112b087b60C1a166130d59266363C45F8aa99db0",tt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",St=1000000n;var Wd=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:J,address:Z,args:[tt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:J,address:Z,args:[tt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:ft,address:Tt,args:[t],functionName:"getUserAccountData"})}};import d from"big.js";import{big as A,erc20 as qe,h160 as Ge}from"@galacticcouncil/common";var{ERC20:F}=qe,{H160:et}=Ge,Ue=1.01,Ve=31536000n,wt=4,V=-1,W=10n**27n,$=class{client;constructor(t){this.client=new U(t)}async getSummary(t){let e=et.fromAny(t),[a,n,s,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[c,u]=n,[o,g,h,v,P,f]=s,S=A.toDecimal(f,18),x=[];for(let w of c){let O=w.underlyingAsset.toLowerCase(),b=r.find(({underlyingAsset:Dt})=>Dt.toLowerCase()===O);if(!b)throw new Error("Missing pool reserve for "+O);let z=w.scaledATokenBalance,C=b.liquidityIndex,It=b.liquidityRate,Ot=b.availableLiquidity,At=b.priceInMarketReferenceCurrency,Bt=i+6,_t=this.calculateLinearInterest(It,b.lastUpdateTimestamp,Bt),Rt=C*_t/W,Ft=z*Rt/W,Et=Number(u!==0&&u===b.eModeCategoryId?b.eModeLiquidationThreshold:b.reserveLiquidationThreshold)/1e4,Ct=b.usageAsCollateralEnabled&&w.usageAsCollateralEnabledOnUser&&w.scaledATokenBalance>0n,kt=F.toAssetId(O);x.push({aTokenBalance:Ft,availableLiquidity:Ot,decimals:Number(b.decimals),isCollateral:Ct,priceInRef:At,reserveId:kt,reserveAsset:O,reserveLiquidationThreshold:Et})}return{healthFactor:Number(S),currentLiquidationThreshold:Number(A.toDecimal(v,wt)),totalCollateral:o,totalDebt:g,reserves:x}}async hasBorrowPositions(t){let e=et.fromAny(t),a=await this.client.getUserAccountData(e),[n,s]=a;return s>0n}async getHealthFactor(t){let e=et.fromAny(t),a=await this.client.getUserAccountData(e),[n,s,i,r,c,u]=a;return this.calculateHealthFactorFromBalances(s,n,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:n,totalDebt:s,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return V;let c=F.fromAssetId(e),u=i.find(O=>O.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,isCollateral:g,priceInRef:h,reserveLiquidationThreshold:v}=u,P=A.toBigInt(a,o),f=g?P*h/10n**BigInt(o):0n,S=n-f;if(S<=0n)return 0;let x=d(n.toString()).mul(r).minus(d(f.toString()).mul(v)).div(S.toString()),w=d(S.toString()).mul(x).div(s.toString()).toFixed(6,d.roundDown);return Number(w)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:n,totalDebt:s,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return V;let c=F.fromAssetId(e),u=i.find(w=>w.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,priceInRef:g,reserveLiquidationThreshold:h}=u,P=A.toBigInt(a,o)*g/10n**BigInt(o),f=n+P;if(f<=0n)return 0;let S=d(n.toString()).mul(r).plus(d(P.toString()).mul(h)).div(f.toString()),x=d(f.toString()).mul(S).div(s.toString()).toFixed(6,d.roundDown);return Number(x)}async getHealthFactorAfterSwap(t,e,a,n,s){let{totalDebt:i,reserves:r,healthFactor:c}=await this.getSummary(t);if(i===0n)return V;let u=F.fromAssetId(a),o=F.fromAssetId(s),g=r.find(C=>C.reserveAsset===u),h=r.find(C=>C.reserveAsset===o);if(!g)throw new Error(`Missing reserve ctx for ${u}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let v=A.toBigInt(e,g.decimals),P=A.toBigInt(n,h.decimals),f=v*g.priceInRef/10n**BigInt(g.decimals),S=P*h.priceInRef/10n**BigInt(h.decimals),x=g.isCollateral?d(f.toString()).mul(g.reserveLiquidationThreshold):d(0),b=(h.isCollateral?d(S.toString()).mul(h.reserveLiquidationThreshold):d(0)).minus(x).div(i.toString()),z=d(c).plus(b).toFixed(6,d.roundDown);return Number(z)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:n,healthFactor:s}=await this.getSummary(t),i=F.fromAssetId(e),r=n.find(c=>c.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:n}=await this.getSummary(t),s={};for(let i of a){let r=this.calculateWithdrawMax(i,e,n);i.reserveId&&(s[i.reserveId]=r)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:n,availableLiquidity:s,decimals:i,priceInRef:r,reserveLiquidationThreshold:c,isCollateral:u}=t,o=n;if(u&&e>0n){let h=a-Ue;if(h>0){let v=d(h).mul(e.toString()).div(c).toFixed(0,d.roundDown),P=d(v).div(r.toString()).mul(10**i).toFixed(0,d.roundDown);o=n<BigInt(P)?n:BigInt(P)}else o=0n}return{amount:o<s?o:s,decimals:i}}calculateLinearInterest(t,e,a){let n=a-e;if(n<=0)return W;let s=t*BigInt(n)/Ve;return W+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let n=e*a/t,s=A.toDecimal(n,wt);return Number(s)}};function vt(l){let t=[],e=l;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var E=class extends T{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new R(t),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:St})}async dryRun(t,e){let a=xt("Signed",t),n=xt("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(n,e.decodedCall,4),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let c=r.type==="Module"?vt(r.value):r.type;throw new Error("Dry run execution error!",{cause:c})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var X=class extends E{_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:n}=e[0],s=await this.balance.getBalance(this.beneficiary,n);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,n=a[0],s=a[a.length-1],i=y.getFraction(t,this.slippagePct),r=n.assetIn,c=s.assetOut,u=t+i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.buy({asset_in:r,asset_out:c,amount:e,max_sell_amount:u}):o=this.api.tx.Router.buy({asset_in:r,asset_out:c,amount_out:e,max_amount_in:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterBuy",o)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,n=a[0],s=a[a.length-1],i=y.getFraction(e,this.slippagePct),r=n.assetIn,c=s.assetOut,u=e-i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.sell({asset_in:r,asset_out:c,amount:t,min_buy_amount:u}):o=this.api.tx.Router.sell({asset_in:r,asset_out:c,amount_in:t,min_amount_out:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterSell",o)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],n=e[e.length-1],s=y.getFraction(t,this.slippagePct),i=a.assetIn,r=n.assetOut,c=t-s,u=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:c,route:I.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};import{Enum as at}from"polkadot-api";var Y=class extends E{_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:n,tradePeriod:s,tradeRoute:i}=this.order,r=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:at("Sell",{asset_in:e,asset_out:a,amount_in:n,min_amount_out:0n,route:i})},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:a,tradeAmountIn:n,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(s,this.slippagePct),u=s-c,o=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:at("Sell",{asset_in:e,asset_out:a,amount_in:n,min_amount_out:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapSell",o)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:n,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(n,this.slippagePct),u=n+c,o=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:at("Buy",{asset_in:e,asset_out:a,amount_out:s,max_amount_in:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapBuy",o)}};var st=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new X(this.client,this.evmClient).setTrade(t)}order(t){return new Y(this.client,this.evmClient).setOrder(t)}};export{st as TxBuilderFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk-next",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Galactic next gen sdk (papi)",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {