@galacticcouncil/sdk-next 1.0.0-beta.0 → 1.0.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 (151) hide show
  1. package/README.md +131 -78
  2. package/build/aave/AaveClient.d.ts +77 -0
  3. package/build/aave/AaveUtils.d.ts +78 -0
  4. package/build/aave/abi/AavePool.d.ts +208 -0
  5. package/build/aave/abi/AavePoolDataProvider.d.ts +384 -0
  6. package/build/aave/abi/index.d.ts +2 -0
  7. package/build/aave/const.d.ts +6 -0
  8. package/build/aave/index.cjs +1 -0
  9. package/build/aave/index.d.ts +4 -0
  10. package/build/aave/index.mjs +1 -0
  11. package/build/aave/types.d.ts +17 -0
  12. package/build/api/Papi.d.ts +10 -0
  13. package/build/api/Watcher.d.ts +11 -0
  14. package/build/api/index.d.ts +3 -0
  15. package/build/api/probe.d.ts +26 -0
  16. package/build/api/provider/index.d.ts +2 -0
  17. package/build/api/provider/smoldot.d.ts +1 -0
  18. package/build/api/provider/websocket.d.ts +4 -0
  19. package/build/{types/client → client}/AssetClient.d.ts +1 -1
  20. package/build/client/BalanceClient.d.ts +20 -0
  21. package/build/client/ChainParams.d.ts +9 -0
  22. package/build/client/index.cjs +1 -0
  23. package/build/{types/client → client}/index.d.ts +1 -0
  24. package/build/client/index.mjs +1 -0
  25. package/build/{types/consts.d.ts → consts.d.ts} +2 -2
  26. package/build/evm/adapter.d.ts +11 -0
  27. package/build/evm/chain.d.ts +2 -0
  28. package/build/evm/client.d.ts +15 -0
  29. package/build/evm/index.cjs +1 -0
  30. package/build/evm/index.d.ts +4 -0
  31. package/build/evm/index.mjs +1 -0
  32. package/build/evm/types.d.ts +7 -0
  33. package/build/factory.d.ts +29 -0
  34. package/build/farm/LiquidityMiningApi.d.ts +29 -0
  35. package/build/farm/LiquidityMiningClient.d.ts +146 -0
  36. package/build/farm/MultiCurrencyContainer.d.ts +8 -0
  37. package/build/farm/RewardClaimSimulator.d.ts +16 -0
  38. package/build/farm/const.d.ts +4 -0
  39. package/build/farm/index.cjs +1 -0
  40. package/build/farm/index.d.ts +3 -0
  41. package/build/farm/index.mjs +1 -0
  42. package/build/farm/types.d.ts +46 -0
  43. package/build/gho/GhoTokenClient.d.ts +6 -0
  44. package/build/gho/abi.d.ts +124 -0
  45. package/build/gho/index.d.ts +2 -0
  46. package/build/index.cjs +1 -1
  47. package/build/{types/index.d.ts → index.d.ts} +6 -0
  48. package/build/index.mjs +1 -1
  49. package/build/oracle/MmOracleClient.d.ts +7 -0
  50. package/build/oracle/abi.d.ts +196 -0
  51. package/build/oracle/index.d.ts +3 -0
  52. package/build/oracle/types.d.ts +5 -0
  53. package/build/pool/PoolClient.d.ts +75 -0
  54. package/build/pool/PoolContextProvider.d.ts +41 -0
  55. package/build/pool/PoolLog.d.ts +11 -0
  56. package/build/pool/PoolStore.d.ts +20 -0
  57. package/build/pool/aave/AaveAbi.d.ts +126 -0
  58. package/build/pool/aave/AavePool.d.ts +24 -0
  59. package/build/pool/aave/AavePoolClient.d.ts +19 -0
  60. package/build/pool/aave/index.d.ts +2 -0
  61. package/build/pool/aave/types.d.ts +13 -0
  62. package/build/pool/hsm/HsmMath.d.ts +21 -0
  63. package/build/pool/hsm/HsmPool.d.ts +63 -0
  64. package/build/pool/hsm/HsmPoolClient.d.ts +26 -0
  65. package/build/pool/hsm/index.d.ts +3 -0
  66. package/build/pool/hsm/types.d.ts +7 -0
  67. package/build/pool/index.cjs +1 -0
  68. package/build/{types/pool → pool}/index.d.ts +4 -2
  69. package/build/pool/index.mjs +1 -0
  70. package/build/{types/pool → pool}/lbp/LbpPool.d.ts +1 -1
  71. package/build/{types/pool → pool}/lbp/LbpPoolClient.d.ts +9 -7
  72. package/build/{types/pool → pool}/omni/OmniMath.d.ts +7 -6
  73. package/build/{types/pool → pool}/omni/OmniPool.d.ts +14 -1
  74. package/build/pool/omni/OmniPoolClient.d.ts +29 -0
  75. package/build/pool/omni/types.d.ts +11 -0
  76. package/build/{types/pool → pool}/stable/StableMath.d.ts +1 -2
  77. package/build/{types/pool → pool}/stable/StableSwap.d.ts +21 -4
  78. package/build/pool/stable/StableSwapClient.d.ts +23 -0
  79. package/build/pool/stable/types.d.ts +15 -0
  80. package/build/{types/pool → pool}/types.d.ts +14 -3
  81. package/build/{types/pool → pool}/xyk/XykPool.d.ts +13 -1
  82. package/build/pool/xyk/XykPoolClient.d.ts +14 -0
  83. package/build/{types/sor → sor}/Router.d.ts +26 -8
  84. package/build/sor/TradeRouteBuilder.d.ts +4 -0
  85. package/build/sor/TradeRouter.d.ts +207 -0
  86. package/build/sor/TradeScheduler.d.ts +111 -0
  87. package/build/sor/const.d.ts +8 -0
  88. package/build/sor/index.cjs +1 -0
  89. package/build/sor/index.d.ts +6 -0
  90. package/build/sor/index.mjs +1 -0
  91. package/build/{types/sor → sor}/route/bfs.d.ts +11 -2
  92. package/build/{types/sor → sor}/route/index.d.ts +1 -1
  93. package/build/sor/route/suggester.d.ts +33 -0
  94. package/build/sor/types.d.ts +68 -0
  95. package/build/staking/StakingApi.d.ts +66 -0
  96. package/build/staking/StakingClient.d.ts +132 -0
  97. package/build/staking/index.cjs +1 -0
  98. package/build/staking/index.d.ts +2 -0
  99. package/build/staking/index.mjs +1 -0
  100. package/build/staking/types.d.ts +16 -0
  101. package/build/staking/utils.d.ts +1 -0
  102. package/build/tx/OrderTxBuilder.d.ts +21 -0
  103. package/build/tx/TradeTxBuilder.d.ts +18 -0
  104. package/build/tx/TxBuilder.d.ts +19 -0
  105. package/build/tx/TxBuilderFactory.d.ts +12 -0
  106. package/build/tx/index.cjs +1 -0
  107. package/build/tx/index.d.ts +2 -0
  108. package/build/tx/index.mjs +1 -0
  109. package/build/tx/types.d.ts +10 -0
  110. package/build/tx/utils.d.ts +5 -0
  111. package/build/{types/types.d.ts → types.d.ts} +9 -2
  112. package/build/utils/QueryBus.d.ts +10 -0
  113. package/build/utils/async.d.ts +1 -0
  114. package/build/utils/calc.d.ts +52 -0
  115. package/build/utils/format.d.ts +11 -0
  116. package/build/utils/index.cjs +1 -0
  117. package/build/{types/utils → utils}/index.d.ts +3 -3
  118. package/build/utils/index.mjs +1 -0
  119. package/build/{types/utils → utils}/math.d.ts +0 -9
  120. package/package.json +70 -15
  121. package/build/types/api/Papi.d.ts +0 -375
  122. package/build/types/api/client.d.ts +0 -2
  123. package/build/types/api/index.d.ts +0 -2
  124. package/build/types/client/BalanceClient.d.ts +0 -17
  125. package/build/types/pool/PoolClient.d.ts +0 -25
  126. package/build/types/pool/PoolContextProvider.d.ts +0 -26
  127. package/build/types/pool/omni/OmniPoolClient.d.ts +0 -13
  128. package/build/types/pool/stable/StableSwapClient.d.ts +0 -16
  129. package/build/types/pool/xyk/XykPoolClient.d.ts +0 -12
  130. package/build/types/sor/TradeRouter.d.ts +0 -155
  131. package/build/types/sor/TradeUtils.d.ts +0 -12
  132. package/build/types/sor/index.d.ts +0 -4
  133. package/build/types/sor/route/suggester.d.ts +0 -24
  134. package/build/types/sor/types.d.ts +0 -31
  135. package/build/types/utils/big.d.ts +0 -3
  136. package/build/types/utils/evm.d.ts +0 -3
  137. package/build/types/utils/format.d.ts +0 -4
  138. package/build/types/utils/xc.d.ts +0 -1
  139. /package/build/{types/errors.d.ts → errors.d.ts} +0 -0
  140. /package/build/{types/pool → pool}/PoolFactory.d.ts +0 -0
  141. /package/build/{types/pool → pool}/lbp/LbpMath.d.ts +0 -0
  142. /package/build/{types/pool → pool}/lbp/index.d.ts +0 -0
  143. /package/build/{types/pool → pool}/omni/index.d.ts +0 -0
  144. /package/build/{types/pool → pool}/stable/index.d.ts +0 -0
  145. /package/build/{types/pool → pool}/xyk/XykMath.d.ts +0 -0
  146. /package/build/{types/pool → pool}/xyk/index.d.ts +0 -0
  147. /package/build/{types/sor → sor}/route/graph.d.ts +0 -0
  148. /package/build/{types/utils → utils}/Queue.d.ts +0 -0
  149. /package/build/{types/utils → utils}/Stack.d.ts +0 -0
  150. /package/build/{types/utils → utils}/json.d.ts +0 -0
  151. /package/build/{types/utils → utils}/traversal/bfs.d.ts +0 -0
@@ -0,0 +1 @@
1
+ "use strict";var ue=Object.create;var J=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var Z=(o,t)=>{for(var e in t)J(o,e,{get:t[e],enumerable:!0})},Bt=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of me(t))!ge.call(o,s)&&s!==e&&J(o,s,{get:()=>t[s],enumerable:!(a=pe(t,s))||a.enumerable});return o};var tt=(o,t,e)=>(e=o!=null?ue(de(o)):{},Bt(t||!o||!o.__esModule?J(e,"default",{value:o,enumerable:!0}):e,o)),he=o=>Bt(J({},"__esModule",{value:!0}),o);var pa={};Z(pa,{TxBuilderFactory:()=>gt});module.exports=he(pa);var Y=require("@galacticcouncil/math-lbp");var Ct=require("@galacticcouncil/common");var et={};Z(et,{withTimeout:()=>be});function be(o,t,e="timeout"){return new Promise((a,s)=>{let n=setTimeout(()=>s(new Error(e)),t);o.then(i=>{clearTimeout(n),a(i)},i=>{clearTimeout(n),s(i)})})}var w={};Z(w,{divSpot:()=>Pe,getFraction:()=>fe,mulScaled:()=>_t,mulSpot:()=>ye});var bt=require("@galacticcouncil/common");function _t(o,t,e,a,s){let n=e+a-s,i=o*t;return n>0?i/BigInt(10)**BigInt(n):n<0?i*BigInt(10)**BigInt(-n):i}function ye(o,t,e,a){return _t(o,t,e,bt.RUNTIME_DECIMALS,a)}function Pe(o,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(bt.RUNTIME_DECIMALS+a-e);return o*s/t}function fe(o,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),s=BigInt(Math.round(t*Number(a)));return o*s/(BigInt(100)*a)}var m={};Z(m,{FeeUtils:()=>yt,shiftNeg:()=>Te});var Ft=tt(require("big.js"));var yt=class o{static toPct(t){let[e,a]=t;return o.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return o.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let s=10**a;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Te(o,t){let e=(0,Ft.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var ve=tt(require("big.js"));var{FeeUtils:Ha}=m;var Re=require("polkadot-api"),it=require("rxjs");var E=require("rxjs"),f=require("rxjs/operators");var nt=require("@galacticcouncil/descriptors");var Mt=require("@galacticcouncil/common"),q=require("rxjs");var F=require("rxjs"),h=require("rxjs/operators");function kt(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,F.defer)(()=>(0,F.from)(o._request("system_health",[]))).pipe((0,h.timeout)({first:e}),(0,h.map)(()=>"online"),(0,h.catchError)(()=>(0,F.of)("offline")));return(0,F.of)({state:"offline",delayMs:0}).pipe((0,h.expand)(n=>(0,F.timer)(n.delayMs).pipe((0,h.switchMap)(a),(0,h.map)(i=>({state:i,delayMs:t})))),(0,h.skip)(1),(0,h.map)(n=>n.state),(0,h.distinctUntilChanged)(),(0,h.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:xe}=Mt.log,st=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,q.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",kt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,q.tap)({error:a=>xe.error(t,a)}),(0,q.shareReplay)({bufferSize:1,refCount:!0}))}};var O=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(nt.hydration),this.apiNext=this.client.getTypedApi(nt.hydrationNext),this.watcher=st.getInstance(this.client)}};var Ie=require("polkadot-api/ws"),Oe=require("polkadot-api/logs-provider");var Ae=require("polkadot-api/sm-provider");var Be=require("polkadot-api");var Dt=require("@galacticcouncil/common"),T=require("rxjs"),c=require("rxjs/operators");var{logger:G}=Dt.log,U=class extends O{erc20Ids=null;constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:"best"});return this.getBreakdown(a)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,T.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,T.combineLatest)([e,a,s]).pipe((0,c.connect)(n=>(0,T.concat)(n.pipe((0,c.take)(1)),n.pipe((0,c.skip)(1),(0,c.debounceTime)(250)))))}).pipe((0,c.map)(e=>e.flat()),(0,c.startWith)([]),(0,c.bufferCount)(2,1),(0,c.map)(([e,a],s)=>s===0?a:this.getDeltas(e,a))).pipe((0,c.tap)({subscribe:()=>G.debug("balance: subscribe",t),error:e=>G.error("balance",e)}),(0,c.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,T.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,c.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,c.tap)({error:a=>G.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,T.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,c.map)(({value:s})=>({id:e,balance:this.getBreakdown(s)})),(0,c.tap)({error:s=>G.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,T.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,c.distinctUntilChanged)((a,s)=>!s.deltas),(0,c.map)(({deltas:a})=>{let s=[];return a?.deleted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),(0,c.tap)({error:a=>G.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,u])=>({id:r,balance:u}));return(0,T.defer)(()=>(0,T.from)(e?Promise.resolve(e):a()).pipe((0,c.switchMap)(n=>this.watcher.bestBlock$.pipe((0,c.switchMap)(()=>(0,T.from)(s(n))))),(0,c.startWith)([]),(0,c.bufferCount)(2,1),(0,c.map)(([n,i],r)=>r===0?i.filter(u=>u.balance.total>0n):this.getDeltas(n,i)),(0,c.distinctUntilChanged)((n,i)=>i.length===0),(0,c.tap)({error:n=>G.error("balance(erc20)",n)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(n,i)=>n!==void 0&&i!==void 0&&n.transferable===i.transferable&&n.total===i.total,s=t.reduce((n,i)=>(n.set(i.id,i.balance),n),new Map);return e.filter(n=>!a(n.balance,s.get(n.id)))}};var _e=require("rxjs");var Lt=require("@galacticcouncil/common");var fs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ss}=Lt.log;var{withTimeout:Ds}=et;var y=require("@galacticcouncil/math-omnipool"),Ee=tt(require("big.js"));var Ce=require("@galacticcouncil/common");var{FeeUtils:ln}=m;var H=require("polkadot-api"),ke=require("@polkadot-api/utils"),N=require("rxjs"),Me=require("@galacticcouncil/common");var{FeeUtils:Tn}=m,vn=H.Binary.toHex(H.Binary.fromText("omnipool")),wn=(0,H.Enum)("Short");var A=require("@galacticcouncil/math-stableswap");var Nt=require("@galacticcouncil/common");var{FeeUtils:Vn}=m;var qt=require("polkadot-api"),Ne=require("@polkadot-api/utils"),qe=require("@noble/hashes/blake2b"),Q=require("rxjs"),Gt=require("@galacticcouncil/common");var{FeeUtils:ei}=m;var B=require("@galacticcouncil/math-xyk");var Ue=require("@galacticcouncil/common");var{FeeUtils:Si}=m;var Ve=require("polkadot-api"),We=require("rxjs");var Ut=require("@galacticcouncil/common");var Vt=require("polkadot-api"),Xe=require("@polkadot-api/utils"),rt=require("rxjs"),Ye=require("viem"),Pt=require("@galacticcouncil/common");var{ERC20:Qi}=Pt.erc20;var M=require("@galacticcouncil/math-hsm");var Wt=require("@galacticcouncil/common");var{FeeUtils:dr}=m;var ft=require("polkadot-api"),Qe=require("@polkadot-api/utils"),V=require("rxjs"),Je=require("viem"),St=require("@galacticcouncil/common");var{FeeUtils:_r}=m,{H160:Rr}=St.h160;var Xt=require("@galacticcouncil/common"),Tt=require("rxjs");var{logger:xo}=Xt.log;var Yt=require("@galacticcouncil/common");var{FeeUtils:Pl}=m;var la=require("@galacticcouncil/common");var vt=require("polkadot-api");var D=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:(0,vt.Enum)("Stableswap",n),asset_in:e,asset_out:a}:{pool:(0,vt.Enum)(s),asset_in:e,asset_out:a})}};var At=require("polkadot-api");var zt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var wt=[{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",jt=1000000n;var sc=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:wt,address:xt,args:[It],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:wt,address:xt,args:[It,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:zt,address:Kt,args:[t],functionName:"getUserAccountData"})}};var g=tt(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:W}=v.erc20,{H160:Ot}=v.h160,ca=1.01,ua=31536000n,Qt=4,lt=-1,ct=10n**27n,ut=class{client;constructor(t){this.client=new ot(t)}async getSummary(t){let e=Ot.fromAny(t),[a,s,n,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[u,p]=s,[l,b,P,C,x,I]=n,_=v.big.toDecimal(I,18),k=[];for(let R of u){let L=R.underlyingAsset.toLowerCase(),S=r.find(({underlyingAsset:ce})=>ce.toLowerCase()===L);if(!S)throw new Error("Missing pool reserve for "+L);let ht=R.scaledATokenBalance,X=S.liquidityIndex,Zt=S.liquidityRate,te=S.availableLiquidity,ee=S.priceInMarketReferenceCurrency,ae=i+6,se=this.calculateLinearInterest(Zt,S.lastUpdateTimestamp,ae),ne=X*se/ct,ie=ht*ne/ct,re=Number(p!==0&&p===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,oe=S.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,le=W.toAssetId(L);k.push({aTokenBalance:ie,availableLiquidity:te,decimals:Number(S.decimals),isCollateral:oe,priceInRef:ee,reserveId:le,reserveAsset:L,reserveLiquidationThreshold:re})}return{healthFactor:Number(_),currentLiquidationThreshold:Number(v.big.toDecimal(C,Qt)),totalCollateral:l,totalDebt:b,reserves:k}}async hasBorrowPositions(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[s,n]=a;return n>0n}async getHealthFactor(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[s,n,i,r,u,p]=a;return this.calculateHealthFactorFromBalances(n,s,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return lt;let u=W.fromAssetId(e),p=i.find(L=>L.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:l,isCollateral:b,priceInRef:P,reserveLiquidationThreshold:C}=p,x=v.big.toBigInt(a,l),I=b?x*P/10n**BigInt(l):0n,_=s-I;if(_<=0n)return 0;let k=(0,g.default)(s.toString()).mul(r).minus((0,g.default)(I.toString()).mul(C)).div(_.toString()),R=(0,g.default)(_.toString()).mul(k).div(n.toString()).toFixed(6,g.default.roundDown);return Number(R)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return lt;let u=W.fromAssetId(e),p=i.find(R=>R.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:l,priceInRef:b,reserveLiquidationThreshold:P}=p,x=v.big.toBigInt(a,l)*b/10n**BigInt(l),I=s+x;if(I<=0n)return 0;let _=(0,g.default)(s.toString()).mul(r).plus((0,g.default)(x.toString()).mul(P)).div(I.toString()),k=(0,g.default)(I.toString()).mul(_).div(n.toString()).toFixed(6,g.default.roundDown);return Number(k)}async getHealthFactorAfterSwap(t,e,a,s,n){let{totalDebt:i,reserves:r,healthFactor:u}=await this.getSummary(t);if(i===0n)return lt;let p=W.fromAssetId(a),l=W.fromAssetId(n),b=r.find(X=>X.reserveAsset===p),P=r.find(X=>X.reserveAsset===l);if(!b)throw new Error(`Missing reserve ctx for ${p}`);if(!P)throw new Error(`Missing reserve ctx for ${P}`);let C=v.big.toBigInt(e,b.decimals),x=v.big.toBigInt(s,P.decimals),I=C*b.priceInRef/10n**BigInt(b.decimals),_=x*P.priceInRef/10n**BigInt(P.decimals),k=b.isCollateral?(0,g.default)(I.toString()).mul(b.reserveLiquidationThreshold):(0,g.default)(0),S=(P.isCollateral?(0,g.default)(_.toString()).mul(P.reserveLiquidationThreshold):(0,g.default)(0)).minus(k).div(i.toString()),ht=(0,g.default)(u).plus(S).toFixed(6,g.default.roundDown);return Number(ht)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:s,healthFactor:n}=await this.getSummary(t),i=W.fromAssetId(e),r=s.find(u=>u.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,n)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:s}=await this.getSummary(t),n={};for(let i of a){let r=this.calculateWithdrawMax(i,e,s);i.reserveId&&(n[i.reserveId]=r)}return n}calculateWithdrawMax(t,e,a){let{aTokenBalance:s,availableLiquidity:n,decimals:i,priceInRef:r,reserveLiquidationThreshold:u,isCollateral:p}=t,l=s;if(p&&e>0n){let P=a-ca;if(P>0){let C=(0,g.default)(P).mul(e.toString()).div(u).toFixed(0,g.default.roundDown),x=(0,g.default)(C).div(r.toString()).mul(10**i).toFixed(0,g.default.roundDown);l=s<BigInt(x)?s:BigInt(x)}else l=0n}return{amount:l<n?l:n,decimals:i}}calculateLinearInterest(t,e,a){let s=a-e;if(s<=0)return ct;let n=t*BigInt(s)/ua;return ct+n}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return lt;let s=e*a/t,n=v.big.toDecimal(s,Qt);return Number(n)}};function Jt(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var $=class extends O{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new U(t),this.aaveUtils=new ut(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:jt})}async dryRun(t,e){let a=(0,At.Enum)("Signed",t),s=(0,At.Enum)("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall,4),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let u=r.type==="Module"?Jt(r.value):r.type;throw new Error("Dry run execution error!",{cause:u})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends ${_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],n=await this.balance.getBalance(this.beneficiary,s);return t>=n.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=w.getFraction(t,this.slippagePct),r=s.assetIn,u=n.assetOut,p=t+i,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.buy({asset_in:r,asset_out:u,amount:e,max_sell_amount:p}):l=this.api.tx.Router.buy({asset_in:r,asset_out:u,amount_out:e,max_amount_in:p,route:D.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterBuy",l)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=w.getFraction(e,this.slippagePct),r=s.assetIn,u=n.assetOut,p=e-i,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.sell({asset_in:r,asset_out:u,amount:t,min_buy_amount:p}):l=this.api.tx.Router.sell({asset_in:r,asset_out:u,amount_in:t,min_amount_out:p,route:D.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSell",l)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],s=e[e.length-1],n=w.getFraction(t,this.slippagePct),i=a.assetIn,r=s.assetOut,u=t-n,p=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:u,route:D.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("RouterSellAll",p)}};var mt=require("polkadot-api");var dt=class extends ${_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradePeriod:n,tradeRoute:i}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(r=await this.dispatchWithExtraGas(r)),this.wrapTx("DcaSchedule",r)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,u=w.getFraction(n,this.slippagePct),p=n-u,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:p,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapSell",l)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,u=w.getFraction(s,this.slippagePct),p=s+u,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,mt.Enum)("Buy",{asset_in:e,asset_out:a,amount_out:n,max_amount_in:p,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapBuy",l)}};var gt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new pt(this.client,this.evmClient).setTrade(t)}order(t){return new dt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
@@ -0,0 +1,2 @@
1
+ export { TxBuilderFactory } from './TxBuilderFactory';
2
+ export * from './types';
@@ -0,0 +1 @@
1
+ var Mt=Object.defineProperty;var K=(l,t)=>{for(var e in t)Mt(l,e,{get:t[e],enumerable:!0})};import Lt from"buffer";typeof window<"u"&&(window.Buffer=Lt.Buffer);import{calculate_in_given_out as sa,calculate_out_given_in as na,calculate_linear_weights as ia,calculate_pool_trade_fee as ra,get_spot_price as oa}from"@galacticcouncil/math-lbp";import{big as Ea,RUNTIME_DECIMALS as Ca}from"@galacticcouncil/common";var N={};K(N,{withTimeout:()=>Ht});function Ht(l,t,e="timeout"){return new Promise((a,n)=>{let s=setTimeout(()=>n(new Error(e)),t);l.then(i=>{clearTimeout(s),a(i)},i=>{clearTimeout(s),n(i)})})}var y={};K(y,{divSpot:()=>qt,getFraction:()=>Gt,mulScaled:()=>it,mulSpot:()=>Nt});import{RUNTIME_DECIMALS as nt}from"@galacticcouncil/common";function it(l,t,e,a,n){let s=e+a-n,i=l*t;return s>0?i/BigInt(10)**BigInt(s):s<0?i*BigInt(10)**BigInt(-s):i}function Nt(l,t,e,a){return it(l,t,e,nt,a)}function qt(l,t,e,a){if(t===0n)return 0n;let n=BigInt(10)**BigInt(nt+a-e);return l*n/t}function Gt(l,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),n=BigInt(Math.round(t*Number(a)));return l*n/(BigInt(100)*a)}var p={};K(p,{FeeUtils:()=>j,shiftNeg:()=>Wt});import Vt from"big.js";var j=class l{static toPct(t){let[e,a]=t;return l.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return l.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let n=10**a;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Wt(l,t){let e=Vt(typeof l=="bigint"?l.toString():l);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import va from"big.js";import{TLRUCache as Ia}from"@thi.ng/cache";var{FeeUtils:$a}=p;import{CompatibilityLevel as ai}from"polkadot-api";import{Subscription as ni,distinctUntilChanged as ii,filter as ri,map as oi}from"rxjs";import{memoize1 as mn}from"@thi.ng/memoize";import{TLRUCache as gn}from"@thi.ng/cache";import{ReplaySubject as Pn,Subscription as fn,combineLatest as Tn,defer as Sn,from as vn,interval as wn,merge as xn,of as In,EMPTY as On}from"rxjs";import{bufferCount as Bn,bufferTime as _n,catchError as Rn,filter as Fn,finalize as En,map as Cn,pairwise as kn,repeat as Dn,skip as Mn,share as Ln,startWith as Hn,switchMap as Nn,tap as qn,throttleTime as Gn}from"rxjs/operators";import{hydration as oe,hydrationNext as le}from"@galacticcouncil/descriptors";import{log as ae}from"@galacticcouncil/common";import{map as se,shareReplay as ne,tap as ie}from"rxjs";import{defer as Xt,from as Yt,of as lt,timer as zt}from"rxjs";import{catchError as Kt,distinctUntilChanged as jt,expand as Qt,map as Q,shareReplay as Jt,skip as Zt,switchMap as te,timeout as ee}from"rxjs/operators";function ct(l,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>Xt(()=>Yt(l._request("system_health",[]))).pipe(ee({first:e}),Q(()=>"online"),Kt(()=>lt("offline")));return lt({state:"offline",delayMs:0}).pipe(Qt(s=>zt(s.delayMs).pipe(te(a),Q(i=>({state:i,delayMs:t})))),Zt(1),Q(s=>s.state),jt(),Jt({bufferSize:1,refCount:!0}))}var{logger:re}=ae,G=class l{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(se(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ct(t))}static getInstance(t){return this.instance||(this.instance=new l(t)),this.instance}watched(t,e){return e.pipe(ie({error:a=>re.error(t,a)}),ne({bufferSize:1,refCount:!0}))}};var T=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(oe),this.apiNext=this.client.getTypedApi(le),this.watcher=G.getInstance(this.client)}};import{getWsProvider as us}from"polkadot-api/ws";import{withLogsRecorder as ms}from"polkadot-api/logs-provider";import{getSmProvider as bs}from"polkadot-api/sm-provider";import{Binary as _s}from"polkadot-api";import{log as ce}from"@galacticcouncil/common";import{combineLatest as ue,concat as pe,defer as D,from as ut}from"rxjs";import{bufferCount as pt,distinctUntilChanged as mt,debounceTime as me,map as B,retry as de,startWith as dt,switchMap as gt,tap as M,take as ge,skip as he,connect as be}from"rxjs/operators";var{logger:_}=ce,R=class extends T{erc20Ids=null;constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:"best"});return this.getBreakdown(a)}async getTokenBalance(t,e){let n=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(n)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return D(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),n=this.watchErc20Balance(t);return ue([e,a,n]).pipe(be(s=>pe(s.pipe(ge(1)),s.pipe(he(1),me(250)))))}).pipe(B(e=>e.flat()),dt([]),pt(2,1),B(([e,a],n)=>n===0?a:this.getDeltas(e,a))).pipe(M({subscribe:()=>_.debug("balance: subscribe",t),error:e=>_.error("balance",e)}),de({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return D(()=>e.watchValue(t,{at:"best"})).pipe(B(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),M({error:a=>_.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return D(()=>a.watchValue(t,e,{at:"best"})).pipe(B(({value:n})=>({id:e,balance:this.getBreakdown(n)})),M({error:n=>_.error("balance(token)",n)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return D(()=>e.watchEntries(t,{at:"best"})).pipe(mt((a,n)=>!n.deltas),B(({deltas:a})=>{let n=[];return a?.deleted.forEach(s=>{let[i,r]=s.args;n.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[i,r]=s.args;n.push({id:r,balance:this.getBreakdown(s.value)})}),n}),M({error:a=>_.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},n=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,c])=>({id:r,balance:c}));return D(()=>ut(e?Promise.resolve(e):a()).pipe(gt(s=>this.watcher.bestBlock$.pipe(gt(()=>ut(n(s))))),dt([]),pt(2,1),B(([s,i],r)=>r===0?i.filter(c=>c.balance.total>0n):this.getDeltas(s,i)),mt((s,i)=>i.length===0),M({error:s=>_.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(s,i)=>s!==void 0&&i!==void 0&&s.transferable===i.transferable&&s.total===i.total,n=t.reduce((s,i)=>(s.set(i.id,i.balance),s),new Map);return e.filter(s=>!a(s.balance,n.get(s.id)))}};import{BehaviorSubject as Js}from"rxjs";import{log as ye}from"@galacticcouncil/common";var nn={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:rn}=ye;var{withTimeout:Jn}=N;import{calculate_in_given_out as vi,calculate_lrna_in_given_out as wi,calculate_out_given_in as xi,calculate_out_given_lrna_in as Ii,calculate_spot_price as Oi,calculate_lrna_spot_price as Ai,calculate_shares as Bi,calculate_liquidity_out as _i,calculate_liquidity_lrna_out as Ri,verify_asset_cap as Fi,calculate_liquidity_hub_in as Ei,is_sell_allowed as Ci,is_buy_allowed as ki,is_add_liquidity_allowed as Di,is_remove_liquidity_allowed as Mi,recalculate_asset_fee as Li,recalculate_protocol_fee as Hi}from"@galacticcouncil/math-omnipool";import qi from"big.js";import{big as Wi}from"@galacticcouncil/common";var{FeeUtils:ar}=p;import{AccountId as lr,Binary as bt,CompatibilityLevel as cr,Enum as fe}from"polkadot-api";import{toHex as mr}from"@polkadot-api/utils";import{Subscription as gr,distinctUntilChanged as hr,filter as br,finalize as yr,map as Pr,merge as fr,tap as Tr}from"rxjs";import{HYDRATION_SS58_PREFIX as vr}from"@galacticcouncil/common";var{FeeUtils:Fr}=p,Er=bt.toHex(bt.fromText("omnipool")),Cr=fe("Short");import{calculate_in_given_out as Gr,calculate_out_given_in as Ur,calculate_amplification as Vr,calculate_add_one_asset as Wr,calculate_liquidity_out_one_asset as $r,calculate_shares as Xr,calculate_shares_for_amount as Yr,calculate_spot_price_with_fee as zr,pool_account_name as Kr,recalculate_peg as jr}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as to,big as eo}from"@galacticcouncil/common";var{FeeUtils:yo}=p;import{AccountId as So,CompatibilityLevel as vo}from"polkadot-api";import{toHex as xo}from"@polkadot-api/utils";import{blake2b as Oo}from"@noble/hashes/blake2b";import{Subscription as Bo,distinctUntilChanged as _o,map as Ro,merge as Fo,tap as Eo}from"rxjs";import{HYDRATION_SS58_PREFIX as ko,RUNTIME_DECIMALS as Do}from"@galacticcouncil/common";var{FeeUtils:Xo}=p;import{calculate_in_given_out as tl,calculate_out_given_in as el,calculate_pool_trade_fee as al,get_spot_price as sl,calculate_liquidity_in as nl,calculate_shares as il,calculate_spot_price as rl,calculate_spot_price_with_fee as ol,calculate_liquidity_out_asset_a as ll,calculate_liquidity_out_asset_b as cl}from"@galacticcouncil/math-xyk";import{big as hl}from"@galacticcouncil/common";var{FeeUtils:Al}=p;import{CompatibilityLevel as Fl}from"polkadot-api";import{Subscription as Cl}from"rxjs";import{big as Kl,RUNTIME_DECIMALS as jl}from"@galacticcouncil/common";import{AccountId as pc,Binary as mc}from"polkadot-api";import{toHex as gc}from"@polkadot-api/utils";import{Subscription as bc,filter as yc,map as Pc,mergeMap as fc}from"rxjs";import{decodeEventLog as Sc}from"viem";import{erc20 as Ie,HYDRATION_SS58_PREFIX as wc}from"@galacticcouncil/common";var{ERC20:Rc}=Ie;import{calculate_collateral_in_given_hollar_out as Lc,calculate_collateral_out_given_hollar_in as Hc,calculate_hollar_in_given_collateral_out as Nc,calculate_hollar_out_given_collateral_in as qc,calculate_imbalance as Gc,calculate_max_price as Uc,calculate_buyback_limit as Vc,calculate_buyback_price_with_fee as Wc}from"@galacticcouncil/math-hsm";import{big as Kc,RUNTIME_DECIMALS as jc}from"@galacticcouncil/common";var{FeeUtils:ou}=p;import{AccountId as Tu,Binary as Su,CompatibilityLevel as vu}from"polkadot-api";import{toHex as Iu}from"@polkadot-api/utils";import{Subscription as Bu,combineLatest as _u,filter as Ru,map as Fu,mergeMap as Eu,pairwise as Cu}from"rxjs";import{decodeEventLog as Du}from"viem";import{h160 as _e,HYDRATION_SS58_PREFIX as Lu}from"@galacticcouncil/common";var{FeeUtils:Wu}=p,{H160:$u}=_e;import{log as Fe}from"@galacticcouncil/common";import{Subject as _p,Subscription as Rp,takeUntil as Fp}from"rxjs";var{logger:Yp}=Fe;import{big as km,RUNTIME_DECIMALS as Dm}from"@galacticcouncil/common";var{FeeUtils:jm}=p;import{big as bd}from"@galacticcouncil/common";import{Enum as Pt}from"polkadot-api";var I=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:n,poolId:s})=>n==="Stableswap"?{pool:Pt("Stableswap",s),asset_in:e,asset_out:a}:{pool:Pt(n),asset_in:e,asset_out:a})}};import{Enum as xt}from"polkadot-api";var ft=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var J=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Tt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Z="0x112b087b60C1a166130d59266363C45F8aa99db0",tt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",St=1000000n;var Xd=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var U=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:J,address:Z,args:[tt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:J,address:Z,args:[tt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:ft,address:Tt,args:[t],functionName:"getUserAccountData"})}};import d from"big.js";import{big as A,erc20 as qe,h160 as Ge}from"@galacticcouncil/common";var{ERC20:F}=qe,{H160:et}=Ge,Ue=1.01,Ve=31536000n,vt=4,V=-1,W=10n**27n,$=class{client;constructor(t){this.client=new U(t)}async getSummary(t){let e=et.fromAny(t),[a,n,s,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[c,u]=n,[o,g,h,w,P,f]=s,S=A.toDecimal(f,18),x=[];for(let v of c){let O=v.underlyingAsset.toLowerCase(),b=r.find(({underlyingAsset:Dt})=>Dt.toLowerCase()===O);if(!b)throw new Error("Missing pool reserve for "+O);let z=v.scaledATokenBalance,C=b.liquidityIndex,It=b.liquidityRate,Ot=b.availableLiquidity,At=b.priceInMarketReferenceCurrency,Bt=i+6,_t=this.calculateLinearInterest(It,b.lastUpdateTimestamp,Bt),Rt=C*_t/W,Ft=z*Rt/W,Et=Number(u!==0&&u===b.eModeCategoryId?b.eModeLiquidationThreshold:b.reserveLiquidationThreshold)/1e4,Ct=b.usageAsCollateralEnabled&&v.usageAsCollateralEnabledOnUser&&v.scaledATokenBalance>0n,kt=F.toAssetId(O);x.push({aTokenBalance:Ft,availableLiquidity:Ot,decimals:Number(b.decimals),isCollateral:Ct,priceInRef:At,reserveId:kt,reserveAsset:O,reserveLiquidationThreshold:Et})}return{healthFactor:Number(S),currentLiquidationThreshold:Number(A.toDecimal(w,vt)),totalCollateral:o,totalDebt:g,reserves:x}}async hasBorrowPositions(t){let e=et.fromAny(t),a=await this.client.getUserAccountData(e),[n,s]=a;return s>0n}async getHealthFactor(t){let e=et.fromAny(t),a=await this.client.getUserAccountData(e),[n,s,i,r,c,u]=a;return this.calculateHealthFactorFromBalances(s,n,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:n,totalDebt:s,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return V;let c=F.fromAssetId(e),u=i.find(O=>O.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,isCollateral:g,priceInRef:h,reserveLiquidationThreshold:w}=u,P=A.toBigInt(a,o),f=g?P*h/10n**BigInt(o):0n,S=n-f;if(S<=0n)return 0;let x=d(n.toString()).mul(r).minus(d(f.toString()).mul(w)).div(S.toString()),v=d(S.toString()).mul(x).div(s.toString()).toFixed(6,d.roundDown);return Number(v)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:n,totalDebt:s,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return V;let c=F.fromAssetId(e),u=i.find(v=>v.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,priceInRef:g,reserveLiquidationThreshold:h}=u,P=A.toBigInt(a,o)*g/10n**BigInt(o),f=n+P;if(f<=0n)return 0;let S=d(n.toString()).mul(r).plus(d(P.toString()).mul(h)).div(f.toString()),x=d(f.toString()).mul(S).div(s.toString()).toFixed(6,d.roundDown);return Number(x)}async getHealthFactorAfterSwap(t,e,a,n,s){let{totalDebt:i,reserves:r,healthFactor:c}=await this.getSummary(t);if(i===0n)return V;let u=F.fromAssetId(a),o=F.fromAssetId(s),g=r.find(C=>C.reserveAsset===u),h=r.find(C=>C.reserveAsset===o);if(!g)throw new Error(`Missing reserve ctx for ${u}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let w=A.toBigInt(e,g.decimals),P=A.toBigInt(n,h.decimals),f=w*g.priceInRef/10n**BigInt(g.decimals),S=P*h.priceInRef/10n**BigInt(h.decimals),x=g.isCollateral?d(f.toString()).mul(g.reserveLiquidationThreshold):d(0),b=(h.isCollateral?d(S.toString()).mul(h.reserveLiquidationThreshold):d(0)).minus(x).div(i.toString()),z=d(c).plus(b).toFixed(6,d.roundDown);return Number(z)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:n,healthFactor:s}=await this.getSummary(t),i=F.fromAssetId(e),r=n.find(c=>c.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:n}=await this.getSummary(t),s={};for(let i of a){let r=this.calculateWithdrawMax(i,e,n);i.reserveId&&(s[i.reserveId]=r)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:n,availableLiquidity:s,decimals:i,priceInRef:r,reserveLiquidationThreshold:c,isCollateral:u}=t,o=n;if(u&&e>0n){let h=a-Ue;if(h>0){let w=d(h).mul(e.toString()).div(c).toFixed(0,d.roundDown),P=d(w).div(r.toString()).mul(10**i).toFixed(0,d.roundDown);o=n<BigInt(P)?n:BigInt(P)}else o=0n}return{amount:o<s?o:s,decimals:i}}calculateLinearInterest(t,e,a){let n=a-e;if(n<=0)return W;let s=t*BigInt(n)/Ve;return W+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let n=e*a/t,s=A.toDecimal(n,vt);return Number(s)}};function wt(l){let t=[],e=l;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var E=class extends T{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new R(t),this.aaveUtils=new $(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:St})}async dryRun(t,e){let a=xt("Signed",t),n=xt("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(n,e.decodedCall,4),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let c=r.type==="Module"?wt(r.value):r.type;throw new Error("Dry run execution error!",{cause:c})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var X=class extends E{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:n}=e[0],s=await this.balance.getBalance(this.beneficiary,n);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,n=a[0],s=a[a.length-1],i=y.getFraction(t,this.slippagePct),r=n.assetIn,c=s.assetOut,u=t+i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.buy({asset_in:r,asset_out:c,amount:e,max_sell_amount:u}):o=this.api.tx.Router.buy({asset_in:r,asset_out:c,amount_out:e,max_amount_in:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterBuy",o)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,n=a[0],s=a[a.length-1],i=y.getFraction(e,this.slippagePct),r=n.assetIn,c=s.assetOut,u=e-i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.sell({asset_in:r,asset_out:c,amount:t,min_buy_amount:u}):o=this.api.tx.Router.sell({asset_in:r,asset_out:c,amount_in:t,min_amount_out:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterSell",o)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],n=e[e.length-1],s=y.getFraction(t,this.slippagePct),i=a.assetIn,r=n.assetOut,c=t-s,u=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:c,route:I.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};import{Enum as at}from"polkadot-api";var Y=class extends E{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:n,tradePeriod:s,tradeRoute:i}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:at("Sell",{asset_in:e,asset_out:a,amount_in:n,min_amount_out:0n,route:i})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(r=await this.dispatchWithExtraGas(r)),this.wrapTx("DcaSchedule",r)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:n,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(s,this.slippagePct),u=s-c,o=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:at("Sell",{asset_in:e,asset_out:a,amount_in:n,min_amount_out:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapSell",o)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:n,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(n,this.slippagePct),u=n+c,o=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:at("Buy",{asset_in:e,asset_out:a,amount_out:s,max_amount_in:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapBuy",o)}};var st=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new X(this.client,this.evmClient).setTrade(t)}order(t){return new Y(this.client,this.evmClient).setOrder(t)}};export{st as TxBuilderFactory};
@@ -0,0 +1,10 @@
1
+ import { Transaction as PapiTransaction } from 'polkadot-api';
2
+ import { HydrationApis } from '@galacticcouncil/descriptors';
3
+ export interface Tx {
4
+ name?: string;
5
+ get(): Transaction;
6
+ dryRun(account: string): Promise<DryRunResult>;
7
+ }
8
+ export type Transaction = PapiTransaction<void | undefined>;
9
+ export type DryRunResult = HydrationApis['DryRunApi']['dry_run_call']['Value'];
10
+ export type DryRunArgs = HydrationApis['DryRunApi']['dry_run_call']['Args'];
@@ -0,0 +1,5 @@
1
+ export type NestedEnum = {
2
+ type: string;
3
+ value?: NestedEnum;
4
+ } | undefined;
5
+ export declare function enumPath(enumObj: NestedEnum): string;
@@ -3,9 +3,9 @@ export type Amount = {
3
3
  amount: bigint;
4
4
  decimals: number;
5
5
  };
6
- export interface AssetAmount {
6
+ export interface AssetBalance {
7
7
  id: number;
8
- amount: bigint;
8
+ balance: Balance;
9
9
  }
10
10
  export interface AssetMetadata {
11
11
  decimals: number;
@@ -34,6 +34,13 @@ export interface ExternalAsset extends AssetMetadata {
34
34
  internalId: number;
35
35
  isWhiteListed?: boolean;
36
36
  }
37
+ export interface Balance {
38
+ free: bigint;
39
+ total: bigint;
40
+ transferable: bigint;
41
+ reserved: bigint;
42
+ frozen: bigint;
43
+ }
37
44
  export type XcmV3Multilocation = {
38
45
  parents: number;
39
46
  interior: XcmV3Junctions;
@@ -0,0 +1,10 @@
1
+ export declare class QueryBus {
2
+ private debug;
3
+ constructor(debug?: boolean);
4
+ private log;
5
+ scope<K extends any[], V>(name: string, fetch: (...args: K) => Promise<V>, toKey: (...args: K) => string, ttlMs?: number): {
6
+ get: (...args: K) => Promise<V>;
7
+ set: (v: V, ...args: K) => void;
8
+ clear: () => void;
9
+ };
10
+ }
@@ -0,0 +1 @@
1
+ export declare function withTimeout<T>(p: Promise<T>, ms: number, label?: string): Promise<T>;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Multiply two fixed-point bigint values and rescale the result
3
+ * to the desired target decimals.
4
+ *
5
+ * This helper is fully generic and supports both scaling down
6
+ * (division) and scaling up (adding trailing zeroes).
7
+ *
8
+ * @param value - base value (native bigint)
9
+ * @param multiplier - multiplier value (native bigint)
10
+ * @param valueDecimals - decimals of the base value
11
+ * @param multiplierDecimals - decimals of the multiplier
12
+ * @param targetDecimals - desired decimals of the result
13
+ * @returns scaled multiplication result
14
+ */
15
+ export declare function mulScaled(value: bigint, multiplier: bigint, valueDecimals: number, multiplierDecimals: number, targetDecimals: number): bigint;
16
+ /**
17
+ * Multiply a value by a spot price and rescale the result
18
+ * to the desired target decimals.
19
+ *
20
+ * Spot price is assumed to be scaled by `RUNTIME_DECIMALS`
21
+ * (currently 18).
22
+ *
23
+ * @param value - base value (native bigint)
24
+ * @param spot - spot price (scaled by RUNTIME_DECIMALS)
25
+ * @param valueDecimals - decimals of the base value
26
+ * @param targetDecimals - desired decimals of the result
27
+ * @returns scaled spot multiplication result
28
+ */
29
+ export declare function mulSpot(value: bigint, spot: bigint, valueDecimals: number, targetDecimals: number): bigint;
30
+ /**
31
+ * Divide a value by a spot price and rescale the result
32
+ * to the desired target decimals.
33
+ *
34
+ * Inverse of `mulSpot` — equivalent to multiplying
35
+ * by the reciprocal (1 / spot).
36
+ *
37
+ * @param value - base value (native bigint)
38
+ * @param spot - spot price (scaled by RUNTIME_DECIMALS)
39
+ * @param valueDecimals - decimals of the base value
40
+ * @param targetDecimals - desired decimals of the result
41
+ * @returns scaled division result
42
+ */
43
+ export declare function divSpot(value: bigint, spot: bigint, valueDecimals: number, targetDecimals: number): bigint;
44
+ /**
45
+ * Get % fraction from native value
46
+ *
47
+ * @param value - native amount
48
+ * @param pct - percentage value (e.g. 0.5 = 0.5%)
49
+ * @param dp - safe decimals margin (2dp = 0.01%)
50
+ * @returns fraction of given amount
51
+ */
52
+ export declare function getFraction(value: bigint, pct: number, dp?: number): bigint;
@@ -0,0 +1,11 @@
1
+ import { PoolFee } from '../pool';
2
+ export declare class FeeUtils {
3
+ static toPct(fee: PoolFee): number;
4
+ static toRaw(fee: PoolFee): number;
5
+ static fromPermill(permill: number): PoolFee;
6
+ static fromPerbill(perbill: number): PoolFee;
7
+ static fromRate(numerator: number, denominator: number): PoolFee;
8
+ static safeDivide(numerator: number, denominator: number, decimals?: number): number;
9
+ static safeRound(value: number): number;
10
+ }
11
+ export declare function shiftNeg(amount: string | number | bigint, decimals: number): string;
@@ -0,0 +1 @@
1
+ "use strict";var W=Object.create;var v=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,Q=Object.prototype.hasOwnProperty;var a=(i,t)=>{for(var e in t)v(i,e,{get:t[e],enumerable:!0})},L=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of G(t))!Q.call(i,s)&&s!==e&&v(i,s,{get:()=>t[s],enumerable:!(r=V(t,s))||r.enumerable});return i};var k=(i,t,e)=>(e=i!=null?W(Z(i)):{},L(t||!i||!i.__esModule?v(e,"default",{value:i,enumerable:!0}):e,i)),tt=i=>L(v({},"__esModule",{value:!0}),i);var St={};a(St,{QueryBus:()=>C,async:()=>T,calc:()=>M,fmt:()=>A,json:()=>N,math:()=>B});module.exports=tt(St);var T={};a(T,{withTimeout:()=>et});function et(i,t,e="timeout"){return new Promise((r,s)=>{let n=setTimeout(()=>s(new Error(e)),t);i.then(o=>{clearTimeout(n),r(o)},o=>{clearTimeout(n),s(o)})})}var M={};a(M,{divSpot:()=>it,getFraction:()=>st,mulScaled:()=>F,mulSpot:()=>rt});var O=require("@galacticcouncil/common");function F(i,t,e,r,s){let n=e+r-s,o=i*t;return n>0?o/BigInt(10)**BigInt(n):n<0?o*BigInt(10)**BigInt(-n):o}function rt(i,t,e,r){return F(i,t,e,O.RUNTIME_DECIMALS,r)}function it(i,t,e,r){if(t===0n)return 0n;let s=BigInt(10)**BigInt(O.RUNTIME_DECIMALS+r-e);return i*s/t}function st(i,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let r=BigInt(10)**BigInt(e),s=BigInt(Math.round(t*Number(r)));return i*s/(BigInt(100)*r)}var A={};a(A,{FeeUtils:()=>P,shiftNeg:()=>ht});var q=k(require("big.js"));var P=class i{static toPct(t){let[e,r]=t;return i.safeDivide(e*100,r)}static toRaw(t){let[e,r]=t;return i.safeDivide(e,r)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,r=12){let s=10**r;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ht(i,t){let e=(0,q.default)(typeof i=="bigint"?i.toString():i);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var N={};a(N,{findNestedKey:()=>lt,findNestedObj:()=>ut,jsonFormatter:()=>at});var lt=(i,t)=>{let e=[];return JSON.stringify(i,(r,s)=>(s&&s[t]&&e.push(s),s)),e[0]},ut=(i,t,e)=>{let r;return JSON.stringify(i,(s,n)=>(n&&n[t]===e&&(r=n),n)),r},at=(i,t)=>typeof t=="bigint"?t.toString():t;var B={};a(B,{calculateBuyFee:()=>mt,calculateDiffToAvg:()=>ft,calculateDiffToRef:()=>pt,calculateSellFee:()=>ct});var u=k(require("big.js"));function ft(i,t){let e=(0,u.default)(i.toString()),r=(0,u.default)(t.toString());return e.minus(r).abs().div(e.plus(r).div(2)).mul(100).round(2).toNumber()}function pt(i,t){if(t===0n)return 0;let e=(0,u.default)(i.toString()),r=(0,u.default)(t.toString());return e.minus(r).div(r).mul(100).round(2).toNumber()}function ct(i,t){if(i===0n)return 0;let e=(0,u.default)(i.toString()),r=(0,u.default)(t.toString());return(0,u.default)(1).minus(r.div(e)).mul(100).round(2).toNumber()}function mt(i,t){if(i===0n)return 0;let e=(0,u.default)(i.toString());return(0,u.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var m=(i,t)=>i===t?0:i==null?t==null?0:-1:t==null?i==null?0:1:typeof i.compare=="function"?i.compare(t):typeof t.compare=="function"?-t.compare(i):i<t?-1:i>t?1:0;var _=(i,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(i(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var dt=_(()=>"illegal argument(s)"),j=i=>{throw new dt(i)};var gt=_(()=>"index out of bounds"),D=i=>{throw new gt(i)},x=(i,t,e)=>(i<t||i>=e)&&D(i);var U=23283064365386963e-26,y=class{float(t=1){return this.int()*U*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*U-.5)*2*t}normMinMax(t,e){let r=this.minmax(t,e);return this.float()<.5?r:-r}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let r=(e|0)-t;return r?t+this.int()%r:t}minmaxUint(t,e){t>>>=0;let r=(e>>>0)-t;return r?t+this.int()%r:t}};var S=class extends y{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var H=new S(Math.random);var Y=i=>i!=null&&typeof i!="function"&&i.length!==void 0;var K=Object.getPrototypeOf({}),w="function",$="string",f=(i,t)=>{let e;if(i===t)return!0;if(i!=null){if(typeof i.equiv===w)return i.equiv(t)}else return i==t;if(t!=null){if(typeof t.equiv===w)return t.equiv(i)}else return i==t;return typeof i===$||typeof t===$?!1:(e=Object.getPrototypeOf(i),(e==null||e===K)&&(e=Object.getPrototypeOf(t),e==null||e===K)?yt(i,t):typeof i!==w&&i.length!==void 0&&typeof t!==w&&t.length!==void 0?vt(i,t):i instanceof Set&&t instanceof Set?_t(i,t):i instanceof Map&&t instanceof Map?xt(i,t):i instanceof Date&&t instanceof Date?i.getTime()===t.getTime():i instanceof RegExp&&t instanceof RegExp?i.toString()===t.toString():i!==i&&t!==t)},vt=(i,t,e=f)=>{let r=i.length;if(r===t.length)for(;r-- >0&&e(i[r],t[r]););return r<0},_t=(i,t,e=f)=>i.size===t.size&&e([...i.keys()].sort(),[...t.keys()].sort()),xt=(i,t,e=f)=>i.size===t.size&&e([...i].sort(),[...t].sort()),yt=(i,t,e=f)=>{if(Object.keys(i).length!==Object.keys(t).length)return!1;for(let r in i)if(!t.hasOwnProperty(r)||!e(i[r],t[r]))return!1;return!0};var R=class{value;constructor(t){this.value=t}deref(){return this.value}};var J=i=>i instanceof R;var b=class i{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return X("next",this._head)}reverseIterator(){return X("prev",this.tail)}clear(){this.release()}compare(t,e=m){let r=this._length;if(r<t._length)return-1;if(r>t._length)return 1;if(r===0)return 0;{let s=this._head,n=t._head,o=0;for(;r-- >0&&o===0;)o=e(s.value,n.value),s=s.next,n=n.next;return o}}concat(...t){let e=this.copy();for(let r of t)e.into(r);return e}equiv(t){if(!(t instanceof i||Y(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!f(r.value,e.next().value))return!1;r=r.next}return!0}filter(t){let e=this.empty();return this.traverse(r=>(t(r.value)&&e.append(r.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||m;for(let r=this._head,s=this._length;s-- >0;){if(e(t,r.value)<=0)return this.insertBefore(r,t);r=r.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let r=this.nthCell(t);return r?r.value:e}nthCellUnsafe(t){let e,r;for(t<=this._length>>>1?(e=this._head,r="next"):(e=this.tail,r="prev",t=this._length-t-1);t-- >0&&e;)e=e[r];return e}peek(){return this.tail?.value}$reduce(t,e){let r=this._head;for(let s=this._length;s-- >0&&!J(e);)e=t(e,r.value),r=r.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let r=this._length;r-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,r=(this._length>>>1)+(this._length&1);for(;t&&e&&r>0;){let s=t.value;t.value=e.value,e.value=s,t=t.next,e=e.prev,r--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let r=this.nthCell(t);return!r&&D(t),r.value=e,r}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let r=t.value;t.value=e.value,e.value=r}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,r){if(!this._head)return;let s=e;do{if(!t(s))break;s=s.next}while(s!==r);return s}_map(t,e){return this.traverse(r=>(t.append(e(r.value)),!0)),t}};function*X(i,t){for(;t;)yield t.value,t=t[i]}var E=class i extends b{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new i(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new i}insertAfter(t,e){let r={value:e,next:t.next,prev:t};return t.next?t.next.prev=r:this._tail=r,t.next=r,this._length++,r}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(x(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let r={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=r:this._head=r,t.prev=r,this._length++,r}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(x(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new i,t)}nth(t,e){let r=this.nthCell(t);return r?r.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let r=this.nthCell(t),s=this.nthCell(e-1),n=o=>({first(){return o.value},next(){return o!==s&&o.next?n(o.next):void 0}});return r?n(r):void 0}shuffle(t,e=H){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let r=this._head;for(;r;){let s=r.next;e.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(t=0,e=this.length){let r=t<0?t+this._length:t,s=e<0?e+this._length:e;(r<0||s<0)&&j("invalid indices: ${from} / ${to}");let n=new i,o=this.nthCell(r);for(;o&&++r<=s;)n.push(o.value),o=o.next;return n}sort(t=m){if(!this._length)return this;let e=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let n=r,o=0;for(let h=0;h<e&&(o++,n=n.next,!!n);h++);let p=e;for(;o>0||p>0&&n;){let h;o===0?(h=n,n=n.next,p--):!n||p===0||t(r.value,n.value)<=0?(h=r,r=r.next,o--):(h=n,n=n.next,p--),this._tail?this._tail.next=h:this._head=h,h.prev=this._tail,this._tail=h}r=n}if(this._tail.next=void 0,s<=1)return this;e*=2}}splice(t,e=0,r){let s;typeof t=="number"?(t<0&&(t+=this._length),x(t,0,this._length),s=this.nthCellUnsafe(t)):s=t;let n=new i;if(e>0)for(;s&&e-- >0;)this.remove(s),n.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let o of r)this.insertBefore(s,o);else for(let o of r)this.push(o);return n}};var z=class i{map;items;opts;_size;constructor(t,e){let r={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=r.map(),this.items=new E,this._size=0,this.opts=r,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new i(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let r=this.map.get(t);return r?this.resetEntry(r):e}set(t,e){let r=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),n=Math.max(0,r-(s?s.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(s,t,e,r):this._size-=n,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let r=this.map.get(t);return r?this.resetEntry(r):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:r}=this.opts;for(;this._size>e||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),t?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,r,s){t?(this.opts.update?.(e,t.value.v,r),t.value.v=r,t.value.s=s,this.items.asTail(t)):(this.items.push({k:e,v:r,s}),this.map.set(e,this.items.tail))}};var d=class i extends z{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new i(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let r=this.map.get(t);if(r){if(r.value.t>=Date.now())return this.resetEntry(r);this.removeEntry(r)}return e}set(t,e,r=this.opts.ttl){let s=this.opts.ksize(t)+this.opts.vsize(e),n=this.map.get(t),o=Math.max(0,s-(n?n.value.s:0));return this._size+=o,this.ensureSize()?this.doSetEntry(n,t,e,s,r):this._size-=o,e}async getSet(t,e,r=this.opts.ttl){let s=this.get(t);return s!==void 0?s:this.set(t,await e(),r)}prune(){let t=Date.now(),e=this.items.head,r=0;for(;e;)e.value.t<t&&(this.removeEntry(e),r++),e=e.next;return r}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>e||this.length>=t);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(t,e,r,s,n=this.opts.ttl){let o=Date.now()+n;t?(this.opts.update?.(e,t.value.v,r),t.value.v=r,t.value.s=s,t.value.t=o,this.items.asTail(t)):(this.items.push({k:e,v:r,s,t:o,ttl:n}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var C=class{debug;constructor(t){this.debug=t||!1}log(t,e,r){this.debug&&console.log(t,e,r)}scope(t,e,r,s){let n=new Map,o=s!==void 0?new d(null,{ttl:s}):new d;return{get:(...g)=>{let l=r(...g);if(n.has(l)){this.log("[live]",t,l);let I=n.get(l);return Promise.resolve(I)}if(o.has(l))return this.log("[memo]",t,l),o.get(l);this.log("[fetch]",t,l);let c=e(...g).catch(I=>{throw o.delete(l),I});return o.set(l,c),c},set:(g,...l)=>{let c=r(...l);this.log("[set-live]",t,c),n.set(c,g)},clear:()=>{this.log("[clear]",t),n.clear(),o.release()}}}};0&&(module.exports={QueryBus,async,calc,fmt,json,math});
@@ -1,6 +1,6 @@
1
- export * as big from './big';
2
- export * as evm from './evm';
1
+ export * as async from './async';
2
+ export * as calc from './calc';
3
3
  export * as fmt from './format';
4
4
  export * as json from './json';
5
5
  export * as math from './math';
6
- export * as xc from './xc';
6
+ export * from './QueryBus';
@@ -0,0 +1 @@
1
+ var N=Object.defineProperty;var g=(r,t)=>{for(var n in t)N(r,n,{get:t[n],enumerable:!0})};import E from"buffer";typeof window<"u"&&(window.Buffer=E.Buffer);var l={};g(l,{withTimeout:()=>_});function _(r,t,n="timeout"){return new Promise((o,e)=>{let i=setTimeout(()=>e(new Error(n)),t);r.then(s=>{clearTimeout(i),o(s)},s=>{clearTimeout(i),e(s)})})}var S={};g(S,{divSpot:()=>v,getFraction:()=>D,mulScaled:()=>d,mulSpot:()=>B});import{RUNTIME_DECIMALS as p}from"@galacticcouncil/common";function d(r,t,n,o,e){let i=n+o-e,s=r*t;return i>0?s/BigInt(10)**BigInt(i):i<0?s*BigInt(10)**BigInt(-i):s}function B(r,t,n,o){return d(r,t,n,p,o)}function v(r,t,n,o){if(t===0n)return 0n;let e=BigInt(10)**BigInt(p+o-n);return r*e/t}function D(r,t,n=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let o=BigInt(10)**BigInt(n),e=BigInt(Math.round(t*Number(o)));return r*e/(BigInt(100)*o)}var x={};g(x,{FeeUtils:()=>a,shiftNeg:()=>O});import R from"big.js";var a=class r{static toPct(t){let[n,o]=t;return r.safeDivide(n*100,o)}static toRaw(t){let[n,o]=t;return r.safeDivide(n,o)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,n){return[t,n]}static safeDivide(t,n,o=12){let e=10**o;return Math.round(t*e/n)/e}static safeRound(t){return parseFloat(t.toPrecision(15))}};function O(r,t){let n=R(typeof r=="bigint"?r.toString():r);return t===0?n.toString():n.div(Math.pow(10,t)).toString()}var I={};g(I,{findNestedKey:()=>w,findNestedObj:()=>M,jsonFormatter:()=>F});var w=(r,t)=>{let n=[];return JSON.stringify(r,(o,e)=>(e&&e[t]&&n.push(e),e)),n[0]},M=(r,t,n)=>{let o;return JSON.stringify(r,(e,i)=>(i&&i[t]===n&&(o=i),i)),o},F=(r,t)=>typeof t=="bigint"?t.toString():t;var P={};g(P,{calculateBuyFee:()=>j,calculateDiffToAvg:()=>L,calculateDiffToRef:()=>C,calculateSellFee:()=>H});import c from"big.js";function L(r,t){let n=c(r.toString()),o=c(t.toString());return n.minus(o).abs().div(n.plus(o).div(2)).mul(100).round(2).toNumber()}function C(r,t){if(t===0n)return 0;let n=c(r.toString()),o=c(t.toString());return n.minus(o).div(o).mul(100).round(2).toNumber()}function H(r,t){if(r===0n)return 0;let n=c(r.toString()),o=c(t.toString());return c(1).minus(o.div(n)).mul(100).round(2).toNumber()}function j(r,t){if(r===0n)return 0;let n=c(r.toString());return c(t.toString()).div(n).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as T}from"@thi.ng/cache";var h=class{debug;constructor(t){this.debug=t||!1}log(t,n,o){this.debug&&console.log(t,n,o)}scope(t,n,o,e){let i=new Map,s=e!==void 0?new T(null,{ttl:e}):new T;return{get:(...b)=>{let u=o(...b);if(i.has(u)){this.log("[live]",t,u);let f=i.get(u);return Promise.resolve(f)}if(s.has(u))return this.log("[memo]",t,u),s.get(u);this.log("[fetch]",t,u);let m=n(...b).catch(f=>{throw s.delete(u),f});return s.set(u,m),m},set:(b,...u)=>{let m=o(...u);this.log("[set-live]",t,m),i.set(m,b)},clear:()=>{this.log("[clear]",t),i.clear(),s.release()}}}};export{h as QueryBus,l as async,S as calc,x as fmt,I as json,P as math};
@@ -51,12 +51,3 @@ export declare function calculateSellFee(delta0Y: bigint, deltaY: bigint): numbe
51
51
  * @param deltaX - the amount in, inclusive of fees
52
52
  */
53
53
  export declare function calculateBuyFee(delta0X: bigint, deltaX: bigint): number;
54
- /**
55
- * Get % fraction from native value
56
- *
57
- * @param value - native amount
58
- * @param pct - percentage value
59
- * @param dp - safe decimals margin (2dp = 0.01%)
60
- * @returns fraction of given amount
61
- */
62
- export declare function getFraction(value: bigint, pct: number, dp?: number): bigint;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk-next",
3
- "version": "1.0.0-beta.0",
3
+ "version": "1.0.0",
4
4
  "description": "Galactic next gen sdk (papi)",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {
@@ -10,10 +10,9 @@
10
10
  },
11
11
  "keywords": [
12
12
  "hydration",
13
- "basilisk",
14
- "sdk",
15
- "definitions",
16
- "types"
13
+ "api",
14
+ "router",
15
+ "sdk"
17
16
  ],
18
17
  "bugs": {
19
18
  "url": "https://github.com/galacticcouncil/sdk/issues"
@@ -23,31 +22,87 @@
23
22
  ],
24
23
  "main": "./build/index.cjs",
25
24
  "module": "./build/index.mjs",
26
- "types": "./build/types/index.d.ts",
25
+ "types": "./build/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./build/index.d.ts",
29
+ "import": "./build/index.mjs",
30
+ "require": "./build/index.cjs"
31
+ },
32
+ "./aave": {
33
+ "types": "./build/aave/index.d.ts",
34
+ "import": "./build/aave/index.mjs",
35
+ "require": "./build/aave/index.cjs"
36
+ },
37
+ "./client": {
38
+ "types": "./build/client/index.d.ts",
39
+ "import": "./build/client/index.mjs",
40
+ "require": "./build/client/index.cjs"
41
+ },
42
+ "./evm": {
43
+ "types": "./build/evm/index.d.ts",
44
+ "import": "./build/evm/index.mjs",
45
+ "require": "./build/evm/index.cjs"
46
+ },
47
+ "./farm": {
48
+ "types": "./build/farm/index.d.ts",
49
+ "import": "./build/farm/index.mjs",
50
+ "require": "./build/farm/index.cjs"
51
+ },
52
+ "./pool": {
53
+ "types": "./build/pool/index.d.ts",
54
+ "import": "./build/pool/index.mjs",
55
+ "require": "./build/pool/index.cjs"
56
+ },
57
+ "./sor": {
58
+ "types": "./build/sor/index.d.ts",
59
+ "import": "./build/sor/index.mjs",
60
+ "require": "./build/sor/index.cjs"
61
+ },
62
+ "./staking": {
63
+ "types": "./build/staking/index.d.ts",
64
+ "import": "./build/staking/index.mjs",
65
+ "require": "./build/staking/index.cjs"
66
+ },
67
+ "./tx": {
68
+ "types": "./build/tx/index.d.ts",
69
+ "import": "./build/tx/index.mjs",
70
+ "require": "./build/tx/index.cjs"
71
+ },
72
+ "./utils": {
73
+ "types": "./build/utils/index.d.ts",
74
+ "import": "./build/utils/index.mjs",
75
+ "require": "./build/utils/index.cjs"
76
+ }
77
+ },
27
78
  "scripts": {
28
79
  "build": "npm run clean && node ./esbuild.dist.mjs",
29
80
  "build:watch": "node ./esbuild.dev.mjs",
30
- "postbuild": "tsc --emitDeclarationOnly --outDir build/types/",
81
+ "postbuild": "tsc --emitDeclarationOnly --outDir build",
31
82
  "clean": "rimraf build",
32
83
  "link": "npm ln",
33
- "test": "NODE_NO_WARNINGS=1 jest"
84
+ "test": "NODE_NO_WARNINGS=1 NODE_OPTIONS=--experimental-vm-modules jest"
34
85
  },
35
86
  "devDependencies": {
36
87
  "@types/big.js": "^6.2.2"
37
88
  },
38
89
  "dependencies": {
39
- "@galacticcouncil/descriptors": "^1.1.0",
40
- "@galacticcouncil/math-lbp": "^1.0.0",
41
- "@galacticcouncil/math-liquidity-mining": "^1.0.0",
42
- "@galacticcouncil/math-omnipool": "^1.1.0",
43
- "@galacticcouncil/math-stableswap": "^2.0.0",
44
- "@galacticcouncil/math-xyk": "^1.0.0",
90
+ "@galacticcouncil/math-hsm": "^1.2.0",
91
+ "@galacticcouncil/math-lbp": "^1.3.0",
92
+ "@galacticcouncil/math-liquidity-mining": "^1.3.0",
93
+ "@galacticcouncil/math-omnipool": "^1.4.0",
94
+ "@galacticcouncil/math-stableswap": "^2.5.0",
95
+ "@galacticcouncil/math-staking": "^1.3.0",
96
+ "@galacticcouncil/math-xyk": "^1.3.0",
45
97
  "@noble/hashes": "^1.6.1",
46
98
  "@thi.ng/cache": "^2.1.35",
47
99
  "@thi.ng/memoize": "^4.0.2",
48
100
  "big.js": "^6.2.1"
49
101
  },
50
102
  "peerDependencies": {
51
- "polkadot-api": "^1.10.0"
103
+ "@galacticcouncil/common": ">=1.0.0",
104
+ "@galacticcouncil/descriptors": ">=2.0.0",
105
+ "polkadot-api": "^2.1.0",
106
+ "viem": "^2.38.3"
52
107
  }
53
108
  }