@galacticcouncil/sdk-next 1.0.0-beta.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 (54) hide show
  1. package/README.md +141 -0
  2. package/build/index.cjs +1 -0
  3. package/build/index.mjs +1 -0
  4. package/build/types/api/Papi.d.ts +375 -0
  5. package/build/types/api/client.d.ts +2 -0
  6. package/build/types/api/index.d.ts +2 -0
  7. package/build/types/client/AssetClient.d.ts +24 -0
  8. package/build/types/client/BalanceClient.d.ts +17 -0
  9. package/build/types/client/index.d.ts +2 -0
  10. package/build/types/consts.d.ts +8 -0
  11. package/build/types/errors.d.ts +10 -0
  12. package/build/types/index.d.ts +8 -0
  13. package/build/types/pool/PoolClient.d.ts +25 -0
  14. package/build/types/pool/PoolContextProvider.d.ts +26 -0
  15. package/build/types/pool/PoolFactory.d.ts +4 -0
  16. package/build/types/pool/index.d.ts +7 -0
  17. package/build/types/pool/lbp/LbpMath.d.ts +7 -0
  18. package/build/types/pool/lbp/LbpPool.d.ts +49 -0
  19. package/build/types/pool/lbp/LbpPoolClient.d.ts +18 -0
  20. package/build/types/pool/lbp/index.d.ts +3 -0
  21. package/build/types/pool/omni/OmniMath.d.ts +19 -0
  22. package/build/types/pool/omni/OmniPool.d.ts +45 -0
  23. package/build/types/pool/omni/OmniPoolClient.d.ts +13 -0
  24. package/build/types/pool/omni/index.d.ts +3 -0
  25. package/build/types/pool/stable/StableMath.d.ts +14 -0
  26. package/build/types/pool/stable/StableSwap.d.ts +46 -0
  27. package/build/types/pool/stable/StableSwapClient.d.ts +16 -0
  28. package/build/types/pool/stable/index.d.ts +3 -0
  29. package/build/types/pool/types.d.ts +84 -0
  30. package/build/types/pool/xyk/XykMath.d.ts +12 -0
  31. package/build/types/pool/xyk/XykPool.d.ts +23 -0
  32. package/build/types/pool/xyk/XykPoolClient.d.ts +12 -0
  33. package/build/types/pool/xyk/index.d.ts +3 -0
  34. package/build/types/sor/Router.d.ts +66 -0
  35. package/build/types/sor/TradeRouter.d.ts +155 -0
  36. package/build/types/sor/TradeUtils.d.ts +12 -0
  37. package/build/types/sor/index.d.ts +4 -0
  38. package/build/types/sor/route/bfs.d.ts +37 -0
  39. package/build/types/sor/route/graph.d.ts +12 -0
  40. package/build/types/sor/route/index.d.ts +3 -0
  41. package/build/types/sor/route/suggester.d.ts +24 -0
  42. package/build/types/sor/types.d.ts +31 -0
  43. package/build/types/types.d.ts +40 -0
  44. package/build/types/utils/Queue.d.ts +13 -0
  45. package/build/types/utils/Stack.d.ts +15 -0
  46. package/build/types/utils/big.d.ts +3 -0
  47. package/build/types/utils/evm.d.ts +3 -0
  48. package/build/types/utils/format.d.ts +4 -0
  49. package/build/types/utils/index.d.ts +6 -0
  50. package/build/types/utils/json.d.ts +3 -0
  51. package/build/types/utils/math.d.ts +62 -0
  52. package/build/types/utils/traversal/bfs.d.ts +27 -0
  53. package/build/types/utils/xc.d.ts +1 -0
  54. package/package.json +53 -0
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # Galactic SDK Next
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@galacticcouncil/sdk-next.svg)](https://www.npmjs.com/package/@galacticcouncil/sdk-next)
4
+
5
+ Next gen hydration sdk build on top of [Polkadot API (Papi)](https://papi.how/).
6
+
7
+ Table of content:
8
+
9
+ - [Installation](#installation)
10
+ - [Components](#components)
11
+ - [PoolContextProvider](#poolcontextprovider)
12
+ - [Router](#router)
13
+ - [TradeRouter](#traderouter)
14
+
15
+ ## Installation
16
+
17
+ Install with [npm](https://www.npmjs.com/):
18
+
19
+ `npm install @galacticcouncil/sdk-next`
20
+
21
+ ## Components
22
+
23
+ ### Pool
24
+
25
+ #### PoolContextProvider
26
+
27
+ Builds and maintains the pool context, handling subscriptions to pool changes.
28
+
29
+ ##### Usage
30
+
31
+ Subscribe to desired AMMs. Only one `ctx` instance should exist!
32
+
33
+ ```typescript
34
+ import { api, pool } from '@galacticcouncil/sdk-next';
35
+
36
+ const client = await api.getWs('wss://rpc.hydradx.cloud');
37
+ const ctx = new pool.PoolContextProvider(client)
38
+ .withOmnipool()
39
+ .withStableswap()
40
+ .withXyk();
41
+
42
+ const pools = await ctx.getPools();
43
+ console.log(pools);
44
+
45
+ // Don't forget to cleanup the resources
46
+ ctx.destroy();
47
+ client.destroy();
48
+ ```
49
+
50
+ ➡️ For type definitions visit [types.ts](src/pool/types.ts)<br />
51
+
52
+ ### SOR
53
+
54
+ #### Router
55
+
56
+ Off-chain routing, build to find the most suitable routes across the pools. Building block for `TradeRouter`.
57
+
58
+ ##### API Reference
59
+
60
+ | Method | Description |
61
+ | :----- | :----------- |
62
+ | `getPools(): PoolBase[]` | Returns the current list of available pools. |
63
+ | `getRoutes(assetIn: number, assetOut: number): Hop[][]` | Computes possible routes between two assets. |
64
+ | `getTradeableAssets(): number[]` | Lists all assets that are tradeable through the router. |
65
+
66
+ #### TradeRouter
67
+
68
+ Off-chain optimization of orders across pools for best price execution. TradeRouter does not perform any on-chain transations.
69
+
70
+ ##### API Reference
71
+
72
+ | Method | Description |
73
+ | :----- | :----------- |
74
+ | `getBestSell(tokenIn: number, tokenOut: number, amountIn: bigint \| string): Trade` | Find the best sell trade for given input amount. |
75
+ | `getBestBuy(tokenIn: number, tokenOut: number, amountOut: bigint \| string): Trade` | Find the best buy trade for given output amount. |
76
+ | `getBuy(tokenIn: number, tokenOut: number, amountOut: bigint \| string, route?: Hop[]): Trade` | Execute a buy using a specified route (optional). |
77
+ | `getSell(tokenIn: number, tokenOut: number, amountIn: bigint \| string, route?: Hop[]): Trade` | Execute a sell using a specified route (optional). |
78
+ | `getSpotPrice(tokenIn: number, tokenOut: number): Amount` | Get the current spot price between two tokens. |
79
+ | `getMostLiquidRoute(tokenIn: number, tokenOut: number): Hop[]` | Find the route with the highest liquidity between two tokens. |
80
+
81
+ ##### Usage
82
+
83
+ Calculate sell of 1 DOT for HDX. For convenience, the router amount can be specified either as a native bigint or as a human-readable string.
84
+
85
+ For example, `"1"` DOT (string) is equivalent to `10_000_000_000n` (bigint), as DOT has 10 decimals.
86
+
87
+ ```typescript
88
+ import { api, pool, sor } from '@galacticcouncil/sdk-next';
89
+
90
+ const client = await api.getWs('wss://rpc.hydradx.cloud');
91
+ const ctx = new pool.PoolContextProvider(client)
92
+ .withOmnipool()
93
+ .withStableswap()
94
+ .withXyk();
95
+
96
+ const router = new sor.TradeRouter(ctx);
97
+ const utils = new sor.TradeUtils(client);
98
+
99
+ const sell = await router.getBestSell(5, 0, 10_000_000_000n);
100
+ const tx = await utils.buildSellTx(sell);
101
+ console.log(sell.toHuman());
102
+ console.log('Transaction hash: ' + tx.asHex());
103
+
104
+ // Don't forget to cleanup the resources
105
+ ctx.destroy();
106
+ client.destroy();
107
+ ```
108
+
109
+ ➡️ For type definitions visit [types.ts](src/sor/types.ts)<br />
110
+
111
+ ### Client
112
+
113
+ #### BalanceClient
114
+
115
+ Subscribe to the balance of the Hydration account.
116
+
117
+ ```typescript
118
+ import { api, client as c } from '@galacticcouncil/sdk-next';
119
+
120
+ const omnipoolAddress = "7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1"
121
+
122
+ const client = await api.getWs('wss://rpc.hydradx.cloud');
123
+ const balanceClient = new c.BalanceClient(client);
124
+ const observable = balanceClient.subscribeBalance(omnipoolAddress);
125
+ const balances = firstValueFrom(observable);
126
+ console.log(balances);
127
+
128
+ // Don't forget to cleanup the resources
129
+ ctx.destroy();
130
+ client.destroy();
131
+ ```
132
+
133
+ ## Examples
134
+
135
+ SDK Examples and testing helpers.
136
+
137
+ ### Run
138
+
139
+ Run: `$ npx tsx ./test/script/examples/<examplePackage>/<exampleName>.ts` with valid example package & name.
140
+
141
+ To demonstrate full working examples on real chain see [script](test/script/examples) section.
@@ -0,0 +1 @@
1
+ "use strict";var ce=Object.create;var ft=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var Ut=(u,t)=>()=>(u&&(t=u(u=0)),t);var A=(u,t)=>{for(var e in t)ft(u,e,{get:t[e],enumerable:!0})},yt=(u,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of me(t))!ge.call(u,i)&&i!==e&&ft(u,i,{get:()=>t[i],enumerable:!(s=ue(t,i))||s.enumerable});return u},U=(u,t,e)=>(yt(u,t,"default"),e&&yt(e,t,"default")),_t=(u,t,e)=>(e=u!=null?ce(pe(u)):{},yt(t||!u||!u.__esModule?ft(e,"default",{value:u,enumerable:!0}):e,u)),de=u=>yt(ft({},"__esModule",{value:!0}),u);var it={};var zt=Ut(()=>{U(it,require("@polkadot-api/ws-provider/node"))});var nt={};var Kt=Ut(()=>{U(nt,require("@polkadot-api/ws-provider/web"))});var qe={};A(qe,{api:()=>Rt,big:()=>h,client:()=>Lt,const:()=>Et,error:()=>Dt,evm:()=>Ct,fmt:()=>d,json:()=>Z,math:()=>w,pool:()=>Xt,sor:()=>jt,xc:()=>qt});module.exports=de(qe);var Rt={};A(Rt,{Papi:()=>L,getWs:()=>be});var Qt=require("polkadot-api"),Jt=require("polkadot-api/polkadot-sdk-compat"),be=async u=>{let t=typeof u=="string"?u.split(","):u,i=(typeof window>"u"?(await Promise.resolve().then(()=>(zt(),it))).getWsProvider:(await Promise.resolve().then(()=>(Kt(),nt))).getWsProvider)(t);return(0,Qt.createClient)((0,Jt.withPolkadotSdkCompat)(i))};var $t=require("@galacticcouncil/descriptors"),L=class{client;constructor(t){this.client=t}get api(){return this.client.getTypedApi($t.hydration)}logSync(t,e,s){let i=t.substring(0,10).concat("..."),n=["\u{1F504} Sync",e,"[",i,"]",s].join(" ");console.log(n)}};var Lt={};A(Lt,{AssetClient:()=>St,BalanceClient:()=>J});var St=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:s})=>{let{asset_type:i}=s;return this.SUPPORTED_TYPES.includes(i.type)}).map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async mapToken(t,e,s,i){let{name:n,asset_type:a,is_sufficient:o,existential_deposit:r}=e,{symbol:l,decimals:c}=s.get(t)??{};return{id:t,name:n?.asText(),symbol:l,decimals:c,icon:l,type:a.type,isSufficient:o,location:i,existentialDeposit:r}}async mapBond(t,e,s,i){let[n,a]=i,{asset_type:o,is_sufficient:r,existential_deposit:l}=e,{symbol:c,decimals:g}=await this.mapToken(n,e,s),m=Number(a),p=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",p.format(m)].join(" ");return{id:t,name:b,symbol:c+"b",decimals:g,icon:c,type:o.type,isSufficient:r,existentialDeposit:l,underlyingAssetId:n,maturity:m}}async mapShares(t,e,s,i){let{assets:n}=i,{name:a,symbol:o,asset_type:r,is_sufficient:l,existential_deposit:c}=e,g=await Promise.all(n.map(async b=>{let{symbol:x}=await this.mapToken(b,e,s);return[b,x]})),m=Object.fromEntries(g),p=Object.values(m);return{id:t,name:p.join(", "),symbol:o?.asText()||a?.asText(),decimals:18,icon:p.join("/"),type:r.type,isSufficient:l,existentialDeposit:c,meta:m}}async mapExternal(t,e,s,i){let n=await this.mapToken(t,e,new Map,i),a=s?.find(o=>o.internalId===n.id);return a?{...n,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:n}parseMetadata(t){return new Map(Array.from(t,([e,s])=>[e,{symbol:s.symbol?.asText(),decimals:s.decimals}]))}async getOnChainAssets(t,e){let[s,i,n,a]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),o=this.parseMetadata(s),r=[];for(let[l,c]of Array.from(s)){let g=i.get(l),{asset_type:m}=c,p;switch(m.type){case"Bond":let b=a.get(l);p=await this.mapBond(l,c,o,b);break;case"StableSwap":let x=n.get(l);p=await this.mapShares(l,c,o,x);break;case"External":p=await this.mapExternal(l,c,e,g);break;default:p=await this.mapToken(l,c,o,g)}r.push(p)}return t?r:r.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var f=require("rxjs");var Et={};A(Et,{HUB_ASSET_ID:()=>kt,HYDRATION_OMNIPOOL_ADDRESS:()=>ye,HYDRATION_PARACHAIN_ID:()=>he,HYDRATION_SS58_PREFIX:()=>X,RUNTIME_DECIMALS:()=>k,SYSTEM_ASSET_DECIMALS:()=>Pe,SYSTEM_ASSET_ID:()=>z,TRADEABLE_DEFAULT:()=>K});var k=18,z=0,Pe=12,he=2034,X=63,ye="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",kt=1,K=15;var Dt={};A(Dt,{AssetNotFound:()=>ot,PoolNotFound:()=>at,RouteNotFound:()=>Q});var ot=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},at=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Q=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var J=class extends L{constructor(t){super(t)}async getBalance(t,e){let i=await this.api.query.AssetRegistry.Assets.getValue(e);if(!i)throw new ot(e);return i.asset_type.type==="Erc20"?this.getErc20Balance(t,e):e===0?this.getSystemBalance(t):this.getTokenBalance(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:s,frozen:i}}=await e.getValue(t);return s-i}async getTokenBalance(t,e){let s=this.api.query.Tokens.Accounts,{free:i,frozen:n}=await s.getValue(t,e);return i-n}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),s=this.subscribeTokensBalance(t),i=this.subscribeErc20Balance(t);return(0,f.combineLatest)([e,s,i]).pipe((0,f.debounceTime)(250),(0,f.map)(n=>n.flat()))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,f.map)(s=>{let{free:i,frozen:n}=s.data;return{id:0,amount:i-n}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,f.map)(i=>{let{free:n,frozen:a}=i;return{id:e,amount:n-a}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,f.distinctUntilChanged)((s,i)=>!i.deltas),(0,f.map)(({deltas:s})=>{let i=[];return s?.deleted.forEach(n=>{let[a,o]=n.args;i.push({id:o,amount:0n})}),s?.upserted.forEach(n=>{let[a,o]=n.args,{free:r,frozen:l}=n.value;i.push({id:o,amount:r-l})}),i}))}subscribeErc20Balance(t,e){let s=new f.Subject,i=s.pipe((0,f.shareReplay)(1)),n=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),a=async()=>{let r=e||await n(),l=async()=>{let m=(await Promise.all(r.map(async p=>{let b=await this.getTokenBalanceData(t,p);return[p,b]}))).map(([p,b])=>({id:p,amount:b}));s.next(m)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},o;return a().then(r=>o=r),i.pipe((0,f.finalize)(()=>o?.()),(0,f.pairwise)(),(0,f.map)(([r,l],c)=>{if(c===0)return l;let g=r.reduce((p,b)=>(p.set(b.id,b.amount),p),new Map);return l.filter(p=>p.amount!==g.get(p.id))}),(0,f.distinctUntilChanged)((r,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:s,frozen:i}=await this.api.apis.CurrenciesApi.account(e,t);return s-i}};var Xt={};A(Xt,{PoolContextProvider:()=>wt,PoolError:()=>$,PoolFactory:()=>et,PoolType:()=>_,lbp:()=>Nt,omni:()=>Gt,stable:()=>Ht,xyk:()=>Wt});var Nt={};A(Nt,{LbpMath:()=>M,LbpPool:()=>rt,LbpPoolClient:()=>lt});var C=require("@galacticcouncil/math-lbp"),M=class{static getSpotPrice(t,e,s,i,n){return(0,C.get_spot_price)(t,e,s,i,n)}static calculateInGivenOut(t,e,s,i,n){return(0,C.calculate_in_given_out)(t,e,s,i,n)}static calculateOutGivenIn(t,e,s,i,n){return(0,C.calculate_out_given_in)(t,e,s,i,n)}static calculateLinearWeights(t,e,s,i,n){return(0,C.calculate_linear_weights)(t,e,s,i,n)}static calculatePoolTradeFee(t,e,s){return(0,C.calculate_pool_trade_fee)(t,e,s)}};var _=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n))(_||{}),$=(n=>(n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n.UnknownError="UnknownError",n))($||{});var h={};A(h,{toBigInt:()=>Se,toDecimal:()=>fe});var Y=_t(require("big.js"));Y.default.NE=-18;function fe(u,t,e=6,s){let i=(0,Y.default)(u.toString()),n=(0,Y.default)(10).pow(t);return i.div(n).round(e,s).toString()}function Se(u,t){let e=(0,Y.default)(10).pow(t),i=(0,Y.default)(u).mul(e).toFixed(0,Y.default.roundDown);return BigInt(i)}var Ct={};A(Ct,{convertFromH160:()=>Ie,convertToH160:()=>Oe,isEvmAccount:()=>xe});var It=require("polkadot-api"),Zt=require("@polkadot-api/utils"),G=require("buffer");var Mt="ETH\0";function Ie(u,t=63){let e=G.Buffer.from(u.slice(2),"hex"),s=G.Buffer.from(Mt),i=Uint8Array.from(G.Buffer.concat([s,e,G.Buffer.alloc(8)])),n=(0,Zt.toHex)(i);return(0,It.AccountId)(t).dec(n)}function Oe(u){let t=(0,It.AccountId)().enc(u),e=G.Buffer.from(Mt),s=t.slice(e.length,-8);return"0x"+G.Buffer.from(s).toString("hex")}function xe(u){if(!u)return!1;try{let t=(0,It.AccountId)().enc(u),e=G.Buffer.from(Mt);return G.Buffer.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}var d={};A(d,{fromPermill:()=>Ae,toDecimals:()=>ve,toPct:()=>we});var te=1e3;function we(u){let[t,e]=u;return t/e*100}function ve(u){let[t,e]=u;return t/e}function Ae(u){return[u/te,te]}var Z={};A(Z,{findNestedKey:()=>Te,findNestedObj:()=>Be,jsonFormatter:()=>Fe});var Te=(u,t)=>{let e=[];return JSON.stringify(u,(s,i)=>(i&&i[t]&&e.push(i),i)),e[0]},Be=(u,t,e)=>{let s;return JSON.stringify(u,(i,n)=>(n&&n[t]===e&&(s=n),n)),s},Fe=(u,t)=>typeof t=="bigint"?t.toString():t;var w={};A(w,{calculateBuyFee:()=>Ee,calculateDiffToAvg:()=>_e,calculateDiffToRef:()=>Re,calculateSellFee:()=>ke,getFraction:()=>De});var q=_t(require("big.js"));function _e(u,t){let e=(0,q.default)(u.toString()),s=(0,q.default)(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function Re(u,t){let e=(0,q.default)(u.toString()),s=(0,q.default)(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function ke(u,t){let e=(0,q.default)(u.toString()),s=(0,q.default)(t.toString());return(0,q.default)(1).minus(s.div(e)).mul(100).round(2).toNumber()}function Ee(u,t){let e=(0,q.default)(u.toString());return(0,q.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function De(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let s=Math.pow(10,e),i=BigInt(t*s);return u*i/BigInt(100*s)}var qt={};A(qt,{convertToId:()=>Le});var ee=require("buffer");function Le(u){let e=ee.Buffer.from(u.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var rt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,s,i,n,a,o){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.fee=a,this.repayFeeApply=o}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:n.balance,decimalsIn:i.decimals,decimalsOut:n.decimals,weightIn:i.weight,weightOut:n.weight}}validateAndBuy(t,e,s){let i=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&n.push("MaxOutRatioExceeded"),i===t.assetOut){let o=this.calculateTradeFee(e,s),r=d.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+o,c=this.calculateInGivenOut(t,l),g=t.balanceIn/this.maxInRatio;return c>g&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:r,errors:n}}else{let o=this.calculateInGivenOut(t,e),r=t.balanceIn/this.maxInRatio;return o>r&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,s){let i=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&n.push("MaxInRatioExceeded"),i===t.assetIn){let o=this.calculateOutGivenIn(t,e),r=t.balanceOut/this.maxOutRatio;return o>r&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(o,s),l=d.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o-r,g=t.balanceOut/this.maxOutRatio;return c>g&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(t,e){let s=M.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}calculateOutGivenIn(t,e){let s=M.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}spotPriceInGivenOut(t){let e=M.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=M.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let s=M.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(s)}};var ie=require("polkadot-api"),V=require("rxjs");var se=(u,t=new Map)=>e=>{let s;return t.has(e)?t.get(e):(t.set(e,s=u(e)),s)};var I=require("rxjs");var N=class extends J{override=[];mem=0;memPools=se(t=>(console.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=(0,I.from)(this.getPoolsMem()).pipe((0,I.switchMap)(e=>this.subscribe(e)),(0,I.combineLatestAll)());return(0,I.firstValueFrom)(t)}getSubscriber(){return(0,I.from)(this.getPoolsMem()).pipe((0,I.switchMap)(t=>this.subscribe(t)),(0,I.mergeAll)())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>(0,I.combineLatest)([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe((0,I.debounceTime)(250),(0,I.map)(([s,i])=>this.updatePool(s,i))))}subscribePoolBalance(t){let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let s=this.subscribeSystemBalance(t.address);e.push(s)}if(this.hasErc20Asset(t)){let s=t.tokens.filter(n=>n.type==="Erc20").map(n=>n.id),i=this.subscribeErc20Balance(t.address,s);e.push(i)}return(0,I.combineLatest)(e).pipe((0,I.map)(s=>s.map(i=>Array.isArray(i)?i:[i]).flat()))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({id:e,decimals:s,balance:i})=>{let n=this.override.find(o=>o.id===e),a=!!s||!!n?.decimals;return i>0n&&a})}updatePool=(t,e)=>{let s=t.tokens.map(i=>{let n=e.find(o=>o.id===i.id),a=this.override.find(o=>o.id===i.id);return n?{...i,balance:n.amount,decimals:i.decimals||a?.decimals}:{...i,decimals:i.decimals||a?.decimals}});return{...t,tokens:s}}};var lt=class extends N{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,s]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),i=e?.relay_parent_number||0,n=t.filter(({value:a})=>e&&this.isActivePool(a,i)).map(async({keyArgs:a,value:o})=>{let[r]=a,l=r.toString(),c=await this.getPoolDelta(l,o,i);return{address:l,type:"LBP",fee:o.fee,...c,...s}});return Promise.all(n)}async getPoolDelta(t,e,s){let{start:i,end:n,assets:a,initial_weight:o,final_weight:r,repay_target:l,fee_collector:c}=e,g=M.calculateLinearWeights(i?i.toString():"0",n?n.toString():"0",o.toString(),r.toString(),s.toString()),[m,p]=a,b=BigInt(g),x=this.MAX_FINAL_WEIGHT-BigInt(b),[v,R,B,F,D]=await Promise.all([this.isRepayFeeApplied(m,l,c.toString()),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:v,tokens:[{id:m,decimals:B?.decimals,existentialDeposit:B?.existential_deposit,balance:R,weight:b,type:B?.asset_type.type},{id:p,decimals:D?.decimals,existentialDeposit:D?.existential_deposit,balance:F,weight:x,type:D?.asset_type.type}]}}isActivePool(t,e){let{start:s,end:i}=t;return s&&i?e>=s&&e<i:!1}async isRepayFeeApplied(t,e,s){if(e===0n)return!1;try{return await this.getBalance(s,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(ie.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,s=this.poolsData.get(t.address);return s?e.watchValue("best").pipe((0,V.switchMap)(i=>i?this.getPoolDelta(t.address,s,i.relay_parent_number):(0,V.of)(t)),(0,V.map)(i=>Object.assign({},t,i))):(0,V.of)(t)}};var Gt={};A(Gt,{OmniMath:()=>S,OmniPool:()=>ct,OmniPoolClient:()=>mt});var P=require("@galacticcouncil/math-omnipool"),j=_t(require("big.js")),S=class{static calculateSpotPrice(t,e,s,i){return(0,P.calculate_spot_price)(t,e,s,i)}static calculateLrnaSpotPrice(t,e){return(0,P.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,s,i,n,a,o,r,l){return(0,P.calculate_in_given_out)(t,e,s,i,n,a,o,r,l)}static calculateLrnaInGivenOut(t,e,s,i,n){return(0,P.calculate_lrna_in_given_out)(t,e,s,i,n)}static calculateOutGivenIn(t,e,s,i,n,a,o,r,l){return(0,P.calculate_out_given_in)(t,e,s,i,n,a,o,r,l)}static calculateOutGivenLrnaIn(t,e,s,i,n){return(0,P.calculate_out_given_lrna_in)(t,e,s,i,n)}static calculatePoolTradeFee(t,e,s){return(0,P.calculate_pool_trade_fee)(t,e,s)}static calculateShares(t,e,s,i){return(0,P.calculate_shares)(t,e,s,i)}static calculateLiquidityOut(t,e,s,i,n,a,o,r){return(0,P.calculate_liquidity_out)(t,e,s,i,n,a,o,r)}static calculateLiquidityLRNAOut(t,e,s,i,n,a,o,r){return(0,P.calculate_liquidity_lrna_out)(t,e,s,i,n,a,o,r)}static calculateCapDifference(t,e,s,i){let n=(0,j.default)(e),a=(0,j.default)(t),o=(0,j.default)(i),r=(0,j.default)(s),l=(0,j.default)(10).pow(18),c=r.div(l);if(n.div(o).lt(c)){let m=c.times(o).minus(n).times(a),p=n.times((0,j.default)(1).minus(c));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,s,i){return(0,P.verify_asset_cap)(t,e,s,i)}static calculateLimitHubIn(t,e,s,i){return(0,P.calculate_liquidity_hub_in)(t,e,s,i)}static isSellAllowed(t){return(0,P.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,P.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,P.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,P.is_remove_liquidity_allowed)(t)}};var ct=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,s,i,n,a){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.hubAssetId=a}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:i.hubReserves,hubReservesOut:n.hubReserves,sharesIn:i.shares,sharesOut:n.shares,decimalsIn:i.decimals,decimalsOut:n.decimals,balanceIn:i.balance,balanceOut:n.balance,tradeableIn:i.tradeable,tradeableOut:n.tradeable,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,s),a=i===0n?0:w.calculateDiffToRef(n,i),o=[],r=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&o.push("MaxOutRatioExceeded");let g=t.balanceIn/this.maxInRatio;return n>g&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:i,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,s),a=w.calculateDiffToRef(i,n),o=[],r=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&o.push("MaxInRatioExceeded");let g=t.balanceOut/this.maxOutRatio;return n>g&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:n,feePct:a,errors:o}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let i=S.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0",s?d.toDecimals(s.protocolFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,s){let i=S.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let i=S.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0",s?d.toDecimals(s.protocolFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,s){let i=S.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=S.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceLrnaInGivenOut(t){let e=S.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=S.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}spotPriceOutGivenLrnaIn(t){let e=S.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}};var Ot=require("polkadot-api"),ne=require("@polkadot-api/utils"),ut=require("rxjs");var mt=class extends N{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[s,i,n,a,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),r=s.map(async({keyArgs:c,value:g})=>{let[m]=c,{hub_reserve:p,shares:b,tradable:x,cap:v,protocol_shares:R}=g,[B,F]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:B?.decimals,existentialDeposit:B?.existential_deposit,balance:F,cap:v,hubReserves:p,protocolShares:R,shares:b,tradeable:x,type:B?.asset_type.type}}),l=await Promise.all(r);return l.push({id:t,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:a,tradeable:i,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...o}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),s=(0,ne.toHex)(e);return(0,Ot.AccountId)(63).dec(s)}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(t,e){let[s,i,n]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),a=s.min_fee+i.min_fee,o=s.max_fee+i.max_fee;if(n){let{asset_fee:r,protocol_fee:l}=n;return{assetFee:d.fromPermill(r),protocolFee:d.fromPermill(l),min:d.fromPermill(a),max:d.fromPermill(o)}}else return{assetFee:d.fromPermill(s.min_fee),protocolFee:d.fromPermill(i.min_fee),min:d.fromPermill(a),max:d.fromPermill(o)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Ot.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,ut.distinctUntilChanged)((s,i)=>!i.deltas),(0,ut.map)(({entries:s})=>s.map(i=>{let[n]=i.args,{hub_reserve:a,shares:o,tradable:r,cap:l,protocol_shares:c}=i.value,g=t.tokens.findIndex(p=>p.id===n);return{...t.tokens[g],cap:l,hubReserves:a,protocolShares:c,shares:o,tradeable:r}})),(0,ut.map)(s=>{let i=t.tokens.find(n=>n.id===1);return{...t,tokens:[...s,i]}}))}};var Ht={};A(Ht,{StableMath:()=>T,StableSwap:()=>pt,StableSwapClient:()=>gt});var y=require("@galacticcouncil/math-stableswap"),T=class{static getPoolAddress(t){return(0,y.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let s=0;s<t;s++)e.push(["1","1"]);return e}static calculateAmplification(t,e,s,i,n){return(0,y.calculate_amplification)(t,e,s,i,n)}static calculateInGivenOut(t,e,s,i,n,a,o){return(0,y.calculate_in_given_out)(t,e,s,i,n,a,o)}static calculateAddOneAsset(t,e,s,i,n,a,o){return(0,y.calculate_add_one_asset)(t,e,s,i,n,a,o)}static calculateSharesForAmount(t,e,s,i,n,a,o){return(0,y.calculate_shares_for_amount)(t,e,s,i,n,a,o)}static calculateOutGivenIn(t,e,s,i,n,a,o){return(0,y.calculate_out_given_in)(t,e,s,i,n,a,o)}static calculateLiquidityOutOneAsset(t,e,s,i,n,a,o){return(0,y.calculate_liquidity_out_one_asset)(t,e,s,i,n,a,o)}static calculateShares(t,e,s,i,n,a){return(0,y.calculate_shares)(t,e,s,i,n,a)}static calculateSpotPriceWithFee(t,e,s,i,n,a,o,r){return(0,y.calculate_spot_price_with_fee)(t,e,s,i,n,a,o,r)}static calculatePoolTradeFee(t,e,s){return(0,y.calculate_pool_trade_fee)(t,e,s)}static recalculatePegs(t,e,s,i,n){return(0,y.recalculate_peg)(t,e,s,i,n)}};var pt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,s,i,n,a,o,r,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.amplification=a,this.id=o,this.fee=r,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:n.balance,decimalsIn:i.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:i.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,s),a=d.toPct(s.fee),o=[],r=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:i,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,s),a=d.toPct(s.fee),o=[],r=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:i,amountOut:n,feePct:a,errors:o}}calculateIn(t,e,s){let i=T.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateAddOneAsset(t,e,s){let i=T.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateSharesForAmount(t,e,s){let i=T.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateInGivenOut(t,e,s){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,s):t.assetIn==this.id?this.calculateSharesForAmount(t,e,s):this.calculateIn(t,e,s)}spotPriceInGivenOut(t){let e=T.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let i=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(i)}let s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateOut(t,e,s){let i=T.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,s){let i=T.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateShares(t,e,s){let i=T.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e,s){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,s):t.assetOut==this.id?this.calculateShares(t,e,s):this.calculateOut(t,e,s)}spotPriceOutGivenIn(t){let e=T.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let i=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(i)}let s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let[s,i]=e.fee,n=T.calculatePoolTradeFee(t.toString(),s,i);return BigInt(n)}getPegs(){let t=T.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:s,decimals:i})=>({asset_id:e,amount:s,decimals:i}));return JSON.stringify(t,Z.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],Z.jsonFormatter)}};var xt=require("polkadot-api"),oe=require("@polkadot-api/utils"),ae=require("@noble/hashes/blake2b"),tt=require("rxjs");var Me=340282366920938463463374607431768211455n,gt=class extends N{poolsData=new Map([]);async loadPools(){let[t,e,s]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),i=t.map(async({keyArgs:n,value:a})=>{let[o]=n,r=this.getPoolAddress(o),[l,c]=await Promise.all([this.getPoolDelta(o,a,e),this.getPoolTokens(o,a)]);return this.poolsData.set(r,a),{address:r,id:o,type:"Stableswap",fee:d.fromPermill(a.fee),tokens:c,...l,...s}});return Promise.all(i)}async getPoolDelta(t,e,s){let{initial_amplification:i,final_amplification:n,initial_block:a,final_block:o}=e,r=T.calculateAmplification(i.toString(),n.toString(),a.toString(),o.toString(),s.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(r),totalIssuance:l}}async getPoolTokens(t,e){let s=this.getPoolAddress(t),i=e.assets.map(async o=>{let[r,l,c]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(s,o)]);return{id:o,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:c,tradeable:r,type:l?.asset_type.type}}),n=await Promise.all(i),a=await this.api.query.AssetRegistry.Assets.getValue(t);return n.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:Me,tradeable:15,type:a?.asset_type.type}),n}getPoolAddress(t){let e=T.getPoolAddress(t),s=(0,ae.blake2b)(e,{dkLen:32}),i=(0,oe.toHex)(s);return(0,xt.AccountId)(63).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(xt.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,s=this.poolsData.get(t.address);return!s||!t.id?(0,tt.of)(t):e.watchValue("best").pipe((0,tt.switchMap)(i=>this.getPoolDelta(t.id,s,i)),(0,tt.map)(i=>Object.assign({},t,i)))}};var Wt={};A(Wt,{XykMath:()=>H,XykPool:()=>dt,XykPoolClient:()=>bt});var O=require("@galacticcouncil/math-xyk"),H=class{static getSpotPrice(t,e,s){return(0,O.get_spot_price)(t,e,s)}static calculateInGivenOut(t,e,s){return(0,O.calculate_in_given_out)(t,e,s)}static calculateOutGivenIn(t,e,s){return(0,O.calculate_out_given_in)(t,e,s)}static calculatePoolTradeFee(t,e,s){return(0,O.calculate_pool_trade_fee)(t,e,s)}static calculateLiquidityIn(t,e,s){return(0,O.calculate_liquidity_in)(t,e,s)}static calculateSpotPrice(t,e){return(0,O.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,s,i){return(0,O.calculate_spot_price_with_fee)(t,e,s,i)}static calculateShares(t,e,s){return(0,O.calculate_shares)(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,i){return(0,O.calculate_liquidity_out_asset_a)(t,e,s,i)}static calculateLiquidityOutAssetB(t,e,s,i){return(0,O.calculate_liquidity_out_asset_b)(t,e,s,i)}};var dt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,s,i,n){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:i.decimals,decimalsOut:n.decimals,balanceIn:i.balance,balanceOut:n.balance,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(i,s),a=d.toPct(s.exchangeFee),o=i+n,r=[];(e<this.minTradingLimit||i<t.assetInEd)&&r.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&r.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return o>c&&r.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:i,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(i,s),a=d.toPct(s.exchangeFee),o=i-n,r=[];(e<this.minTradingLimit||i<t.assetOutEd)&&r.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&r.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return o>c&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:o,feePct:a,errors:r}}calculateInGivenOut(t,e){let s=H.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}calculateOutGivenIn(t,e){let s=H.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}spotPriceInGivenOut(t){let e=H.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceOutGivenIn(t){let e=H.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let s=H.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}};var re=require("polkadot-api"),le=require("rxjs");var bt=class extends N{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,s]=await Promise.all([t.getEntries(),this.getPoolLimits()]),i=e.map(async({keyArgs:n,value:a})=>{let[o]=n,[r,l]=a,[c,g,m,p]=await Promise.all([this.getBalance(o,r),this.api.query.AssetRegistry.Assets.getValue(r),this.getBalance(o,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:o,type:"XYK",tokens:[{id:r,decimals:g?.decimals,existentialDeposit:g?.existential_deposit,balance:c,type:g?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...s}});return Promise.all(i)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(re.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return(0,le.of)(t)}};var et=class{static get(t){switch(t.type){case"XYK":return dt.fromPool(t);case"Omnipool":return ct.fromPool(t);case"LBP":return rt.fromPool(t);case"Stableswap":return pt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var E=require("rxjs");var wt=class extends L{lbpClient;omniClient;stableClient;xykClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=E.Subscription.EMPTY;omniSub=E.Subscription.EMPTY;stableSub=E.Subscription.EMPTY;xykSub=E.Subscription.EMPTY;isReady=!1;isDestroyed=new E.Subject;constructor(t){super(t),this.lbpClient=new lt(t),this.omniClient=new mt(t),this.stableClient=new gt(t),this.xykClient=new bt(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient]}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.omniClient.getSubscriber().pipe((0,E.takeUntil)(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.stableClient.getSubscriber().pipe((0,E.takeUntil)(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.lbpClient.getSubscriber().pipe((0,E.takeUntil)(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("LBP"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.xykClient.getSubscriber().pipe((0,E.takeUntil)(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)}),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let s=this.clients.find(i=>i.getPoolType()===t.type);if(s)return s.getPoolFees(t,e);throw new at(t.type)}};var jt={};A(jt,{Router:()=>st,TradeRouter:()=>Tt,TradeType:()=>At,TradeUtils:()=>Bt});var vt=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Ce=5,Pt=class{isNotVisited(t,e){let s=!0;return e.forEach(i=>{(i[0]===t[0]||i[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let i=[],n=new vt,a=[];for(a.push([e,""]),n.enqueue(a);n.size()>0;){let o=n.dequeue();if(o==null||o.length>Ce)return i;let r=o[o.length-1];(s===null||r[0]===s)&&i.push(o),t.get(r[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let g=[...o];g.push(c),n.enqueue(g)}})}return i}buildAndPopulateGraph(t,e){let s=new Map;for(let i of t)s.set(parseInt(i),[]);for(let[i,n,a]of e)s.get(n)?.push([a,i]);return s}};function Yt(u){let t={};for(let e of u){let s=e.tokens.length;for(let i=0;i<s;i++){t[e.tokens[i].id]||(t[e.tokens[i].id]=[]);for(let n=0;n<s;n++){if(i==n)continue;let a=[e.address,e.tokens[i].id,e.tokens[n].id];t[e.tokens[i].id].push(a)}}}return t}var ht=class{getProposals(t,e,s){let i=Yt(s),n=Object.keys(i),a=n.map(c=>i[c]).flat(),o=new Pt,r=o.buildAndPopulateGraph(n,a),l=o.findPaths(r,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let s of t){let i=[];for(let n=0;n<s.length;n++){let a=s[n],o=s[n+1];if(o==null)break;i.push(this.toEdge(a,o))}e.push(i)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var st=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new ht,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(s=>e.includes(s.type))}async getRoutes(t,e){let s=await this.getPools();return this.validateInput(t,e,s),this.getPaths(t,e,s)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,s){if(s.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let i=this.getAssets(s);if(!i.has(t))throw new Error(t+" is not supported asset");if(!i.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(i=>i.id)).flat().sort((s,i)=>s>i?1:-1);return new Set(e)}getPaths(t,e,s){let i=this.toPoolsMap(s);return this.routeSuggester.getProposals(t,e,s).filter(a=>this.validPath(a,i)).map(a=>this.toHops(a,i))}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,i)=>s&&i)}validEdge([t,e,s],i){return i.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,et.get(e)]))}toHops(t,e){return t.map(([s,i,n])=>{let a=e.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:i,assetOut:n}})}};var At=(e=>(e.Buy="Buy",e.Sell="Sell",e))(At||{});var Tt=class extends st{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,i)=>{let n=s[s.length-1].amountOut,a=i[i.length-1].amountOut;return n>a?-1:1});return e.find(s=>s.every(i=>i.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,a)=>n+a),i=t.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,a)=>n+a);return[s,i]}}getPoolFeeRange(t){let e=t.min?d.toPct(t.min):void 0,s=t.max?d.toPct(t.max):void 0;if(e&&s)return[e,s]}async getBestSell(t,e,s){return this.getSell(t,e,s)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let s=t.map(o=>o.assetOutDecimals).reduce((o,r)=>o+r),i=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),n=s-e.assetOutDecimals,a=Math.pow(10,n);return i/BigInt(a)}async getSell(t,e,s,i){let n=await super.getPools(),a=super.validateInput(t,e,n),o=super.getPaths(t,e,n);if(o.length===0)throw new Q(t,e);let r;if(i)r=await this.toSellSwaps(s,i,a);else{let W=await Promise.all(o.map(Ft=>this.toSellSwaps(s,Ft,a)));r=this.findBestSellRoute(W)}let l=r[0],c=r[r.length-1],g=this.isDirectTrade(r),m=await this.getSellSpot(r),p=c.amountOut,b=g?c.calculatedOut:this.calculateDelta0Y(l.amountIn,r,a),x=b-p,v=this.getRouteFeeRange(r),R=g?c.tradeFeePct:w.calculateSellFee(b,p),B=Math.pow(10,l.assetInDecimals),F=l.amountIn*m/BigInt(B),D=w.calculateDiffToRef(b,F);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:m,tradeFee:x,tradeFeePct:R,tradeFeeRange:v,priceImpactPct:D,swaps:r,toHuman(){return{type:"Sell",amountIn:h.toDecimal(l.amountIn,l.assetInDecimals),amountOut:h.toDecimal(c.amountOut,c.assetOutDecimals),spotPrice:h.toDecimal(m,c.assetOutDecimals),tradeFee:h.toDecimal(x,c.assetOutDecimals),tradeFeePct:R,tradeFeeRange:v,priceImpactPct:D,swaps:r.map(W=>W.toHuman())}}}}calculateDelta0Y(t,e,s){let i=[];for(let n=0;n<e.length;n++){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n>0?l=i[n-1]:l=t;let c=o.calculateOutGivenIn(r,l);i.push(c)}return i[i.length-1]}async toSellSwaps(t,e,s){let i=[];for(let n=0;n<e.length;n++){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n>0?l=i[n-1].amountOut:l=typeof t=="string"?h.toBigInt(t,r.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountOut:g,calculatedOut:m,feePct:p,errors:b}=o.validateAndSell(r,l,c),x=this.getPoolFeeRange(c),v=o.spotPriceOutGivenIn(r),R=Math.pow(10,r.decimalsIn),B=l*v/BigInt(R),F=w.calculateDiffToRef(m,B);i.push({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountIn:l,amountOut:g,calculatedOut:m,spotPrice:v,tradeFeePct:p,tradeFeeRange:x,priceImpactPct:F,errors:b,toHuman(){return{...a,amountIn:h.toDecimal(l,r.decimalsIn),amountOut:h.toDecimal(g,r.decimalsOut),calculatedOut:h.toDecimal(m,r.decimalsOut),spotPrice:h.toDecimal(v,r.decimalsOut),tradeFeePct:p,tradeFeeRange:x,priceImpactPct:F,errors:b}}})}return i}async getMostLiquidRoute(t,e){let s=await super.getPools(),i=super.validateInput(t,e,s),n=super.getPaths(t,e,s),r=s.filter(m=>m.tokens.some(p=>p.id===t&&p.id!==m.id)).map(m=>m.type==="Aave"?m.tokens:m.tokens.filter(p=>p.id===t)).map(m=>m.map(p=>p.balance).reduce((p,b)=>p+b)).sort((m,p)=>p<m?-1:1)[0],l=w.getFraction(r,.1),c=await Promise.all(n.map(m=>this.toSellSwaps(l,m,i)));return this.findBestSellRoute(c).map(m=>({poolAddress:m.poolAddress,poolId:m?.poolId,pool:m.pool,assetIn:m.assetIn,assetOut:m.assetOut}))}async getSpotPrice(t,e){let s=await super.getPools(),i=super.validateInput(t,e,s),n=await this.getMostLiquidRoute(t,e),a=await this.toSellSwaps("1",n,i),o=await this.getSellSpot(a),r=a[a.length-1].assetOutDecimals;return{amount:o,decimals:r}}findBestBuyRoute(t){let e=t.sort((s,i)=>{let n=s[0].amountIn,a=i[0].amountIn;return n>a?1:-1});return e.find(s=>s.every(i=>i.errors.length==0))||e[0]}async getBestBuy(t,e,s){return this.getBuy(t,e,s)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let s=t.map(o=>o.assetInDecimals).reduce((o,r)=>o+r),i=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),n=s-e.assetInDecimals,a=Math.pow(10,n);return i/BigInt(a)}async getBuy(t,e,s,i){let n=await super.getPools(),a=super.validateInput(t,e,n),o=super.getPaths(t,e,n);if(o.length===0)throw new Q(t,e);let r;if(i)r=await this.toBuySwaps(s,i,a);else{let W=await Promise.all(o.map(Ft=>this.toBuySwaps(s,Ft,a)));r=this.findBestBuyRoute(W)}let l=r[r.length-1],c=r[0],g=this.isDirectTrade(r),m=await this.getBuySpot(r),p=c.amountIn,b=g?c.calculatedIn:this.calculateDelta0X(l.amountOut,r,a),x=p-b,v=this.getRouteFeeRange(r),R=g?c.tradeFeePct:w.calculateBuyFee(b,p),B=Math.pow(10,l.assetOutDecimals),F=l.amountOut*m/BigInt(B),D;return b===0n?D=-100:D=w.calculateDiffToRef(F,b),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:m,tradeFee:x,tradeFeePct:R,tradeFeeRange:v,priceImpactPct:D,swaps:r,toHuman(){return{type:"Buy",amountOut:h.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:h.toDecimal(c.amountIn,c.assetInDecimals),spotPrice:h.toDecimal(m,c.assetInDecimals),tradeFee:h.toDecimal(x,c.assetInDecimals),tradeFeePct:R,tradeFeeRange:v,priceImpactPct:D,swaps:r.map(W=>W.toHuman())}}}}calculateDelta0X(t,e,s){let i=[];for(let n=e.length-1;n>=0;n--){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n==e.length-1?l=t:l=i[0];let c=o.calculateInGivenOut(r,l);i.unshift(c)}return i[0]}async toBuySwaps(t,e,s){let i=[];for(let n=e.length-1;n>=0;n--){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n==e.length-1?l=typeof t=="string"?h.toBigInt(t,r.decimalsOut):t:l=i[0].amountIn;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountIn:g,calculatedIn:m,feePct:p,errors:b}=o.validateAndBuy(r,l,c),x=this.getPoolFeeRange(c),v=o.spotPriceInGivenOut(r),R=Math.pow(10,r.decimalsOut),B=l*v/BigInt(R),F;m===0n?F=-100:F=w.calculateDiffToRef(B,m),i.unshift({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountOut:l,amountIn:g,calculatedIn:m,spotPrice:v,tradeFeePct:p,tradeFeeRange:x,priceImpactPct:F,errors:b,toHuman(){return{...a,amountOut:h.toDecimal(l,r.decimalsOut),amountIn:h.toDecimal(g,r.decimalsIn),calculatedIn:h.toDecimal(m,r.decimalsIn),spotPrice:h.toDecimal(v,r.decimalsIn),tradeFeePct:p,tradeFeeRange:x,priceImpactPct:F,errors:b}}})}return i}};var Vt=require("polkadot-api");var Bt=class extends L{constructor(t){super(t)}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}tradeCheck(t,e){if(e!==t.type)throw new Error("Not permitted")}async buildBuyTx(t,e=1){this.tradeCheck(t,"Buy");let{amountIn:s,amountOut:i,swaps:n}=t,a=n[0],o=n[n.length-1],r=w.getFraction(s,e),l=a.assetIn,c=o.assetOut,g=s+r;return this.isDirectOmnipoolTrade(n)?this.api.tx.Omnipool.buy({asset_in:l,asset_out:c,amount:i,max_sell_amount:g}).getEncodedData():this.api.tx.Router.buy({asset_in:l,asset_out:c,amount_out:i,max_amount_in:g,route:this.buildRoute(n)}).getEncodedData()}async buildSellTx(t,e=1){this.tradeCheck(t,"Sell");let{amountIn:s,amountOut:i,swaps:n}=t,a=n[0],o=n[n.length-1],r=w.getFraction(i,e),l=a.assetIn,c=o.assetOut,g=i-r;return this.isDirectOmnipoolTrade(n)?this.api.tx.Omnipool.sell({asset_in:l,asset_out:c,amount:s,min_buy_amount:g}).getEncodedData():this.api.tx.Router.sell({asset_in:l,asset_out:c,amount_in:s,min_amount_out:g,route:this.buildRoute(n)}).getEncodedData()}async buildSellAllTx(t,e=1){this.tradeCheck(t,"Sell");let{amountOut:s,swaps:i}=t,n=i[0],a=i[i.length-1],o=w.getFraction(s,e),r=n.assetIn,l=a.assetOut,c=s-o;return this.api.tx.Router.sell_all({asset_in:r,asset_out:l,min_amount_out:c,route:this.buildRoute(i)}).getEncodedData()}buildRoute(t){return t.map(({assetIn:e,assetOut:s,pool:i,poolId:n})=>i==="Stableswap"?{pool:(0,Vt.Enum)("Stableswap",n),asset_in:e,asset_out:s}:{pool:(0,Vt.Enum)(i),asset_in:e,asset_out:s})}};0&&(module.exports={api,big,client,const:null,error,evm,fmt,json,math,pool,sor,xc});
@@ -0,0 +1 @@
1
+ var Gt=Object.defineProperty;var O=(u,t)=>{for(var e in t)Gt(u,e,{get:t[e],enumerable:!0})};var xt={};O(xt,{Papi:()=>F,getWs:()=>Xt});import{createClient as Ht}from"polkadot-api";import{withPolkadotSdkCompat as Wt}from"polkadot-api/polkadot-sdk-compat";var Xt=async u=>{let t=typeof u=="string"?u.split(","):u,i=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return Ht(Wt(i))};import{hydration as Yt}from"@galacticcouncil/descriptors";var F=class{client;constructor(t){this.client=t}get api(){return this.client.getTypedApi(Yt)}logSync(t,e,s){let i=t.substring(0,10).concat("..."),n=["\u{1F504} Sync",e,"[",i,"]",s].join(" ");console.log(n)}};var Tt={};O(Tt,{AssetClient:()=>at,BalanceClient:()=>G});var at=class extends F{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:s})=>{let{asset_type:i}=s;return this.SUPPORTED_TYPES.includes(i.type)}).map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async mapToken(t,e,s,i){let{name:n,asset_type:a,is_sufficient:o,existential_deposit:r}=e,{symbol:l,decimals:c}=s.get(t)??{};return{id:t,name:n?.asText(),symbol:l,decimals:c,icon:l,type:a.type,isSufficient:o,location:i,existentialDeposit:r}}async mapBond(t,e,s,i){let[n,a]=i,{asset_type:o,is_sufficient:r,existential_deposit:l}=e,{symbol:c,decimals:g}=await this.mapToken(n,e,s),m=Number(a),p=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",p.format(m)].join(" ");return{id:t,name:b,symbol:c+"b",decimals:g,icon:c,type:o.type,isSufficient:r,existentialDeposit:l,underlyingAssetId:n,maturity:m}}async mapShares(t,e,s,i){let{assets:n}=i,{name:a,symbol:o,asset_type:r,is_sufficient:l,existential_deposit:c}=e,g=await Promise.all(n.map(async b=>{let{symbol:y}=await this.mapToken(b,e,s);return[b,y]})),m=Object.fromEntries(g),p=Object.values(m);return{id:t,name:p.join(", "),symbol:o?.asText()||a?.asText(),decimals:18,icon:p.join("/"),type:r.type,isSufficient:l,existentialDeposit:c,meta:m}}async mapExternal(t,e,s,i){let n=await this.mapToken(t,e,new Map,i),a=s?.find(o=>o.internalId===n.id);return a?{...n,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:n}parseMetadata(t){return new Map(Array.from(t,([e,s])=>[e,{symbol:s.symbol?.asText(),decimals:s.decimals}]))}async getOnChainAssets(t,e){let[s,i,n,a]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),o=this.parseMetadata(s),r=[];for(let[l,c]of Array.from(s)){let g=i.get(l),{asset_type:m}=c,p;switch(m.type){case"Bond":let b=a.get(l);p=await this.mapBond(l,c,o,b);break;case"StableSwap":let y=n.get(l);p=await this.mapShares(l,c,o,y);break;case"External":p=await this.mapExternal(l,c,e,g);break;default:p=await this.mapToken(l,c,o,g)}r.push(p)}return t?r:r.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};import{Subject as zt,combineLatest as Kt,debounceTime as Qt,distinctUntilChanged as At,finalize as Jt,map as z,pairwise as $t,shareReplay as Zt}from"rxjs";var wt={};O(wt,{HUB_ASSET_ID:()=>bt,HYDRATION_OMNIPOOL_ADDRESS:()=>Ut,HYDRATION_PARACHAIN_ID:()=>jt,HYDRATION_SS58_PREFIX:()=>M,RUNTIME_DECIMALS:()=>T,SYSTEM_ASSET_DECIMALS:()=>Vt,SYSTEM_ASSET_ID:()=>C,TRADEABLE_DEFAULT:()=>q});var T=18,C=0,Vt=12,jt=2034,M=63,Ut="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",bt=1,q=15;var vt={};O(vt,{AssetNotFound:()=>j,PoolNotFound:()=>U,RouteNotFound:()=>N});var j=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},U=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},N=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var G=class extends F{constructor(t){super(t)}async getBalance(t,e){let i=await this.api.query.AssetRegistry.Assets.getValue(e);if(!i)throw new j(e);return i.asset_type.type==="Erc20"?this.getErc20Balance(t,e):e===0?this.getSystemBalance(t):this.getTokenBalance(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:s,frozen:i}}=await e.getValue(t);return s-i}async getTokenBalance(t,e){let s=this.api.query.Tokens.Accounts,{free:i,frozen:n}=await s.getValue(t,e);return i-n}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),s=this.subscribeTokensBalance(t),i=this.subscribeErc20Balance(t);return Kt([e,s,i]).pipe(Qt(250),z(n=>n.flat()))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(z(s=>{let{free:i,frozen:n}=s.data;return{id:0,amount:i-n}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(z(i=>{let{free:n,frozen:a}=i;return{id:e,amount:n-a}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(At((s,i)=>!i.deltas),z(({deltas:s})=>{let i=[];return s?.deleted.forEach(n=>{let[a,o]=n.args;i.push({id:o,amount:0n})}),s?.upserted.forEach(n=>{let[a,o]=n.args,{free:r,frozen:l}=n.value;i.push({id:o,amount:r-l})}),i}))}subscribeErc20Balance(t,e){let s=new zt,i=s.pipe(Zt(1)),n=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),a=async()=>{let r=e||await n(),l=async()=>{let m=(await Promise.all(r.map(async p=>{let b=await this.getTokenBalanceData(t,p);return[p,b]}))).map(([p,b])=>({id:p,amount:b}));s.next(m)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},o;return a().then(r=>o=r),i.pipe(Jt(()=>o?.()),$t(),z(([r,l],c)=>{if(c===0)return l;let g=r.reduce((p,b)=>(p.set(b.id,b.amount),p),new Map);return l.filter(p=>p.amount!==g.get(p.id))}),At((r,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:s,frozen:i}=await this.api.apis.CurrenciesApi.account(e,t);return s-i}};var Ct={};O(Ct,{PoolContextProvider:()=>ct,PoolError:()=>H,PoolFactory:()=>Y,PoolType:()=>v,lbp:()=>yt,omni:()=>ft,stable:()=>St,xyk:()=>It});var yt={};O(yt,{LbpMath:()=>_,LbpPool:()=>Q,LbpPoolClient:()=>J});import{calculate_in_given_out as te,calculate_out_given_in as ee,calculate_linear_weights as se,calculate_pool_trade_fee as ie,get_spot_price as ne}from"@galacticcouncil/math-lbp";var _=class{static getSpotPrice(t,e,s,i,n){return ne(t,e,s,i,n)}static calculateInGivenOut(t,e,s,i,n){return te(t,e,s,i,n)}static calculateOutGivenIn(t,e,s,i,n){return ee(t,e,s,i,n)}static calculateLinearWeights(t,e,s,i,n){return se(t,e,s,i,n)}static calculatePoolTradeFee(t,e,s){return ie(t,e,s)}};var v=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n))(v||{}),H=(n=>(n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n.UnknownError="UnknownError",n))(H||{});var P={};O(P,{toBigInt:()=>ae,toDecimal:()=>oe});import W from"big.js";W.NE=-18;function oe(u,t,e=6,s){let i=W(u.toString()),n=W(10).pow(t);return i.div(n).round(e,s).toString()}function ae(u,t){let e=W(10).pow(t),i=W(u).mul(e).toFixed(0,W.roundDown);return BigInt(i)}var Bt={};O(Bt,{convertFromH160:()=>le,convertToH160:()=>ce,isEvmAccount:()=>ue});import{AccountId as Pt}from"polkadot-api";import{toHex as re}from"@polkadot-api/utils";import{Buffer as D}from"buffer";var ht="ETH\0";function le(u,t=63){let e=D.from(u.slice(2),"hex"),s=D.from(ht),i=Uint8Array.from(D.concat([s,e,D.alloc(8)])),n=re(i);return Pt(t).dec(n)}function ce(u){let t=Pt().enc(u),e=D.from(ht),s=t.slice(e.length,-8);return"0x"+D.from(s).toString("hex")}function ue(u){if(!u)return!1;try{let t=Pt().enc(u),e=D.from(ht);return D.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}var d={};O(d,{fromPermill:()=>ge,toDecimals:()=>pe,toPct:()=>me});var Ft=1e3;function me(u){let[t,e]=u;return t/e*100}function pe(u){let[t,e]=u;return t/e}function ge(u){return[u/Ft,Ft]}var K={};O(K,{findNestedKey:()=>de,findNestedObj:()=>be,jsonFormatter:()=>Pe});var de=(u,t)=>{let e=[];return JSON.stringify(u,(s,i)=>(i&&i[t]&&e.push(i),i)),e[0]},be=(u,t,e)=>{let s;return JSON.stringify(u,(i,n)=>(n&&n[t]===e&&(s=n),n)),s},Pe=(u,t)=>typeof t=="bigint"?t.toString():t;var S={};O(S,{calculateBuyFee:()=>Se,calculateDiffToAvg:()=>he,calculateDiffToRef:()=>ye,calculateSellFee:()=>fe,getFraction:()=>Ie});import k from"big.js";function he(u,t){let e=k(u.toString()),s=k(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function ye(u,t){let e=k(u.toString()),s=k(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function fe(u,t){let e=k(u.toString()),s=k(t.toString());return k(1).minus(s.div(e)).mul(100).round(2).toNumber()}function Se(u,t){let e=k(u.toString());return k(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Ie(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let s=Math.pow(10,e),i=BigInt(t*s);return u*i/BigInt(100*s)}var _t={};O(_t,{convertToId:()=>xe});import{Buffer as Oe}from"buffer";function xe(u){let e=Oe.from(u.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var Q=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,s,i,n,a,o){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.fee=a,this.repayFeeApply=o}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:n.balance,decimalsIn:i.decimals,decimalsOut:n.decimals,weightIn:i.weight,weightOut:n.weight}}validateAndBuy(t,e,s){let i=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&n.push("MaxOutRatioExceeded"),i===t.assetOut){let o=this.calculateTradeFee(e,s),r=d.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+o,c=this.calculateInGivenOut(t,l),g=t.balanceIn/this.maxInRatio;return c>g&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:r,errors:n}}else{let o=this.calculateInGivenOut(t,e),r=t.balanceIn/this.maxInRatio;return o>r&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,s){let i=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&n.push("MaxInRatioExceeded"),i===t.assetIn){let o=this.calculateOutGivenIn(t,e),r=t.balanceOut/this.maxOutRatio;return o>r&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(o,s),l=d.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o-r,g=t.balanceOut/this.maxOutRatio;return c>g&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(t,e){let s=_.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}calculateOutGivenIn(t,e){let s=_.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}spotPriceInGivenOut(t){let e=_.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=_.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let s=_.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as Fe}from"polkadot-api";import{map as _e,of as Lt,switchMap as Re}from"rxjs";import{memoize1 as we}from"@thi.ng/memoize";import{combineLatest as Rt,combineLatestAll as ve,debounceTime as Ae,firstValueFrom as Te,from as kt,map as Et,mergeAll as Be,switchMap as Dt}from"rxjs";var R=class extends G{override=[];mem=0;memPools=we(t=>(console.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=kt(this.getPoolsMem()).pipe(Dt(e=>this.subscribe(e)),ve());return Te(t)}getSubscriber(){return kt(this.getPoolsMem()).pipe(Dt(t=>this.subscribe(t)),Be())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>Rt([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe(Ae(250),Et(([s,i])=>this.updatePool(s,i))))}subscribePoolBalance(t){let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let s=this.subscribeSystemBalance(t.address);e.push(s)}if(this.hasErc20Asset(t)){let s=t.tokens.filter(n=>n.type==="Erc20").map(n=>n.id),i=this.subscribeErc20Balance(t.address,s);e.push(i)}return Rt(e).pipe(Et(s=>s.map(i=>Array.isArray(i)?i:[i]).flat()))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({id:e,decimals:s,balance:i})=>{let n=this.override.find(o=>o.id===e),a=!!s||!!n?.decimals;return i>0n&&a})}updatePool=(t,e)=>{let s=t.tokens.map(i=>{let n=e.find(o=>o.id===i.id),a=this.override.find(o=>o.id===i.id);return n?{...i,balance:n.amount,decimals:i.decimals||a?.decimals}:{...i,decimals:i.decimals||a?.decimals}});return{...t,tokens:s}}};var J=class extends R{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,s]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),i=e?.relay_parent_number||0,n=t.filter(({value:a})=>e&&this.isActivePool(a,i)).map(async({keyArgs:a,value:o})=>{let[r]=a,l=r.toString(),c=await this.getPoolDelta(l,o,i);return{address:l,type:"LBP",fee:o.fee,...c,...s}});return Promise.all(n)}async getPoolDelta(t,e,s){let{start:i,end:n,assets:a,initial_weight:o,final_weight:r,repay_target:l,fee_collector:c}=e,g=_.calculateLinearWeights(i?i.toString():"0",n?n.toString():"0",o.toString(),r.toString(),s.toString()),[m,p]=a,b=BigInt(g),y=this.MAX_FINAL_WEIGHT-BigInt(b),[f,A,x,w,B]=await Promise.all([this.isRepayFeeApplied(m,l,c.toString()),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:f,tokens:[{id:m,decimals:x?.decimals,existentialDeposit:x?.existential_deposit,balance:A,weight:b,type:x?.asset_type.type},{id:p,decimals:B?.decimals,existentialDeposit:B?.existential_deposit,balance:w,weight:y,type:B?.asset_type.type}]}}isActivePool(t,e){let{start:s,end:i}=t;return s&&i?e>=s&&e<i:!1}async isRepayFeeApplied(t,e,s){if(e===0n)return!1;try{return await this.getBalance(s,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Fe.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,s=this.poolsData.get(t.address);return s?e.watchValue("best").pipe(Re(i=>i?this.getPoolDelta(t.address,s,i.relay_parent_number):Lt(t)),_e(i=>Object.assign({},t,i))):Lt(t)}};var ft={};O(ft,{OmniMath:()=>h,OmniPool:()=>$,OmniPoolClient:()=>Z});import{calculate_in_given_out as ke,calculate_lrna_in_given_out as Ee,calculate_out_given_in as De,calculate_out_given_lrna_in as Le,calculate_pool_trade_fee as Me,calculate_spot_price as Ce,calculate_lrna_spot_price as qe,calculate_shares as Ne,calculate_liquidity_out as Ge,calculate_liquidity_lrna_out as He,verify_asset_cap as We,calculate_liquidity_hub_in as Xe,is_sell_allowed as Ye,is_buy_allowed as Ve,is_add_liquidity_allowed as je,is_remove_liquidity_allowed as Ue}from"@galacticcouncil/math-omnipool";import X from"big.js";var h=class{static calculateSpotPrice(t,e,s,i){return Ce(t,e,s,i)}static calculateLrnaSpotPrice(t,e){return qe(t,e)}static calculateInGivenOut(t,e,s,i,n,a,o,r,l){return ke(t,e,s,i,n,a,o,r,l)}static calculateLrnaInGivenOut(t,e,s,i,n){return Ee(t,e,s,i,n)}static calculateOutGivenIn(t,e,s,i,n,a,o,r,l){return De(t,e,s,i,n,a,o,r,l)}static calculateOutGivenLrnaIn(t,e,s,i,n){return Le(t,e,s,i,n)}static calculatePoolTradeFee(t,e,s){return Me(t,e,s)}static calculateShares(t,e,s,i){return Ne(t,e,s,i)}static calculateLiquidityOut(t,e,s,i,n,a,o,r){return Ge(t,e,s,i,n,a,o,r)}static calculateLiquidityLRNAOut(t,e,s,i,n,a,o,r){return He(t,e,s,i,n,a,o,r)}static calculateCapDifference(t,e,s,i){let n=X(e),a=X(t),o=X(i),r=X(s),l=X(10).pow(18),c=r.div(l);if(n.div(o).lt(c)){let m=c.times(o).minus(n).times(a),p=n.times(X(1).minus(c));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,s,i){return We(t,e,s,i)}static calculateLimitHubIn(t,e,s,i){return Xe(t,e,s,i)}static isSellAllowed(t){return Ye(t)}static isBuyAllowed(t){return Ve(t)}static isAddLiquidityAllowed(t){return je(t)}static isRemoveLiquidityAllowed(t){return Ue(t)}};var $=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,s,i,n,a){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.hubAssetId=a}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:i.hubReserves,hubReservesOut:n.hubReserves,sharesIn:i.shares,sharesOut:n.shares,decimalsIn:i.decimals,decimalsOut:n.decimals,balanceIn:i.balance,balanceOut:n.balance,tradeableIn:i.tradeable,tradeableOut:n.tradeable,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,s),a=i===0n?0:S.calculateDiffToRef(n,i),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&o.push("MaxOutRatioExceeded");let g=t.balanceIn/this.maxInRatio;return n>g&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:i,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,s),a=S.calculateDiffToRef(i,n),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&o.push("MaxInRatioExceeded");let g=t.balanceOut/this.maxOutRatio;return n>g&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:n,feePct:a,errors:o}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let i=h.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0",s?d.toDecimals(s.protocolFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,s){let i=h.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let i=h.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0",s?d.toDecimals(s.protocolFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,s){let i=h.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=h.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceLrnaInGivenOut(t){let e=h.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=h.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}spotPriceOutGivenLrnaIn(t){let e=h.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}};import{AccountId as ze,CompatibilityLevel as Ke}from"polkadot-api";import{toHex as Qe}from"@polkadot-api/utils";import{distinctUntilChanged as Je,map as Mt}from"rxjs";var Z=class extends R{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[s,i,n,a,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),r=s.map(async({keyArgs:c,value:g})=>{let[m]=c,{hub_reserve:p,shares:b,tradable:y,cap:f,protocol_shares:A}=g,[x,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:x?.decimals,existentialDeposit:x?.existential_deposit,balance:w,cap:f,hubReserves:p,protocolShares:A,shares:b,tradeable:y,type:x?.asset_type.type}}),l=await Promise.all(r);return l.push({id:t,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:a,tradeable:i,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...o}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),s=Qe(e);return ze(63).dec(s)}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(t,e){let[s,i,n]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),a=s.min_fee+i.min_fee,o=s.max_fee+i.max_fee;if(n){let{asset_fee:r,protocol_fee:l}=n;return{assetFee:d.fromPermill(r),protocolFee:d.fromPermill(l),min:d.fromPermill(a),max:d.fromPermill(o)}}else return{assetFee:d.fromPermill(s.min_fee),protocolFee:d.fromPermill(i.min_fee),min:d.fromPermill(a),max:d.fromPermill(o)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Ke.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(Je((s,i)=>!i.deltas),Mt(({entries:s})=>s.map(i=>{let[n]=i.args,{hub_reserve:a,shares:o,tradable:r,cap:l,protocol_shares:c}=i.value,g=t.tokens.findIndex(p=>p.id===n);return{...t.tokens[g],cap:l,hubReserves:a,protocolShares:c,shares:o,tradeable:r}})),Mt(s=>{let i=t.tokens.find(n=>n.id===1);return{...t,tokens:[...s,i]}}))}};var St={};O(St,{StableMath:()=>I,StableSwap:()=>tt,StableSwapClient:()=>et});import{calculate_in_given_out as $e,calculate_out_given_in as Ze,calculate_amplification as ts,calculate_add_one_asset as es,calculate_liquidity_out_one_asset as ss,calculate_pool_trade_fee as is,calculate_shares as ns,calculate_shares_for_amount as os,calculate_spot_price_with_fee as as,pool_account_name as rs,recalculate_peg as ls}from"@galacticcouncil/math-stableswap";var I=class{static getPoolAddress(t){return rs(t)}static defaultPegs(t){let e=[];for(let s=0;s<t;s++)e.push(["1","1"]);return e}static calculateAmplification(t,e,s,i,n){return ts(t,e,s,i,n)}static calculateInGivenOut(t,e,s,i,n,a,o){return $e(t,e,s,i,n,a,o)}static calculateAddOneAsset(t,e,s,i,n,a,o){return es(t,e,s,i,n,a,o)}static calculateSharesForAmount(t,e,s,i,n,a,o){return os(t,e,s,i,n,a,o)}static calculateOutGivenIn(t,e,s,i,n,a,o){return Ze(t,e,s,i,n,a,o)}static calculateLiquidityOutOneAsset(t,e,s,i,n,a,o){return ss(t,e,s,i,n,a,o)}static calculateShares(t,e,s,i,n,a){return ns(t,e,s,i,n,a)}static calculateSpotPriceWithFee(t,e,s,i,n,a,o,r){return as(t,e,s,i,n,a,o,r)}static calculatePoolTradeFee(t,e,s){return is(t,e,s)}static recalculatePegs(t,e,s,i,n){return ls(t,e,s,i,n)}};var tt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,s,i,n,a,o,r,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.amplification=a,this.id=o,this.fee=r,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:n.balance,decimalsIn:i.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:i.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,s),a=d.toPct(s.fee),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:i,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,s),a=d.toPct(s.fee),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:i,amountOut:n,feePct:a,errors:o}}calculateIn(t,e,s){let i=I.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateAddOneAsset(t,e,s){let i=I.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateSharesForAmount(t,e,s){let i=I.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateInGivenOut(t,e,s){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,s):t.assetIn==this.id?this.calculateSharesForAmount(t,e,s):this.calculateIn(t,e,s)}spotPriceInGivenOut(t){let e=I.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let i=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(i)}let s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateOut(t,e,s){let i=I.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,s){let i=I.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateShares(t,e,s){let i=I.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e,s){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,s):t.assetOut==this.id?this.calculateShares(t,e,s):this.calculateOut(t,e,s)}spotPriceOutGivenIn(t){let e=I.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let i=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(i)}let s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let[s,i]=e.fee,n=I.calculatePoolTradeFee(t.toString(),s,i);return BigInt(n)}getPegs(){let t=I.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:s,decimals:i})=>({asset_id:e,amount:s,decimals:i}));return JSON.stringify(t,K.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],K.jsonFormatter)}};import{AccountId as cs,CompatibilityLevel as us}from"polkadot-api";import{toHex as ms}from"@polkadot-api/utils";import{blake2b as ps}from"@noble/hashes/blake2b";import{map as gs,of as ds,switchMap as bs}from"rxjs";var Ps=340282366920938463463374607431768211455n,et=class extends R{poolsData=new Map([]);async loadPools(){let[t,e,s]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),i=t.map(async({keyArgs:n,value:a})=>{let[o]=n,r=this.getPoolAddress(o),[l,c]=await Promise.all([this.getPoolDelta(o,a,e),this.getPoolTokens(o,a)]);return this.poolsData.set(r,a),{address:r,id:o,type:"Stableswap",fee:d.fromPermill(a.fee),tokens:c,...l,...s}});return Promise.all(i)}async getPoolDelta(t,e,s){let{initial_amplification:i,final_amplification:n,initial_block:a,final_block:o}=e,r=I.calculateAmplification(i.toString(),n.toString(),a.toString(),o.toString(),s.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(r),totalIssuance:l}}async getPoolTokens(t,e){let s=this.getPoolAddress(t),i=e.assets.map(async o=>{let[r,l,c]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(s,o)]);return{id:o,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:c,tradeable:r,type:l?.asset_type.type}}),n=await Promise.all(i),a=await this.api.query.AssetRegistry.Assets.getValue(t);return n.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:Ps,tradeable:15,type:a?.asset_type.type}),n}getPoolAddress(t){let e=I.getPoolAddress(t),s=ps(e,{dkLen:32}),i=ms(s);return cs(63).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(us.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,s=this.poolsData.get(t.address);return!s||!t.id?ds(t):e.watchValue("best").pipe(bs(i=>this.getPoolDelta(t.id,s,i)),gs(i=>Object.assign({},t,i)))}};var It={};O(It,{XykMath:()=>E,XykPool:()=>st,XykPoolClient:()=>it});import{calculate_in_given_out as hs,calculate_out_given_in as ys,calculate_pool_trade_fee as fs,get_spot_price as Ss,calculate_liquidity_in as Is,calculate_shares as Os,calculate_spot_price as xs,calculate_spot_price_with_fee as ws,calculate_liquidity_out_asset_a as vs,calculate_liquidity_out_asset_b as As}from"@galacticcouncil/math-xyk";var E=class{static getSpotPrice(t,e,s){return Ss(t,e,s)}static calculateInGivenOut(t,e,s){return hs(t,e,s)}static calculateOutGivenIn(t,e,s){return ys(t,e,s)}static calculatePoolTradeFee(t,e,s){return fs(t,e,s)}static calculateLiquidityIn(t,e,s){return Is(t,e,s)}static calculateSpotPrice(t,e){return xs(t,e)}static calculateSpotPriceWithFee(t,e,s,i){return ws(t,e,s,i)}static calculateShares(t,e,s){return Os(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,i){return vs(t,e,s,i)}static calculateLiquidityOutAssetB(t,e,s,i){return As(t,e,s,i)}};var st=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,s,i,n){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:i.decimals,decimalsOut:n.decimals,balanceIn:i.balance,balanceOut:n.balance,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(i,s),a=d.toPct(s.exchangeFee),o=i+n,r=[];(e<this.minTradingLimit||i<t.assetInEd)&&r.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&r.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return o>c&&r.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:i,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(i,s),a=d.toPct(s.exchangeFee),o=i-n,r=[];(e<this.minTradingLimit||i<t.assetOutEd)&&r.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&r.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return o>c&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:o,feePct:a,errors:r}}calculateInGivenOut(t,e){let s=E.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}calculateOutGivenIn(t,e){let s=E.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}spotPriceInGivenOut(t){let e=E.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceOutGivenIn(t){let e=E.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let s=E.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as Ts}from"polkadot-api";import{of as Bs}from"rxjs";var it=class extends R{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,s]=await Promise.all([t.getEntries(),this.getPoolLimits()]),i=e.map(async({keyArgs:n,value:a})=>{let[o]=n,[r,l]=a,[c,g,m,p]=await Promise.all([this.getBalance(o,r),this.api.query.AssetRegistry.Assets.getValue(r),this.getBalance(o,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:o,type:"XYK",tokens:[{id:r,decimals:g?.decimals,existentialDeposit:g?.existential_deposit,balance:c,type:g?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...s}});return Promise.all(i)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Ts.BackwardsCompatible,e)}subscribePoolChange(t){return Bs(t)}};var Y=class{static get(t){switch(t.type){case"XYK":return st.fromPool(t);case"Omnipool":return $.fromPool(t);case"LBP":return Q.fromPool(t);case"Stableswap":return tt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as Fs,Subscription as rt,takeUntil as lt}from"rxjs";var ct=class extends F{lbpClient;omniClient;stableClient;xykClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=rt.EMPTY;omniSub=rt.EMPTY;stableSub=rt.EMPTY;xykSub=rt.EMPTY;isReady=!1;isDestroyed=new Fs;constructor(t){super(t),this.lbpClient=new J(t),this.omniClient=new Z(t),this.stableClient=new et(t),this.xykClient=new it(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient]}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.omniClient.getSubscriber().pipe(lt(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.stableClient.getSubscriber().pipe(lt(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.lbpClient.getSubscriber().pipe(lt(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("LBP"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.xykClient.getSubscriber().pipe(lt(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)}),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let s=this.clients.find(i=>i.getPoolType()===t.type);if(s)return s.getPoolFees(t,e);throw new U(t.type)}};var Nt={};O(Nt,{Router:()=>V,TradeRouter:()=>pt,TradeType:()=>mt,TradeUtils:()=>gt});var ut=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var _s=5,nt=class{isNotVisited(t,e){let s=!0;return e.forEach(i=>{(i[0]===t[0]||i[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let i=[],n=new ut,a=[];for(a.push([e,""]),n.enqueue(a);n.size()>0;){let o=n.dequeue();if(o==null||o.length>_s)return i;let r=o[o.length-1];(s===null||r[0]===s)&&i.push(o),t.get(r[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let g=[...o];g.push(c),n.enqueue(g)}})}return i}buildAndPopulateGraph(t,e){let s=new Map;for(let i of t)s.set(parseInt(i),[]);for(let[i,n,a]of e)s.get(n)?.push([a,i]);return s}};function Ot(u){let t={};for(let e of u){let s=e.tokens.length;for(let i=0;i<s;i++){t[e.tokens[i].id]||(t[e.tokens[i].id]=[]);for(let n=0;n<s;n++){if(i==n)continue;let a=[e.address,e.tokens[i].id,e.tokens[n].id];t[e.tokens[i].id].push(a)}}}return t}var ot=class{getProposals(t,e,s){let i=Ot(s),n=Object.keys(i),a=n.map(c=>i[c]).flat(),o=new nt,r=o.buildAndPopulateGraph(n,a),l=o.findPaths(r,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let s of t){let i=[];for(let n=0;n<s.length;n++){let a=s[n],o=s[n+1];if(o==null)break;i.push(this.toEdge(a,o))}e.push(i)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var V=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new ot,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(s=>e.includes(s.type))}async getRoutes(t,e){let s=await this.getPools();return this.validateInput(t,e,s),this.getPaths(t,e,s)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,s){if(s.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let i=this.getAssets(s);if(!i.has(t))throw new Error(t+" is not supported asset");if(!i.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(i=>i.id)).flat().sort((s,i)=>s>i?1:-1);return new Set(e)}getPaths(t,e,s){let i=this.toPoolsMap(s);return this.routeSuggester.getProposals(t,e,s).filter(a=>this.validPath(a,i)).map(a=>this.toHops(a,i))}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,i)=>s&&i)}validEdge([t,e,s],i){return i.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Y.get(e)]))}toHops(t,e){return t.map(([s,i,n])=>{let a=e.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:i,assetOut:n}})}};var mt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(mt||{});var pt=class extends V{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,i)=>{let n=s[s.length-1].amountOut,a=i[i.length-1].amountOut;return n>a?-1:1});return e.find(s=>s.every(i=>i.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,a)=>n+a),i=t.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,a)=>n+a);return[s,i]}}getPoolFeeRange(t){let e=t.min?d.toPct(t.min):void 0,s=t.max?d.toPct(t.max):void 0;if(e&&s)return[e,s]}async getBestSell(t,e,s){return this.getSell(t,e,s)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let s=t.map(o=>o.assetOutDecimals).reduce((o,r)=>o+r),i=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),n=s-e.assetOutDecimals,a=Math.pow(10,n);return i/BigInt(a)}async getSell(t,e,s,i){let n=await super.getPools(),a=super.validateInput(t,e,n),o=super.getPaths(t,e,n);if(o.length===0)throw new N(t,e);let r;if(i)r=await this.toSellSwaps(s,i,a);else{let L=await Promise.all(o.map(dt=>this.toSellSwaps(s,dt,a)));r=this.findBestSellRoute(L)}let l=r[0],c=r[r.length-1],g=this.isDirectTrade(r),m=await this.getSellSpot(r),p=c.amountOut,b=g?c.calculatedOut:this.calculateDelta0Y(l.amountIn,r,a),y=b-p,f=this.getRouteFeeRange(r),A=g?c.tradeFeePct:S.calculateSellFee(b,p),x=Math.pow(10,l.assetInDecimals),w=l.amountIn*m/BigInt(x),B=S.calculateDiffToRef(b,w);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:m,tradeFee:y,tradeFeePct:A,tradeFeeRange:f,priceImpactPct:B,swaps:r,toHuman(){return{type:"Sell",amountIn:P.toDecimal(l.amountIn,l.assetInDecimals),amountOut:P.toDecimal(c.amountOut,c.assetOutDecimals),spotPrice:P.toDecimal(m,c.assetOutDecimals),tradeFee:P.toDecimal(y,c.assetOutDecimals),tradeFeePct:A,tradeFeeRange:f,priceImpactPct:B,swaps:r.map(L=>L.toHuman())}}}}calculateDelta0Y(t,e,s){let i=[];for(let n=0;n<e.length;n++){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n>0?l=i[n-1]:l=t;let c=o.calculateOutGivenIn(r,l);i.push(c)}return i[i.length-1]}async toSellSwaps(t,e,s){let i=[];for(let n=0;n<e.length;n++){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n>0?l=i[n-1].amountOut:l=typeof t=="string"?P.toBigInt(t,r.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountOut:g,calculatedOut:m,feePct:p,errors:b}=o.validateAndSell(r,l,c),y=this.getPoolFeeRange(c),f=o.spotPriceOutGivenIn(r),A=Math.pow(10,r.decimalsIn),x=l*f/BigInt(A),w=S.calculateDiffToRef(m,x);i.push({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountIn:l,amountOut:g,calculatedOut:m,spotPrice:f,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:b,toHuman(){return{...a,amountIn:P.toDecimal(l,r.decimalsIn),amountOut:P.toDecimal(g,r.decimalsOut),calculatedOut:P.toDecimal(m,r.decimalsOut),spotPrice:P.toDecimal(f,r.decimalsOut),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:b}}})}return i}async getMostLiquidRoute(t,e){let s=await super.getPools(),i=super.validateInput(t,e,s),n=super.getPaths(t,e,s),r=s.filter(m=>m.tokens.some(p=>p.id===t&&p.id!==m.id)).map(m=>m.type==="Aave"?m.tokens:m.tokens.filter(p=>p.id===t)).map(m=>m.map(p=>p.balance).reduce((p,b)=>p+b)).sort((m,p)=>p<m?-1:1)[0],l=S.getFraction(r,.1),c=await Promise.all(n.map(m=>this.toSellSwaps(l,m,i)));return this.findBestSellRoute(c).map(m=>({poolAddress:m.poolAddress,poolId:m?.poolId,pool:m.pool,assetIn:m.assetIn,assetOut:m.assetOut}))}async getSpotPrice(t,e){let s=await super.getPools(),i=super.validateInput(t,e,s),n=await this.getMostLiquidRoute(t,e),a=await this.toSellSwaps("1",n,i),o=await this.getSellSpot(a),r=a[a.length-1].assetOutDecimals;return{amount:o,decimals:r}}findBestBuyRoute(t){let e=t.sort((s,i)=>{let n=s[0].amountIn,a=i[0].amountIn;return n>a?1:-1});return e.find(s=>s.every(i=>i.errors.length==0))||e[0]}async getBestBuy(t,e,s){return this.getBuy(t,e,s)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let s=t.map(o=>o.assetInDecimals).reduce((o,r)=>o+r),i=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),n=s-e.assetInDecimals,a=Math.pow(10,n);return i/BigInt(a)}async getBuy(t,e,s,i){let n=await super.getPools(),a=super.validateInput(t,e,n),o=super.getPaths(t,e,n);if(o.length===0)throw new N(t,e);let r;if(i)r=await this.toBuySwaps(s,i,a);else{let L=await Promise.all(o.map(dt=>this.toBuySwaps(s,dt,a)));r=this.findBestBuyRoute(L)}let l=r[r.length-1],c=r[0],g=this.isDirectTrade(r),m=await this.getBuySpot(r),p=c.amountIn,b=g?c.calculatedIn:this.calculateDelta0X(l.amountOut,r,a),y=p-b,f=this.getRouteFeeRange(r),A=g?c.tradeFeePct:S.calculateBuyFee(b,p),x=Math.pow(10,l.assetOutDecimals),w=l.amountOut*m/BigInt(x),B;return b===0n?B=-100:B=S.calculateDiffToRef(w,b),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:m,tradeFee:y,tradeFeePct:A,tradeFeeRange:f,priceImpactPct:B,swaps:r,toHuman(){return{type:"Buy",amountOut:P.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:P.toDecimal(c.amountIn,c.assetInDecimals),spotPrice:P.toDecimal(m,c.assetInDecimals),tradeFee:P.toDecimal(y,c.assetInDecimals),tradeFeePct:A,tradeFeeRange:f,priceImpactPct:B,swaps:r.map(L=>L.toHuman())}}}}calculateDelta0X(t,e,s){let i=[];for(let n=e.length-1;n>=0;n--){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n==e.length-1?l=t:l=i[0];let c=o.calculateInGivenOut(r,l);i.unshift(c)}return i[0]}async toBuySwaps(t,e,s){let i=[];for(let n=e.length-1;n>=0;n--){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n==e.length-1?l=typeof t=="string"?P.toBigInt(t,r.decimalsOut):t:l=i[0].amountIn;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountIn:g,calculatedIn:m,feePct:p,errors:b}=o.validateAndBuy(r,l,c),y=this.getPoolFeeRange(c),f=o.spotPriceInGivenOut(r),A=Math.pow(10,r.decimalsOut),x=l*f/BigInt(A),w;m===0n?w=-100:w=S.calculateDiffToRef(x,m),i.unshift({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountOut:l,amountIn:g,calculatedIn:m,spotPrice:f,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:b,toHuman(){return{...a,amountOut:P.toDecimal(l,r.decimalsOut),amountIn:P.toDecimal(g,r.decimalsIn),calculatedIn:P.toDecimal(m,r.decimalsIn),spotPrice:P.toDecimal(f,r.decimalsIn),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:b}}})}return i}};import{Enum as qt}from"polkadot-api";var gt=class extends F{constructor(t){super(t)}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}tradeCheck(t,e){if(e!==t.type)throw new Error("Not permitted")}async buildBuyTx(t,e=1){this.tradeCheck(t,"Buy");let{amountIn:s,amountOut:i,swaps:n}=t,a=n[0],o=n[n.length-1],r=S.getFraction(s,e),l=a.assetIn,c=o.assetOut,g=s+r;return this.isDirectOmnipoolTrade(n)?this.api.tx.Omnipool.buy({asset_in:l,asset_out:c,amount:i,max_sell_amount:g}).getEncodedData():this.api.tx.Router.buy({asset_in:l,asset_out:c,amount_out:i,max_amount_in:g,route:this.buildRoute(n)}).getEncodedData()}async buildSellTx(t,e=1){this.tradeCheck(t,"Sell");let{amountIn:s,amountOut:i,swaps:n}=t,a=n[0],o=n[n.length-1],r=S.getFraction(i,e),l=a.assetIn,c=o.assetOut,g=i-r;return this.isDirectOmnipoolTrade(n)?this.api.tx.Omnipool.sell({asset_in:l,asset_out:c,amount:s,min_buy_amount:g}).getEncodedData():this.api.tx.Router.sell({asset_in:l,asset_out:c,amount_in:s,min_amount_out:g,route:this.buildRoute(n)}).getEncodedData()}async buildSellAllTx(t,e=1){this.tradeCheck(t,"Sell");let{amountOut:s,swaps:i}=t,n=i[0],a=i[i.length-1],o=S.getFraction(s,e),r=n.assetIn,l=a.assetOut,c=s-o;return this.api.tx.Router.sell_all({asset_in:r,asset_out:l,min_amount_out:c,route:this.buildRoute(i)}).getEncodedData()}buildRoute(t){return t.map(({assetIn:e,assetOut:s,pool:i,poolId:n})=>i==="Stableswap"?{pool:qt("Stableswap",n),asset_in:e,asset_out:s}:{pool:qt(i),asset_in:e,asset_out:s})}};export{xt as api,P as big,Tt as client,wt as const,vt as error,Bt as evm,d as fmt,K as json,S as math,Ct as pool,Nt as sor,_t as xc};