@galacticcouncil/sdk-next 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +223 -0
- package/build/index.cjs +1 -0
- package/build/index.mjs +1 -0
- package/build/types/api/Papi.d.ts +385 -0
- package/build/types/api/client.d.ts +2 -0
- package/build/types/api/index.d.ts +2 -0
- package/build/types/client/AssetClient.d.ts +24 -0
- package/build/types/client/BalanceClient.d.ts +17 -0
- package/build/types/client/index.d.ts +2 -0
- package/build/types/consts.d.ts +8 -0
- package/build/types/errors.d.ts +10 -0
- package/build/types/index.d.ts +8 -0
- package/build/types/pool/PoolClient.d.ts +25 -0
- package/build/types/pool/PoolContextProvider.d.ts +30 -0
- package/build/types/pool/PoolFactory.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 +8 -0
- package/build/types/pool/lbp/LbpMath.d.ts +7 -0
- package/build/types/pool/lbp/LbpPool.d.ts +49 -0
- package/build/types/pool/lbp/LbpPoolClient.d.ts +18 -0
- package/build/types/pool/lbp/index.d.ts +3 -0
- package/build/types/pool/omni/OmniMath.d.ts +19 -0
- package/build/types/pool/omni/OmniPool.d.ts +45 -0
- package/build/types/pool/omni/OmniPoolClient.d.ts +13 -0
- package/build/types/pool/omni/index.d.ts +3 -0
- package/build/types/pool/stable/StableMath.d.ts +14 -0
- package/build/types/pool/stable/StableSwap.d.ts +46 -0
- package/build/types/pool/stable/StableSwapClient.d.ts +16 -0
- package/build/types/pool/stable/index.d.ts +3 -0
- package/build/types/pool/types.d.ts +84 -0
- package/build/types/pool/xyk/XykMath.d.ts +12 -0
- package/build/types/pool/xyk/XykPool.d.ts +23 -0
- package/build/types/pool/xyk/XykPoolClient.d.ts +12 -0
- package/build/types/pool/xyk/index.d.ts +3 -0
- package/build/types/sor/Router.d.ts +66 -0
- package/build/types/sor/TradeRouter.d.ts +155 -0
- package/build/types/sor/TradeUtils.d.ts +12 -0
- package/build/types/sor/index.d.ts +4 -0
- package/build/types/sor/route/bfs.d.ts +37 -0
- package/build/types/sor/route/graph.d.ts +12 -0
- package/build/types/sor/route/index.d.ts +3 -0
- package/build/types/sor/route/suggester.d.ts +24 -0
- package/build/types/sor/types.d.ts +31 -0
- package/build/types/types.d.ts +40 -0
- package/build/types/utils/Queue.d.ts +13 -0
- package/build/types/utils/Stack.d.ts +15 -0
- package/build/types/utils/big.d.ts +3 -0
- package/build/types/utils/erc20.d.ts +5 -0
- package/build/types/utils/evm.d.ts +3 -0
- package/build/types/utils/format.d.ts +4 -0
- package/build/types/utils/index.d.ts +7 -0
- package/build/types/utils/json.d.ts +3 -0
- package/build/types/utils/math.d.ts +62 -0
- package/build/types/utils/traversal/bfs.d.ts +27 -0
- package/build/types/utils/xc.d.ts +1 -0
- package/package.json +53 -0
package/README.md
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# Galactic SDK Next
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@galacticcouncil/sdk-next)
|
|
4
|
+
|
|
5
|
+
Next gen hydration sdk build on top of [Polkadot API (Papi)](https://papi.how/).
|
|
6
|
+
|
|
7
|
+
Table of content:
|
|
8
|
+
|
|
9
|
+
- [Installation](#installation)
|
|
10
|
+
- [Usage](#usage)
|
|
11
|
+
- [PoolContextProvider](#poolcontextprovider)
|
|
12
|
+
- [Router](#router)
|
|
13
|
+
- [TradeRouter](#traderouter)
|
|
14
|
+
- [BalanceClient](#balanceclient)
|
|
15
|
+
- [AssetClient](#assetclient)
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
Install with [npm](https://www.npmjs.com/):
|
|
20
|
+
|
|
21
|
+
`npm install @galacticcouncil/sdk-next`
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
### PoolContextProvider
|
|
26
|
+
|
|
27
|
+
Build and subscribe to the given AMM types, supplying data for the Router API.
|
|
28
|
+
|
|
29
|
+
⚠️ **Note:** Make sure to keep only single instance of context per session.
|
|
30
|
+
|
|
31
|
+
#### API Reference (internal)
|
|
32
|
+
|
|
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.
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
import { api, pool, sor } from '@galacticcouncil/sdk-next';
|
|
46
|
+
|
|
47
|
+
const client = await api.getWs('wss://hydradx-rpc.dwellir.com');
|
|
48
|
+
|
|
49
|
+
const ctx = new pool.PoolContextProvider(client)
|
|
50
|
+
.withOmnipool()
|
|
51
|
+
.withStableswap()
|
|
52
|
+
.withXyk();
|
|
53
|
+
|
|
54
|
+
// Don't forget to cleanup the resources
|
|
55
|
+
ctx.destroy();
|
|
56
|
+
client.destroy();
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Router
|
|
60
|
+
|
|
61
|
+
Off-chain routing, build to find the most suitable routes across the pools. Building block for `TradeRouter`.
|
|
62
|
+
|
|
63
|
+
#### API Reference
|
|
64
|
+
|
|
65
|
+
| Method | Description |
|
|
66
|
+
| :----- | :----------- |
|
|
67
|
+
| `getPools(): PoolBase[]` | Returns the current list of available pools. |
|
|
68
|
+
| `getRoutes(assetIn: number, assetOut: number): Hop[][]` | Computes possible routes between two assets. |
|
|
69
|
+
| `getTradeableAssets(): number[]` | Lists all assets that are tradeable through the router. |
|
|
70
|
+
|
|
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
|
|
99
|
+
|
|
100
|
+
Off-chain optimization of orders across pools for best price execution. TradeRouter does not perform any on-chain transations.
|
|
101
|
+
|
|
102
|
+
#### Api Reference
|
|
103
|
+
|
|
104
|
+
| Method | Description |
|
|
105
|
+
| :----- | :----------- |
|
|
106
|
+
| `getBestSell(tokenIn: number, tokenOut: number, amountIn: bigint \| string): Trade` | Find the best sell trade for given input amount. |
|
|
107
|
+
| `getBestBuy(tokenIn: number, tokenOut: number, amountOut: bigint \| string): Trade` | Find the best buy trade for given output amount. |
|
|
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). |
|
|
110
|
+
| `getSpotPrice(tokenIn: number, tokenOut: number): Amount` | Get the current spot price between two tokens. |
|
|
111
|
+
| `getMostLiquidRoute(tokenIn: number, tokenOut: number): Hop[]` | Find the route with the highest liquidity between two tokens. |
|
|
112
|
+
|
|
113
|
+
➡️ For type definitions visit [types.ts](src/sor/types.ts)<br />
|
|
114
|
+
|
|
115
|
+
#### Example
|
|
116
|
+
|
|
117
|
+
Calculate sell of 1 DOT for HDX & build tx with 5% slippage (default to 1% if not specified)
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
import { api, pool, sor } from '@galacticcouncil/sdk-next';
|
|
121
|
+
|
|
122
|
+
const client = await api.getWs('wss://hydradx-rpc.dwellir.com');
|
|
123
|
+
|
|
124
|
+
const ctx = new pool.PoolContextProvider(client)
|
|
125
|
+
.withOmnipool()
|
|
126
|
+
.withStableswap()
|
|
127
|
+
.withXyk();
|
|
128
|
+
|
|
129
|
+
const router = new sor.TradeRouter(ctx);
|
|
130
|
+
const utils = new sor.TradeUtils(client);
|
|
131
|
+
|
|
132
|
+
const sell = await router.getBestSell(5, 0, 10_000_000_000n);
|
|
133
|
+
const tx = await utils.buildSellTx(sell, 5);
|
|
134
|
+
console.log(sell.toHuman());
|
|
135
|
+
console.log('Transaction hash:', tx.asHex());
|
|
136
|
+
|
|
137
|
+
// Don't forget to cleanup the resources
|
|
138
|
+
ctx.destroy();
|
|
139
|
+
client.destroy();
|
|
140
|
+
```
|
|
141
|
+
|
|
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"
|
|
153
|
+
|
|
154
|
+
#### API Reference
|
|
155
|
+
|
|
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 />
|
|
164
|
+
|
|
165
|
+
#### Example
|
|
166
|
+
|
|
167
|
+
Subscribe hydration treasury account.
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
import { api, client as c } from '@galacticcouncil/sdk-next';
|
|
171
|
+
|
|
172
|
+
const account = "7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1"
|
|
173
|
+
|
|
174
|
+
const client = await api.getWs('wss://hydradx-rpc.dwellir.com');
|
|
175
|
+
const balanceClient = new c.BalanceClient(client);
|
|
176
|
+
|
|
177
|
+
const subscription = balanceClient
|
|
178
|
+
.subscribeBalance(account)
|
|
179
|
+
.subscribe((balances) => {
|
|
180
|
+
console.log(balances);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
// Don't forget to cleanup the resources
|
|
184
|
+
subscription.unsubscribe();
|
|
185
|
+
client.destroy();
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
### AssetClient
|
|
189
|
+
|
|
190
|
+
Helper class to fetch registry metadata.
|
|
191
|
+
|
|
192
|
+
#### API Reference
|
|
193
|
+
|
|
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
|
|
218
|
+
|
|
219
|
+
To demonstrate more full working examples on real chain see [script](test/script/examples) section.
|
|
220
|
+
|
|
221
|
+
### Execution
|
|
222
|
+
|
|
223
|
+
Run: `$ npx tsx ./test/script/examples/<examplePackage>/<exampleName>.ts` with valid example package & name.
|
package/build/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
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};
|