@galacticcouncil/sdk-next 1.1.0 → 1.2.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.
@@ -0,0 +1,15 @@
1
+ import { Trade } from '../sor';
2
+ import { TxBuilder } from './TxBuilder';
3
+ import { Tx } from './types';
4
+ export declare class IntentMarketTxBuilder extends TxBuilder {
5
+ private _trade?;
6
+ private _beneficiary?;
7
+ private _slippagePct;
8
+ setTrade(trade: Trade): this;
9
+ withBeneficiary(beneficiary: string): this;
10
+ withSlippage(slippage: number): this;
11
+ private get trade();
12
+ private get beneficiary();
13
+ private get slippagePct();
14
+ build(): Promise<Tx>;
15
+ }
@@ -0,0 +1,17 @@
1
+ import { TradeOrder } from '../sor';
2
+ import { TxBuilder } from './TxBuilder';
3
+ import { Tx } from './types';
4
+ export declare class IntentOrderTxBuilder extends TxBuilder {
5
+ private _order?;
6
+ private _beneficiary?;
7
+ private _slippagePct;
8
+ setOrder(order: TradeOrder): this;
9
+ withBeneficiary(beneficiary: string): this;
10
+ withSlippage(slippage: number): this;
11
+ private get order();
12
+ private get beneficiary();
13
+ private get slippagePct();
14
+ build(): Promise<Tx>;
15
+ private buildDcaTx;
16
+ private buildTwapTx;
17
+ }
@@ -3,10 +3,16 @@ import { EvmClient } from '../evm';
3
3
  import { Trade, TradeOrder } from '../sor';
4
4
  import { TradeTxBuilder } from './TradeTxBuilder';
5
5
  import { OrderTxBuilder } from './OrderTxBuilder';
6
+ import { IntentMarketTxBuilder } from './IntentMarketTxBuilder';
7
+ import { IntentLimitTxBuilder } from './IntentLimitTxBuilder';
8
+ import { IntentOrderTxBuilder } from './IntentOrderTxBuilder';
6
9
  export declare class TxBuilderFactory {
7
10
  private client;
8
11
  private evmClient;
9
12
  constructor(client: PolkadotClient, evmClient: EvmClient);
10
13
  trade(trade: Trade): TradeTxBuilder;
11
14
  order(order: TradeOrder): OrderTxBuilder;
15
+ intentMarket(trade: Trade): IntentMarketTxBuilder;
16
+ intentLimit(trade: Trade): IntentLimitTxBuilder;
17
+ intentOrder(order: TradeOrder): IntentOrderTxBuilder;
12
18
  }
@@ -1 +1 @@
1
- "use strict";var ue=Object.create;var J=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var Z=(o,t)=>{for(var e in t)J(o,e,{get:t[e],enumerable:!0})},Bt=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of me(t))!ge.call(o,s)&&s!==e&&J(o,s,{get:()=>t[s],enumerable:!(a=pe(t,s))||a.enumerable});return o};var tt=(o,t,e)=>(e=o!=null?ue(de(o)):{},Bt(t||!o||!o.__esModule?J(e,"default",{value:o,enumerable:!0}):e,o)),he=o=>Bt(J({},"__esModule",{value:!0}),o);var da={};Z(da,{TxBuilderFactory:()=>gt});module.exports=he(da);var z=require("@galacticcouncil/math-lbp");var Ct=require("@galacticcouncil/common");var et={};Z(et,{withTimeout:()=>be});function be(o,t,e="timeout"){return new Promise((a,s)=>{let n=setTimeout(()=>s(new Error(e)),t);o.then(i=>{clearTimeout(n),a(i)},i=>{clearTimeout(n),s(i)})})}var v={};Z(v,{divSpot:()=>Pe,getFraction:()=>fe,mulScaled:()=>_t,mulSpot:()=>ye});var bt=require("@galacticcouncil/common");function _t(o,t,e,a,s){let n=e+a-s,i=o*t;return n>0?i/BigInt(10)**BigInt(n):n<0?i*BigInt(10)**BigInt(-n):i}function ye(o,t,e,a){return _t(o,t,e,bt.RUNTIME_DECIMALS,a)}function Pe(o,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(bt.RUNTIME_DECIMALS+a-e);return o*s/t}function fe(o,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),s=BigInt(Math.round(t*Number(a)));return o*s/(BigInt(100)*a)}var m={};Z(m,{FeeUtils:()=>yt,shiftNeg:()=>Te});var Rt=tt(require("big.js"));var yt=class o{static toPct(t){let[e,a]=t;return o.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return o.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let s=10**a;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Te(o,t){let e=(0,Rt.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var xe=tt(require("big.js"));var{FeeUtils:qa}=m;var _e=require("polkadot-api"),it=require("rxjs");var E=require("rxjs"),f=require("rxjs/operators");var nt=require("@galacticcouncil/descriptors");var Dt=require("@galacticcouncil/common"),q=require("rxjs");var R=require("rxjs"),h=require("rxjs/operators");function kt(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,R.defer)(()=>(0,R.from)(o._request("system_health",[]))).pipe((0,h.timeout)({first:e}),(0,h.map)(()=>"online"),(0,h.catchError)(()=>(0,R.of)("offline")));return(0,R.of)({state:"offline",delayMs:0}).pipe((0,h.expand)(n=>(0,R.timer)(n.delayMs).pipe((0,h.switchMap)(a),(0,h.map)(i=>({state:i,delayMs:t})))),(0,h.skip)(1),(0,h.map)(n=>n.state),(0,h.distinctUntilChanged)(),(0,h.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:we}=Dt.log,st=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,q.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",kt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,q.tap)({error:a=>we.error(t,a)}),(0,q.shareReplay)({bufferSize:1,refCount:!0}))}};var O=class{client;api;apiNext;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(nt.hydration),this.apiNext=this.client.getTypedApi(nt.hydrationNext),this.watcher=st.getInstance(this.client),this.at=e??"best"}};var Ie=require("polkadot-api/ws"),Oe=require("polkadot-api/logs-provider");var Ae=require("polkadot-api");var Mt=require("@galacticcouncil/common"),T=require("rxjs"),c=require("rxjs/operators");var{logger:G}=Mt.log,V=class extends O{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(0,T.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,T.combineLatest)([e,a,s]).pipe((0,c.connect)(n=>(0,T.concat)(n.pipe((0,c.take)(1)),n.pipe((0,c.skip)(1),(0,c.debounceTime)(250)))))}).pipe((0,c.map)(e=>e.flat()),(0,c.startWith)([]),(0,c.bufferCount)(2,1),(0,c.map)(([e,a],s)=>s===0?a:this.getDeltas(e,a))).pipe((0,c.tap)({subscribe:()=>G.debug("balance: subscribe",t),error:e=>G.error("balance",e)}),(0,c.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,T.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,c.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,c.tap)({error:a=>G.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,T.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,c.map)(({value:s})=>({id:e,balance:this.getBreakdown(s)})),(0,c.tap)({error:s=>G.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,T.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,c.distinctUntilChanged)((a,s)=>!s.deltas),(0,c.map)(({deltas:a})=>{let s=[];return a?.deleted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),(0,c.tap)({error:a=>G.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,u])=>({id:r,balance:u}));return(0,T.defer)(()=>(0,T.from)(e?Promise.resolve(e):a()).pipe((0,c.switchMap)(n=>this.watcher.bestBlock$.pipe((0,c.switchMap)(()=>(0,T.from)(s(n))))),(0,c.startWith)([]),(0,c.bufferCount)(2,1),(0,c.map)(([n,i],r)=>r===0?i.filter(u=>u.balance.total>0n):this.getDeltas(n,i)),(0,c.distinctUntilChanged)((n,i)=>i.length===0),(0,c.tap)({error:n=>G.error("balance(erc20)",n)})))}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=(n,i)=>n!==void 0&&i!==void 0&&n.transferable===i.transferable&&n.total===i.total,s=t.reduce((n,i)=>(n.set(i.id,i.balance),n),new Map);return e.filter(n=>!a(n.balance,s.get(n.id)))}};var Be=require("rxjs");var Lt=require("@galacticcouncil/common");var xs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:vs}=Lt.log;var{withTimeout:qs}=et;var y=require("@galacticcouncil/math-omnipool"),Re=tt(require("big.js"));var Ee=require("@galacticcouncil/common");var{FeeUtils:dn}=m;var H=require("polkadot-api"),De=require("@polkadot-api/utils"),N=require("rxjs"),Me=require("@galacticcouncil/common");var{FeeUtils:Pn}=m;var{FeeUtils:Cn}=m,kn=H.Binary.toHex(H.Binary.fromText("omnipool")),Dn=(0,H.Enum)("Short");var A=require("@galacticcouncil/math-stableswap");var Nt=require("@galacticcouncil/common");var{FeeUtils:ni}=m;var qt=require("polkadot-api"),qe=require("@polkadot-api/utils"),Ge=require("@noble/hashes/blake2b"),Q=require("rxjs"),Gt=require("@galacticcouncil/common");var{FeeUtils:bi}=m;var B=require("@galacticcouncil/math-xyk");var Ve=require("@galacticcouncil/common");var{FeeUtils:Di}=m;var We=require("polkadot-api"),$e=require("rxjs");var Ut=require("@galacticcouncil/common");var Vt=require("polkadot-api"),Ye=require("@polkadot-api/utils"),rt=require("rxjs"),ze=require("viem"),Pt=require("@galacticcouncil/common");var{ERC20:dr}=Pt.erc20;var D=require("@galacticcouncil/math-hsm");var Wt=require("@galacticcouncil/common");var{FeeUtils:_r}=m;var ft=require("polkadot-api"),Je=require("@polkadot-api/utils"),W=require("rxjs"),Ze=require("viem"),St=require("@galacticcouncil/common");var{FeeUtils:$r}=m,{H160:Xr}=St.h160;var Xt=require("@galacticcouncil/common"),Tt=require("rxjs");var{logger:qo}=Xt.log;var Yt=require("@galacticcouncil/common");var{FeeUtils:Kl}=m;var ua=require("@galacticcouncil/common");var xt=require("polkadot-api");var M=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:(0,xt.Enum)("Stableswap",n),asset_in:e,asset_out:a}:{pool:(0,xt.Enum)(s),asset_in:e,asset_out:a})}};var At=require("polkadot-api");var zt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var vt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",wt="0x112b087b60C1a166130d59266363C45F8aa99db0",It="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",jt=1000000n;var kc=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ot=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:vt,address:wt,args:[It],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:vt,address:wt,args:[It,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:zt,address:Kt,args:[t],functionName:"getUserAccountData"})}};var g=tt(require("big.js")),x=require("@galacticcouncil/common");var{ERC20:$}=x.erc20,{H160:Ot}=x.h160,pa=1.01,ma=31536000n,Qt=4,lt=-1,ct=10n**27n,ut=class{client;constructor(t){this.client=new ot(t)}async getSummary(t){let e=Ot.fromAny(t),[a,s,n,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[u,p]=s,[l,b,P,C,w,I]=n,_=x.big.toDecimal(I,18),k=[];for(let F of u){let L=F.underlyingAsset.toLowerCase(),S=r.find(({underlyingAsset:ce})=>ce.toLowerCase()===L);if(!S)throw new Error("Missing pool reserve for "+L);let ht=F.scaledATokenBalance,Y=S.liquidityIndex,Zt=S.liquidityRate,te=S.availableLiquidity,ee=S.priceInMarketReferenceCurrency,ae=i+6,se=this.calculateLinearInterest(Zt,S.lastUpdateTimestamp,ae),ne=Y*se/ct,ie=ht*ne/ct,re=Number(p!==0&&p===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,oe=S.usageAsCollateralEnabled&&F.usageAsCollateralEnabledOnUser&&F.scaledATokenBalance>0n,le=$.toAssetId(L);k.push({aTokenBalance:ie,availableLiquidity:te,decimals:Number(S.decimals),isCollateral:oe,priceInRef:ee,reserveId:le,reserveAsset:L,reserveLiquidationThreshold:re})}return{healthFactor:Number(_),currentLiquidationThreshold:Number(x.big.toDecimal(C,Qt)),totalCollateral:l,totalDebt:b,reserves:k}}async hasBorrowPositions(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[s,n]=a;return n>0n}async getHealthFactor(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[s,n,i,r,u,p]=a;return this.calculateHealthFactorFromBalances(n,s,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return lt;let u=$.fromAssetId(e),p=i.find(L=>L.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:l,isCollateral:b,priceInRef:P,reserveLiquidationThreshold:C}=p,w=x.big.toBigInt(a,l),I=b?w*P/10n**BigInt(l):0n,_=s-I;if(_<=0n)return 0;let k=(0,g.default)(s.toString()).mul(r).minus((0,g.default)(I.toString()).mul(C)).div(_.toString()),F=(0,g.default)(_.toString()).mul(k).div(n.toString()).toFixed(6,g.default.roundDown);return Number(F)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return lt;let u=$.fromAssetId(e),p=i.find(F=>F.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:l,priceInRef:b,reserveLiquidationThreshold:P}=p,w=x.big.toBigInt(a,l)*b/10n**BigInt(l),I=s+w;if(I<=0n)return 0;let _=(0,g.default)(s.toString()).mul(r).plus((0,g.default)(w.toString()).mul(P)).div(I.toString()),k=(0,g.default)(I.toString()).mul(_).div(n.toString()).toFixed(6,g.default.roundDown);return Number(k)}async getHealthFactorAfterSwap(t,e,a,s,n){let{totalDebt:i,reserves:r,healthFactor:u}=await this.getSummary(t);if(i===0n)return lt;let p=$.fromAssetId(a),l=$.fromAssetId(n),b=r.find(Y=>Y.reserveAsset===p),P=r.find(Y=>Y.reserveAsset===l);if(!b)throw new Error(`Missing reserve ctx for ${p}`);if(!P)throw new Error(`Missing reserve ctx for ${P}`);let C=x.big.toBigInt(e,b.decimals),w=x.big.toBigInt(s,P.decimals),I=C*b.priceInRef/10n**BigInt(b.decimals),_=w*P.priceInRef/10n**BigInt(P.decimals),k=b.isCollateral?(0,g.default)(I.toString()).mul(b.reserveLiquidationThreshold):(0,g.default)(0),S=(P.isCollateral?(0,g.default)(_.toString()).mul(P.reserveLiquidationThreshold):(0,g.default)(0)).minus(k).div(i.toString()),ht=(0,g.default)(u).plus(S).toFixed(6,g.default.roundDown);return Number(ht)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:s,healthFactor:n}=await this.getSummary(t),i=$.fromAssetId(e),r=s.find(u=>u.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,n)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:s}=await this.getSummary(t),n={};for(let i of a){let r=this.calculateWithdrawMax(i,e,s);i.reserveId&&(n[i.reserveId]=r)}return n}calculateWithdrawMax(t,e,a){let{aTokenBalance:s,availableLiquidity:n,decimals:i,priceInRef:r,reserveLiquidationThreshold:u,isCollateral:p}=t,l=s;if(p&&e>0n){let P=a-pa;if(P>0){let C=(0,g.default)(P).mul(e.toString()).div(u).toFixed(0,g.default.roundDown),w=(0,g.default)(C).div(r.toString()).mul(10**i).toFixed(0,g.default.roundDown);l=s<BigInt(w)?s:BigInt(w)}else l=0n}return{amount:l<n?l:n,decimals:i}}calculateLinearInterest(t,e,a){let s=a-e;if(s<=0)return ct;let n=t*BigInt(s)/ma;return ct+n}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return lt;let s=e*a/t,n=x.big.toDecimal(s,Qt);return Number(n)}};function Jt(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var X=class extends O{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new V(t),this.aaveUtils=new ut(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:jt})}async dryRun(t,e){let a=(0,At.Enum)("Signed",t),s=(0,At.Enum)("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall,4),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let u=r.type==="Module"?Jt(r.value):r.type;throw new Error("Dry run execution error!",{cause:u})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends X{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],n=await this.balance.getBalance(this.beneficiary,s);return t>=n.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=v.getFraction(t,this.slippagePct),r=s.assetIn,u=n.assetOut,p=t+i,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.buy({asset_in:r,asset_out:u,amount:e,max_sell_amount:p}):l=this.api.tx.Router.buy({asset_in:r,asset_out:u,amount_out:e,max_amount_in:p,route:M.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],n=a[a.length-1],i=v.getFraction(e,this.slippagePct),r=s.assetIn,u=n.assetOut,p=e-i,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.sell({asset_in:r,asset_out:u,amount:t,min_buy_amount:p}):l=this.api.tx.Router.sell({asset_in:r,asset_out:u,amount_in:t,min_amount_out:p,route:M.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],n=v.getFraction(t,this.slippagePct),i=a.assetIn,r=s.assetOut,u=t-n,p=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:u,route:M.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("RouterSellAll",p)}};var mt=require("polkadot-api");var dt=class extends X{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradePeriod:n,tradeRoute:i}=this.order,r=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:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:s,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:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,u=v.getFraction(n,this.slippagePct),p=n-u,l=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:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:p,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:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,u=v.getFraction(s,this.slippagePct),p=s+u,l=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:(0,mt.Enum)("Buy",{asset_in:e,asset_out:a,amount_out:n,max_amount_in:p,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapBuy",l)}};var gt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new pt(this.client,this.evmClient).setTrade(t)}order(t){return new dt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
1
+ "use strict";var ye=Object.create;var Z=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var tt=(o,t)=>{for(var e in t)Z(o,e,{get:t[e],enumerable:!0})},Rt=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Pe(t))!Se.call(o,i)&&i!==e&&Z(o,i,{get:()=>t[i],enumerable:!(a=fe(t,i))||a.enumerable});return o};var et=(o,t,e)=>(e=o!=null?ye(Te(o)):{},Rt(t||!o||!o.__esModule?Z(e,"default",{value:o,enumerable:!0}):e,o)),we=o=>Rt(Z({},"__esModule",{value:!0}),o);var Pa={};tt(Pa,{TxBuilderFactory:()=>yt});module.exports=we(Pa);var K=require("@galacticcouncil/math-lbp");var Lt=require("@galacticcouncil/common");var at={};tt(at,{withTimeout:()=>xe});function xe(o,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);o.then(n=>{clearTimeout(s),a(n)},n=>{clearTimeout(s),i(n)})})}var P={};tt(P,{divSpot:()=>Ie,getFraction:()=>Oe,mulScaled:()=>Ct,mulSpot:()=>ve});var Pt=require("@galacticcouncil/common");function Ct(o,t,e,a,i){let s=e+a-i,n=o*t;return s>0?n/BigInt(10)**BigInt(s):s<0?n*BigInt(10)**BigInt(-s):n}function ve(o,t,e,a){return Ct(o,t,e,Pt.RUNTIME_DECIMALS,a)}function Ie(o,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(Pt.RUNTIME_DECIMALS+a-e);return o*i/t}function Oe(o,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),i=BigInt(Math.round(t*Number(a)));return o*i/(BigInt(100)*a)}var d={};tt(d,{FeeUtils:()=>Tt,shiftNeg:()=>Be});var Dt=et(require("big.js"));var Tt=class o{static toPct(t){let[e,a]=t;return o.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return o.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let i=10**a;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Be(o,t){let e=(0,Dt.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var _e=et(require("big.js"));var{FeeUtils:Xa}=d;var Me=require("polkadot-api"),nt=require("rxjs");var C=require("rxjs"),T=require("rxjs/operators");var U=require("@galacticcouncil/descriptors");var Nt=require("@galacticcouncil/common"),G=require("rxjs");var R=require("rxjs"),b=require("rxjs/operators");function Ht(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,R.defer)(()=>(0,R.from)(o._request("system_health",[]))).pipe((0,b.timeout)({first:e}),(0,b.map)(()=>"online"),(0,b.catchError)(()=>(0,R.of)("offline")));return(0,R.of)({state:"offline",delayMs:0}).pipe((0,b.expand)(s=>(0,R.timer)(s.delayMs).pipe((0,b.switchMap)(a),(0,b.map)(n=>({state:n,delayMs:t})))),(0,b.skip)(1),(0,b.map)(s=>s.state),(0,b.distinctUntilChanged)(),(0,b.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Ee}=Nt.log,it=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,G.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Ht(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,G.tap)({error:a=>Ee.error(t,a)}),(0,G.shareReplay)({bufferSize:1,refCount:!0}))}};var A=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(U.hydration),this.apiNext=this.client.getTypedApi(U.hydrationNext),this.apiIce=this.client.getTypedApi(U.hydrationIce),this.watcher=it.getInstance(this.client),this.at=e??"best"}};var Re=require("polkadot-api/ws"),Ce=require("polkadot-api/logs-provider");var ke=require("polkadot-api");var qt=require("@galacticcouncil/common"),w=require("rxjs"),p=require("rxjs/operators");var{logger:V}=qt.log,$=class extends A{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,w.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),i=this.watchErc20Balance(t);return(0,w.combineLatest)([e,a,i]).pipe((0,p.connect)(s=>(0,w.concat)(s.pipe((0,p.take)(1)),s.pipe((0,p.skip)(1),(0,p.debounceTime)(250)))))}).pipe((0,p.map)(e=>e.flat()),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([e,a],i)=>i===0?a:this.getDeltas(e,a))).pipe((0,p.tap)({subscribe:()=>V.debug("balance: subscribe",t),error:e=>V.error("balance",e)}),(0,p.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,w.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,p.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,p.tap)({error:a=>V.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,p.map)(({value:i})=>({id:e,balance:this.getBreakdown(i)})),(0,p.tap)({error:i=>V.error("balance(token)",i)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,p.distinctUntilChanged)((a,i)=>!i.deltas),(0,p.map)(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown(s.value)})}),i}),(0,p.tap)({error:a=>V.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,l])=>({id:r,balance:l}));return(0,w.defer)(()=>(0,w.from)(e?Promise.resolve(e):a()).pipe((0,p.switchMap)(s=>this.watcher.bestBlock$.pipe((0,p.switchMap)(()=>(0,w.from)(i(s))))),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([s,n],r)=>r===0?n.filter(l=>l.balance.total>0n):this.getDeltas(s,n)),(0,p.distinctUntilChanged)((s,n)=>n.length===0),(0,p.tap)({error:s=>V.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(s,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,i=t.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return e.filter(s=>!a(s.balance,i.get(s.id)))}};var De=require("rxjs");var Gt=require("@galacticcouncil/common");var Bs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:_s}=Gt.log;var{withTimeout:Xs}=at;var y=require("@galacticcouncil/math-omnipool"),He=et(require("big.js"));var Ne=require("@galacticcouncil/common");var{FeeUtils:fi}=d;var N=require("polkadot-api"),Ue=require("@polkadot-api/utils"),q=require("rxjs"),Ve=require("@galacticcouncil/common");var{FeeUtils:xi}=d;var{FeeUtils:Hi}=d,Ni=N.Binary.toHex(N.Binary.fromText("omnipool")),qi=(0,N.Enum)("Short");var B=require("@galacticcouncil/math-stableswap");var Vt=require("@galacticcouncil/common");var{FeeUtils:un}=d;var Wt=require("polkadot-api"),Ye=require("@polkadot-api/utils"),ze=require("@noble/hashes/blake2b"),J=require("rxjs"),$t=require("@galacticcouncil/common");var{FeeUtils:wn}=d;var _=require("@galacticcouncil/math-xyk");var je=require("@galacticcouncil/common");var{FeeUtils:Gn}=d;var Qe=require("polkadot-api"),Je=require("rxjs");var Xt=require("@galacticcouncil/common");var Yt=require("polkadot-api"),ta=require("@polkadot-api/utils"),rt=require("rxjs"),ea=require("viem"),St=require("@galacticcouncil/common");var{ERC20:Pr}=St.erc20;var M=require("@galacticcouncil/math-hsm");var zt=require("@galacticcouncil/common");var{FeeUtils:Dr}=d;var wt=require("polkadot-api"),na=require("@polkadot-api/utils"),X=require("rxjs"),ra=require("viem"),xt=require("@galacticcouncil/common");var{FeeUtils:Qr}=d,{H160:Jr}=xt.h160;var jt=require("@galacticcouncil/common"),vt=require("rxjs");var{logger:Xo}=jt.log;var Qt=require("@galacticcouncil/common");var{FeeUtils:ec}=d;var ba=require("@galacticcouncil/common");var It=require("polkadot-api");var L=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s})=>i==="Stableswap"?{pool:(0,It.Enum)("Stableswap",s),asset_in:e,asset_out:a}:{pool:(0,It.Enum)(i),asset_in:e,asset_out:a})}};var Ft=require("polkadot-api");var Zt=[{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 Ot=[{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 te="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",At="0x112b087b60C1a166130d59266363C45F8aa99db0",Bt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ee=1000000n;var Gc=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ot=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:Ot,address:At,args:[Bt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Ot,address:At,args:[Bt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:Zt,address:te,args:[t],functionName:"getUserAccountData"})}};var h=et(require("big.js")),x=require("@galacticcouncil/common");var{ERC20:Y}=x.erc20,{H160:_t}=x.h160,ya=1.01,fa=31536000n,ae=4,lt=-1,ct=10n**27n,ut=class{client;constructor(t){this.client=new ot(t)}async getSummary(t){let e=_t.fromAny(t),[a,i,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[l,u]=i,[c,m,f,k,I,O]=s,F=x.big.toDecimal(O,18),D=[];for(let E of l){let H=E.underlyingAsset.toLowerCase(),S=r.find(({underlyingAsset:be})=>be.toLowerCase()===H);if(!S)throw new Error("Missing pool reserve for "+H);let ft=E.scaledATokenBalance,z=S.liquidityIndex,re=S.liquidityRate,oe=S.availableLiquidity,le=S.priceInMarketReferenceCurrency,ce=n+6,ue=this.calculateLinearInterest(re,S.lastUpdateTimestamp,ce),pe=z*ue/ct,me=ft*pe/ct,de=Number(u!==0&&u===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,ge=S.usageAsCollateralEnabled&&E.usageAsCollateralEnabledOnUser&&E.scaledATokenBalance>0n,he=Y.toAssetId(H);D.push({aTokenBalance:me,availableLiquidity:oe,decimals:Number(S.decimals),isCollateral:ge,priceInRef:le,reserveId:he,reserveAsset:H,reserveLiquidationThreshold:de})}return{healthFactor:Number(F),currentLiquidationThreshold:Number(x.big.toDecimal(k,ae)),totalCollateral:c,totalDebt:m,reserves:D}}async hasBorrowPositions(t){let e=_t.fromAny(t),a=await this.client.getUserAccountData(e),[i,s]=a;return s>0n}async getHealthFactor(t){let e=_t.fromAny(t),a=await this.client.getUserAccountData(e),[i,s,n,r,l,u]=a;return this.calculateHealthFactorFromBalances(s,i,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return lt;let l=Y.fromAssetId(e),u=n.find(H=>H.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,isCollateral:m,priceInRef:f,reserveLiquidationThreshold:k}=u,I=x.big.toBigInt(a,c),O=m?I*f/10n**BigInt(c):0n,F=i-O;if(F<=0n)return 0;let D=(0,h.default)(i.toString()).mul(r).minus((0,h.default)(O.toString()).mul(k)).div(F.toString()),E=(0,h.default)(F.toString()).mul(D).div(s.toString()).toFixed(6,h.default.roundDown);return Number(E)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return lt;let l=Y.fromAssetId(e),u=n.find(E=>E.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,priceInRef:m,reserveLiquidationThreshold:f}=u,I=x.big.toBigInt(a,c)*m/10n**BigInt(c),O=i+I;if(O<=0n)return 0;let F=(0,h.default)(i.toString()).mul(r).plus((0,h.default)(I.toString()).mul(f)).div(O.toString()),D=(0,h.default)(O.toString()).mul(F).div(s.toString()).toFixed(6,h.default.roundDown);return Number(D)}async getHealthFactorAfterSwap(t,e,a,i,s){let{totalDebt:n,reserves:r,healthFactor:l}=await this.getSummary(t);if(n===0n)return lt;let u=Y.fromAssetId(a),c=Y.fromAssetId(s),m=r.find(z=>z.reserveAsset===u),f=r.find(z=>z.reserveAsset===c);if(!m)throw new Error(`Missing reserve ctx for ${u}`);if(!f)throw new Error(`Missing reserve ctx for ${f}`);let k=x.big.toBigInt(e,m.decimals),I=x.big.toBigInt(i,f.decimals),O=k*m.priceInRef/10n**BigInt(m.decimals),F=I*f.priceInRef/10n**BigInt(f.decimals),D=m.isCollateral?(0,h.default)(O.toString()).mul(m.reserveLiquidationThreshold):(0,h.default)(0),S=(f.isCollateral?(0,h.default)(F.toString()).mul(f.reserveLiquidationThreshold):(0,h.default)(0)).minus(D).div(n.toString()),ft=(0,h.default)(l).plus(S).toFixed(6,h.default.roundDown);return Number(ft)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:i,healthFactor:s}=await this.getSummary(t),n=Y.fromAssetId(e),r=i.find(l=>l.reserveAsset===n);if(!r)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(r,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:i}=await this.getSummary(t),s={};for(let n of a){let r=this.calculateWithdrawMax(n,e,i);n.reserveId&&(s[n.reserveId]=r)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:i,availableLiquidity:s,decimals:n,priceInRef:r,reserveLiquidationThreshold:l,isCollateral:u}=t,c=i;if(u&&e>0n){let f=a-ya;if(f>0){let k=(0,h.default)(f).mul(e.toString()).div(l).toFixed(0,h.default.roundDown),I=(0,h.default)(k).div(r.toString()).mul(10**n).toFixed(0,h.default.roundDown);c=i<BigInt(I)?i:BigInt(I)}else c=0n}return{amount:c<s?c:s,decimals:n}}calculateLinearInterest(t,e,a){let i=a-e;if(i<=0)return ct;let s=t*BigInt(i)/fa;return ct+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return lt;let i=e*a/t,s=x.big.toDecimal(i,ae);return Number(s)}};function se(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var v=class extends A{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new $(t),this.aaveUtils=new ut(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:ee})}async dryRun(t,e){let a=(0,Ft.Enum)("Signed",t),i=(0,Ft.Enum)("system",a),n=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4),r=n.success&&!n.value.execution_result.success?n.value.execution_result.value.error:null;if(r){let l=r.type==="Module"?se(r.value):r.type;throw new Error("Dry run execution error!",{cause:l})}return n}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends v{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],s=await this.balance.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],n=P.getFraction(t,this.slippagePct),r=i.assetIn,l=s.assetOut,u=t+n,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.buy({asset_in:r,asset_out:l,amount:e,max_sell_amount:u}):c=this.api.tx.Router.buy({asset_in:r,asset_out:l,amount_out:e,max_amount_in:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],n=P.getFraction(e,this.slippagePct),r=i.assetIn,l=s.assetOut,u=e-n,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.sell({asset_in:r,asset_out:l,amount:t,min_buy_amount:u}):c=this.api.tx.Router.sell({asset_in:r,asset_out:l,amount_in:t,min_amount_out:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],i=e[e.length-1],s=P.getFraction(t,this.slippagePct),n=a.assetIn,r=i.assetOut,l=t-s,u=this.api.tx.Router.sell_all({asset_in:n,asset_out:r,min_amount_out:l,route:L.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};var mt=require("polkadot-api");var dt=class extends v{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradePeriod:s,tradeRoute:n}=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:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,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:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n,tradeRoute:r}=this.order,l=P.getFraction(s,this.slippagePct),u=s-l,c=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:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapSell",c)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n,tradeRoute:r}=this.order,l=P.getFraction(i,this.slippagePct),u=i+l,c=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:(0,mt.Enum)("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)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapBuy",c)}};var ie=require("polkadot-api");var gt=class extends v{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],n=i.assetIn,r=s.assetOut,l=P.getFraction(e,this.slippagePct),u=e-l,c=(0,ie.Enum)("Swap",{asset_in:n,asset_out:r,amount_in:t,amount_out:u,partial:!1}),m=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(m=await this.dispatchWithExtraGas(m)),this.wrapTx("IntentSwap",m)}};var ne=require("polkadot-api");var ht=class extends v{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],n=i.assetIn,r=s.assetOut,l=(0,ne.Enum)("Swap",{asset_in:n,asset_out:r,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentLimitOrder",u)}};var Et=require("polkadot-api");var bt=class extends v{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:i,tradeAmountIn:s,tradePeriod:n}=this.order,r=(0,Et.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:i,slippage:this.slippagePct*1e4,budget:t,period:n}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:r}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule",l)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n}=this.order,r=P.getFraction(s,this.slippagePct),l=s-r,u=(0,Et.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:i,amount_out:l,slippage:this.slippagePct*1e4,budget:t,period:n}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentDcaSchedule.twap",c)}};var yt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new pt(this.client,this.evmClient).setTrade(t)}order(t){return new dt(this.client,this.evmClient).setOrder(t)}intentMarket(t){return new gt(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new ht(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new bt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
@@ -1 +1 @@
1
- var 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 ra,calculate_out_given_in as oa,calculate_linear_weights as la,calculate_pool_trade_fee as ca,get_spot_price as ua}from"@galacticcouncil/math-lbp";import{big as Da,RUNTIME_DECIMALS as Ma}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 Ia from"big.js";import{TLRUCache as Ba}from"@thi.ng/cache";var{FeeUtils:za}=p;import{CompatibilityLevel as ii}from"polkadot-api";import{Subscription as oi,distinctUntilChanged as li,filter as ci,map as ui}from"rxjs";import{memoize1 as gn}from"@thi.ng/memoize";import{TLRUCache as bn}from"@thi.ng/cache";import{ReplaySubject as Sn,Subscription as Tn,combineLatest as xn,defer as vn,from as wn,interval as In,merge as On,of as An,EMPTY as Bn}from"rxjs";import{bufferCount as Fn,bufferTime as Rn,catchError as En,filter as Cn,finalize as kn,map as Dn,pairwise as Mn,repeat as Ln,skip as Hn,share as Nn,startWith as qn,switchMap as Gn,tap as Un,throttleTime as Vn}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 S=class{client;api;apiNext;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(oe),this.apiNext=this.client.getTypedApi(le),this.watcher=G.getInstance(this.client),this.at=e??"best"}};import{getWsProvider as ds}from"polkadot-api/ws";import{withLogsRecorder as hs}from"polkadot-api/logs-provider";import{Binary as Fs}from"polkadot-api";import{log as ce}from"@galacticcouncil/common";import{combineLatest as ue,concat as pe,defer as M,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 L,take as ge,skip as he,connect as be}from"rxjs/operators";var{logger:_}=ce,R=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 n=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(n)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return M(()=>{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(L({subscribe:()=>_.debug("balance: subscribe",t),error:e=>_.error("balance",e)}),de({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return M(()=>e.watchValue(t,{at:"best"})).pipe(B(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),L({error:a=>_.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return M(()=>a.watchValue(t,e,{at:"best"})).pipe(B(({value:n})=>({id:e,balance:this.getBreakdown(n)})),L({error:n=>_.error("balance(token)",n)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return M(()=>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}),L({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 M(()=>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),L({error:s=>_.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(s,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 tn}from"rxjs";import{log as ye}from"@galacticcouncil/common";var on={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:ln}=ye;var{withTimeout:ei}=N;import{calculate_in_given_out as Ai,calculate_lrna_in_given_out as Bi,calculate_out_given_in as _i,calculate_out_given_lrna_in as Fi,calculate_spot_price as Ri,calculate_lrna_spot_price as Ei,calculate_shares as Ci,calculate_liquidity_out as ki,calculate_liquidity_lrna_out as Di,verify_asset_cap as Mi,calculate_liquidity_hub_in as Li,is_sell_allowed as Hi,is_buy_allowed as Ni,is_add_liquidity_allowed as qi,is_remove_liquidity_allowed as Gi,recalculate_asset_fee as Ui,recalculate_protocol_fee as Vi}from"@galacticcouncil/math-omnipool";import $i from"big.js";import{big as Ki}from"@galacticcouncil/common";var{FeeUtils:or}=p;import{AccountId as xr,Binary as bt,CompatibilityLevel as vr,Enum as Te}from"polkadot-api";import{toHex as Or}from"@polkadot-api/utils";import{Subscription as Br,distinctUntilChanged as _r,filter as Fr,finalize as Rr,map as Er,merge as Cr,tap as kr}from"rxjs";import{HYDRATION_SS58_PREFIX as Mr}from"@galacticcouncil/common";var{FeeUtils:dr}=p;var{FeeUtils:$r}=p,Xr=bt.toHex(bt.fromText("omnipool")),Yr=Te("Short");import{calculate_in_given_out as io,calculate_out_given_in as ro,calculate_amplification as oo,calculate_add_one_asset as lo,calculate_liquidity_out_one_asset as co,calculate_shares as uo,calculate_shares_for_amount as po,calculate_spot_price_with_fee as mo,pool_account_name as go,recalculate_peg as ho}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as fo,big as So}from"@galacticcouncil/common";var{FeeUtils:Do}=p;import{AccountId as No,CompatibilityLevel as qo}from"polkadot-api";import{toHex as Uo}from"@polkadot-api/utils";import{blake2b as Wo}from"@noble/hashes/blake2b";import{Subscription as Xo,distinctUntilChanged as Yo,map as zo,merge as Ko,tap as jo}from"rxjs";import{HYDRATION_SS58_PREFIX as Jo,RUNTIME_DECIMALS as Zo}from"@galacticcouncil/common";var{FeeUtils:ul}=p;import{calculate_in_given_out as Pl,calculate_out_given_in as fl,calculate_pool_trade_fee as Sl,get_spot_price as Tl,calculate_liquidity_in as xl,calculate_shares as vl,calculate_spot_price as wl,calculate_spot_price_with_fee as Il,calculate_liquidity_out_asset_a as Ol,calculate_liquidity_out_asset_b as Al}from"@galacticcouncil/math-xyk";import{big as Cl}from"@galacticcouncil/common";var{FeeUtils:$l}=p;import{CompatibilityLevel as Kl}from"polkadot-api";import{Subscription as Ql}from"rxjs";import{big as hc,RUNTIME_DECIMALS as bc}from"@galacticcouncil/common";import{AccountId as Rc,Binary as Ec}from"polkadot-api";import{toHex as kc}from"@polkadot-api/utils";import{Subscription as Mc,filter as Lc,map as Hc,mergeMap as Nc}from"rxjs";import{decodeEventLog as Gc}from"viem";import{erc20 as Ae,HYDRATION_SS58_PREFIX as Vc}from"@galacticcouncil/common";var{ERC20:jc}=Ae;import{calculate_collateral_in_given_hollar_out as su,calculate_collateral_out_given_hollar_in as nu,calculate_hollar_in_given_collateral_out as iu,calculate_hollar_out_given_collateral_in as ru,calculate_imbalance as ou,calculate_max_price as lu,calculate_buyback_limit as cu,calculate_buyback_price_with_fee as uu}from"@galacticcouncil/math-hsm";import{big as hu,RUNTIME_DECIMALS as bu}from"@galacticcouncil/common";var{FeeUtils:Au}=p;import{AccountId as qu,Binary as Gu,CompatibilityLevel as Uu}from"polkadot-api";import{toHex as $u}from"@polkadot-api/utils";import{Subscription as zu,combineLatest as Ku,filter as ju,map as Qu,mergeMap as Ju,pairwise as Zu}from"rxjs";import{decodeEventLog as ep}from"viem";import{h160 as Re,HYDRATION_SS58_PREFIX as sp}from"@galacticcouncil/common";var{FeeUtils:up}=p,{H160:pp}=Re;import{log as ke}from"@galacticcouncil/common";import{Subject as zp,Subscription as Kp,takeUntil as jp}from"rxjs";var{logger:dm}=ke;import{big as bd,RUNTIME_DECIMALS as yd}from"@galacticcouncil/common";var{FeeUtils:Ed}=p;import{big as Jd}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 wt}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 St="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Z="0x112b087b60C1a166130d59266363C45F8aa99db0",tt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Tt=1000000n;var Bg=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:St,args:[t],functionName:"getUserAccountData"})}};import d from"big.js";import{big as A,erc20 as Ve,h160 as We}from"@galacticcouncil/common";var{ERC20:E}=Ve,{H160:et}=We,$e=1.01,Xe=31536000n,xt=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,T=A.toDecimal(f,18),w=[];for(let x of c){let O=x.underlyingAsset.toLowerCase(),b=r.find(({underlyingAsset:Dt})=>Dt.toLowerCase()===O);if(!b)throw new Error("Missing pool reserve for "+O);let z=x.scaledATokenBalance,k=b.liquidityIndex,It=b.liquidityRate,Ot=b.availableLiquidity,At=b.priceInMarketReferenceCurrency,Bt=i+6,_t=this.calculateLinearInterest(It,b.lastUpdateTimestamp,Bt),Ft=k*_t/W,Rt=z*Ft/W,Et=Number(u!==0&&u===b.eModeCategoryId?b.eModeLiquidationThreshold:b.reserveLiquidationThreshold)/1e4,Ct=b.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,kt=E.toAssetId(O);w.push({aTokenBalance:Rt,availableLiquidity:Ot,decimals:Number(b.decimals),isCollateral:Ct,priceInRef:At,reserveId:kt,reserveAsset:O,reserveLiquidationThreshold:Et})}return{healthFactor:Number(T),currentLiquidationThreshold:Number(A.toDecimal(v,xt)),totalCollateral:o,totalDebt:g,reserves:w}}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=E.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,T=n-f;if(T<=0n)return 0;let w=d(n.toString()).mul(r).minus(d(f.toString()).mul(v)).div(T.toString()),x=d(T.toString()).mul(w).div(s.toString()).toFixed(6,d.roundDown);return Number(x)}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=E.fromAssetId(e),u=i.find(x=>x.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 T=d(n.toString()).mul(r).plus(d(P.toString()).mul(h)).div(f.toString()),w=d(f.toString()).mul(T).div(s.toString()).toFixed(6,d.roundDown);return Number(w)}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=E.fromAssetId(a),o=E.fromAssetId(s),g=r.find(k=>k.reserveAsset===u),h=r.find(k=>k.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),T=P*h.priceInRef/10n**BigInt(h.decimals),w=g.isCollateral?d(f.toString()).mul(g.reserveLiquidationThreshold):d(0),b=(h.isCollateral?d(T.toString()).mul(h.reserveLiquidationThreshold):d(0)).minus(w).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=E.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-$e;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)/Xe;return W+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let n=e*a/t,s=A.toDecimal(n,xt);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 C=class extends S{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:Tt})}async dryRun(t,e){let a=wt("Signed",t),n=wt("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 C{_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 C{_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 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 da,calculate_out_given_in as ga,calculate_linear_weights as ha,calculate_pool_trade_fee as ba,get_spot_price as ya}from"@galacticcouncil/math-lbp";import{big as Ua,RUNTIME_DECIMALS as Va}from"@galacticcouncil/common";var N={};J(N,{withTimeout:()=>Vt});function Vt(u,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);u.then(n=>{clearTimeout(s),a(n)},n=>{clearTimeout(s),i(n)})})}var b={};J(b,{divSpot:()=>$t,getFraction:()=>Xt,mulScaled:()=>lt,mulSpot:()=>Wt});import{RUNTIME_DECIMALS as ot}from"@galacticcouncil/common";function lt(u,t,e,a,i){let s=e+a-i,n=u*t;return s>0?n/BigInt(10)**BigInt(s):s<0?n*BigInt(10)**BigInt(-s):n}function Wt(u,t,e,a){return lt(u,t,e,ot,a)}function $t(u,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(ot+a-e);return u*i/t}function Xt(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),i=BigInt(Math.round(t*Number(a)));return u*i/(BigInt(100)*a)}var m={};J(m,{FeeUtils:()=>Z,shiftNeg:()=>Kt});import zt from"big.js";var Z=class u{static toPct(t){let[e,a]=t;return u.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return u.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let i=10**a;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Kt(u,t){let e=zt(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import Ea from"big.js";import{TLRUCache as Da}from"@thi.ng/cache";var{FeeUtils:es}=m;import{CompatibilityLevel as mn}from"polkadot-api";import{Subscription as gn,distinctUntilChanged as hn,filter as bn,map as yn}from"rxjs";import{memoize1 as Ti}from"@thi.ng/memoize";import{TLRUCache as xi}from"@thi.ng/cache";import{ReplaySubject as Oi,Subscription as Ai,combineLatest as Bi,defer as _i,from as Fi,interval as Ri,merge as Ei,of as Ci,EMPTY as ki}from"rxjs";import{bufferCount as Mi,bufferTime as Li,catchError as Hi,filter as Ni,finalize as qi,map as Gi,pairwise as Ui,repeat as Vi,skip as Wi,share as $i,startWith as Xi,switchMap as Yi,tap as zi,throttleTime as Ki}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 pt,timer as Zt}from"rxjs";import{catchError as te,distinctUntilChanged as ee,expand as ae,map as tt,shareReplay as se,skip as ie,switchMap as ne,timeout as re}from"rxjs/operators";function mt(u,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>Qt(()=>Jt(u._request("system_health",[]))).pipe(re({first:e}),tt(()=>"online"),te(()=>pt("offline")));return pt({state:"offline",delayMs:0}).pipe(ae(s=>Zt(s.delayMs).pipe(ne(a),tt(n=>({state:n,delayMs:t})))),ie(1),tt(s=>s.state),ee(),se({bufferSize:1,refCount:!0}))}var{logger:pe}=oe,G=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(le(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",mt(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 Ts}from"polkadot-api/ws";import{withLogsRecorder as xs}from"polkadot-api/logs-provider";import{Binary as Ls}from"polkadot-api";import{log as he}from"@galacticcouncil/common";import{combineLatest as be,concat as ye,defer as M,from as dt}from"rxjs";import{bufferCount as gt,distinctUntilChanged as ht,debounceTime as fe,map as _,retry as Pe,startWith as bt,switchMap as yt,tap as L,take as Te,skip as Se,connect as xe}from"rxjs/operators";var{logger:F}=he,E=class extends S{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return M(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),i=this.watchErc20Balance(t);return be([e,a,i]).pipe(xe(s=>ye(s.pipe(Te(1)),s.pipe(Se(1),fe(250)))))}).pipe(_(e=>e.flat()),bt([]),gt(2,1),_(([e,a],i)=>i===0?a:this.getDeltas(e,a))).pipe(L({subscribe:()=>F.debug("balance: subscribe",t),error:e=>F.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=>F.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return M(()=>a.watchValue(t,e,{at:"best"})).pipe(_(({value:i})=>({id:e,balance:this.getBreakdown(i)})),L({error:i=>F.error("balance(token)",i)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return M(()=>e.watchEntries(t,{at:"best"})).pipe(ht((a,i)=>!i.deltas),_(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown(s.value)})}),i}),L({error:a=>F.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:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,o])=>({id:r,balance:o}));return M(()=>dt(e?Promise.resolve(e):a()).pipe(yt(s=>this.watcher.bestBlock$.pipe(yt(()=>dt(i(s))))),bt([]),gt(2,1),_(([s,n],r)=>r===0?n.filter(o=>o.balance.total>0n):this.getDeltas(s,n)),ht((s,n)=>n.length===0),L({error:s=>F.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(s,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,i=t.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return e.filter(s=>!a(s.balance,i.get(s.id)))}};import{BehaviorSubject as oi}from"rxjs";import{log as we}from"@galacticcouncil/common";var di={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:gi}=we;var{withTimeout:ln}=N;import{calculate_in_given_out as kn,calculate_lrna_in_given_out as Dn,calculate_out_given_in as Mn,calculate_out_given_lrna_in as Ln,calculate_spot_price as Hn,calculate_lrna_spot_price as Nn,calculate_shares as qn,calculate_liquidity_out as Gn,calculate_liquidity_lrna_out as Un,verify_asset_cap as Vn,calculate_liquidity_hub_in as Wn,is_sell_allowed as $n,is_buy_allowed as Xn,is_add_liquidity_allowed as Yn,is_remove_liquidity_allowed as zn,recalculate_asset_fee as Kn,recalculate_protocol_fee as jn}from"@galacticcouncil/math-omnipool";import Jn from"big.js";import{big as ar}from"@galacticcouncil/common";var{FeeUtils:gr}=m;import{AccountId as _r,Binary as Pt,CompatibilityLevel as Fr,Enum as Ae}from"polkadot-api";import{toHex as Cr}from"@polkadot-api/utils";import{Subscription as Dr,distinctUntilChanged as Mr,filter as Lr,finalize as Hr,map as Nr,merge as qr,tap as Gr}from"rxjs";import{HYDRATION_SS58_PREFIX as Vr}from"@galacticcouncil/common";var{FeeUtils:Tr}=m;var{FeeUtils:Jr}=m,Zr=Pt.toHex(Pt.fromText("omnipool")),to=Ae("Short");import{calculate_in_given_out as mo,calculate_out_given_in as go,calculate_amplification as ho,calculate_add_one_asset as bo,calculate_liquidity_out_one_asset as yo,calculate_shares as fo,calculate_shares_for_amount as Po,calculate_spot_price_with_fee as To,pool_account_name as So,recalculate_peg as xo}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as Oo,big as Ao}from"@galacticcouncil/common";var{FeeUtils:Uo}=m;import{AccountId as Xo,CompatibilityLevel as Yo}from"polkadot-api";import{toHex as Ko}from"@polkadot-api/utils";import{blake2b as Qo}from"@noble/hashes/blake2b";import{Subscription as Zo,distinctUntilChanged as tl,map as el,merge as al,tap as sl}from"rxjs";import{HYDRATION_SS58_PREFIX as nl,RUNTIME_DECIMALS as rl}from"@galacticcouncil/common";var{FeeUtils:yl}=m;import{calculate_in_given_out as Il,calculate_out_given_in as Ol,calculate_pool_trade_fee as Al,get_spot_price as Bl,calculate_liquidity_in as _l,calculate_shares as Fl,calculate_spot_price as Rl,calculate_spot_price_with_fee as El,calculate_liquidity_out_asset_a as Cl,calculate_liquidity_out_asset_b as kl}from"@galacticcouncil/math-xyk";import{big as ql}from"@galacticcouncil/common";var{FeeUtils:Jl}=m;import{CompatibilityLevel as ac}from"polkadot-api";import{Subscription as ic}from"rxjs";import{big as xc,RUNTIME_DECIMALS as wc}from"@galacticcouncil/common";import{AccountId as Hc,Binary as Nc}from"polkadot-api";import{toHex as Gc}from"@polkadot-api/utils";import{Subscription as Vc,filter as Wc,map as $c,mergeMap as Xc}from"rxjs";import{decodeEventLog as zc}from"viem";import{erc20 as Ce,HYDRATION_SS58_PREFIX as jc}from"@galacticcouncil/common";var{ERC20:su}=Ce;import{calculate_collateral_in_given_hollar_out as uu,calculate_collateral_out_given_hollar_in as pu,calculate_hollar_in_given_collateral_out as mu,calculate_hollar_out_given_collateral_in as du,calculate_imbalance as gu,calculate_max_price as hu,calculate_buyback_limit as bu,calculate_buyback_price_with_fee as yu}from"@galacticcouncil/math-hsm";import{big as xu,RUNTIME_DECIMALS as wu}from"@galacticcouncil/common";var{FeeUtils:ku}=m;import{AccountId as Yu,Binary as zu,CompatibilityLevel as Ku}from"polkadot-api";import{toHex as Ju}from"@polkadot-api/utils";import{Subscription as ep,combineLatest as ap,filter as sp,map as ip,mergeMap as np,pairwise as rp}from"rxjs";import{decodeEventLog as lp}from"viem";import{h160 as Le,HYDRATION_SS58_PREFIX as up}from"@galacticcouncil/common";var{FeeUtils:yp}=m,{H160:fp}=Le;import{log as qe}from"@galacticcouncil/common";import{Subject as em,Subscription as am,takeUntil as sm}from"rxjs";var{logger:Tm}=qe;import{big as wd,RUNTIME_DECIMALS as vd}from"@galacticcouncil/common";var{FeeUtils:Nd}=m;import{big as ng}from"@galacticcouncil/common";import{Enum as St}from"polkadot-api";var O=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s})=>i==="Stableswap"?{pool:St("Stableswap",s),asset_in:e,asset_out:a}:{pool:St(i),asset_in:e,asset_out:a})}};import{Enum as Bt}from"polkadot-api";var wt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var et=[{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 vt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",at="0x112b087b60C1a166130d59266363C45F8aa99db0",st="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",It=1000000n;var Mg=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:et,address:at,args:[st],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:et,address:at,args:[st,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:wt,address:vt,args:[t],functionName:"getUserAccountData"})}};import g from"big.js";import{big as B,erc20 as ze,h160 as Ke}from"@galacticcouncil/common";var{ERC20:C}=ze,{H160:it}=Ke,je=1.01,Qe=31536000n,Ot=4,V=-1,W=10n**27n,$=class{client;constructor(t){this.client=new U(t)}async getSummary(t){let e=it.fromAny(t),[a,i,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[o,c]=i,[l,p,h,v,P,T]=s,x=B.toDecimal(T,18),I=[];for(let w of o){let A=w.underlyingAsset.toLowerCase(),y=r.find(({underlyingAsset:qt})=>qt.toLowerCase()===A);if(!y)throw new Error("Missing pool reserve for "+A);let Q=w.scaledATokenBalance,k=y.liquidityIndex,Ft=y.liquidityRate,Rt=y.availableLiquidity,Et=y.priceInMarketReferenceCurrency,Ct=n+6,kt=this.calculateLinearInterest(Ft,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&&w.usageAsCollateralEnabledOnUser&&w.scaledATokenBalance>0n,Nt=C.toAssetId(A);I.push({aTokenBalance:Mt,availableLiquidity:Rt,decimals:Number(y.decimals),isCollateral:Ht,priceInRef:Et,reserveId:Nt,reserveAsset:A,reserveLiquidationThreshold:Lt})}return{healthFactor:Number(x),currentLiquidationThreshold:Number(B.toDecimal(v,Ot)),totalCollateral:l,totalDebt:p,reserves:I}}async hasBorrowPositions(t){let e=it.fromAny(t),a=await this.client.getUserAccountData(e),[i,s]=a;return s>0n}async getHealthFactor(t){let e=it.fromAny(t),a=await this.client.getUserAccountData(e),[i,s,n,r,o,c]=a;return this.calculateHealthFactorFromBalances(s,i,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return V;let o=C.fromAssetId(e),c=n.find(A=>A.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:p,priceInRef:h,reserveLiquidationThreshold:v}=c,P=B.toBigInt(a,l),T=p?P*h/10n**BigInt(l):0n,x=i-T;if(x<=0n)return 0;let I=g(i.toString()).mul(r).minus(g(T.toString()).mul(v)).div(x.toString()),w=g(x.toString()).mul(I).div(s.toString()).toFixed(6,g.roundDown);return Number(w)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return V;let o=C.fromAssetId(e),c=n.find(w=>w.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:p,reserveLiquidationThreshold:h}=c,P=B.toBigInt(a,l)*p/10n**BigInt(l),T=i+P;if(T<=0n)return 0;let x=g(i.toString()).mul(r).plus(g(P.toString()).mul(h)).div(T.toString()),I=g(T.toString()).mul(x).div(s.toString()).toFixed(6,g.roundDown);return Number(I)}async getHealthFactorAfterSwap(t,e,a,i,s){let{totalDebt:n,reserves:r,healthFactor:o}=await this.getSummary(t);if(n===0n)return V;let c=C.fromAssetId(a),l=C.fromAssetId(s),p=r.find(k=>k.reserveAsset===c),h=r.find(k=>k.reserveAsset===l);if(!p)throw new Error(`Missing reserve ctx for ${c}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let v=B.toBigInt(e,p.decimals),P=B.toBigInt(i,h.decimals),T=v*p.priceInRef/10n**BigInt(p.decimals),x=P*h.priceInRef/10n**BigInt(h.decimals),I=p.isCollateral?g(T.toString()).mul(p.reserveLiquidationThreshold):g(0),y=(h.isCollateral?g(x.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:a,reserves:i,healthFactor:s}=await this.getSummary(t),n=C.fromAssetId(e),r=i.find(o=>o.reserveAsset===n);if(!r)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(r,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:i}=await this.getSummary(t),s={};for(let n of a){let r=this.calculateWithdrawMax(n,e,i);n.reserveId&&(s[n.reserveId]=r)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:i,availableLiquidity:s,decimals:n,priceInRef:r,reserveLiquidationThreshold:o,isCollateral:c}=t,l=i;if(c&&e>0n){let h=a-je;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=i<BigInt(P)?i:BigInt(P)}else l=0n}return{amount:l<s?l:s,decimals:n}}calculateLinearInterest(t,e,a){let i=a-e;if(i<=0)return W;let s=t*BigInt(i)/Qe;return W+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let i=e*a/t,s=B.toDecimal(i,Ot);return Number(s)}};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){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new E(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:It})}async dryRun(t,e){let a=Bt("Signed",t),i=Bt("system",a),n=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4),r=n.success&&!n.value.execution_result.success?n.value.execution_result.value.error:null;if(r){let o=r.type==="Module"?At(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:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],s=await this.balance.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],n=b.getFraction(t,this.slippagePct),r=i.assetIn,o=s.assetOut,c=t+n,l;return this.isDirectOmnipoolTrade(a)?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(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterBuy",l)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],n=b.getFraction(e,this.slippagePct),r=i.assetIn,o=s.assetOut,c=e-n,l;return this.isDirectOmnipoolTrade(a)?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(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSell",l)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],i=e[e.length-1],s=b.getFraction(t,this.slippagePct),n=a.assetIn,r=i.assetOut,o=t-s,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 nt}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:a,tradeAmountIn:i,tradePeriod:s,tradeRoute:n}=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:nt("Sell",{asset_in:e,asset_out:a,amount_in:i,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:a,tradeAmountIn:i,tradeAmountOut:s,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:nt("Sell",{asset_in:e,asset_out:a,amount_in:i,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:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n,tradeRoute:r}=this.order,o=b.getFraction(i,this.slippagePct),c=i+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:nt("Buy",{asset_in:e,asset_out:a,amount_out:s,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 Je}from"polkadot-api";var z=class extends f{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],n=i.assetIn,r=s.assetOut,o=b.getFraction(e,this.slippagePct),c=e-o,l=Je("Swap",{asset_in:n,asset_out:r,amount_in:t,amount_out:c,partial:!1}),p=this.apiIce.tx.Intent.submit_intent({intent:{data:l}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("IntentSwap",p)}};import{Enum as Ze}from"polkadot-api";var K=class extends f{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],n=i.assetIn,r=s.assetOut,o=Ze("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 _t}from"polkadot-api";var j=class extends f{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:i,tradeAmountIn:s,tradePeriod:n}=this.order,r=_t("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:i,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:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n}=this.order,r=b.getFraction(s,this.slippagePct),o=s-r,c=_t("Dca",{asset_in:e,asset_out:a,amount_in:i,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 rt=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)}intentMarket(t){return new z(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new K(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new j(this.client,this.evmClient).setOrder(t)}};export{rt as TxBuilderFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk-next",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Galactic next gen sdk (papi)",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {
@@ -101,7 +101,7 @@
101
101
  },
102
102
  "peerDependencies": {
103
103
  "@galacticcouncil/common": ">=1.0.0",
104
- "@galacticcouncil/descriptors": ">=2.0.0",
104
+ "@galacticcouncil/descriptors": ">=2.2.0",
105
105
  "polkadot-api": "^2.1.0",
106
106
  "viem": "^2.38.3"
107
107
  }