@galacticcouncil/sdk-next 1.0.0-beta.0 → 1.0.0-pr159-5456ce2
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.
- package/README.md +127 -45
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/types/api/Papi.d.ts +15 -6
- package/build/types/pool/PoolContextProvider.d.ts +4 -0
- package/build/types/pool/aave/AaveAbi.d.ts +126 -0
- package/build/types/pool/aave/AavePool.d.ts +24 -0
- package/build/types/pool/aave/AavePoolClient.d.ts +14 -0
- package/build/types/pool/aave/index.d.ts +2 -0
- package/build/types/pool/index.d.ts +1 -0
- package/build/types/sor/TradeRouter.d.ts +5 -5
- package/build/types/utils/erc20.d.ts +5 -0
- package/build/types/utils/index.d.ts +1 -0
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -7,10 +7,12 @@ Next gen hydration sdk build on top of [Polkadot API (Papi)](https://papi.how/).
|
|
|
7
7
|
Table of content:
|
|
8
8
|
|
|
9
9
|
- [Installation](#installation)
|
|
10
|
-
- [
|
|
10
|
+
- [Usage](#usage)
|
|
11
11
|
- [PoolContextProvider](#poolcontextprovider)
|
|
12
12
|
- [Router](#router)
|
|
13
13
|
- [TradeRouter](#traderouter)
|
|
14
|
+
- [BalanceClient](#balanceclient)
|
|
15
|
+
- [AssetClient](#assetclient)
|
|
14
16
|
|
|
15
17
|
## Installation
|
|
16
18
|
|
|
@@ -18,76 +20,107 @@ Install with [npm](https://www.npmjs.com/):
|
|
|
18
20
|
|
|
19
21
|
`npm install @galacticcouncil/sdk-next`
|
|
20
22
|
|
|
21
|
-
##
|
|
23
|
+
## Usage
|
|
22
24
|
|
|
23
|
-
###
|
|
25
|
+
### PoolContextProvider
|
|
24
26
|
|
|
25
|
-
|
|
27
|
+
Build and subscribe to the given AMM types, supplying data for the Router API.
|
|
26
28
|
|
|
27
|
-
|
|
29
|
+
⚠️ **Note:** Make sure to keep only single instance of context per session.
|
|
28
30
|
|
|
29
|
-
|
|
31
|
+
#### API Reference (internal)
|
|
30
32
|
|
|
31
|
-
|
|
33
|
+
| Method | Description |
|
|
34
|
+
| :----- | :----------- |
|
|
35
|
+
| `getPools(): Promise<PoolBase[]>` | Returns list of available pools. |
|
|
36
|
+
| `getPoolFees(pool: PoolBase, feeAsset: number): Promise<PoolFees>` | Returns current pool fees |
|
|
37
|
+
|
|
38
|
+
➡️ For type definitions visit [types.ts](src/pool/types.ts)<br />
|
|
39
|
+
|
|
40
|
+
#### Example
|
|
41
|
+
|
|
42
|
+
Initialize pool context supporting Omnipool, Stableswap & XYK pools.
|
|
32
43
|
|
|
33
44
|
```typescript
|
|
34
|
-
import { api, pool } from '@galacticcouncil/sdk-next';
|
|
45
|
+
import { api, pool, sor } from '@galacticcouncil/sdk-next';
|
|
46
|
+
|
|
47
|
+
const client = await api.getWs('wss://hydradx-rpc.dwellir.com');
|
|
35
48
|
|
|
36
|
-
const client = await api.getWs('wss://rpc.hydradx.cloud');
|
|
37
49
|
const ctx = new pool.PoolContextProvider(client)
|
|
38
50
|
.withOmnipool()
|
|
39
51
|
.withStableswap()
|
|
40
52
|
.withXyk();
|
|
41
53
|
|
|
42
|
-
const pools = await ctx.getPools();
|
|
43
|
-
console.log(pools);
|
|
44
|
-
|
|
45
54
|
// Don't forget to cleanup the resources
|
|
46
55
|
ctx.destroy();
|
|
47
56
|
client.destroy();
|
|
48
57
|
```
|
|
49
58
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
### SOR
|
|
53
|
-
|
|
54
|
-
#### Router
|
|
59
|
+
### Router
|
|
55
60
|
|
|
56
61
|
Off-chain routing, build to find the most suitable routes across the pools. Building block for `TradeRouter`.
|
|
57
62
|
|
|
58
|
-
|
|
63
|
+
#### API Reference
|
|
59
64
|
|
|
60
|
-
| Method | Description
|
|
65
|
+
| Method | Description |
|
|
61
66
|
| :----- | :----------- |
|
|
62
67
|
| `getPools(): PoolBase[]` | Returns the current list of available pools. |
|
|
63
68
|
| `getRoutes(assetIn: number, assetOut: number): Hop[][]` | Computes possible routes between two assets. |
|
|
64
69
|
| `getTradeableAssets(): number[]` | Lists all assets that are tradeable through the router. |
|
|
65
70
|
|
|
66
|
-
|
|
71
|
+
➡️ For type definitions visit [types.ts](src/sor/types.ts)<br />
|
|
72
|
+
|
|
73
|
+
#### Example
|
|
74
|
+
|
|
75
|
+
List all tradable assets available in the current pool context.
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
import { api, pool, sor } from '@galacticcouncil/sdk-next';
|
|
79
|
+
|
|
80
|
+
const client = await api.getWs('wss://hydradx-rpc.dwellir.com');
|
|
81
|
+
|
|
82
|
+
// Make sure to keep only single instance of context per session
|
|
83
|
+
const ctx = new pool.PoolContextProvider(client)
|
|
84
|
+
.withOmnipool()
|
|
85
|
+
.withStableswap()
|
|
86
|
+
.withXyk();
|
|
87
|
+
|
|
88
|
+
const router = new sor.Router(ctx);
|
|
89
|
+
|
|
90
|
+
const assets = await router.getTradeableAssets();
|
|
91
|
+
console.log(assets);
|
|
92
|
+
|
|
93
|
+
// Don't forget to cleanup the resources
|
|
94
|
+
ctx.destroy();
|
|
95
|
+
client.destroy();
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### TradeRouter
|
|
67
99
|
|
|
68
100
|
Off-chain optimization of orders across pools for best price execution. TradeRouter does not perform any on-chain transations.
|
|
69
101
|
|
|
70
|
-
|
|
102
|
+
#### Api Reference
|
|
71
103
|
|
|
72
|
-
| Method | Description
|
|
104
|
+
| Method | Description |
|
|
73
105
|
| :----- | :----------- |
|
|
74
106
|
| `getBestSell(tokenIn: number, tokenOut: number, amountIn: bigint \| string): Trade` | Find the best sell trade for given input amount. |
|
|
75
107
|
| `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` |
|
|
77
|
-
| `getSell(tokenIn: number, tokenOut: number, amountIn: bigint \| string, route?: Hop[]): Trade` |
|
|
108
|
+
| `getBuy(tokenIn: number, tokenOut: number, amountOut: bigint \| string, route?: Hop[]): Trade` | Calculate a buy using a specific route (optional). |
|
|
109
|
+
| `getSell(tokenIn: number, tokenOut: number, amountIn: bigint \| string, route?: Hop[]): Trade` | Calculate a sell using a specific route (optional). |
|
|
78
110
|
| `getSpotPrice(tokenIn: number, tokenOut: number): Amount` | Get the current spot price between two tokens. |
|
|
79
111
|
| `getMostLiquidRoute(tokenIn: number, tokenOut: number): Hop[]` | Find the route with the highest liquidity between two tokens. |
|
|
80
112
|
|
|
81
|
-
|
|
113
|
+
➡️ For type definitions visit [types.ts](src/sor/types.ts)<br />
|
|
82
114
|
|
|
83
|
-
|
|
115
|
+
#### Example
|
|
84
116
|
|
|
85
|
-
|
|
117
|
+
Calculate sell of 1 DOT for HDX & build tx with 5% slippage (default to 1% if not specified)
|
|
86
118
|
|
|
87
119
|
```typescript
|
|
88
120
|
import { api, pool, sor } from '@galacticcouncil/sdk-next';
|
|
89
121
|
|
|
90
|
-
const client = await api.getWs('wss://rpc.
|
|
122
|
+
const client = await api.getWs('wss://hydradx-rpc.dwellir.com');
|
|
123
|
+
|
|
91
124
|
const ctx = new pool.PoolContextProvider(client)
|
|
92
125
|
.withOmnipool()
|
|
93
126
|
.withStableswap()
|
|
@@ -97,45 +130,94 @@ const router = new sor.TradeRouter(ctx);
|
|
|
97
130
|
const utils = new sor.TradeUtils(client);
|
|
98
131
|
|
|
99
132
|
const sell = await router.getBestSell(5, 0, 10_000_000_000n);
|
|
100
|
-
const tx = await utils.buildSellTx(sell);
|
|
133
|
+
const tx = await utils.buildSellTx(sell, 5);
|
|
101
134
|
console.log(sell.toHuman());
|
|
102
|
-
console.log('Transaction hash:
|
|
135
|
+
console.log('Transaction hash:', tx.asHex());
|
|
103
136
|
|
|
104
137
|
// Don't forget to cleanup the resources
|
|
105
138
|
ctx.destroy();
|
|
106
139
|
client.destroy();
|
|
107
140
|
```
|
|
108
141
|
|
|
109
|
-
|
|
142
|
+
**Note:** For convenience, the router amount can be specified either as a native bigint or as a human-readable string.
|
|
143
|
+
|
|
144
|
+
For example, `"1"` DOT (string) is equivalent to `10_000_000_000n` (bigint), as DOT has 10 decimals.
|
|
145
|
+
|
|
146
|
+
### BalanceClient
|
|
147
|
+
|
|
148
|
+
Helper class supporting the following standards:
|
|
149
|
+
|
|
150
|
+
- "Native assets"
|
|
151
|
+
- "Token assets"
|
|
152
|
+
- "ERC-20 tokens"
|
|
110
153
|
|
|
111
|
-
|
|
154
|
+
#### API Reference
|
|
112
155
|
|
|
113
|
-
|
|
156
|
+
| Method | Description |
|
|
157
|
+
| :----- | :----------- |
|
|
158
|
+
| `subscribeSystemBalance(address: string): Observable<AssetAmount>` | Subscribe native account balance. |
|
|
159
|
+
| `subscribeTokenBalance(address: string, assetId: number): Observable<AssetAmount>` | Subscribe token account balance. |
|
|
160
|
+
| `subscribeTokensBalance(address: string): Observable<AssetAmount[]>` | Subscribe tokens account balances. |
|
|
161
|
+
| `subscribeErc20Balance(address: string, includeOnly?: number[]): Observable<AssetAmount[]>` | Subscribe erc20 assets balances |
|
|
162
|
+
|
|
163
|
+
➡️ For type definitions visit [types.ts](src/types.ts)<br />
|
|
114
164
|
|
|
115
|
-
|
|
165
|
+
#### Example
|
|
166
|
+
|
|
167
|
+
Subscribe hydration treasury account.
|
|
116
168
|
|
|
117
169
|
```typescript
|
|
118
170
|
import { api, client as c } from '@galacticcouncil/sdk-next';
|
|
119
171
|
|
|
120
|
-
const
|
|
172
|
+
const account = "7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1"
|
|
121
173
|
|
|
122
|
-
const client = await api.getWs('wss://rpc.
|
|
174
|
+
const client = await api.getWs('wss://hydradx-rpc.dwellir.com');
|
|
123
175
|
const balanceClient = new c.BalanceClient(client);
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
|
|
176
|
+
|
|
177
|
+
const subscription = balanceClient
|
|
178
|
+
.subscribeBalance(account)
|
|
179
|
+
.subscribe((balances) => {
|
|
180
|
+
console.log(balances);
|
|
181
|
+
});
|
|
127
182
|
|
|
128
183
|
// Don't forget to cleanup the resources
|
|
129
|
-
|
|
184
|
+
subscription.unsubscribe();
|
|
130
185
|
client.destroy();
|
|
131
186
|
```
|
|
132
187
|
|
|
133
|
-
|
|
188
|
+
### AssetClient
|
|
189
|
+
|
|
190
|
+
Helper class to fetch registry metadata.
|
|
191
|
+
|
|
192
|
+
#### API Reference
|
|
134
193
|
|
|
135
|
-
|
|
194
|
+
| Method | Description |
|
|
195
|
+
| :----- | :----------- |
|
|
196
|
+
| `getOnChainAssets(includeInvalid?: boolean, external?: ExternalAsset[]): Promise<Asset[]>` | Returns assets with metadata from registry. |
|
|
197
|
+
|
|
198
|
+
➡️ For type definitions visit [types.ts](src/types.ts)<br />
|
|
199
|
+
|
|
200
|
+
#### Example
|
|
201
|
+
|
|
202
|
+
Get default on-chain data.
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
import { api, client as c } from '@galacticcouncil/sdk-next';
|
|
206
|
+
|
|
207
|
+
const client = await api.getWs('wss://hydradx-rpc.dwellir.com');
|
|
208
|
+
const assetClient = new c.AssetClient(client);
|
|
209
|
+
|
|
210
|
+
const assets = await assetClient.getOnChainAssets();
|
|
211
|
+
console.log(assets);
|
|
212
|
+
|
|
213
|
+
// Don't forget to cleanup the resources
|
|
214
|
+
client.destroy();
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Examples
|
|
136
218
|
|
|
137
|
-
|
|
219
|
+
To demonstrate more full working examples on real chain see [script](test/script/examples) section.
|
|
138
220
|
|
|
139
|
-
|
|
221
|
+
### Execution
|
|
140
222
|
|
|
141
|
-
|
|
223
|
+
Run: `$ npx tsx ./test/script/examples/<examplePackage>/<exampleName>.ts` with valid example package & name.
|
package/build/index.cjs
CHANGED
|
@@ -1 +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});
|
|
1
|
+
"use strict";var Se=Object.create;var Ot=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var te=(u,t)=>()=>(u&&(t=u(u=0)),t);var w=(u,t)=>{for(var e in t)Ot(u,e,{get:t[e],enumerable:!0})},It=(u,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ie(t))!we.call(u,n)&&n!==e&&Ot(u,n,{get:()=>t[n],enumerable:!(s=xe(t,n))||s.enumerable});return u},K=(u,t,e)=>(It(u,t,"default"),e&&It(e,t,"default")),Dt=(u,t,e)=>(e=u!=null?Se(Oe(u)):{},It(t||!u||!u.__esModule?Ot(e,"default",{value:u,enumerable:!0}):e,u)),ve=u=>It(Ot({},"__esModule",{value:!0}),u);var it={};var ee=te(()=>{K(it,require("@polkadot-api/ws-provider/node"))});var ot={};var se=te(()=>{K(ot,require("@polkadot-api/ws-provider/web"))});var Qe={};w(Qe,{api:()=>Lt,big:()=>y,client:()=>qt,const:()=>Ct,erc20:()=>lt,error:()=>Gt,evm:()=>Xt,fmt:()=>g,json:()=>X,math:()=>v,pool:()=>Qt,sor:()=>Zt,xc:()=>Vt});module.exports=ve(Qe);var Lt={};w(Lt,{Papi:()=>L,getWs:()=>Ae});var ne=require("polkadot-api"),ie=require("polkadot-api/polkadot-sdk-compat"),Ae=async u=>{let t=typeof u=="string"?u.split(","):u,n=(typeof window>"u"?(await Promise.resolve().then(()=>(ee(),it))).getWsProvider:(await Promise.resolve().then(()=>(se(),ot))).getWsProvider)(t);return(0,ne.createClient)((0,ie.withPolkadotSdkCompat)(n))};var oe=require("@galacticcouncil/descriptors"),L=class{client;constructor(t){this.client=t}get api(){return this.client.getTypedApi(oe.hydration)}logSync(t,e,s){let n=t.substring(0,10).concat("..."),i=["\u{1F504} Sync",e,"[",n,"]",s].join(" ");console.log(i)}};var qt={};w(qt,{AssetClient:()=>wt,BalanceClient:()=>$});var wt=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:n})=>{let[i]=s;return[i,n]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:s,value:n})=>{let[i]=s;return[i,n]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:s})=>{let{asset_type:n}=s;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:s,value:n})=>{let[i]=s;return[i,n]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:s,value:n})=>{let[i]=s;return[i,n]}))}async mapToken(t,e,s,n){let{name:i,asset_type:a,is_sufficient:o,existential_deposit:r}=e,{symbol:l,decimals:c}=s.get(t)??{};return{id:t,name:i?.asText(),symbol:l,decimals:c,icon:l,type:a.type,isSufficient:o,location:n,existentialDeposit:r}}async mapBond(t,e,s,n){let[i,a]=n,{asset_type:o,is_sufficient:r,existential_deposit:l}=e,{symbol:c,decimals:d}=await this.mapToken(i,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:d,icon:c,type:o.type,isSufficient:r,existentialDeposit:l,underlyingAssetId:i,maturity:m}}async mapShares(t,e,s,n){let{assets:i}=n,{name:a,symbol:o,asset_type:r,is_sufficient:l,existential_deposit:c}=e,d=await Promise.all(i.map(async b=>{let{symbol:O}=await this.mapToken(b,e,s);return[b,O]})),m=Object.fromEntries(d),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,n){let i=await this.mapToken(t,e,new Map,n),a=s?.find(o=>o.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}parseMetadata(t){return new Map(Array.from(t,([e,s])=>[e,{symbol:s.symbol?.asText(),decimals:s.decimals}]))}async getOnChainAssets(t,e){let[s,n,i,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 d=n.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 O=i.get(l);p=await this.mapShares(l,c,o,O);break;case"External":p=await this.mapExternal(l,c,e,d);break;default:p=await this.mapToken(l,c,o,d)}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 h=require("rxjs");var Ct={};w(Ct,{HUB_ASSET_ID:()=>Mt,HYDRATION_OMNIPOOL_ADDRESS:()=>Fe,HYDRATION_PARACHAIN_ID:()=>Be,HYDRATION_SS58_PREFIX:()=>G,RUNTIME_DECIMALS:()=>k,SYSTEM_ASSET_DECIMALS:()=>Te,SYSTEM_ASSET_ID:()=>Q,TRADEABLE_DEFAULT:()=>J});var k=18,Q=0,Te=12,Be=2034,G=63,Fe="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Mt=1,J=15;var $=class extends L{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:s,frozen:n}}=await e.getValue(t);return s-n}async getTokenBalance(t,e){let s=this.api.query.Tokens.Accounts,{free:n,frozen:i}=await s.getValue(t,e);return n-i}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),s=this.subscribeTokensBalance(t),n=this.subscribeErc20Balance(t);return(0,h.combineLatest)([e,s,n]).pipe((0,h.debounceTime)(250),(0,h.map)(i=>i.flat()),(0,h.startWith)([]),(0,h.bufferCount)(2,1),(0,h.map)(([i,a],o)=>{if(o===0)return a;let r=i.reduce((c,d)=>(c.set(d.id,d.amount),c),new Map);return a.filter(c=>c.amount!==r.get(c.id))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,h.map)(s=>{let{free:n,frozen:i}=s.data;return{id:0,amount:n-i}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,h.map)(n=>{let{free:i,frozen:a}=n;return{id:e,amount:i-a}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,h.distinctUntilChanged)((s,n)=>!n.deltas),(0,h.map)(({deltas:s})=>{let n=[];return s?.deleted.forEach(i=>{let[a,o]=i.args;n.push({id:o,amount:0n})}),s?.upserted.forEach(i=>{let[a,o]=i.args,{free:r,frozen:l}=i.value;n.push({id:o,amount:r-l})}),n}))}subscribeErc20Balance(t,e){let s=new h.Subject,n=s.pipe((0,h.shareReplay)(1)),i=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 i(),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),n.pipe((0,h.finalize)(()=>o?.()),(0,h.pairwise)(),(0,h.map)(([r,l],c)=>{if(c===0)return l;let d=r.reduce((p,b)=>(p.set(b.id,b.amount),p),new Map);return l.filter(p=>p.amount!==d.get(p.id))}),(0,h.distinctUntilChanged)((r,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:s,frozen:n}=await this.api.apis.CurrenciesApi.account(e,t);return s-n}};var Gt={};w(Gt,{AssetNotFound:()=>Nt,PoolNotFound:()=>at,RouteNotFound:()=>Z});var Nt=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"}},Z=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Qt={};w(Qt,{PoolContextProvider:()=>Bt,PoolError:()=>Y,PoolFactory:()=>st,PoolType:()=>T,aave:()=>Kt,lbp:()=>Yt,omni:()=>Ut,stable:()=>jt,xyk:()=>zt});var Yt={};w(Yt,{LbpMath:()=>M,LbpPool:()=>ct,LbpPoolClient:()=>ut});var C=require("@galacticcouncil/math-lbp"),M=class{static getSpotPrice(t,e,s,n,i){return(0,C.get_spot_price)(t,e,s,n,i)}static calculateInGivenOut(t,e,s,n,i){return(0,C.calculate_in_given_out)(t,e,s,n,i)}static calculateOutGivenIn(t,e,s,n,i){return(0,C.calculate_out_given_in)(t,e,s,n,i)}static calculateLinearWeights(t,e,s,n,i){return(0,C.calculate_linear_weights)(t,e,s,n,i)}static calculatePoolTradeFee(t,e,s){return(0,C.calculate_pool_trade_fee)(t,e,s)}};var T=(i=>(i.Aave="Aave",i.LBP="LBP",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="XYK",i))(T||{}),Y=(i=>(i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i.UnknownError="UnknownError",i))(Y||{});var y={};w(y,{toBigInt:()=>Re,toDecimal:()=>_e});var U=Dt(require("big.js"));U.default.NE=-18;function _e(u,t,e=6,s){let n=(0,U.default)(u.toString()),i=(0,U.default)(10).pow(t);return n.div(i).round(e,s).toString()}function Re(u,t){let e=(0,U.default)(10).pow(t),n=(0,U.default)(u).mul(e).toFixed(0,U.default.roundDown);return BigInt(n)}var lt={};w(lt,{ERC20Mapping:()=>Ht});var rt=require("buffer"),Ht=class{static encodeEvmAddress(t){let e=rt.Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static decodeEvmAddress(t){let e=rt.Buffer.from(t.replace("0x",""),"hex");if(e.length!==20||!this.isAssetAddress(t))throw new Error("Unable to decode evm address");return e.readUInt32BE(16)}static isAssetAddress(t){let e=rt.Buffer.from("0000000000000000000000000000000100000000","hex"),s=rt.Buffer.from(t.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(e.subarray(0,16))}};var Xt={};w(Xt,{convertFromH160:()=>ke,convertToH160:()=>Ee,isEvmAccount:()=>De});var vt=require("polkadot-api"),ae=require("@polkadot-api/utils"),H=require("buffer");var Wt="ETH\0";function ke(u,t=63){let e=H.Buffer.from(u.slice(2),"hex"),s=H.Buffer.from(Wt),n=Uint8Array.from(H.Buffer.concat([s,e,H.Buffer.alloc(8)])),i=(0,ae.toHex)(n);return(0,vt.AccountId)(t).dec(i)}function Ee(u){let t=(0,vt.AccountId)().enc(u),e=H.Buffer.from(Wt),s=t.slice(e.length,-8);return"0x"+H.Buffer.from(s).toString("hex")}function De(u){if(!u)return!1;try{let t=(0,vt.AccountId)().enc(u),e=H.Buffer.from(Wt);return H.Buffer.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}var g={};w(g,{fromPermill:()=>Ce,toDecimals:()=>Me,toPct:()=>Le});var re=1e3;function Le(u){let[t,e]=u;return t/e*100}function Me(u){let[t,e]=u;return t/e}function Ce(u){return[u/re,re]}var X={};w(X,{findNestedKey:()=>qe,findNestedObj:()=>Ne,jsonFormatter:()=>Ge});var qe=(u,t)=>{let e=[];return JSON.stringify(u,(s,n)=>(n&&n[t]&&e.push(n),n)),e[0]},Ne=(u,t,e)=>{let s;return JSON.stringify(u,(n,i)=>(i&&i[t]===e&&(s=i),i)),s},Ge=(u,t)=>typeof t=="bigint"?t.toString():t;var v={};w(v,{calculateBuyFee:()=>Ve,calculateDiffToAvg:()=>He,calculateDiffToRef:()=>We,calculateSellFee:()=>Xe,getFraction:()=>Ye});var q=Dt(require("big.js"));function He(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 We(u,t){if(t===0n)return 0;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 Xe(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 Ve(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 Ye(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let s=Math.pow(10,e),n=BigInt(t*s);return u*n/BigInt(100*s)}var Vt={};w(Vt,{convertToId:()=>Ue});var le=require("buffer");function Ue(u){let e=le.Buffer.from(u.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var ct=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,n,i,a,o){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i,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])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,weightIn:n.weight,weightOut:i.weight}}validateAndBuy(t,e,s){let n=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&i.push("MaxOutRatioExceeded"),n===t.assetOut){let o=this.calculateTradeFee(e,s),r=g.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+o,c=this.calculateInGivenOut(t,l),d=t.balanceIn/this.maxInRatio;return c>d&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:r,errors:i}}else{let o=this.calculateInGivenOut(t,e),r=t.balanceIn/this.maxInRatio;return o>r&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,s){let n=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&i.push("MaxInRatioExceeded"),n===t.assetIn){let o=this.calculateOutGivenIn(t,e),r=t.balanceOut/this.maxOutRatio;return o>r&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(o,s),l=g.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o-r,d=t.balanceOut/this.maxOutRatio;return c>d&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(t,e){let s=M.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e){let s=M.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(s);return n<0n?0n:n}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 ue=require("polkadot-api"),j=require("rxjs");var ce=(u,t=new Map)=>e=>{let s;return t.has(e)?t.get(e):(t.set(e,s=u(e)),s)};var f=require("rxjs");var E=class extends ${override=[];mem=0;memPools=ce(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,f.from)(this.getPoolsMem()).pipe((0,f.switchMap)(e=>this.subscribe(e)),(0,f.combineLatestAll)());return(0,f.firstValueFrom)(t)}getSubscriber(){return(0,f.from)(this.getPoolsMem()).pipe((0,f.switchMap)(t=>this.subscribe(t)),(0,f.mergeAll)())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>(0,f.combineLatest)([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe((0,f.debounceTime)(250),(0,f.map)(([s,n])=>this.updatePool(s,n))))}subscribePoolBalance(t){if(t.type==="Aave")return(0,f.of)([]);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(i=>i.type==="Erc20").map(i=>i.id),n=this.subscribeErc20Balance(t.address,s);e.push(n)}return(0,f.combineLatest)(e).pipe((0,f.map)(s=>s.map(n=>Array.isArray(n)?n:[n]).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:n})=>{let i=this.override.find(o=>o.id===e),a=!!s||!!i?.decimals;return n>0n&&a})}updatePool=(t,e)=>{let s=t.tokens.map(n=>{let i=e.find(o=>o.id===n.id),a=this.override.find(o=>o.id===n.id);return i?{...n,balance:i.amount,decimals:n.decimals||a?.decimals}:{...n,decimals:n.decimals||a?.decimals}});return{...t,tokens:s}}};var ut=class extends E{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()]),n=e?.relay_parent_number||0,i=t.filter(({value:a})=>e&&this.isActivePool(a,n)).map(async({keyArgs:a,value:o})=>{let[r]=a,l=r.toString(),c=await this.getPoolDelta(l,o,n);return{address:l,type:"LBP",fee:o.fee,...c,...s}});return Promise.all(i)}async getPoolDelta(t,e,s){let{start:n,end:i,assets:a,initial_weight:o,final_weight:r,repay_target:l,fee_collector:c}=e,d=M.calculateLinearWeights(n?n.toString():"0",i?i.toString():"0",o.toString(),r.toString(),s.toString()),[m,p]=a,b=BigInt(d),O=this.MAX_FINAL_WEIGHT-BigInt(b),[A,R,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:A,tokens:[{id:m,decimals:F?.decimals,existentialDeposit:F?.existential_deposit,balance:R,weight:b,type:F?.asset_type.type},{id:p,decimals:D?.decimals,existentialDeposit:D?.existential_deposit,balance:_,weight:O,type:D?.asset_type.type}]}}isActivePool(t,e){let{start:s,end:n}=t;return s&&n?e>=s&&e<n:!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(ue.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,j.switchMap)(n=>n?this.getPoolDelta(t.address,s,n.relay_parent_number):(0,j.of)(t)),(0,j.map)(n=>Object.assign({},t,n))):(0,j.of)(t)}};var Ut={};w(Ut,{OmniMath:()=>x,OmniPool:()=>mt,OmniPoolClient:()=>dt});var P=require("@galacticcouncil/math-omnipool"),z=Dt(require("big.js")),x=class{static calculateSpotPrice(t,e,s,n){return(0,P.calculate_spot_price)(t,e,s,n)}static calculateLrnaSpotPrice(t,e){return(0,P.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,s,n,i,a,o,r,l){return(0,P.calculate_in_given_out)(t,e,s,n,i,a,o,r,l)}static calculateLrnaInGivenOut(t,e,s,n,i){return(0,P.calculate_lrna_in_given_out)(t,e,s,n,i)}static calculateOutGivenIn(t,e,s,n,i,a,o,r,l){return(0,P.calculate_out_given_in)(t,e,s,n,i,a,o,r,l)}static calculateOutGivenLrnaIn(t,e,s,n,i){return(0,P.calculate_out_given_lrna_in)(t,e,s,n,i)}static calculatePoolTradeFee(t,e,s){return(0,P.calculate_pool_trade_fee)(t,e,s)}static calculateShares(t,e,s,n){return(0,P.calculate_shares)(t,e,s,n)}static calculateLiquidityOut(t,e,s,n,i,a,o,r){return(0,P.calculate_liquidity_out)(t,e,s,n,i,a,o,r)}static calculateLiquidityLRNAOut(t,e,s,n,i,a,o,r){return(0,P.calculate_liquidity_lrna_out)(t,e,s,n,i,a,o,r)}static calculateCapDifference(t,e,s,n){let i=(0,z.default)(e),a=(0,z.default)(t),o=(0,z.default)(n),r=(0,z.default)(s),l=(0,z.default)(10).pow(18),c=r.div(l);if(i.div(o).lt(c)){let m=c.times(o).minus(i).times(a),p=i.times((0,z.default)(1).minus(c));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,s,n){return(0,P.verify_asset_cap)(t,e,s,n)}static calculateLimitHubIn(t,e,s,n){return(0,P.calculate_liquidity_hub_in)(t,e,s,n)}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 mt=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,n,i,a){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i,this.hubAssetId=a}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:n.hubReserves,hubReservesOut:i.hubReserves,sharesIn:n.shares,sharesOut:i.shares,decimalsIn:n.decimals,decimalsOut:i.decimals,balanceIn:n.balance,balanceOut:i.balance,tradeableIn:n.tradeable,tradeableOut:i.tradeable,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let n=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),a=n===0n?0:v.calculateDiffToRef(i,n),o=[],r=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&o.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&o.push("MaxOutRatioExceeded");let d=t.balanceIn/this.maxInRatio;return i>d&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:n,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let n=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),a=v.calculateDiffToRef(n,i),o=[],r=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&o.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&o.push("MaxInRatioExceeded");let d=t.balanceOut/this.maxOutRatio;return i>d&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:i,feePct:a,errors:o}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let n=x.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?g.toDecimals(s.assetFee).toString():"0",s?g.toDecimals(s.protocolFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,s){let n=x.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?g.toDecimals(s.assetFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let n=x.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?g.toDecimals(s.assetFee).toString():"0",s?g.toDecimals(s.protocolFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,s){let n=x.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?g.toDecimals(s.assetFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=x.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=x.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=x.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=x.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}};var At=require("polkadot-api"),me=require("@polkadot-api/utils"),pt=require("rxjs");var dt=class extends E{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[s,n,i,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:d})=>{let[m]=c,{hub_reserve:p,shares:b,tradable:O,cap:A,protocol_shares:R}=d,[F,_]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:F?.decimals,existentialDeposit:F?.existential_deposit,balance:_,cap:A,hubReserves:p,protocolShares:R,shares:b,tradeable:O,type:F?.asset_type.type}}),l=await Promise.all(r);return l.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:a,tradeable:n,type:i?.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,me.toHex)(e);return(0,At.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,n,i]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),a=s.min_fee+n.min_fee,o=s.max_fee+n.max_fee;if(i){let{asset_fee:r,protocol_fee:l}=i;return{assetFee:g.fromPermill(r),protocolFee:g.fromPermill(l),min:g.fromPermill(a),max:g.fromPermill(o)}}else return{assetFee:g.fromPermill(s.min_fee),protocolFee:g.fromPermill(n.min_fee),min:g.fromPermill(a),max:g.fromPermill(o)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(At.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,pt.distinctUntilChanged)((s,n)=>!n.deltas),(0,pt.map)(({entries:s})=>s.map(n=>{let[i]=n.args,{hub_reserve:a,shares:o,tradable:r,cap:l,protocol_shares:c}=n.value,d=t.tokens.findIndex(p=>p.id===i);return{...t.tokens[d],cap:l,hubReserves:a,protocolShares:c,shares:o,tradeable:r}})),(0,pt.map)(s=>{let n=t.tokens.find(i=>i.id===1);return{...t,tokens:[...s,n]}}))}};var jt={};w(jt,{StableMath:()=>B,StableSwap:()=>gt,StableSwapClient:()=>bt});var S=require("@galacticcouncil/math-stableswap"),B=class{static getPoolAddress(t){return(0,S.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,n,i){return(0,S.calculate_amplification)(t,e,s,n,i)}static calculateInGivenOut(t,e,s,n,i,a,o){return(0,S.calculate_in_given_out)(t,e,s,n,i,a,o)}static calculateAddOneAsset(t,e,s,n,i,a,o){return(0,S.calculate_add_one_asset)(t,e,s,n,i,a,o)}static calculateSharesForAmount(t,e,s,n,i,a,o){return(0,S.calculate_shares_for_amount)(t,e,s,n,i,a,o)}static calculateOutGivenIn(t,e,s,n,i,a,o){return(0,S.calculate_out_given_in)(t,e,s,n,i,a,o)}static calculateLiquidityOutOneAsset(t,e,s,n,i,a,o){return(0,S.calculate_liquidity_out_one_asset)(t,e,s,n,i,a,o)}static calculateShares(t,e,s,n,i,a){return(0,S.calculate_shares)(t,e,s,n,i,a)}static calculateSpotPriceWithFee(t,e,s,n,i,a,o,r){return(0,S.calculate_spot_price_with_fee)(t,e,s,n,i,a,o,r)}static calculatePoolTradeFee(t,e,s){return(0,S.calculate_pool_trade_fee)(t,e,s)}static recalculatePegs(t,e,s,n,i){return(0,S.recalculate_peg)(t,e,s,n,i)}};var gt=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,n,i,a,o,r,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i,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])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:n.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let n=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),a=g.toPct(s.fee),o=[],r=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:n,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let n=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),a=g.toPct(s.fee),o=[],r=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&o.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:n,amountOut:i,feePct:a,errors:o}}calculateIn(t,e,s){let n=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateAddOneAsset(t,e,s){let n=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateSharesForAmount(t,e,s){let n=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}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=B.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 n=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(n)}let s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateOut(t,e,s){let n=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,s){let n=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateShares(t,e,s){let n=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}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=B.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 n=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(n)}let s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let[s,n]=e.fee,i=B.calculatePoolTradeFee(t.toString(),s,n);return BigInt(i)}getPegs(){let t=B.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:n})=>({asset_id:e,amount:s,decimals:n}));return JSON.stringify(t,X.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],X.jsonFormatter)}};var Tt=require("polkadot-api"),pe=require("@polkadot-api/utils"),de=require("@noble/hashes/blake2b"),tt=require("rxjs");var je=340282366920938463463374607431768211455n,bt=class extends E{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()]),n=t.map(async({keyArgs:i,value:a})=>{let[o]=i,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:g.fromPermill(a.fee),tokens:c,...l,...s}});return Promise.all(n)}async getPoolDelta(t,e,s){let{initial_amplification:n,final_amplification:i,initial_block:a,final_block:o}=e,r=B.calculateAmplification(n.toString(),i.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),n=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}}),i=await Promise.all(n),a=await this.api.query.AssetRegistry.Assets.getValue(t);return i.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:je,tradeable:15,type:a?.asset_type.type}),i}getPoolAddress(t){let e=B.getPoolAddress(t),s=(0,de.blake2b)(e,{dkLen:32}),n=(0,pe.toHex)(s);return(0,Tt.AccountId)(63).dec(n)}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(Tt.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)(n=>this.getPoolDelta(t.id,s,n)),(0,tt.map)(n=>Object.assign({},t,n)))}};var zt={};w(zt,{XykMath:()=>W,XykPool:()=>Pt,XykPoolClient:()=>ht});var I=require("@galacticcouncil/math-xyk"),W=class{static getSpotPrice(t,e,s){return(0,I.get_spot_price)(t,e,s)}static calculateInGivenOut(t,e,s){return(0,I.calculate_in_given_out)(t,e,s)}static calculateOutGivenIn(t,e,s){return(0,I.calculate_out_given_in)(t,e,s)}static calculatePoolTradeFee(t,e,s){return(0,I.calculate_pool_trade_fee)(t,e,s)}static calculateLiquidityIn(t,e,s){return(0,I.calculate_liquidity_in)(t,e,s)}static calculateSpotPrice(t,e){return(0,I.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,s,n){return(0,I.calculate_spot_price_with_fee)(t,e,s,n)}static calculateShares(t,e,s){return(0,I.calculate_shares)(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,n){return(0,I.calculate_liquidity_out_asset_a)(t,e,s,n)}static calculateLiquidityOutAssetB(t,e,s,n){return(0,I.calculate_liquidity_out_asset_b)(t,e,s,n)}};var Pt=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,n,i){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:n.decimals,decimalsOut:i.decimals,balanceIn:n.balance,balanceOut:i.balance,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let n=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(n,s),a=g.toPct(s.exchangeFee),o=n+i,r=[];(e<this.minTradingLimit||n<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:n,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,s){let n=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(n,s),a=g.toPct(s.exchangeFee),o=n-i,r=[];(e<this.minTradingLimit||n<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:n,amountOut:o,feePct:a,errors:r}}calculateInGivenOut(t,e){let s=W.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e){let s=W.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(s);return n<0n?0n:n}spotPriceInGivenOut(t){let e=W.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceOutGivenIn(t){let e=W.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let s=W.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}};var ge=require("polkadot-api"),be=require("rxjs");var ht=class extends E{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,s]=await Promise.all([t.getEntries(),this.getPoolLimits()]),n=e.map(async({keyArgs:i,value:a})=>{let[o]=i,[r,l]=a,[c,d,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:d?.decimals,existentialDeposit:d?.existential_deposit,balance:c,type:d?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...s}});return Promise.all(n)}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(ge.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return(0,be.of)(t)}};var Kt={};w(Kt,{AavePool:()=>yt,AavePoolClient:()=>ft});var yt=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,n,i){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,s){let n=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,s){let n=this.calculateOutGivenIn(t,e),i=[];return n>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:i}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};var he=require("polkadot-api"),ye=require("@polkadot-api/utils"),et=require("rxjs"),fe=require("viem");var Pe=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var ze=["Supply","Withdraw","Repay","Borrow"],ft=class extends E{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:s,atoken:n,liqudity_in:i,liqudity_out:a})=>{let[o,r,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s),this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n)]);return{address:this.getPoolId(s,n),type:"Aave",tokens:[{id:s,decimals:o?.decimals,existentialDeposit:o?.existential_deposit,balance:i,location:r,type:o?.asset_type.type},{id:n,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:a,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,s]=t.tokens,{liqudity_in:n,liqudity_out:i}=await this.api.apis.AaveTradeExecutor.pool(e.id,s.id);return t.tokens.map(a=>{let o=a.id===e.id?n:i;return{...a,balance:o}})}getPoolId(t,e){let s=t+"/"+e,n=new TextEncoder().encode(s.padEnd(32,"\0")),i=(0,ye.toHex)(n);return(0,he.AccountId)(63).dec(i)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,s]=t.tokens,n=this.getReserveH160Id(e),i=this.api.event.Router.Executed.watch(({asset_in:o,asset_out:r})=>o===s.id||r===s.id),a=this.api.event.EVM.Log.watch(({log:o})=>{let{topics:r,data:l}=o,c=r.map(b=>b.asHex()),d=l.asHex(),{eventName:m,args:p}=(0,fe.decodeEventLog)({abi:Pe,topics:c,data:d});return ze.includes(m)&&p.reserve.toLowerCase()===n.toLowerCase()});return(0,et.merge)([i,a]).pipe((0,et.switchMap)(()=>this.getPoolDelta(t)),(0,et.map)(o=>({...t,tokens:[...o]})))}getReserveH160Id(t){return t.type==="Erc20"?X.findNestedKey(t.location,"AccountKey20").AccountKey20.key:lt.ERC20Mapping.encodeEvmAddress(t.id)}};var st=class{static get(t){switch(t.type){case"Aave":return yt.fromPool(t);case"XYK":return Pt.fromPool(t);case"Omnipool":return mt.fromPool(t);case"LBP":return ct.fromPool(t);case"Stableswap":return gt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var N=require("rxjs");var Bt=class extends L{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=N.Subscription.EMPTY;omniSub=N.Subscription.EMPTY;stableSub=N.Subscription.EMPTY;xykSub=N.Subscription.EMPTY;aaveSub=N.Subscription.EMPTY;isReady=!1;isDestroyed=new N.Subject;constructor(t){super(t),this.lbpClient=new ut(t),this.omniClient=new dt(t),this.stableClient=new bt(t),this.xykClient=new ht(t),this.aaveClient=new ft(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe((0,N.takeUntil)(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),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(n=>n.getPoolType()===t.type);if(s)return s.getPoolFees(t,e);throw new at(t.type)}};var Zt={};w(Zt,{Router:()=>nt,TradeRouter:()=>Rt,TradeType:()=>_t,TradeUtils:()=>kt});var Ft=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 Ke=5,St=class{isNotVisited(t,e){let s=!0;return e.forEach(n=>{(n[0]===t[0]||n[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let n=[],i=new Ft,a=[];for(a.push([e,""]),i.enqueue(a);i.size()>0;){let o=i.dequeue();if(o==null||o.length>Ke)return n;let r=o[o.length-1];(s===null||r[0]===s)&&n.push(o),t.get(r[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let d=[...o];d.push(c),i.enqueue(d)}})}return n}buildAndPopulateGraph(t,e){let s=new Map;for(let n of t)s.set(parseInt(n),[]);for(let[n,i,a]of e)s.get(i)?.push([a,n]);return s}};function Jt(u){let t={};for(let e of u){let s=e.tokens.length;for(let n=0;n<s;n++){t[e.tokens[n].id]||(t[e.tokens[n].id]=[]);for(let i=0;i<s;i++){if(n==i)continue;let a=[e.address,e.tokens[n].id,e.tokens[i].id];t[e.tokens[n].id].push(a)}}}return t}var xt=class{getProposals(t,e,s){let n=Jt(s),i=Object.keys(n),a=i.map(c=>n[c]).flat(),o=new St,r=o.buildAndPopulateGraph(i,a),l=o.findPaths(r,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let s of t){let n=[];for(let i=0;i<s.length;i++){let a=s[i],o=s[i+1];if(o==null)break;n.push(this.toEdge(a,o))}e.push(n)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var nt=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new xt,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 n=this.getAssets(s);if(!n.has(t))throw new Error(t+" is not supported asset");if(!n.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(n=>n.id)).flat().sort((s,n)=>s>n?1:-1);return new Set(e)}getPaths(t,e,s){let n=this.toPoolsMap(s);return this.routeSuggester.getProposals(t,e,s).filter(a=>this.validPath(a,n)).map(a=>this.toHops(a,n))}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,n)=>s&&n)}validEdge([t,e,s],n){return n.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,st.get(e)]))}toHops(t,e){return t.map(([s,n,i])=>{let a=e.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:n,assetOut:i}})}};var _t=(e=>(e.Buy="Buy",e.Sell="Sell",e))(_t||{});var Rt=class extends nt{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,n)=>{let i=s[s.length-1].amountOut,a=n[n.length-1].amountOut;return i>a?-1:1});return e.find(s=>s.every(n=>n.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),n=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,n]}}getPoolFeeRange(t){let e=t.min?g.toPct(t.min):void 0,s=t.max?g.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),n=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),i=s-e.assetOutDecimals,a=Math.pow(10,i);return n/BigInt(a)}async getSell(t,e,s,n){let i=await super.getPools(),a=super.validateInput(t,e,i),o=super.getPaths(t,e,i);if(o.length===0)throw new Z(t,e);let r;if(n)r=await this.toSellSwaps(s,n,a);else{let V=await Promise.all(o.map(Et=>this.toSellSwaps(s,Et,a)));r=this.findBestSellRoute(V)}let l=r[0],c=r[r.length-1],d=this.isDirectTrade(r),m=await this.getSellSpot(r),p=c.amountOut,b=d?c.calculatedOut:this.calculateDelta0Y(l.amountIn,r,a),O=b-p,A=this.getRouteFeeRange(r),R=d?c.tradeFeePct:v.calculateSellFee(b,p),F=Math.pow(10,l.assetInDecimals),_=l.amountIn*m/BigInt(F),D=v.calculateDiffToRef(b,_);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:m,tradeFee:O,tradeFeePct:R,tradeFeeRange:A,priceImpactPct:D,swaps:r,toHuman(){return{type:"Sell",amountIn:y.toDecimal(l.amountIn,l.assetInDecimals),amountOut:y.toDecimal(c.amountOut,c.assetOutDecimals),spotPrice:y.toDecimal(m,c.assetOutDecimals),tradeFee:y.toDecimal(O,c.assetOutDecimals),tradeFeePct:R,tradeFeeRange:A,priceImpactPct:D,swaps:r.map(V=>V.toHuman())}}}}calculateDelta0Y(t,e,s){let n=[];for(let i=0;i<e.length;i++){let a=e[i],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;i>0?l=n[i-1]:l=t;let c=o.calculateOutGivenIn(r,l);n.push(c)}return n[n.length-1]}async toSellSwaps(t,e,s){let n=[];for(let i=0;i<e.length;i++){let a=e[i],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;i>0?l=n[i-1].amountOut:l=typeof t=="string"?y.toBigInt(t,r.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountOut:d,calculatedOut:m,feePct:p,errors:b}=o.validateAndSell(r,l,c),O=this.getPoolFeeRange(c),A=o.spotPriceOutGivenIn(r),R=Math.pow(10,r.decimalsIn),F=l*A/BigInt(R),_=v.calculateDiffToRef(m,F);n.push({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountIn:l,amountOut:d,calculatedOut:m,spotPrice:A,tradeFeePct:p,tradeFeeRange:O,priceImpactPct:_,errors:b,toHuman(){return{...a,amountIn:y.toDecimal(l,r.decimalsIn),amountOut:y.toDecimal(d,r.decimalsOut),calculatedOut:y.toDecimal(m,r.decimalsOut),spotPrice:y.toDecimal(A,r.decimalsOut),tradeFeePct:p,tradeFeeRange:O,priceImpactPct:_,errors:b}}})}return n}async getMostLiquidRoute(t,e){let s=await super.getPools(),n=super.validateInput(t,e,s),i=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=v.getFraction(r,.1),c=await Promise.all(i.map(m=>this.toSellSwaps(l,m,n)));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(),n=super.validateInput(t,e,s),i=await this.getMostLiquidRoute(t,e),a=await this.toSellSwaps("1",i,n),o=await this.getSellSpot(a),r=a[a.length-1].assetOutDecimals;return{amount:o,decimals:r}}findBestBuyRoute(t){let e=t.sort((s,n)=>{let i=s[0].amountIn,a=n[0].amountIn;return i>a?1:-1});return e.find(s=>s.every(n=>n.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),n=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),i=s-e.assetInDecimals,a=Math.pow(10,i);return n/BigInt(a)}async getBuy(t,e,s,n){let i=await super.getPools(),a=super.validateInput(t,e,i),o=super.getPaths(t,e,i);if(o.length===0)throw new Z(t,e);let r;if(n)r=await this.toBuySwaps(s,n,a);else{let V=await Promise.all(o.map(Et=>this.toBuySwaps(s,Et,a)));r=this.findBestBuyRoute(V)}let l=r[r.length-1],c=r[0],d=this.isDirectTrade(r),m=await this.getBuySpot(r),p=c.amountIn,b=d?c.calculatedIn:this.calculateDelta0X(l.amountOut,r,a),O=p-b,A=this.getRouteFeeRange(r),R=d?c.tradeFeePct:v.calculateBuyFee(b,p),F=Math.pow(10,l.assetOutDecimals),_=l.amountOut*m/BigInt(F),D;return b===0n?D=-100:D=v.calculateDiffToRef(_,b),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:m,tradeFee:O,tradeFeePct:R,tradeFeeRange:A,priceImpactPct:D,swaps:r,toHuman(){return{type:"Buy",amountOut:y.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:y.toDecimal(c.amountIn,c.assetInDecimals),spotPrice:y.toDecimal(m,c.assetInDecimals),tradeFee:y.toDecimal(O,c.assetInDecimals),tradeFeePct:R,tradeFeeRange:A,priceImpactPct:D,swaps:r.map(V=>V.toHuman())}}}}calculateDelta0X(t,e,s){let n=[];for(let i=e.length-1;i>=0;i--){let a=e[i],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;i==e.length-1?l=t:l=n[0];let c=o.calculateInGivenOut(r,l);n.unshift(c)}return n[0]}async toBuySwaps(t,e,s){let n=[];for(let i=e.length-1;i>=0;i--){let a=e[i],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;i==e.length-1?l=typeof t=="string"?y.toBigInt(t,r.decimalsOut):t:l=n[0].amountIn;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountIn:d,calculatedIn:m,feePct:p,errors:b}=o.validateAndBuy(r,l,c),O=this.getPoolFeeRange(c),A=o.spotPriceInGivenOut(r),R=Math.pow(10,r.decimalsOut),F=l*A/BigInt(R),_;m===0n?_=-100:_=v.calculateDiffToRef(F,m),n.unshift({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountOut:l,amountIn:d,calculatedIn:m,spotPrice:A,tradeFeePct:p,tradeFeeRange:O,priceImpactPct:_,errors:b,toHuman(){return{...a,amountOut:y.toDecimal(l,r.decimalsOut),amountIn:y.toDecimal(d,r.decimalsIn),calculatedIn:y.toDecimal(m,r.decimalsIn),spotPrice:y.toDecimal(A,r.decimalsIn),tradeFeePct:p,tradeFeeRange:O,priceImpactPct:_,errors:b}}})}return n}};var $t=require("polkadot-api");var kt=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:n,swaps:i}=t,a=i[0],o=i[i.length-1],r=v.getFraction(s,e),l=a.assetIn,c=o.assetOut,d=s+r;return this.isDirectOmnipoolTrade(i)?this.api.tx.Omnipool.buy({asset_in:l,asset_out:c,amount:n,max_sell_amount:d}).getEncodedData():this.api.tx.Router.buy({asset_in:l,asset_out:c,amount_out:n,max_amount_in:d,route:this.buildRoute(i)}).getEncodedData()}async buildSellTx(t,e=1){this.tradeCheck(t,"Sell");let{amountIn:s,amountOut:n,swaps:i}=t,a=i[0],o=i[i.length-1],r=v.getFraction(n,e),l=a.assetIn,c=o.assetOut,d=n-r;return this.isDirectOmnipoolTrade(i)?this.api.tx.Omnipool.sell({asset_in:l,asset_out:c,amount:s,min_buy_amount:d}).getEncodedData():this.api.tx.Router.sell({asset_in:l,asset_out:c,amount_in:s,min_amount_out:d,route:this.buildRoute(i)}).getEncodedData()}async buildSellAllTx(t,e=1){this.tradeCheck(t,"Sell");let{amountOut:s,swaps:n}=t,i=n[0],a=n[n.length-1],o=v.getFraction(s,e),r=i.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(n)}).getEncodedData()}buildRoute(t){return t.map(({assetIn:e,assetOut:s,pool:n,poolId:i})=>n==="Stableswap"?{pool:(0,$t.Enum)("Stableswap",i),asset_in:e,asset_out:s}:{pool:(0,$t.Enum)(n),asset_in:e,asset_out:s})}};0&&(module.exports={api,big,client,const:null,erc20,error,evm,fmt,json,math,pool,sor,xc});
|
package/build/index.mjs
CHANGED
|
@@ -1 +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};
|
|
1
|
+
var Ut=Object.defineProperty;var f=(u,t)=>{for(var e in t)Ut(u,e,{get:t[e],enumerable:!0})};var Bt={};f(Bt,{Papi:()=>_,getWs:()=>zt});import{createClient as jt}from"polkadot-api";import{withPolkadotSdkCompat as Kt}from"polkadot-api/polkadot-sdk-compat";var zt=async u=>{let t=typeof u=="string"?u.split(","):u,n=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return jt(Kt(n))};import{hydration as Qt}from"@galacticcouncil/descriptors";var _=class{client;constructor(t){this.client=t}get api(){return this.client.getTypedApi(Qt)}logSync(t,e,s){let n=t.substring(0,10).concat("..."),i=["\u{1F504} Sync",e,"[",n,"]",s].join(" ");console.log(i)}};var Rt={};f(Rt,{AssetClient:()=>lt,BalanceClient:()=>W});var lt=class extends _{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:n})=>{let[i]=s;return[i,n]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:s,value:n})=>{let[i]=s;return[i,n]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:s})=>{let{asset_type:n}=s;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:s,value:n})=>{let[i]=s;return[i,n]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:s,value:n})=>{let[i]=s;return[i,n]}))}async mapToken(t,e,s,n){let{name:i,asset_type:a,is_sufficient:o,existential_deposit:r}=e,{symbol:l,decimals:c}=s.get(t)??{};return{id:t,name:i?.asText(),symbol:l,decimals:c,icon:l,type:a.type,isSufficient:o,location:n,existentialDeposit:r}}async mapBond(t,e,s,n){let[i,a]=n,{asset_type:o,is_sufficient:r,existential_deposit:l}=e,{symbol:c,decimals:d}=await this.mapToken(i,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:d,icon:c,type:o.type,isSufficient:r,existentialDeposit:l,underlyingAssetId:i,maturity:m}}async mapShares(t,e,s,n){let{assets:i}=n,{name:a,symbol:o,asset_type:r,is_sufficient:l,existential_deposit:c}=e,d=await Promise.all(i.map(async b=>{let{symbol:y}=await this.mapToken(b,e,s);return[b,y]})),m=Object.fromEntries(d),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,n){let i=await this.mapToken(t,e,new Map,n),a=s?.find(o=>o.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}parseMetadata(t){return new Map(Array.from(t,([e,s])=>[e,{symbol:s.symbol?.asText(),decimals:s.decimals}]))}async getOnChainAssets(t,e){let[s,n,i,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 d=n.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=i.get(l);p=await this.mapShares(l,c,o,y);break;case"External":p=await this.mapExternal(l,c,e,d);break;default:p=await this.mapToken(l,c,o,d)}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 te,bufferCount as ee,combineLatest as se,debounceTime as ne,distinctUntilChanged as _t,finalize as ie,map as H,pairwise as oe,shareReplay as ae,startWith as re}from"rxjs";var Ft={};f(Ft,{HUB_ASSET_ID:()=>ht,HYDRATION_OMNIPOOL_ADDRESS:()=>Zt,HYDRATION_PARACHAIN_ID:()=>$t,HYDRATION_SS58_PREFIX:()=>k,RUNTIME_DECIMALS:()=>T,SYSTEM_ASSET_DECIMALS:()=>Jt,SYSTEM_ASSET_ID:()=>N,TRADEABLE_DEFAULT:()=>G});var T=18,N=0,Jt=12,$t=2034,k=63,Zt="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",ht=1,G=15;var W=class extends _{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:s,frozen:n}}=await e.getValue(t);return s-n}async getTokenBalance(t,e){let s=this.api.query.Tokens.Accounts,{free:n,frozen:i}=await s.getValue(t,e);return n-i}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),s=this.subscribeTokensBalance(t),n=this.subscribeErc20Balance(t);return se([e,s,n]).pipe(ne(250),H(i=>i.flat()),re([]),ee(2,1),H(([i,a],o)=>{if(o===0)return a;let r=i.reduce((c,d)=>(c.set(d.id,d.amount),c),new Map);return a.filter(c=>c.amount!==r.get(c.id))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(H(s=>{let{free:n,frozen:i}=s.data;return{id:0,amount:n-i}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(H(n=>{let{free:i,frozen:a}=n;return{id:e,amount:i-a}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(_t((s,n)=>!n.deltas),H(({deltas:s})=>{let n=[];return s?.deleted.forEach(i=>{let[a,o]=i.args;n.push({id:o,amount:0n})}),s?.upserted.forEach(i=>{let[a,o]=i.args,{free:r,frozen:l}=i.value;n.push({id:o,amount:r-l})}),n}))}subscribeErc20Balance(t,e){let s=new te,n=s.pipe(ae(1)),i=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 i(),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),n.pipe(ie(()=>o?.()),oe(),H(([r,l],c)=>{if(c===0)return l;let d=r.reduce((p,b)=>(p.set(b.id,b.amount),p),new Map);return l.filter(p=>p.amount!==d.get(p.id))}),_t((r,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:s,frozen:n}=await this.api.apis.CurrenciesApi.account(e,t);return s-n}};var kt={};f(kt,{AssetNotFound:()=>yt,PoolNotFound:()=>K,RouteNotFound:()=>X});var yt=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},K=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},X=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Xt={};f(Xt,{PoolContextProvider:()=>mt,PoolError:()=>C,PoolFactory:()=>U,PoolType:()=>x,aave:()=>At,lbp:()=>It,omni:()=>Ot,stable:()=>wt,xyk:()=>vt});var It={};f(It,{LbpMath:()=>R,LbpPool:()=>z,LbpPoolClient:()=>Q});import{calculate_in_given_out as le,calculate_out_given_in as ce,calculate_linear_weights as ue,calculate_pool_trade_fee as me,get_spot_price as pe}from"@galacticcouncil/math-lbp";var R=class{static getSpotPrice(t,e,s,n,i){return pe(t,e,s,n,i)}static calculateInGivenOut(t,e,s,n,i){return le(t,e,s,n,i)}static calculateOutGivenIn(t,e,s,n,i){return ce(t,e,s,n,i)}static calculateLinearWeights(t,e,s,n,i){return ue(t,e,s,n,i)}static calculatePoolTradeFee(t,e,s){return me(t,e,s)}};var x=(i=>(i.Aave="Aave",i.LBP="LBP",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="XYK",i))(x||{}),C=(i=>(i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i.UnknownError="UnknownError",i))(C||{});var P={};f(P,{toBigInt:()=>ge,toDecimal:()=>de});import V from"big.js";V.NE=-18;function de(u,t,e=6,s){let n=V(u.toString()),i=V(10).pow(t);return n.div(i).round(e,s).toString()}function ge(u,t){let e=V(10).pow(t),n=V(u).mul(e).toFixed(0,V.roundDown);return BigInt(n)}var ut={};f(ut,{ERC20Mapping:()=>ft});import{Buffer as ct}from"buffer";var ft=class{static encodeEvmAddress(t){let e=ct.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static decodeEvmAddress(t){let e=ct.from(t.replace("0x",""),"hex");if(e.length!==20||!this.isAssetAddress(t))throw new Error("Unable to decode evm address");return e.readUInt32BE(16)}static isAssetAddress(t){let e=ct.from("0000000000000000000000000000000100000000","hex"),s=ct.from(t.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(e.subarray(0,16))}};var Et={};f(Et,{convertFromH160:()=>Pe,convertToH160:()=>he,isEvmAccount:()=>ye});import{AccountId as St}from"polkadot-api";import{toHex as be}from"@polkadot-api/utils";import{Buffer as L}from"buffer";var xt="ETH\0";function Pe(u,t=63){let e=L.from(u.slice(2),"hex"),s=L.from(xt),n=Uint8Array.from(L.concat([s,e,L.alloc(8)])),i=be(n);return St(t).dec(i)}function he(u){let t=St().enc(u),e=L.from(xt),s=t.slice(e.length,-8);return"0x"+L.from(s).toString("hex")}function ye(u){if(!u)return!1;try{let t=St().enc(u),e=L.from(xt);return L.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}var g={};f(g,{fromPermill:()=>xe,toDecimals:()=>Se,toPct:()=>fe});var Dt=1e3;function fe(u){let[t,e]=u;return t/e*100}function Se(u){let[t,e]=u;return t/e}function xe(u){return[u/Dt,Dt]}var q={};f(q,{findNestedKey:()=>Ie,findNestedObj:()=>Oe,jsonFormatter:()=>we});var Ie=(u,t)=>{let e=[];return JSON.stringify(u,(s,n)=>(n&&n[t]&&e.push(n),n)),e[0]},Oe=(u,t,e)=>{let s;return JSON.stringify(u,(n,i)=>(i&&i[t]===e&&(s=i),i)),s},we=(u,t)=>typeof t=="bigint"?t.toString():t;var I={};f(I,{calculateBuyFee:()=>Be,calculateDiffToAvg:()=>ve,calculateDiffToRef:()=>Ae,calculateSellFee:()=>Te,getFraction:()=>Fe});import E from"big.js";function ve(u,t){let e=E(u.toString()),s=E(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function Ae(u,t){if(t===0n)return 0;let e=E(u.toString()),s=E(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function Te(u,t){let e=E(u.toString()),s=E(t.toString());return E(1).minus(s.div(e)).mul(100).round(2).toNumber()}function Be(u,t){let e=E(u.toString());return E(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Fe(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let s=Math.pow(10,e),n=BigInt(t*s);return u*n/BigInt(100*s)}var Lt={};f(Lt,{convertToId:()=>Re});import{Buffer as _e}from"buffer";function Re(u){let e=_e.from(u.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var z=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,n,i,a,o){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i,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])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,weightIn:n.weight,weightOut:i.weight}}validateAndBuy(t,e,s){let n=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&i.push("MaxOutRatioExceeded"),n===t.assetOut){let o=this.calculateTradeFee(e,s),r=g.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+o,c=this.calculateInGivenOut(t,l),d=t.balanceIn/this.maxInRatio;return c>d&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:r,errors:i}}else{let o=this.calculateInGivenOut(t,e),r=t.balanceIn/this.maxInRatio;return o>r&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,s){let n=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&i.push("MaxInRatioExceeded"),n===t.assetIn){let o=this.calculateOutGivenIn(t,e),r=t.balanceOut/this.maxOutRatio;return o>r&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(o,s),l=g.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o-r,d=t.balanceOut/this.maxOutRatio;return c>d&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(t,e){let s=R.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e){let s=R.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(s);return n<0n?0n:n}spotPriceInGivenOut(t){let e=R.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=R.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let s=R.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 qe}from"polkadot-api";import{map as Ne,of as Gt,switchMap as Ge}from"rxjs";import{memoize1 as ke}from"@thi.ng/memoize";import{combineLatest as Mt,combineLatestAll as Ee,debounceTime as De,firstValueFrom as Le,from as Ct,map as qt,mergeAll as Me,of as Ce,switchMap as Nt}from"rxjs";var B=class extends W{override=[];mem=0;memPools=ke(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=Ct(this.getPoolsMem()).pipe(Nt(e=>this.subscribe(e)),Ee());return Le(t)}getSubscriber(){return Ct(this.getPoolsMem()).pipe(Nt(t=>this.subscribe(t)),Me())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>Mt([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe(De(250),qt(([s,n])=>this.updatePool(s,n))))}subscribePoolBalance(t){if(t.type==="Aave")return Ce([]);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(i=>i.type==="Erc20").map(i=>i.id),n=this.subscribeErc20Balance(t.address,s);e.push(n)}return Mt(e).pipe(qt(s=>s.map(n=>Array.isArray(n)?n:[n]).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:n})=>{let i=this.override.find(o=>o.id===e),a=!!s||!!i?.decimals;return n>0n&&a})}updatePool=(t,e)=>{let s=t.tokens.map(n=>{let i=e.find(o=>o.id===n.id),a=this.override.find(o=>o.id===n.id);return i?{...n,balance:i.amount,decimals:n.decimals||a?.decimals}:{...n,decimals:n.decimals||a?.decimals}});return{...t,tokens:s}}};var Q=class extends B{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()]),n=e?.relay_parent_number||0,i=t.filter(({value:a})=>e&&this.isActivePool(a,n)).map(async({keyArgs:a,value:o})=>{let[r]=a,l=r.toString(),c=await this.getPoolDelta(l,o,n);return{address:l,type:"LBP",fee:o.fee,...c,...s}});return Promise.all(i)}async getPoolDelta(t,e,s){let{start:n,end:i,assets:a,initial_weight:o,final_weight:r,repay_target:l,fee_collector:c}=e,d=R.calculateLinearWeights(n?n.toString():"0",i?i.toString():"0",o.toString(),r.toString(),s.toString()),[m,p]=a,b=BigInt(d),y=this.MAX_FINAL_WEIGHT-BigInt(b),[S,A,w,v,F]=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:S,tokens:[{id:m,decimals:w?.decimals,existentialDeposit:w?.existential_deposit,balance:A,weight:b,type:w?.asset_type.type},{id:p,decimals:F?.decimals,existentialDeposit:F?.existential_deposit,balance:v,weight:y,type:F?.asset_type.type}]}}isActivePool(t,e){let{start:s,end:n}=t;return s&&n?e>=s&&e<n:!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(qe.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,s=this.poolsData.get(t.address);return s?e.watchValue("best").pipe(Ge(n=>n?this.getPoolDelta(t.address,s,n.relay_parent_number):Gt(t)),Ne(n=>Object.assign({},t,n))):Gt(t)}};var Ot={};f(Ot,{OmniMath:()=>h,OmniPool:()=>J,OmniPoolClient:()=>$});import{calculate_in_given_out as He,calculate_lrna_in_given_out as We,calculate_out_given_in as Xe,calculate_out_given_lrna_in as Ve,calculate_pool_trade_fee as Ye,calculate_spot_price as Ue,calculate_lrna_spot_price as je,calculate_shares as Ke,calculate_liquidity_out as ze,calculate_liquidity_lrna_out as Qe,verify_asset_cap as Je,calculate_liquidity_hub_in as $e,is_sell_allowed as Ze,is_buy_allowed as ts,is_add_liquidity_allowed as es,is_remove_liquidity_allowed as ss}from"@galacticcouncil/math-omnipool";import Y from"big.js";var h=class{static calculateSpotPrice(t,e,s,n){return Ue(t,e,s,n)}static calculateLrnaSpotPrice(t,e){return je(t,e)}static calculateInGivenOut(t,e,s,n,i,a,o,r,l){return He(t,e,s,n,i,a,o,r,l)}static calculateLrnaInGivenOut(t,e,s,n,i){return We(t,e,s,n,i)}static calculateOutGivenIn(t,e,s,n,i,a,o,r,l){return Xe(t,e,s,n,i,a,o,r,l)}static calculateOutGivenLrnaIn(t,e,s,n,i){return Ve(t,e,s,n,i)}static calculatePoolTradeFee(t,e,s){return Ye(t,e,s)}static calculateShares(t,e,s,n){return Ke(t,e,s,n)}static calculateLiquidityOut(t,e,s,n,i,a,o,r){return ze(t,e,s,n,i,a,o,r)}static calculateLiquidityLRNAOut(t,e,s,n,i,a,o,r){return Qe(t,e,s,n,i,a,o,r)}static calculateCapDifference(t,e,s,n){let i=Y(e),a=Y(t),o=Y(n),r=Y(s),l=Y(10).pow(18),c=r.div(l);if(i.div(o).lt(c)){let m=c.times(o).minus(i).times(a),p=i.times(Y(1).minus(c));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,s,n){return Je(t,e,s,n)}static calculateLimitHubIn(t,e,s,n){return $e(t,e,s,n)}static isSellAllowed(t){return Ze(t)}static isBuyAllowed(t){return ts(t)}static isAddLiquidityAllowed(t){return es(t)}static isRemoveLiquidityAllowed(t){return ss(t)}};var J=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,n,i,a){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i,this.hubAssetId=a}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:n.hubReserves,hubReservesOut:i.hubReserves,sharesIn:n.shares,sharesOut:i.shares,decimalsIn:n.decimals,decimalsOut:i.decimals,balanceIn:n.balance,balanceOut:i.balance,tradeableIn:n.tradeable,tradeableOut:i.tradeable,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let n=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),a=n===0n?0:I.calculateDiffToRef(i,n),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&o.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&o.push("MaxOutRatioExceeded");let d=t.balanceIn/this.maxInRatio;return i>d&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:n,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let n=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),a=I.calculateDiffToRef(n,i),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&o.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&o.push("MaxInRatioExceeded");let d=t.balanceOut/this.maxOutRatio;return i>d&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:i,feePct:a,errors:o}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let n=h.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?g.toDecimals(s.assetFee).toString():"0",s?g.toDecimals(s.protocolFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,s){let n=h.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?g.toDecimals(s.assetFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let n=h.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?g.toDecimals(s.assetFee).toString():"0",s?g.toDecimals(s.protocolFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,s){let n=h.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?g.toDecimals(s.assetFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}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 ns,CompatibilityLevel as is}from"polkadot-api";import{toHex as os}from"@polkadot-api/utils";import{distinctUntilChanged as as,map as Ht}from"rxjs";var $=class extends B{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[s,n,i,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:d})=>{let[m]=c,{hub_reserve:p,shares:b,tradable:y,cap:S,protocol_shares:A}=d,[w,v]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:w?.decimals,existentialDeposit:w?.existential_deposit,balance:v,cap:S,hubReserves:p,protocolShares:A,shares:b,tradeable:y,type:w?.asset_type.type}}),l=await Promise.all(r);return l.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:a,tradeable:n,type:i?.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=os(e);return ns(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,n,i]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),a=s.min_fee+n.min_fee,o=s.max_fee+n.max_fee;if(i){let{asset_fee:r,protocol_fee:l}=i;return{assetFee:g.fromPermill(r),protocolFee:g.fromPermill(l),min:g.fromPermill(a),max:g.fromPermill(o)}}else return{assetFee:g.fromPermill(s.min_fee),protocolFee:g.fromPermill(n.min_fee),min:g.fromPermill(a),max:g.fromPermill(o)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(is.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(as((s,n)=>!n.deltas),Ht(({entries:s})=>s.map(n=>{let[i]=n.args,{hub_reserve:a,shares:o,tradable:r,cap:l,protocol_shares:c}=n.value,d=t.tokens.findIndex(p=>p.id===i);return{...t.tokens[d],cap:l,hubReserves:a,protocolShares:c,shares:o,tradeable:r}})),Ht(s=>{let n=t.tokens.find(i=>i.id===1);return{...t,tokens:[...s,n]}}))}};var wt={};f(wt,{StableMath:()=>O,StableSwap:()=>Z,StableSwapClient:()=>tt});import{calculate_in_given_out as rs,calculate_out_given_in as ls,calculate_amplification as cs,calculate_add_one_asset as us,calculate_liquidity_out_one_asset as ms,calculate_pool_trade_fee as ps,calculate_shares as ds,calculate_shares_for_amount as gs,calculate_spot_price_with_fee as bs,pool_account_name as Ps,recalculate_peg as hs}from"@galacticcouncil/math-stableswap";var O=class{static getPoolAddress(t){return Ps(t)}static defaultPegs(t){let e=[];for(let s=0;s<t;s++)e.push(["1","1"]);return e}static calculateAmplification(t,e,s,n,i){return cs(t,e,s,n,i)}static calculateInGivenOut(t,e,s,n,i,a,o){return rs(t,e,s,n,i,a,o)}static calculateAddOneAsset(t,e,s,n,i,a,o){return us(t,e,s,n,i,a,o)}static calculateSharesForAmount(t,e,s,n,i,a,o){return gs(t,e,s,n,i,a,o)}static calculateOutGivenIn(t,e,s,n,i,a,o){return ls(t,e,s,n,i,a,o)}static calculateLiquidityOutOneAsset(t,e,s,n,i,a,o){return ms(t,e,s,n,i,a,o)}static calculateShares(t,e,s,n,i,a){return ds(t,e,s,n,i,a)}static calculateSpotPriceWithFee(t,e,s,n,i,a,o,r){return bs(t,e,s,n,i,a,o,r)}static calculatePoolTradeFee(t,e,s){return ps(t,e,s)}static recalculatePegs(t,e,s,n,i){return hs(t,e,s,n,i)}};var Z=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,n,i,a,o,r,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i,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])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:n.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let n=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),a=g.toPct(s.fee),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:n,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let n=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),a=g.toPct(s.fee),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&o.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:n,amountOut:i,feePct:a,errors:o}}calculateIn(t,e,s){let n=O.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateAddOneAsset(t,e,s){let n=O.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateSharesForAmount(t,e,s){let n=O.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}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=O.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 n=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(n)}let s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateOut(t,e,s){let n=O.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,s){let n=O.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateShares(t,e,s){let n=O.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?g.toDecimals(s.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}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=O.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 n=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(n)}let s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let[s,n]=e.fee,i=O.calculatePoolTradeFee(t.toString(),s,n);return BigInt(i)}getPegs(){let t=O.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:n})=>({asset_id:e,amount:s,decimals:n}));return JSON.stringify(t,q.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],q.jsonFormatter)}};import{AccountId as ys,CompatibilityLevel as fs}from"polkadot-api";import{toHex as Ss}from"@polkadot-api/utils";import{blake2b as xs}from"@noble/hashes/blake2b";import{map as Is,of as Os,switchMap as ws}from"rxjs";var vs=340282366920938463463374607431768211455n,tt=class extends B{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()]),n=t.map(async({keyArgs:i,value:a})=>{let[o]=i,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:g.fromPermill(a.fee),tokens:c,...l,...s}});return Promise.all(n)}async getPoolDelta(t,e,s){let{initial_amplification:n,final_amplification:i,initial_block:a,final_block:o}=e,r=O.calculateAmplification(n.toString(),i.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),n=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}}),i=await Promise.all(n),a=await this.api.query.AssetRegistry.Assets.getValue(t);return i.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:vs,tradeable:15,type:a?.asset_type.type}),i}getPoolAddress(t){let e=O.getPoolAddress(t),s=xs(e,{dkLen:32}),n=Ss(s);return ys(63).dec(n)}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(fs.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,s=this.poolsData.get(t.address);return!s||!t.id?Os(t):e.watchValue("best").pipe(ws(n=>this.getPoolDelta(t.id,s,n)),Is(n=>Object.assign({},t,n)))}};var vt={};f(vt,{XykMath:()=>D,XykPool:()=>et,XykPoolClient:()=>st});import{calculate_in_given_out as As,calculate_out_given_in as Ts,calculate_pool_trade_fee as Bs,get_spot_price as Fs,calculate_liquidity_in as _s,calculate_shares as Rs,calculate_spot_price as ks,calculate_spot_price_with_fee as Es,calculate_liquidity_out_asset_a as Ds,calculate_liquidity_out_asset_b as Ls}from"@galacticcouncil/math-xyk";var D=class{static getSpotPrice(t,e,s){return Fs(t,e,s)}static calculateInGivenOut(t,e,s){return As(t,e,s)}static calculateOutGivenIn(t,e,s){return Ts(t,e,s)}static calculatePoolTradeFee(t,e,s){return Bs(t,e,s)}static calculateLiquidityIn(t,e,s){return _s(t,e,s)}static calculateSpotPrice(t,e){return ks(t,e)}static calculateSpotPriceWithFee(t,e,s,n){return Es(t,e,s,n)}static calculateShares(t,e,s){return Rs(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,n){return Ds(t,e,s,n)}static calculateLiquidityOutAssetB(t,e,s,n){return Ls(t,e,s,n)}};var et=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,n,i){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:n.decimals,decimalsOut:i.decimals,balanceIn:n.balance,balanceOut:i.balance,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let n=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(n,s),a=g.toPct(s.exchangeFee),o=n+i,r=[];(e<this.minTradingLimit||n<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:n,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,s){let n=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(n,s),a=g.toPct(s.exchangeFee),o=n-i,r=[];(e<this.minTradingLimit||n<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:n,amountOut:o,feePct:a,errors:r}}calculateInGivenOut(t,e){let s=D.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e){let s=D.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(s);return n<0n?0n:n}spotPriceInGivenOut(t){let e=D.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceOutGivenIn(t){let e=D.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let s=D.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as Ms}from"polkadot-api";import{of as Cs}from"rxjs";var st=class extends B{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,s]=await Promise.all([t.getEntries(),this.getPoolLimits()]),n=e.map(async({keyArgs:i,value:a})=>{let[o]=i,[r,l]=a,[c,d,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:d?.decimals,existentialDeposit:d?.existential_deposit,balance:c,type:d?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...s}});return Promise.all(n)}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(Ms.BackwardsCompatible,e)}subscribePoolChange(t){return Cs(t)}};var At={};f(At,{AavePool:()=>nt,AavePoolClient:()=>it});var nt=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,n,i){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=n,this.minTradingLimit=i}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),n=s.get(t),i=s.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,s){let n=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,s){let n=this.calculateOutGivenIn(t,e),i=[];return n>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:i}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};import{AccountId as qs}from"polkadot-api";import{toHex as Ns}from"@polkadot-api/utils";import{map as Gs,merge as Hs,switchMap as Ws}from"rxjs";import{decodeEventLog as Xs}from"viem";var Wt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var Vs=["Supply","Withdraw","Repay","Borrow"],it=class extends B{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:s,atoken:n,liqudity_in:i,liqudity_out:a})=>{let[o,r,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s),this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n)]);return{address:this.getPoolId(s,n),type:"Aave",tokens:[{id:s,decimals:o?.decimals,existentialDeposit:o?.existential_deposit,balance:i,location:r,type:o?.asset_type.type},{id:n,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:a,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,s]=t.tokens,{liqudity_in:n,liqudity_out:i}=await this.api.apis.AaveTradeExecutor.pool(e.id,s.id);return t.tokens.map(a=>{let o=a.id===e.id?n:i;return{...a,balance:o}})}getPoolId(t,e){let s=t+"/"+e,n=new TextEncoder().encode(s.padEnd(32,"\0")),i=Ns(n);return qs(63).dec(i)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,s]=t.tokens,n=this.getReserveH160Id(e),i=this.api.event.Router.Executed.watch(({asset_in:o,asset_out:r})=>o===s.id||r===s.id),a=this.api.event.EVM.Log.watch(({log:o})=>{let{topics:r,data:l}=o,c=r.map(b=>b.asHex()),d=l.asHex(),{eventName:m,args:p}=Xs({abi:Wt,topics:c,data:d});return Vs.includes(m)&&p.reserve.toLowerCase()===n.toLowerCase()});return Hs([i,a]).pipe(Ws(()=>this.getPoolDelta(t)),Gs(o=>({...t,tokens:[...o]})))}getReserveH160Id(t){return t.type==="Erc20"?q.findNestedKey(t.location,"AccountKey20").AccountKey20.key:ut.ERC20Mapping.encodeEvmAddress(t.id)}};var U=class{static get(t){switch(t.type){case"Aave":return nt.fromPool(t);case"XYK":return et.fromPool(t);case"Omnipool":return J.fromPool(t);case"LBP":return z.fromPool(t);case"Stableswap":return Z.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as Ys,Subscription as ot,takeUntil as Us}from"rxjs";var mt=class extends _{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=ot.EMPTY;omniSub=ot.EMPTY;stableSub=ot.EMPTY;xykSub=ot.EMPTY;aaveSub=ot.EMPTY;isReady=!1;isDestroyed=new Ys;constructor(t){super(t),this.lbpClient=new Q(t),this.omniClient=new $(t),this.stableClient=new tt(t),this.xykClient=new st(t),this.aaveClient=new it(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe(Us(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),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(n=>n.getPoolType()===t.type);if(s)return s.getPoolFees(t,e);throw new K(t.type)}};var Yt={};f(Yt,{Router:()=>j,TradeRouter:()=>gt,TradeType:()=>dt,TradeUtils:()=>bt});var pt=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 js=5,at=class{isNotVisited(t,e){let s=!0;return e.forEach(n=>{(n[0]===t[0]||n[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let n=[],i=new pt,a=[];for(a.push([e,""]),i.enqueue(a);i.size()>0;){let o=i.dequeue();if(o==null||o.length>js)return n;let r=o[o.length-1];(s===null||r[0]===s)&&n.push(o),t.get(r[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let d=[...o];d.push(c),i.enqueue(d)}})}return n}buildAndPopulateGraph(t,e){let s=new Map;for(let n of t)s.set(parseInt(n),[]);for(let[n,i,a]of e)s.get(i)?.push([a,n]);return s}};function Tt(u){let t={};for(let e of u){let s=e.tokens.length;for(let n=0;n<s;n++){t[e.tokens[n].id]||(t[e.tokens[n].id]=[]);for(let i=0;i<s;i++){if(n==i)continue;let a=[e.address,e.tokens[n].id,e.tokens[i].id];t[e.tokens[n].id].push(a)}}}return t}var rt=class{getProposals(t,e,s){let n=Tt(s),i=Object.keys(n),a=i.map(c=>n[c]).flat(),o=new at,r=o.buildAndPopulateGraph(i,a),l=o.findPaths(r,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let s of t){let n=[];for(let i=0;i<s.length;i++){let a=s[i],o=s[i+1];if(o==null)break;n.push(this.toEdge(a,o))}e.push(n)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var j=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new rt,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 n=this.getAssets(s);if(!n.has(t))throw new Error(t+" is not supported asset");if(!n.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(n=>n.id)).flat().sort((s,n)=>s>n?1:-1);return new Set(e)}getPaths(t,e,s){let n=this.toPoolsMap(s);return this.routeSuggester.getProposals(t,e,s).filter(a=>this.validPath(a,n)).map(a=>this.toHops(a,n))}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,n)=>s&&n)}validEdge([t,e,s],n){return n.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,U.get(e)]))}toHops(t,e){return t.map(([s,n,i])=>{let a=e.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:n,assetOut:i}})}};var dt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(dt||{});var gt=class extends j{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,n)=>{let i=s[s.length-1].amountOut,a=n[n.length-1].amountOut;return i>a?-1:1});return e.find(s=>s.every(n=>n.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),n=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,n]}}getPoolFeeRange(t){let e=t.min?g.toPct(t.min):void 0,s=t.max?g.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),n=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),i=s-e.assetOutDecimals,a=Math.pow(10,i);return n/BigInt(a)}async getSell(t,e,s,n){let i=await super.getPools(),a=super.validateInput(t,e,i),o=super.getPaths(t,e,i);if(o.length===0)throw new X(t,e);let r;if(n)r=await this.toSellSwaps(s,n,a);else{let M=await Promise.all(o.map(Pt=>this.toSellSwaps(s,Pt,a)));r=this.findBestSellRoute(M)}let l=r[0],c=r[r.length-1],d=this.isDirectTrade(r),m=await this.getSellSpot(r),p=c.amountOut,b=d?c.calculatedOut:this.calculateDelta0Y(l.amountIn,r,a),y=b-p,S=this.getRouteFeeRange(r),A=d?c.tradeFeePct:I.calculateSellFee(b,p),w=Math.pow(10,l.assetInDecimals),v=l.amountIn*m/BigInt(w),F=I.calculateDiffToRef(b,v);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:m,tradeFee:y,tradeFeePct:A,tradeFeeRange:S,priceImpactPct:F,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:S,priceImpactPct:F,swaps:r.map(M=>M.toHuman())}}}}calculateDelta0Y(t,e,s){let n=[];for(let i=0;i<e.length;i++){let a=e[i],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;i>0?l=n[i-1]:l=t;let c=o.calculateOutGivenIn(r,l);n.push(c)}return n[n.length-1]}async toSellSwaps(t,e,s){let n=[];for(let i=0;i<e.length;i++){let a=e[i],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;i>0?l=n[i-1].amountOut:l=typeof t=="string"?P.toBigInt(t,r.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountOut:d,calculatedOut:m,feePct:p,errors:b}=o.validateAndSell(r,l,c),y=this.getPoolFeeRange(c),S=o.spotPriceOutGivenIn(r),A=Math.pow(10,r.decimalsIn),w=l*S/BigInt(A),v=I.calculateDiffToRef(m,w);n.push({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountIn:l,amountOut:d,calculatedOut:m,spotPrice:S,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:v,errors:b,toHuman(){return{...a,amountIn:P.toDecimal(l,r.decimalsIn),amountOut:P.toDecimal(d,r.decimalsOut),calculatedOut:P.toDecimal(m,r.decimalsOut),spotPrice:P.toDecimal(S,r.decimalsOut),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:v,errors:b}}})}return n}async getMostLiquidRoute(t,e){let s=await super.getPools(),n=super.validateInput(t,e,s),i=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=I.getFraction(r,.1),c=await Promise.all(i.map(m=>this.toSellSwaps(l,m,n)));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(),n=super.validateInput(t,e,s),i=await this.getMostLiquidRoute(t,e),a=await this.toSellSwaps("1",i,n),o=await this.getSellSpot(a),r=a[a.length-1].assetOutDecimals;return{amount:o,decimals:r}}findBestBuyRoute(t){let e=t.sort((s,n)=>{let i=s[0].amountIn,a=n[0].amountIn;return i>a?1:-1});return e.find(s=>s.every(n=>n.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),n=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),i=s-e.assetInDecimals,a=Math.pow(10,i);return n/BigInt(a)}async getBuy(t,e,s,n){let i=await super.getPools(),a=super.validateInput(t,e,i),o=super.getPaths(t,e,i);if(o.length===0)throw new X(t,e);let r;if(n)r=await this.toBuySwaps(s,n,a);else{let M=await Promise.all(o.map(Pt=>this.toBuySwaps(s,Pt,a)));r=this.findBestBuyRoute(M)}let l=r[r.length-1],c=r[0],d=this.isDirectTrade(r),m=await this.getBuySpot(r),p=c.amountIn,b=d?c.calculatedIn:this.calculateDelta0X(l.amountOut,r,a),y=p-b,S=this.getRouteFeeRange(r),A=d?c.tradeFeePct:I.calculateBuyFee(b,p),w=Math.pow(10,l.assetOutDecimals),v=l.amountOut*m/BigInt(w),F;return b===0n?F=-100:F=I.calculateDiffToRef(v,b),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:m,tradeFee:y,tradeFeePct:A,tradeFeeRange:S,priceImpactPct:F,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:S,priceImpactPct:F,swaps:r.map(M=>M.toHuman())}}}}calculateDelta0X(t,e,s){let n=[];for(let i=e.length-1;i>=0;i--){let a=e[i],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;i==e.length-1?l=t:l=n[0];let c=o.calculateInGivenOut(r,l);n.unshift(c)}return n[0]}async toBuySwaps(t,e,s){let n=[];for(let i=e.length-1;i>=0;i--){let a=e[i],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;i==e.length-1?l=typeof t=="string"?P.toBigInt(t,r.decimalsOut):t:l=n[0].amountIn;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountIn:d,calculatedIn:m,feePct:p,errors:b}=o.validateAndBuy(r,l,c),y=this.getPoolFeeRange(c),S=o.spotPriceInGivenOut(r),A=Math.pow(10,r.decimalsOut),w=l*S/BigInt(A),v;m===0n?v=-100:v=I.calculateDiffToRef(w,m),n.unshift({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountOut:l,amountIn:d,calculatedIn:m,spotPrice:S,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:v,errors:b,toHuman(){return{...a,amountOut:P.toDecimal(l,r.decimalsOut),amountIn:P.toDecimal(d,r.decimalsIn),calculatedIn:P.toDecimal(m,r.decimalsIn),spotPrice:P.toDecimal(S,r.decimalsIn),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:v,errors:b}}})}return n}};import{Enum as Vt}from"polkadot-api";var bt=class extends _{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:n,swaps:i}=t,a=i[0],o=i[i.length-1],r=I.getFraction(s,e),l=a.assetIn,c=o.assetOut,d=s+r;return this.isDirectOmnipoolTrade(i)?this.api.tx.Omnipool.buy({asset_in:l,asset_out:c,amount:n,max_sell_amount:d}).getEncodedData():this.api.tx.Router.buy({asset_in:l,asset_out:c,amount_out:n,max_amount_in:d,route:this.buildRoute(i)}).getEncodedData()}async buildSellTx(t,e=1){this.tradeCheck(t,"Sell");let{amountIn:s,amountOut:n,swaps:i}=t,a=i[0],o=i[i.length-1],r=I.getFraction(n,e),l=a.assetIn,c=o.assetOut,d=n-r;return this.isDirectOmnipoolTrade(i)?this.api.tx.Omnipool.sell({asset_in:l,asset_out:c,amount:s,min_buy_amount:d}).getEncodedData():this.api.tx.Router.sell({asset_in:l,asset_out:c,amount_in:s,min_amount_out:d,route:this.buildRoute(i)}).getEncodedData()}async buildSellAllTx(t,e=1){this.tradeCheck(t,"Sell");let{amountOut:s,swaps:n}=t,i=n[0],a=n[n.length-1],o=I.getFraction(s,e),r=i.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(n)}).getEncodedData()}buildRoute(t){return t.map(({assetIn:e,assetOut:s,pool:n,poolId:i})=>n==="Stableswap"?{pool:Vt("Stableswap",i),asset_in:e,asset_out:s}:{pool:Vt(n),asset_in:e,asset_out:s})}};export{Bt as api,P as big,Rt as client,Ft as const,ut as erc20,kt as error,Et as evm,g as fmt,q as json,I as math,Xt as pool,Yt as sor,Lt as xc};
|
|
@@ -115,21 +115,22 @@ export declare abstract class Papi {
|
|
|
115
115
|
Omnipool: {
|
|
116
116
|
sell: import("polkadot-api").TxDescriptor<{
|
|
117
117
|
amount: bigint;
|
|
118
|
-
asset_out: number;
|
|
119
118
|
asset_in: number;
|
|
119
|
+
asset_out: number;
|
|
120
120
|
min_buy_amount: bigint;
|
|
121
121
|
}>;
|
|
122
122
|
buy: import("polkadot-api").TxDescriptor<{
|
|
123
123
|
amount: bigint;
|
|
124
|
-
asset_out: number;
|
|
125
124
|
asset_in: number;
|
|
125
|
+
asset_out: number;
|
|
126
126
|
max_sell_amount: bigint;
|
|
127
127
|
}>;
|
|
128
128
|
};
|
|
129
129
|
Router: {
|
|
130
130
|
sell: import("polkadot-api").TxDescriptor<{
|
|
131
|
-
asset_out: number;
|
|
132
131
|
asset_in: number;
|
|
132
|
+
asset_out: number;
|
|
133
|
+
amount_in: bigint;
|
|
133
134
|
route: {
|
|
134
135
|
pool: import("polkadot-api").Enum<{
|
|
135
136
|
"XYK": undefined;
|
|
@@ -141,12 +142,11 @@ export declare abstract class Papi {
|
|
|
141
142
|
asset_in: number;
|
|
142
143
|
asset_out: number;
|
|
143
144
|
}[];
|
|
144
|
-
amount_in: bigint;
|
|
145
145
|
min_amount_out: bigint;
|
|
146
146
|
}>;
|
|
147
147
|
buy: import("polkadot-api").TxDescriptor<{
|
|
148
|
-
asset_out: number;
|
|
149
148
|
asset_in: number;
|
|
149
|
+
asset_out: number;
|
|
150
150
|
amount_out: bigint;
|
|
151
151
|
max_amount_in: bigint;
|
|
152
152
|
route: {
|
|
@@ -162,8 +162,8 @@ export declare abstract class Papi {
|
|
|
162
162
|
}[];
|
|
163
163
|
}>;
|
|
164
164
|
sell_all: import("polkadot-api").TxDescriptor<{
|
|
165
|
-
asset_out: number;
|
|
166
165
|
asset_in: number;
|
|
166
|
+
asset_out: number;
|
|
167
167
|
route: {
|
|
168
168
|
pool: import("polkadot-api").Enum<{
|
|
169
169
|
"XYK": undefined;
|
|
@@ -180,6 +180,15 @@ export declare abstract class Papi {
|
|
|
180
180
|
};
|
|
181
181
|
};
|
|
182
182
|
__event: {
|
|
183
|
+
Router: {
|
|
184
|
+
Executed: import("polkadot-api").PlainDescriptor<{
|
|
185
|
+
asset_in: number;
|
|
186
|
+
asset_out: number;
|
|
187
|
+
amount_in: bigint;
|
|
188
|
+
amount_out: bigint;
|
|
189
|
+
event_id: number;
|
|
190
|
+
}>;
|
|
191
|
+
};
|
|
183
192
|
EVM: {
|
|
184
193
|
Log: import("polkadot-api").PlainDescriptor<{
|
|
185
194
|
log: {
|
|
@@ -6,6 +6,7 @@ export declare class PoolContextProvider extends Papi implements IPoolCtxProvide
|
|
|
6
6
|
private readonly omniClient;
|
|
7
7
|
private readonly stableClient;
|
|
8
8
|
private readonly xykClient;
|
|
9
|
+
private readonly aaveClient;
|
|
9
10
|
private readonly active;
|
|
10
11
|
private readonly clients;
|
|
11
12
|
private readonly pools;
|
|
@@ -13,12 +14,15 @@ export declare class PoolContextProvider extends Papi implements IPoolCtxProvide
|
|
|
13
14
|
private omniSub;
|
|
14
15
|
private stableSub;
|
|
15
16
|
private xykSub;
|
|
17
|
+
private aaveSub;
|
|
16
18
|
private isReady;
|
|
17
19
|
private isDestroyed;
|
|
18
20
|
constructor(client: PolkadotClient);
|
|
21
|
+
private subscribe;
|
|
19
22
|
withOmnipool(): this;
|
|
20
23
|
withStableswap(): this;
|
|
21
24
|
withLbp(): this;
|
|
25
|
+
withAave(): this;
|
|
22
26
|
withXyk(override?: PoolTokenOverride[]): this;
|
|
23
27
|
destroy(): void;
|
|
24
28
|
getPools(): Promise<PoolBase[]>;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
export declare const AAVE_ABI: readonly [{
|
|
2
|
+
readonly anonymous: false;
|
|
3
|
+
readonly inputs: readonly [{
|
|
4
|
+
readonly indexed: true;
|
|
5
|
+
readonly internalType: "address";
|
|
6
|
+
readonly name: "reserve";
|
|
7
|
+
readonly type: "address";
|
|
8
|
+
}, {
|
|
9
|
+
readonly indexed: false;
|
|
10
|
+
readonly internalType: "address";
|
|
11
|
+
readonly name: "user";
|
|
12
|
+
readonly type: "address";
|
|
13
|
+
}, {
|
|
14
|
+
readonly indexed: true;
|
|
15
|
+
readonly internalType: "address";
|
|
16
|
+
readonly name: "onBehalfOf";
|
|
17
|
+
readonly type: "address";
|
|
18
|
+
}, {
|
|
19
|
+
readonly indexed: false;
|
|
20
|
+
readonly internalType: "uint256";
|
|
21
|
+
readonly name: "amount";
|
|
22
|
+
readonly type: "uint256";
|
|
23
|
+
}, {
|
|
24
|
+
readonly indexed: true;
|
|
25
|
+
readonly internalType: "uint16";
|
|
26
|
+
readonly name: "referralCode";
|
|
27
|
+
readonly type: "uint16";
|
|
28
|
+
}];
|
|
29
|
+
readonly name: "Supply";
|
|
30
|
+
readonly type: "event";
|
|
31
|
+
}, {
|
|
32
|
+
readonly anonymous: false;
|
|
33
|
+
readonly inputs: readonly [{
|
|
34
|
+
readonly indexed: true;
|
|
35
|
+
readonly internalType: "address";
|
|
36
|
+
readonly name: "reserve";
|
|
37
|
+
readonly type: "address";
|
|
38
|
+
}, {
|
|
39
|
+
readonly indexed: true;
|
|
40
|
+
readonly internalType: "address";
|
|
41
|
+
readonly name: "user";
|
|
42
|
+
readonly type: "address";
|
|
43
|
+
}, {
|
|
44
|
+
readonly indexed: true;
|
|
45
|
+
readonly internalType: "address";
|
|
46
|
+
readonly name: "to";
|
|
47
|
+
readonly type: "address";
|
|
48
|
+
}, {
|
|
49
|
+
readonly indexed: false;
|
|
50
|
+
readonly internalType: "uint256";
|
|
51
|
+
readonly name: "amount";
|
|
52
|
+
readonly type: "uint256";
|
|
53
|
+
}];
|
|
54
|
+
readonly name: "Withdraw";
|
|
55
|
+
readonly type: "event";
|
|
56
|
+
}, {
|
|
57
|
+
readonly anonymous: false;
|
|
58
|
+
readonly inputs: readonly [{
|
|
59
|
+
readonly indexed: true;
|
|
60
|
+
readonly internalType: "address";
|
|
61
|
+
readonly name: "reserve";
|
|
62
|
+
readonly type: "address";
|
|
63
|
+
}, {
|
|
64
|
+
readonly indexed: false;
|
|
65
|
+
readonly internalType: "address";
|
|
66
|
+
readonly name: "user";
|
|
67
|
+
readonly type: "address";
|
|
68
|
+
}, {
|
|
69
|
+
readonly indexed: true;
|
|
70
|
+
readonly internalType: "address";
|
|
71
|
+
readonly name: "onBehalfOf";
|
|
72
|
+
readonly type: "address";
|
|
73
|
+
}, {
|
|
74
|
+
readonly indexed: false;
|
|
75
|
+
readonly internalType: "uint256";
|
|
76
|
+
readonly name: "amount";
|
|
77
|
+
readonly type: "uint256";
|
|
78
|
+
}, {
|
|
79
|
+
readonly indexed: false;
|
|
80
|
+
readonly internalType: "enum DataTypes.InterestRateMode";
|
|
81
|
+
readonly name: "interestRateMode";
|
|
82
|
+
readonly type: "uint8";
|
|
83
|
+
}, {
|
|
84
|
+
readonly indexed: false;
|
|
85
|
+
readonly internalType: "uint256";
|
|
86
|
+
readonly name: "borrowRate";
|
|
87
|
+
readonly type: "uint256";
|
|
88
|
+
}, {
|
|
89
|
+
readonly indexed: true;
|
|
90
|
+
readonly internalType: "uint16";
|
|
91
|
+
readonly name: "referralCode";
|
|
92
|
+
readonly type: "uint16";
|
|
93
|
+
}];
|
|
94
|
+
readonly name: "Borrow";
|
|
95
|
+
readonly type: "event";
|
|
96
|
+
}, {
|
|
97
|
+
readonly anonymous: false;
|
|
98
|
+
readonly inputs: readonly [{
|
|
99
|
+
readonly indexed: true;
|
|
100
|
+
readonly internalType: "address";
|
|
101
|
+
readonly name: "reserve";
|
|
102
|
+
readonly type: "address";
|
|
103
|
+
}, {
|
|
104
|
+
readonly indexed: true;
|
|
105
|
+
readonly internalType: "address";
|
|
106
|
+
readonly name: "user";
|
|
107
|
+
readonly type: "address";
|
|
108
|
+
}, {
|
|
109
|
+
readonly indexed: true;
|
|
110
|
+
readonly internalType: "address";
|
|
111
|
+
readonly name: "repayer";
|
|
112
|
+
readonly type: "address";
|
|
113
|
+
}, {
|
|
114
|
+
readonly indexed: false;
|
|
115
|
+
readonly internalType: "uint256";
|
|
116
|
+
readonly name: "amount";
|
|
117
|
+
readonly type: "uint256";
|
|
118
|
+
}, {
|
|
119
|
+
readonly indexed: false;
|
|
120
|
+
readonly internalType: "bool";
|
|
121
|
+
readonly name: "useATokens";
|
|
122
|
+
readonly type: "bool";
|
|
123
|
+
}];
|
|
124
|
+
readonly name: "Repay";
|
|
125
|
+
readonly type: "event";
|
|
126
|
+
}];
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { BuyCtx, Pool, PoolBase, PoolFees, PoolPair, PoolToken, PoolType, SellCtx } from '../types';
|
|
2
|
+
import { XcmV3Multilocation } from '../../types';
|
|
3
|
+
export type AavePoolToken = PoolToken & {
|
|
4
|
+
location: XcmV3Multilocation;
|
|
5
|
+
};
|
|
6
|
+
export declare class AavePool implements Pool {
|
|
7
|
+
type: PoolType;
|
|
8
|
+
address: string;
|
|
9
|
+
tokens: AavePoolToken[];
|
|
10
|
+
maxInRatio: bigint;
|
|
11
|
+
maxOutRatio: bigint;
|
|
12
|
+
minTradingLimit: bigint;
|
|
13
|
+
static fromPool(pool: PoolBase): AavePool;
|
|
14
|
+
constructor(address: string, tokens: AavePoolToken[], maxInRation: bigint, maxOutRatio: bigint, minTradeLimit: bigint);
|
|
15
|
+
validatePair(_tokenIn: number, _tokenOut: number): boolean;
|
|
16
|
+
parsePair(tokenIn: number, tokenOut: number): PoolPair;
|
|
17
|
+
validateAndBuy(poolPair: PoolPair, amountOut: bigint, _fees: PoolFees): BuyCtx;
|
|
18
|
+
validateAndSell(poolPair: PoolPair, amountIn: bigint, _fees: PoolFees): SellCtx;
|
|
19
|
+
calculateInGivenOut(_poolPair: PoolPair, amountOut: bigint): bigint;
|
|
20
|
+
calculateOutGivenIn(_poolPair: PoolPair, amountIn: bigint): bigint;
|
|
21
|
+
spotPriceInGivenOut(poolPair: PoolPair): bigint;
|
|
22
|
+
spotPriceOutGivenIn(poolPair: PoolPair): bigint;
|
|
23
|
+
calculateTradeFee(_amount: bigint, _fees: PoolFees): bigint;
|
|
24
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Observable } from 'rxjs';
|
|
2
|
+
import { PoolBase, PoolFees, PoolType } from '../types';
|
|
3
|
+
import { PoolClient } from '../PoolClient';
|
|
4
|
+
export declare class AavePoolClient extends PoolClient<PoolBase> {
|
|
5
|
+
loadPools(): Promise<PoolBase[]>;
|
|
6
|
+
private getPoolDelta;
|
|
7
|
+
private getPoolId;
|
|
8
|
+
private getPoolLimits;
|
|
9
|
+
getPoolFees(_pool: PoolBase, _feeAsset: number): Promise<PoolFees>;
|
|
10
|
+
getPoolType(): PoolType;
|
|
11
|
+
isSupported(): Promise<boolean>;
|
|
12
|
+
subscribePoolChange(pool: PoolBase): Observable<PoolBase>;
|
|
13
|
+
private getReserveH160Id;
|
|
14
|
+
}
|
|
@@ -36,8 +36,8 @@ export declare class TradeRouter extends Router {
|
|
|
36
36
|
/**
|
|
37
37
|
* Calculate and return best possible sell trade for assetIn>assetOut
|
|
38
38
|
*
|
|
39
|
-
* @param {
|
|
40
|
-
* @param {
|
|
39
|
+
* @param {number} assetIn - assetIn id
|
|
40
|
+
* @param {number} assetOut - assetOut id
|
|
41
41
|
* @param {bigint} amountIn - amount of assetIn to sell for assetOut
|
|
42
42
|
* @returns best possible sell trade of given token pair
|
|
43
43
|
*/
|
|
@@ -52,8 +52,8 @@ export declare class TradeRouter extends Router {
|
|
|
52
52
|
/**
|
|
53
53
|
* Calculate and return sell trade for assetIn>assetOut
|
|
54
54
|
*
|
|
55
|
-
* @param {
|
|
56
|
-
* @param {
|
|
55
|
+
* @param {number} assetIn - assetIn id
|
|
56
|
+
* @param {number} assetOut - assetOut id
|
|
57
57
|
* @param {bigint} amountIn - amount of assetIn to sell for assetOut
|
|
58
58
|
* @param {Hop[]} route - explicit route to use for trade
|
|
59
59
|
* @returns sell trade of given token pair
|
|
@@ -127,7 +127,7 @@ export declare class TradeRouter extends Router {
|
|
|
127
127
|
*
|
|
128
128
|
* @param {number} assetIn - assetIn id
|
|
129
129
|
* @param {number} assetOut - assetOut id
|
|
130
|
-
* @param {bigint} amountOut - amount of
|
|
130
|
+
* @param {bigint} amountOut - amount of assetOut to buy for assetIn
|
|
131
131
|
* @param {Hop[]} route - explicit route to use for trade
|
|
132
132
|
* @returns buy trade of given token pair
|
|
133
133
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@galacticcouncil/sdk-next",
|
|
3
|
-
"version": "1.0.0-
|
|
3
|
+
"version": "1.0.0-pr159-5456ce2",
|
|
4
4
|
"description": "Galactic next gen sdk (papi)",
|
|
5
5
|
"author": "GalacticCouncil",
|
|
6
6
|
"repository": {
|
|
@@ -10,10 +10,9 @@
|
|
|
10
10
|
},
|
|
11
11
|
"keywords": [
|
|
12
12
|
"hydration",
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"types"
|
|
13
|
+
"api",
|
|
14
|
+
"router",
|
|
15
|
+
"sdk"
|
|
17
16
|
],
|
|
18
17
|
"bugs": {
|
|
19
18
|
"url": "https://github.com/galacticcouncil/sdk/issues"
|
|
@@ -48,6 +47,7 @@
|
|
|
48
47
|
"big.js": "^6.2.1"
|
|
49
48
|
},
|
|
50
49
|
"peerDependencies": {
|
|
51
|
-
"polkadot-api": "^1.10.0"
|
|
50
|
+
"polkadot-api": "^1.10.0",
|
|
51
|
+
"viem": "^2.23.7"
|
|
52
52
|
}
|
|
53
53
|
}
|