@galacticcouncil/sdk-next 1.2.0 → 1.3.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.
Files changed (48) hide show
  1. package/build/aave/AaveLog.d.ts +4 -0
  2. package/build/aave/index.cjs +1 -1
  3. package/build/aave/index.d.ts +2 -0
  4. package/build/aave/index.mjs +1 -1
  5. package/build/aave/types.d.ts +7 -0
  6. package/build/evm/adapter.d.ts +3 -1
  7. package/build/evm/client.d.ts +3 -1
  8. package/build/evm/index.cjs +1 -1
  9. package/build/evm/index.mjs +1 -1
  10. package/build/gho/GhoTokenLog.d.ts +4 -0
  11. package/build/gho/index.d.ts +4 -2
  12. package/build/{pool/hsm → gho}/types.d.ts +1 -1
  13. package/build/index.cjs +1 -1
  14. package/build/index.d.ts +1 -0
  15. package/build/index.mjs +1 -1
  16. package/build/indexer/BlockFetcher.d.ts +10 -0
  17. package/build/indexer/Indexer.d.ts +19 -0
  18. package/build/indexer/IndexerStats.d.ts +33 -0
  19. package/build/indexer/RpcPool.d.ts +12 -0
  20. package/build/indexer/Semaphore.d.ts +9 -0
  21. package/build/indexer/index.cjs +1 -0
  22. package/build/indexer/index.d.ts +9 -0
  23. package/build/indexer/index.mjs +1 -0
  24. package/build/indexer/scale.d.ts +1 -0
  25. package/build/indexer/types.d.ts +17 -0
  26. package/build/oracle/MmOracleClient.d.ts +1 -1
  27. package/build/oracle/MmOracleLog.d.ts +4 -0
  28. package/build/oracle/abi.d.ts +11 -84
  29. package/build/oracle/index.d.ts +2 -0
  30. package/build/oracle/mappings.d.ts +25 -0
  31. package/build/oracle/types.d.ts +11 -0
  32. package/build/pool/aave/AavePoolClient.d.ts +0 -1
  33. package/build/pool/aave/types.d.ts +0 -6
  34. package/build/pool/hsm/HsmPoolClient.d.ts +0 -1
  35. package/build/pool/index.cjs +1 -1
  36. package/build/pool/index.mjs +1 -1
  37. package/build/pool/stable/StableSwap.d.ts +1 -1
  38. package/build/pool/stable/StableSwapClient.d.ts +12 -3
  39. package/build/pool/stable/StableSwapPeg.d.ts +7 -0
  40. package/build/pool/stable/types.d.ts +12 -1
  41. package/build/sor/index.cjs +1 -1
  42. package/build/sor/index.mjs +1 -1
  43. package/build/tx/TxBuilder.d.ts +2 -2
  44. package/build/tx/TxBuilderFactory.d.ts +3 -1
  45. package/build/tx/index.cjs +1 -1
  46. package/build/tx/index.mjs +1 -1
  47. package/package.json +6 -1
  48. package/build/pool/aave/AaveAbi.d.ts +0 -126
@@ -1 +1 @@
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
+ "use strict";var be=Object.create;var Z=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var tt=(o,t)=>{for(var e in t)Z(o,e,{get:t[e],enumerable:!0})},Ct=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fe(t))!Te.call(o,i)&&i!==e&&Z(o,i,{get:()=>t[i],enumerable:!(a=ye(t,i))||a.enumerable});return o};var et=(o,t,e)=>(e=o!=null?be(Pe(o)):{},Ct(t||!o||!o.__esModule?Z(e,"default",{value:o,enumerable:!0}):e,o)),Se=o=>Ct(Z({},"__esModule",{value:!0}),o);var Ia={};tt(Ia,{TxBuilderFactory:()=>yt});module.exports=Se(Ia);var j=require("@galacticcouncil/math-lbp");var Lt=require("@galacticcouncil/common");var at={};tt(at,{withTimeout:()=>we});function we(o,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);o.then(r=>{clearTimeout(s),a(r)},r=>{clearTimeout(s),i(r)})})}var P={};tt(P,{divSpot:()=>xe,getFraction:()=>Ie,mulScaled:()=>kt,mulSpot:()=>ve});var Pt=require("@galacticcouncil/common");function kt(o,t,e,a,i){let s=e+a-i,r=o*t;return s>0?r/BigInt(10)**BigInt(s):s<0?r*BigInt(10)**BigInt(-s):r}function ve(o,t,e,a){return kt(o,t,e,Pt.RUNTIME_DECIMALS,a)}function xe(o,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(Pt.RUNTIME_DECIMALS+a-e);return o*i/t}function Ie(o,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),i=BigInt(Math.round(t*Number(a)));return o*i/(BigInt(100)*a)}var m={};tt(m,{FeeUtils:()=>Tt,shiftNeg:()=>Ae});var Mt=et(require("big.js"));var Tt=class o{static toPct(t){let[e,a]=t;return o.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return o.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let i=10**a;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ae(o,t){let e=(0,Mt.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Be=et(require("big.js"));var{FeeUtils:Ja}=m;var Me=require("polkadot-api"),rt=require("rxjs");var C=require("rxjs"),T=require("rxjs/operators");var U=require("@galacticcouncil/descriptors");var Ht=require("@galacticcouncil/common"),G=require("rxjs");var F=require("rxjs"),b=require("rxjs/operators");function Nt(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,F.defer)(()=>(0,F.from)(o._request("system_health",[]))).pipe((0,b.timeout)({first:e}),(0,b.map)(()=>"online"),(0,b.catchError)(()=>(0,F.of)("offline")));return(0,F.of)({state:"offline",delayMs:0}).pipe((0,b.expand)(s=>(0,F.timer)(s.delayMs).pipe((0,b.switchMap)(a),(0,b.map)(r=>({state:r,delayMs:t})))),(0,b.skip)(1),(0,b.map)(s=>s.state),(0,b.distinctUntilChanged)(),(0,b.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Ee}=Ht.log,it=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,G.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Nt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,G.tap)({error:a=>Ee.error(t,a)}),(0,G.shareReplay)({bufferSize:1,refCount:!0}))}};var A=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(U.hydration),this.apiNext=this.client.getTypedApi(U.hydrationNext),this.apiIce=this.client.getTypedApi(U.hydrationIce),this.watcher=it.getInstance(this.client),this.at=e??"best"}};var Re=require("polkadot-api/ws"),Fe=require("polkadot-api/logs-provider");var Ce=require("polkadot-api");var qt=require("@galacticcouncil/common"),w=require("rxjs"),p=require("rxjs/operators");var{logger:V}=qt.log,$=class extends A{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,w.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),i=this.watchErc20Balance(t);return(0,w.combineLatest)([e,a,i]).pipe((0,p.connect)(s=>(0,w.concat)(s.pipe((0,p.take)(1)),s.pipe((0,p.skip)(1),(0,p.debounceTime)(250)))))}).pipe((0,p.map)(e=>e.flat()),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([e,a],i)=>i===0?a:this.getDeltas(e,a))).pipe((0,p.tap)({subscribe:()=>V.debug("balance: subscribe",t),error:e=>V.error("balance",e)}),(0,p.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,w.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,p.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,p.tap)({error:a=>V.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,p.map)(({value:i})=>({id:e,balance:this.getBreakdown(i)})),(0,p.tap)({error:i=>V.error("balance(token)",i)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,p.distinctUntilChanged)((a,i)=>!i.deltas),(0,p.map)(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown(s.value)})}),i}),(0,p.tap)({error:a=>V.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[n]=r;return n}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async n=>[n,await this.getBalanceData(t,n)]))).map(([n,l])=>({id:n,balance:l}));return(0,w.defer)(()=>(0,w.from)(e?Promise.resolve(e):a()).pipe((0,p.switchMap)(s=>this.watcher.bestBlock$.pipe((0,p.switchMap)(()=>(0,w.from)(i(s))))),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([s,r],n)=>n===0?r.filter(l=>l.balance.total>0n):this.getDeltas(s,r)),(0,p.distinctUntilChanged)((s,r)=>r.length===0),(0,p.tap)({error:s=>V.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(s,r)=>s!==void 0&&r!==void 0&&s.transferable===r.transferable&&s.total===r.total,i=t.reduce((s,r)=>(s.set(r.id,r.balance),s),new Map);return e.filter(s=>!a(s.balance,i.get(s.id)))}};var ke=require("rxjs");var Gt=require("@galacticcouncil/common");var ks={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ms}=Gt.log;var{withTimeout:Js}=at;var y=require("@galacticcouncil/math-omnipool"),Le=et(require("big.js"));var Ne=require("@galacticcouncil/common");var{FeeUtils:xi}=m;var H=require("polkadot-api"),Ue=require("@polkadot-api/utils"),q=require("rxjs"),Ve=require("@galacticcouncil/common");var{FeeUtils:_i}=m;var{FeeUtils:Vi}=m,Wi=H.Binary.toHex(H.Binary.fromText("omnipool")),$i=(0,H.Enum)("Short");var B=require("@galacticcouncil/math-stableswap");var Wt=require("@galacticcouncil/common");var{FeeUtils:gr}=m;var $t=require("polkadot-api"),je=require("@polkadot-api/utils"),Qe=require("@noble/hashes/blake2b"),Y=require("rxjs"),Yt=require("@galacticcouncil/common");var Ye=require("polkadot-api"),Xe=require("viem");var{FeeUtils:kr}=m;var{FeeUtils:en}=m;var _=require("@galacticcouncil/math-xyk");var Ze=require("@galacticcouncil/common");var{FeeUtils:Sn}=m;var ta=require("polkadot-api"),ea=require("rxjs");var Xt=require("@galacticcouncil/common");var oa=require("polkadot-api"),la=require("@polkadot-api/utils"),ut=require("rxjs"),At=require("@galacticcouncil/common");var wt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var vt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",xt="0x112b087b60C1a166130d59266363C45F8aa99db0",It="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",zt=1000000n;var jn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var nt=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:vt,address:xt,args:[It],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:vt,address:xt,args:[It,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:wt,address:Kt,args:[t],functionName:"getUserAccountData"})}};var sa=require("polkadot-api"),ia=require("viem");var h=et(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:X}=v.erc20,{H160:Ot}=v.h160,ra=1.01,na=31536000n,jt=4,ot=-1,lt=10n**27n,ct=class{client;constructor(t){this.client=new nt(t)}async getSummary(t){let e=Ot.fromAny(t),[a,i,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[n]=a,[l,u]=i,[c,d,f,k,I,O]=s,E=v.big.toDecimal(O,18),M=[];for(let R of l){let N=R.underlyingAsset.toLowerCase(),S=n.find(({underlyingAsset:he})=>he.toLowerCase()===N);if(!S)throw new Error("Missing pool reserve for "+N);let ft=R.scaledATokenBalance,z=S.liquidityIndex,re=S.liquidityRate,ne=S.availableLiquidity,oe=S.priceInMarketReferenceCurrency,le=r+6,ce=this.calculateLinearInterest(re,S.lastUpdateTimestamp,le),ue=z*ce/lt,pe=ft*ue/lt,me=Number(u!==0&&u===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,de=S.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,ge=X.toAssetId(N);M.push({aTokenBalance:pe,availableLiquidity:ne,decimals:Number(S.decimals),isCollateral:de,priceInRef:oe,reserveId:ge,reserveAsset:N,reserveLiquidationThreshold:me})}return{healthFactor:Number(E),currentLiquidationThreshold:Number(v.big.toDecimal(k,jt)),totalCollateral:c,totalDebt:d,reserves:M}}async hasBorrowPositions(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[i,s]=a;return s>0n}async getHealthFactor(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[i,s,r,n,l,u]=a;return this.calculateHealthFactorFromBalances(s,i,n)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return ot;let l=X.fromAssetId(e),u=r.find(N=>N.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,isCollateral:d,priceInRef:f,reserveLiquidationThreshold:k}=u,I=v.big.toBigInt(a,c),O=d?I*f/10n**BigInt(c):0n,E=i-O;if(E<=0n)return 0;let M=(0,h.default)(i.toString()).mul(n).minus((0,h.default)(O.toString()).mul(k)).div(E.toString()),R=(0,h.default)(E.toString()).mul(M).div(s.toString()).toFixed(6,h.default.roundDown);return Number(R)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return ot;let l=X.fromAssetId(e),u=r.find(R=>R.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,priceInRef:d,reserveLiquidationThreshold:f}=u,I=v.big.toBigInt(a,c)*d/10n**BigInt(c),O=i+I;if(O<=0n)return 0;let E=(0,h.default)(i.toString()).mul(n).plus((0,h.default)(I.toString()).mul(f)).div(O.toString()),M=(0,h.default)(O.toString()).mul(E).div(s.toString()).toFixed(6,h.default.roundDown);return Number(M)}async getHealthFactorAfterSwap(t,e,a,i,s){let{totalDebt:r,reserves:n,healthFactor:l}=await this.getSummary(t);if(r===0n)return ot;let u=X.fromAssetId(a),c=X.fromAssetId(s),d=n.find(z=>z.reserveAsset===u),f=n.find(z=>z.reserveAsset===c);if(!d)throw new Error(`Missing reserve ctx for ${u}`);if(!f)throw new Error(`Missing reserve ctx for ${f}`);let k=v.big.toBigInt(e,d.decimals),I=v.big.toBigInt(i,f.decimals),O=k*d.priceInRef/10n**BigInt(d.decimals),E=I*f.priceInRef/10n**BigInt(f.decimals),M=d.isCollateral?(0,h.default)(O.toString()).mul(d.reserveLiquidationThreshold):(0,h.default)(0),S=(f.isCollateral?(0,h.default)(E.toString()).mul(f.reserveLiquidationThreshold):(0,h.default)(0)).minus(M).div(r.toString()),ft=(0,h.default)(l).plus(S).toFixed(6,h.default.roundDown);return Number(ft)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:i,healthFactor:s}=await this.getSummary(t),r=X.fromAssetId(e),n=i.find(l=>l.reserveAsset===r);if(!n)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(n,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:i}=await this.getSummary(t),s={};for(let r of a){let n=this.calculateWithdrawMax(r,e,i);r.reserveId&&(s[r.reserveId]=n)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:i,availableLiquidity:s,decimals:r,priceInRef:n,reserveLiquidationThreshold:l,isCollateral:u}=t,c=i;if(u&&e>0n){let f=a-ra;if(f>0){let k=(0,h.default)(f).mul(e.toString()).div(l).toFixed(0,h.default.roundDown),I=(0,h.default)(k).div(n.toString()).mul(10**r).toFixed(0,h.default.roundDown);c=i<BigInt(I)?i:BigInt(I)}else c=0n}return{amount:c<s?c:s,decimals:r}}calculateLinearInterest(t,e,a){let i=a-e;if(i<=0)return lt;let s=t*BigInt(i)/na;return lt+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return ot;let i=e*a/t,s=v.big.toDecimal(i,jt);return Number(s)}};var{ERC20:So}=At.erc20;var D=require("@galacticcouncil/math-hsm");var Qt=require("@galacticcouncil/common");var{FeeUtils:Lo}=m;var Jt=require("polkadot-api"),ga=require("@polkadot-api/utils"),K=require("rxjs"),Bt=require("@galacticcouncil/common");var ma=require("polkadot-api"),da=require("viem");var{FeeUtils:nl}=m,{H160:ol}=Bt.h160;var Zt=require("@galacticcouncil/common"),_t=require("rxjs");var{logger:tc}=Zt.log;var te=require("@galacticcouncil/common");var{FeeUtils:cu}=m;var xa=require("@galacticcouncil/common");var Et=require("polkadot-api");var L=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s})=>i==="Stableswap"?{pool:(0,Et.Enum)("Stableswap",s),asset_in:e,asset_out:a}:{pool:(0,Et.Enum)(i),asset_in:e,asset_out:a})}};var Rt=require("polkadot-api");function ae(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var x=class extends A{evm;evmClient;balance;aaveUtils;constructor(t,e,a){super(t,a),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new $(t,a),this.aaveUtils=new ct(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:zt})}async dryRun(t,e){let a=(0,Rt.Enum)("Signed",t),i=(0,Rt.Enum)("system",a),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4,{at:this.at}),n=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(n){let l=n.type==="Module"?ae(n.value):n.type;throw new Error("Dry run execution error!",{cause:l})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends x{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],s=await this.balance.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=P.getFraction(t,this.slippagePct),n=i.assetIn,l=s.assetOut,u=t+r,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.buy({asset_in:n,asset_out:l,amount:e,max_sell_amount:u}):c=this.api.tx.Router.buy({asset_in:n,asset_out:l,amount_out:e,max_amount_in:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=P.getFraction(e,this.slippagePct),n=i.assetIn,l=s.assetOut,u=e-r,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.sell({asset_in:n,asset_out:l,amount:t,min_buy_amount:u}):c=this.api.tx.Router.sell({asset_in:n,asset_out:l,amount_in:t,min_amount_out:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],i=e[e.length-1],s=P.getFraction(t,this.slippagePct),r=a.assetIn,n=i.assetOut,l=t-s,u=this.api.tx.Router.sell_all({asset_in:r,asset_out:n,min_amount_out:l,route:L.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};var mt=require("polkadot-api");var dt=class extends x{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradePeriod:s,tradeRoute:r}=this.order,n=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:0n,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(n=await this.dispatchWithExtraGas(n)),this.wrapTx("DcaSchedule",n)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,l=P.getFraction(s,this.slippagePct),u=s-l,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,min_amount_out:u,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapSell",c)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,l=P.getFraction(i,this.slippagePct),u=i+l,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Buy",{asset_in:e,asset_out:a,amount_out:s,max_amount_in:u,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapBuy",c)}};var se=require("polkadot-api");var gt=class extends x{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,l=P.getFraction(e,this.slippagePct),u=e-l,c=(0,se.Enum)("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:u,partial:!1}),d=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(d=await this.dispatchWithExtraGas(d)),this.wrapTx("IntentSwap",d)}};var ie=require("polkadot-api");var ht=class extends x{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,l=(0,ie.Enum)("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentLimitOrder",u)}};var Ft=require("polkadot-api");var bt=class extends x{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:i,tradeAmountIn:s,tradePeriod:r}=this.order,n=(0,Ft.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:i,slippage:this.slippagePct*1e4,budget:t,period:r}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:n}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule",l)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r}=this.order,n=P.getFraction(s,this.slippagePct),l=s-n,u=(0,Ft.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:i,amount_out:l,slippage:this.slippagePct*1e4,budget:t,period:r}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentDcaSchedule.twap",c)}};var yt=class{client;evmClient;at;constructor(t,e,a){this.client=t,this.evmClient=e,this.at=a}trade(t){return new pt(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new dt(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new gt(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new ht(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new bt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
@@ -1 +1 @@
1
- var Gt=Object.defineProperty;var J=(u,t)=>{for(var e in t)Gt(u,e,{get:t[e],enumerable:!0})};import Ut from"buffer";typeof window<"u"&&(window.Buffer=Ut.Buffer);import{calculate_in_given_out as 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};
1
+ var Gt=Object.defineProperty;var J=(u,t)=>{for(var e in t)Gt(u,e,{get:t[e],enumerable:!0})};import Ut from"buffer";typeof window<"u"&&(window.Buffer=Ut.Buffer);import{calculate_in_given_out as ha,calculate_out_given_in as ba,calculate_linear_weights as ya,calculate_pool_trade_fee as fa,get_spot_price as Pa}from"@galacticcouncil/math-lbp";import{big as Wa,RUNTIME_DECIMALS as $a}from"@galacticcouncil/common";var N={};J(N,{withTimeout:()=>Vt});function Vt(u,t,e="timeout"){return new Promise((a,s)=>{let i=setTimeout(()=>s(new Error(e)),t);u.then(r=>{clearTimeout(i),a(r)},r=>{clearTimeout(i),s(r)})})}var b={};J(b,{divSpot:()=>$t,getFraction:()=>Yt,mulScaled:()=>ut,mulSpot:()=>Wt});import{RUNTIME_DECIMALS as ct}from"@galacticcouncil/common";function ut(u,t,e,a,s){let i=e+a-s,r=u*t;return i>0?r/BigInt(10)**BigInt(i):i<0?r*BigInt(10)**BigInt(-i):r}function Wt(u,t,e,a){return ut(u,t,e,ct,a)}function $t(u,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(ct+a-e);return u*s/t}function Yt(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),s=BigInt(Math.round(t*Number(a)));return u*s/(BigInt(100)*a)}var p={};J(p,{FeeUtils:()=>Z,shiftNeg:()=>zt});import Kt from"big.js";var Z=class u{static toPct(t){let[e,a]=t;return u.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return u.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let s=10**a;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function zt(u,t){let e=Kt(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import ka from"big.js";import{TLRUCache as La}from"@thi.ng/cache";var{FeeUtils:ii}=p;import{CompatibilityLevel as dr}from"polkadot-api";import{Subscription as hr,distinctUntilChanged as br,filter as yr,map as fr}from"rxjs";import{memoize1 as ws}from"@thi.ng/memoize";import{TLRUCache as xs}from"@thi.ng/cache";import{ReplaySubject as Bs,Subscription as _s,combineLatest as Es,defer as Rs,from as Fs,interval as Cs,merge as ks,of as Ds,EMPTY as Ms}from"rxjs";import{bufferCount as Hs,bufferTime as Ns,catchError as qs,filter as Gs,finalize as Us,map as Vs,pairwise as Ws,repeat as $s,skip as Ys,share as Xs,startWith as Ks,switchMap as zs,tap as js,throttleTime as Qs}from"rxjs/operators";import{hydration as me,hydrationNext as de,hydrationIce as ge}from"@galacticcouncil/descriptors";import{log as oe}from"@galacticcouncil/common";import{map as le,shareReplay as ce,tap as ue}from"rxjs";import{defer as Qt,from as Jt,of as mt,timer as Zt}from"rxjs";import{catchError as te,distinctUntilChanged as ee,expand as ae,map as et,shareReplay as ie,skip as se,switchMap as re,timeout as ne}from"rxjs/operators";function dt(u,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>Qt(()=>Jt(u._request("system_health",[]))).pipe(ne({first:e}),et(()=>"online"),te(()=>mt("offline")));return mt({state:"offline",delayMs:0}).pipe(ae(i=>Zt(i.delayMs).pipe(re(a),et(r=>({state:r,delayMs:t})))),se(1),et(i=>i.state),ee(),ie({bufferSize:1,refCount:!0}))}var{logger:pe}=oe,G=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(le(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",dt(t))}static getInstance(t){return this.instance||(this.instance=new u(t)),this.instance}watched(t,e){return e.pipe(ue({error:a=>pe.error(t,a)}),ce({bufferSize:1,refCount:!0}))}};var S=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(me),this.apiNext=this.client.getTypedApi(de),this.apiIce=this.client.getTypedApi(ge),this.watcher=G.getInstance(this.client),this.at=e??"best"}};import{getWsProvider as wi}from"polkadot-api/ws";import{withLogsRecorder as xi}from"polkadot-api/logs-provider";import{Binary as Ni}from"polkadot-api";import{log as he}from"@galacticcouncil/common";import{combineLatest as be,concat as ye,defer as M,from as gt}from"rxjs";import{bufferCount as ht,distinctUntilChanged as bt,debounceTime as fe,map as _,retry as Pe,startWith as yt,switchMap as ft,tap as L,take as Te,skip as Se,connect as we}from"rxjs/operators";var{logger:E}=he,F=class extends S{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return M(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return be([e,a,s]).pipe(we(i=>ye(i.pipe(Te(1)),i.pipe(Se(1),fe(250)))))}).pipe(_(e=>e.flat()),yt([]),ht(2,1),_(([e,a],s)=>s===0?a:this.getDeltas(e,a))).pipe(L({subscribe:()=>E.debug("balance: subscribe",t),error:e=>E.error("balance",e)}),Pe({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return M(()=>e.watchValue(t,{at:"best"})).pipe(_(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),L({error:a=>E.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return M(()=>a.watchValue(t,e,{at:"best"})).pipe(_(({value:s})=>({id:e,balance:this.getBreakdown(s)})),L({error:s=>E.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return M(()=>e.watchEntries(t,{at:"best"})).pipe(bt((a,s)=>!s.deltas),_(({deltas:a})=>{let s=[];return a?.deleted.forEach(i=>{let[r,n]=i.args;s.push({id:n,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(i=>{let[r,n]=i.args;s.push({id:n,balance:this.getBreakdown(i.value)})}),s}),L({error:a=>E.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let i=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=i.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[n]=r;return n}),this.erc20Ids},s=async i=>(await Promise.all(i.map(async n=>[n,await this.getBalanceData(t,n)]))).map(([n,o])=>({id:n,balance:o}));return M(()=>gt(e?Promise.resolve(e):a()).pipe(ft(i=>this.watcher.bestBlock$.pipe(ft(()=>gt(s(i))))),yt([]),ht(2,1),_(([i,r],n)=>n===0?r.filter(o=>o.balance.total>0n):this.getDeltas(i,r)),bt((i,r)=>r.length===0),L({error:i=>E.error("balance(erc20)",i)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(i,r)=>i!==void 0&&r!==void 0&&i.transferable===r.transferable&&i.total===r.total,s=t.reduce((i,r)=>(i.set(r.id,r.balance),i),new Map);return e.filter(i=>!a(i.balance,s.get(i.id)))}};import{BehaviorSubject as cs}from"rxjs";import{log as ve}from"@galacticcouncil/common";var hs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:bs}=ve;var{withTimeout:cr}=N;import{calculate_in_given_out as Dr,calculate_lrna_in_given_out as Mr,calculate_out_given_in as Lr,calculate_out_given_lrna_in as Hr,calculate_spot_price as Nr,calculate_lrna_spot_price as qr,calculate_shares as Gr,calculate_liquidity_out as Ur,calculate_liquidity_lrna_out as Vr,verify_asset_cap as Wr,calculate_liquidity_hub_in as $r,is_sell_allowed as Yr,is_buy_allowed as Xr,is_add_liquidity_allowed as Kr,is_remove_liquidity_allowed as zr,recalculate_asset_fee as jr,recalculate_protocol_fee as Qr}from"@galacticcouncil/math-omnipool";import Zr from"big.js";import{big as sn}from"@galacticcouncil/common";var{FeeUtils:bn}=p;import{AccountId as En,Binary as Tt,CompatibilityLevel as Rn,Enum as Be}from"polkadot-api";import{toHex as kn}from"@polkadot-api/utils";import{Subscription as Mn,distinctUntilChanged as Ln,filter as Hn,finalize as Nn,map as qn,merge as Gn,tap as Un}from"rxjs";import{HYDRATION_SS58_PREFIX as Wn}from"@galacticcouncil/common";var{FeeUtils:wn}=p;var{FeeUtils:Zn}=p,to=Tt.toHex(Tt.fromText("omnipool")),eo=Be("Short");import{calculate_in_given_out as go,calculate_out_given_in as ho,calculate_amplification as bo,calculate_add_one_asset as yo,calculate_liquidity_out_one_asset as fo,calculate_shares as Po,calculate_shares_for_amount as To,calculate_spot_price_with_fee as So,pool_account_name as wo,recalculate_peg as vo}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as Ao,big as Bo}from"@galacticcouncil/common";var{FeeUtils:Vo}=p;import{AccountId as _l,CompatibilityLevel as El}from"polkadot-api";import{toHex as Fl}from"@polkadot-api/utils";import{blake2b as kl}from"@noble/hashes/blake2b";import{Subscription as Ml,distinctUntilChanged as Ll,filter as Hl,map as Nl,merge as ql,tap as Gl}from"rxjs";import{HYDRATION_SS58_PREFIX as Vl,RUNTIME_DECIMALS as Wl}from"@galacticcouncil/common";import{Binary as Qo}from"polkadot-api";import{decodeEventLog as Zo}from"viem";var{FeeUtils:Tl}=p;var{FeeUtils:rc}=p;import{calculate_in_given_out as dc,calculate_out_given_in as gc,calculate_pool_trade_fee as hc,get_spot_price as bc,calculate_liquidity_in as yc,calculate_shares as fc,calculate_spot_price as Pc,calculate_spot_price_with_fee as Tc,calculate_liquidity_out_asset_a as Sc,calculate_liquidity_out_asset_b as wc}from"@galacticcouncil/math-xyk";import{big as Bc}from"@galacticcouncil/common";var{FeeUtils:qc}=p;import{CompatibilityLevel as Wc}from"polkadot-api";import{Subscription as Yc}from"rxjs";import{big as uu,RUNTIME_DECIMALS as pu}from"@galacticcouncil/common";import{AccountId as np}from"polkadot-api";import{toHex as lp}from"@polkadot-api/utils";import{Subscription as up,filter as pp,map as mp,mergeMap as dp}from"rxjs";import{erc20 as Ne,HYDRATION_SS58_PREFIX as hp}from"@galacticcouncil/common";var at=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var it=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var wt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",st="0x112b087b60C1a166130d59266363C45F8aa99db0",rt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",vt=1000000n;var Eu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var U=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:it,address:st,args:[rt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:it,address:st,args:[rt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:at,address:wt,args:[t],functionName:"getUserAccountData"})}};import{Binary as Hu}from"polkadot-api";import{decodeEventLog as qu}from"viem";import g from"big.js";import{big as B,erc20 as De,h160 as Me}from"@galacticcouncil/common";var{ERC20:C}=De,{H160:nt}=Me,Le=1.01,He=31536000n,xt=4,V=-1,W=10n**27n,$=class{client;constructor(t){this.client=new U(t)}async getSummary(t){let e=nt.fromAny(t),[a,s,i,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[n]=a,[o,c]=s,[l,m,h,x,P,T]=i,w=B.toDecimal(T,18),I=[];for(let v of o){let A=v.underlyingAsset.toLowerCase(),y=n.find(({underlyingAsset:qt})=>qt.toLowerCase()===A);if(!y)throw new Error("Missing pool reserve for "+A);let Q=v.scaledATokenBalance,k=y.liquidityIndex,Et=y.liquidityRate,Rt=y.availableLiquidity,Ft=y.priceInMarketReferenceCurrency,Ct=r+6,kt=this.calculateLinearInterest(Et,y.lastUpdateTimestamp,Ct),Dt=k*kt/W,Mt=Q*Dt/W,Lt=Number(c!==0&&c===y.eModeCategoryId?y.eModeLiquidationThreshold:y.reserveLiquidationThreshold)/1e4,Ht=y.usageAsCollateralEnabled&&v.usageAsCollateralEnabledOnUser&&v.scaledATokenBalance>0n,Nt=C.toAssetId(A);I.push({aTokenBalance:Mt,availableLiquidity:Rt,decimals:Number(y.decimals),isCollateral:Ht,priceInRef:Ft,reserveId:Nt,reserveAsset:A,reserveLiquidationThreshold:Lt})}return{healthFactor:Number(w),currentLiquidationThreshold:Number(B.toDecimal(x,xt)),totalCollateral:l,totalDebt:m,reserves:I}}async hasBorrowPositions(t){let e=nt.fromAny(t),a=await this.client.getUserAccountData(e),[s,i]=a;return i>0n}async getHealthFactor(t){let e=nt.fromAny(t),a=await this.client.getUserAccountData(e),[s,i,r,n,o,c]=a;return this.calculateHealthFactorFromBalances(i,s,n)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:s,totalDebt:i,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(i===0n)return V;let o=C.fromAssetId(e),c=r.find(A=>A.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:m,priceInRef:h,reserveLiquidationThreshold:x}=c,P=B.toBigInt(a,l),T=m?P*h/10n**BigInt(l):0n,w=s-T;if(w<=0n)return 0;let I=g(s.toString()).mul(n).minus(g(T.toString()).mul(x)).div(w.toString()),v=g(w.toString()).mul(I).div(i.toString()).toFixed(6,g.roundDown);return Number(v)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:s,totalDebt:i,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(i===0n)return V;let o=C.fromAssetId(e),c=r.find(v=>v.reserveAsset===o);if(!c)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:m,reserveLiquidationThreshold:h}=c,P=B.toBigInt(a,l)*m/10n**BigInt(l),T=s+P;if(T<=0n)return 0;let w=g(s.toString()).mul(n).plus(g(P.toString()).mul(h)).div(T.toString()),I=g(T.toString()).mul(w).div(i.toString()).toFixed(6,g.roundDown);return Number(I)}async getHealthFactorAfterSwap(t,e,a,s,i){let{totalDebt:r,reserves:n,healthFactor:o}=await this.getSummary(t);if(r===0n)return V;let c=C.fromAssetId(a),l=C.fromAssetId(i),m=n.find(k=>k.reserveAsset===c),h=n.find(k=>k.reserveAsset===l);if(!m)throw new Error(`Missing reserve ctx for ${c}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let x=B.toBigInt(e,m.decimals),P=B.toBigInt(s,h.decimals),T=x*m.priceInRef/10n**BigInt(m.decimals),w=P*h.priceInRef/10n**BigInt(h.decimals),I=m.isCollateral?g(T.toString()).mul(m.reserveLiquidationThreshold):g(0),y=(h.isCollateral?g(w.toString()).mul(h.reserveLiquidationThreshold):g(0)).minus(I).div(r.toString()),Q=g(o).plus(y).toFixed(6,g.roundDown);return Number(Q)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:s,healthFactor:i}=await this.getSummary(t),r=C.fromAssetId(e),n=s.find(o=>o.reserveAsset===r);if(!n)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(n,a,i)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:s}=await this.getSummary(t),i={};for(let r of a){let n=this.calculateWithdrawMax(r,e,s);r.reserveId&&(i[r.reserveId]=n)}return i}calculateWithdrawMax(t,e,a){let{aTokenBalance:s,availableLiquidity:i,decimals:r,priceInRef:n,reserveLiquidationThreshold:o,isCollateral:c}=t,l=s;if(c&&e>0n){let h=a-Le;if(h>0){let x=g(h).mul(e.toString()).div(o).toFixed(0,g.roundDown),P=g(x).div(n.toString()).mul(10**r).toFixed(0,g.roundDown);l=s<BigInt(P)?s:BigInt(P)}else l=0n}return{amount:l<i?l:i,decimals:r}}calculateLinearInterest(t,e,a){let s=a-e;if(s<=0)return W;let i=t*BigInt(s)/He;return W+i}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let s=e*a/t,i=B.toDecimal(s,xt);return Number(i)}};var{ERC20:vp}=Ne;import{calculate_collateral_in_given_hollar_out as Ep,calculate_collateral_out_given_hollar_in as Rp,calculate_hollar_in_given_collateral_out as Fp,calculate_hollar_out_given_collateral_in as Cp,calculate_imbalance as kp,calculate_max_price as Dp,calculate_buyback_limit as Mp,calculate_buyback_price_with_fee as Lp}from"@galacticcouncil/math-hsm";import{big as Up,RUNTIME_DECIMALS as Vp}from"@galacticcouncil/common";var{FeeUtils:tm}=p;import{AccountId as Im,CompatibilityLevel as Om}from"polkadot-api";import{toHex as _m}from"@polkadot-api/utils";import{Subscription as Fm,combineLatest as Cm,filter as km,map as Dm,mergeMap as Mm,pairwise as Lm}from"rxjs";import{h160 as Ve,HYDRATION_SS58_PREFIX as Nm}from"@galacticcouncil/common";import{Binary as nm}from"polkadot-api";import{decodeEventLog as lm}from"viem";var{FeeUtils:Xm}=p,{H160:Km}=Ve;import{log as Ye}from"@galacticcouncil/common";import{Subject as Rd,Subscription as Fd,takeUntil as Cd}from"rxjs";var{logger:jd}=Ye;import{big as Zg,RUNTIME_DECIMALS as th}from"@galacticcouncil/common";var{FeeUtils:hh}=p;import{big as Dh}from"@galacticcouncil/common";import{Enum as It}from"polkadot-api";var O=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:i})=>s==="Stableswap"?{pool:It("Stableswap",i),asset_in:e,asset_out:a}:{pool:It(s),asset_in:e,asset_out:a})}};import{Enum as Bt}from"polkadot-api";function At(u){let t=[],e=u;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var f=class extends S{evm;evmClient;balance;aaveUtils;constructor(t,e,a){super(t,a),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new F(t,a),this.aaveUtils=new $(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:vt})}async dryRun(t,e){let a=Bt("Signed",t),s=Bt("system",a),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall,4,{at:this.at}),n=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(n){let o=n.type==="Module"?At(n.value):n.type;throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Y=class extends f{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],i=await this.balance.getBalance(this.beneficiary,s);return t>=i.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],i=a[a.length-1],r=b.getFraction(t,this.slippagePct),n=s.assetIn,o=i.assetOut,c=t+r,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.buy({asset_in:n,asset_out:o,amount:e,max_sell_amount:c}):l=this.api.tx.Router.buy({asset_in:n,asset_out:o,amount_out:e,max_amount_in:c,route:O.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterBuy",l)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],i=a[a.length-1],r=b.getFraction(e,this.slippagePct),n=s.assetIn,o=i.assetOut,c=e-r,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.sell({asset_in:n,asset_out:o,amount:t,min_buy_amount:c}):l=this.api.tx.Router.sell({asset_in:n,asset_out:o,amount_in:t,min_amount_out:c,route:O.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSell",l)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],s=e[e.length-1],i=b.getFraction(t,this.slippagePct),r=a.assetIn,n=s.assetOut,o=t-i,c=this.api.tx.Router.sell_all({asset_in:r,asset_out:n,min_amount_out:o,route:O.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSellAll",c)}};import{Enum as ot}from"polkadot-api";var X=class extends f{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradePeriod:i,tradeRoute:r}=this.order,n=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:0n,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(n=await this.dispatchWithExtraGas(n)),this.wrapTx("DcaSchedule",n)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:r,tradeRoute:n}=this.order,o=b.getFraction(i,this.slippagePct),c=i-o,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:c,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapSell",l)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:r,tradeRoute:n}=this.order,o=b.getFraction(s,this.slippagePct),c=s+o,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Buy",{asset_in:e,asset_out:a,amount_out:i,max_amount_in:c,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapBuy",l)}};import{Enum as ta}from"polkadot-api";var K=class extends f{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],i=a[a.length-1],r=s.assetIn,n=i.assetOut,o=b.getFraction(e,this.slippagePct),c=e-o,l=ta("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:c,partial:!1}),m=this.apiIce.tx.Intent.submit_intent({intent:{data:l}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(m=await this.dispatchWithExtraGas(m)),this.wrapTx("IntentSwap",m)}};import{Enum as ea}from"polkadot-api";var z=class extends f{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],i=a[a.length-1],r=s.assetIn,n=i.assetOut,o=ea("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:o,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentLimitOrder",c)}};import{Enum as _t}from"polkadot-api";var j=class extends f{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:s,tradeAmountIn:i,tradePeriod:r}=this.order,n=_t("Dca",{asset_in:e,asset_out:a,amount_in:i,amount_out:s,slippage:this.slippagePct*1e4,budget:t,period:r}),o=this.apiIce.tx.Intent.submit_intent({intent:{data:n}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("IntentDcaSchedule",o)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:r}=this.order,n=b.getFraction(i,this.slippagePct),o=i-n,c=_t("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:o,slippage:this.slippagePct*1e4,budget:t,period:r}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule.twap",l)}};var lt=class{client;evmClient;at;constructor(t,e,a){this.client=t,this.evmClient=e,this.at=a}trade(t){return new Y(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new X(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new K(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new z(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new j(this.client,this.evmClient).setOrder(t)}};export{lt as TxBuilderFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk-next",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Galactic next gen sdk (papi)",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {
@@ -49,6 +49,11 @@
49
49
  "import": "./build/farm/index.mjs",
50
50
  "require": "./build/farm/index.cjs"
51
51
  },
52
+ "./indexer": {
53
+ "types": "./build/indexer/index.d.ts",
54
+ "import": "./build/indexer/index.mjs",
55
+ "require": "./build/indexer/index.cjs"
56
+ },
52
57
  "./pool": {
53
58
  "types": "./build/pool/index.d.ts",
54
59
  "import": "./build/pool/index.mjs",
@@ -1,126 +0,0 @@
1
- export declare const AAVE_ABI: readonly [{
2
- readonly anonymous: false;
3
- readonly inputs: readonly [{
4
- readonly indexed: true;
5
- readonly internalType: "address";
6
- readonly name: "reserve";
7
- readonly type: "address";
8
- }, {
9
- readonly indexed: false;
10
- readonly internalType: "address";
11
- readonly name: "user";
12
- readonly type: "address";
13
- }, {
14
- readonly indexed: true;
15
- readonly internalType: "address";
16
- readonly name: "onBehalfOf";
17
- readonly type: "address";
18
- }, {
19
- readonly indexed: false;
20
- readonly internalType: "uint256";
21
- readonly name: "amount";
22
- readonly type: "uint256";
23
- }, {
24
- readonly indexed: true;
25
- readonly internalType: "uint16";
26
- readonly name: "referralCode";
27
- readonly type: "uint16";
28
- }];
29
- readonly name: "Supply";
30
- readonly type: "event";
31
- }, {
32
- readonly anonymous: false;
33
- readonly inputs: readonly [{
34
- readonly indexed: true;
35
- readonly internalType: "address";
36
- readonly name: "reserve";
37
- readonly type: "address";
38
- }, {
39
- readonly indexed: true;
40
- readonly internalType: "address";
41
- readonly name: "user";
42
- readonly type: "address";
43
- }, {
44
- readonly indexed: true;
45
- readonly internalType: "address";
46
- readonly name: "to";
47
- readonly type: "address";
48
- }, {
49
- readonly indexed: false;
50
- readonly internalType: "uint256";
51
- readonly name: "amount";
52
- readonly type: "uint256";
53
- }];
54
- readonly name: "Withdraw";
55
- readonly type: "event";
56
- }, {
57
- readonly anonymous: false;
58
- readonly inputs: readonly [{
59
- readonly indexed: true;
60
- readonly internalType: "address";
61
- readonly name: "reserve";
62
- readonly type: "address";
63
- }, {
64
- readonly indexed: false;
65
- readonly internalType: "address";
66
- readonly name: "user";
67
- readonly type: "address";
68
- }, {
69
- readonly indexed: true;
70
- readonly internalType: "address";
71
- readonly name: "onBehalfOf";
72
- readonly type: "address";
73
- }, {
74
- readonly indexed: false;
75
- readonly internalType: "uint256";
76
- readonly name: "amount";
77
- readonly type: "uint256";
78
- }, {
79
- readonly indexed: false;
80
- readonly internalType: "enum DataTypes.InterestRateMode";
81
- readonly name: "interestRateMode";
82
- readonly type: "uint8";
83
- }, {
84
- readonly indexed: false;
85
- readonly internalType: "uint256";
86
- readonly name: "borrowRate";
87
- readonly type: "uint256";
88
- }, {
89
- readonly indexed: true;
90
- readonly internalType: "uint16";
91
- readonly name: "referralCode";
92
- readonly type: "uint16";
93
- }];
94
- readonly name: "Borrow";
95
- readonly type: "event";
96
- }, {
97
- readonly anonymous: false;
98
- readonly inputs: readonly [{
99
- readonly indexed: true;
100
- readonly internalType: "address";
101
- readonly name: "reserve";
102
- readonly type: "address";
103
- }, {
104
- readonly indexed: true;
105
- readonly internalType: "address";
106
- readonly name: "user";
107
- readonly type: "address";
108
- }, {
109
- readonly indexed: true;
110
- readonly internalType: "address";
111
- readonly name: "repayer";
112
- readonly type: "address";
113
- }, {
114
- readonly indexed: false;
115
- readonly internalType: "uint256";
116
- readonly name: "amount";
117
- readonly type: "uint256";
118
- }, {
119
- readonly indexed: false;
120
- readonly internalType: "bool";
121
- readonly name: "useATokens";
122
- readonly type: "bool";
123
- }];
124
- readonly name: "Repay";
125
- readonly type: "event";
126
- }];