@galacticcouncil/sdk 6.2.0 → 7.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 +99 -41
- package/build/index.cjs +2 -2
- package/build/index.mjs +2 -2
- package/build/types/{client → api}/PolkadotApi.d.ts +3 -0
- package/build/types/api/index.d.ts +2 -3
- package/build/types/api/types.d.ts +8 -0
- package/build/types/client/AssetClient.d.ts +2 -2
- package/build/types/client/BalanceClient.d.ts +1 -1
- package/build/types/client/FarmClient.d.ts +1 -1
- package/build/types/client/index.d.ts +0 -1
- package/build/types/consts.d.ts +6 -7
- package/build/types/errors.d.ts +1 -1
- package/build/types/{pool/aave/AaveAbi.d.ts → evm/abi/Aave.d.ts} +48 -0
- package/build/types/evm/abi/Erc20.d.ts +150 -0
- package/build/types/evm/abi/index.d.ts +1 -0
- package/build/types/evm/chain.d.ts +2 -0
- package/build/types/evm/client.d.ts +11 -0
- package/build/types/evm/const.d.ts +4 -0
- package/build/types/evm/index.d.ts +4 -0
- package/build/types/index.d.ts +7 -4
- package/build/types/pool/CachingPoolService.d.ts +2 -2
- package/build/types/pool/PoolClient.d.ts +2 -1
- package/build/types/pool/PoolFactory.d.ts +1 -1
- package/build/types/pool/PoolService.d.ts +10 -14
- package/build/types/pool/aave/AavePool.d.ts +3 -3
- package/build/types/pool/aave/AavePoolClient.d.ts +1 -1
- package/build/types/pool/index.d.ts +1 -1
- package/build/types/pool/lbp/LbpPool.d.ts +3 -3
- package/build/types/pool/lbp/LbpPoolClient.d.ts +1 -1
- package/build/types/pool/omni/OmniPool.d.ts +3 -3
- package/build/types/pool/omni/OmniPoolClient.d.ts +1 -1
- package/build/types/pool/stable/StableSwap.d.ts +3 -3
- package/build/types/pool/stable/StableSwapClient.d.ts +1 -1
- package/build/types/pool/types.d.ts +81 -0
- package/build/types/pool/xyk/XykPool.d.ts +3 -3
- package/build/types/pool/xyk/XykPoolClient.d.ts +1 -1
- package/build/types/{api → sor}/Router.d.ts +2 -1
- package/build/types/{api → sor}/TradeRouter.d.ts +3 -1
- package/build/types/sor/TradeUtils.d.ts +25 -0
- package/build/types/sor/index.d.ts +4 -0
- package/build/types/{route → sor/route}/graph.d.ts +1 -1
- package/build/types/{route → sor/route}/suggester.d.ts +1 -1
- package/build/types/sor/types.d.ts +34 -0
- package/build/types/types.d.ts +8 -127
- package/build/types/utils/erc20.d.ts +3 -3
- package/build/types/utils/h160.d.ts +11 -0
- package/build/types/utils/mapper.d.ts +1 -1
- package/build/types/utils/math.d.ts +8 -0
- package/package.json +1 -1
- package/build/types/api/WalletCtx.d.ts +0 -20
- package/build/types/pool/PoolUtils.d.ts +0 -12
- package/build/types/{route → sor/route}/bfs.d.ts +0 -0
- package/build/types/{route → sor/route}/index.d.ts +1 -1
package/README.md
CHANGED
|
@@ -2,18 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@galacticcouncil/sdk)
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
<br />
|
|
8
|
-
<br />
|
|
5
|
+
Hydration sdk build on top of [@polkadot{.js} (Pjs)](https://polkadot.js.org/).
|
|
6
|
+
|
|
9
7
|
Table of content:
|
|
10
8
|
|
|
11
9
|
- [Installation](#installation)
|
|
12
|
-
- [
|
|
10
|
+
- [Troubleshooting](#troubleshooting)
|
|
11
|
+
- [Usage](#usage)
|
|
12
|
+
- [PoolService](#poolservice)
|
|
13
13
|
- [Router](#router)
|
|
14
14
|
- [TradeRouter](#traderouter)
|
|
15
|
-
- [Examples](#examples)
|
|
16
|
-
- [Roadmap](#roadmap)
|
|
17
15
|
|
|
18
16
|
## Installation
|
|
19
17
|
|
|
@@ -21,7 +19,7 @@ Install with [npm](https://www.npmjs.com/):
|
|
|
21
19
|
|
|
22
20
|
`npm install @galacticcouncil/sdk`
|
|
23
21
|
|
|
24
|
-
|
|
22
|
+
## Troubleshooting
|
|
25
23
|
|
|
26
24
|
As of **v2.x** .wasm files are no longer embedded in bundle
|
|
27
25
|
but rather deferred to improve load performance & decrease
|
|
@@ -29,71 +27,130 @@ module size (esm only).
|
|
|
29
27
|
|
|
30
28
|
For more details visit [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
|
|
31
29
|
|
|
32
|
-
##
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
### PoolService
|
|
33
|
+
|
|
34
|
+
Build and subscribe to the given AMM types, supplying data for the Router API.
|
|
35
|
+
|
|
36
|
+
⚠️ **Note:** Make sure to keep only single instance of service per session.
|
|
37
|
+
|
|
38
|
+
#### API Reference (internal)
|
|
39
|
+
|
|
40
|
+
| Method | Description |
|
|
41
|
+
| :----- | :----------- |
|
|
42
|
+
| `getPools(): Promise<PoolBase[]>` | Returns list of available pools. |
|
|
43
|
+
| `getPoolFees(pool: PoolBase, feeAsset: string): Promise<PoolFees>` | Returns current pool fees |
|
|
44
|
+
|
|
45
|
+
➡️ For type definitions visit [types.ts](src/pool/types.ts)<br />
|
|
46
|
+
|
|
47
|
+
#### Example
|
|
48
|
+
|
|
49
|
+
Initialize pool context and sync registry.
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { ApiPromise, WsProvider } from '@polkadot/api';
|
|
53
|
+
import { TradeRouter, PoolService, PoolType } from '@galacticcouncil/sdk';
|
|
54
|
+
|
|
55
|
+
const wsProvider = new WsProvider('wss://rpc.hydradx.cloud');
|
|
56
|
+
const api = await ApiPromise.create({ provider: wsProvider });
|
|
57
|
+
|
|
58
|
+
const poolService = new PoolService(api);
|
|
59
|
+
await poolService.syncRegistry();
|
|
60
|
+
|
|
61
|
+
// Don't forget to cleanup the resources
|
|
62
|
+
poolService.destroy();
|
|
63
|
+
api.disconnect();
|
|
64
|
+
```
|
|
33
65
|
|
|
34
66
|
### Router
|
|
35
67
|
|
|
36
|
-
Off-chain routing, build to find the most suitable routes across the pools. Building block for TradeRouter
|
|
68
|
+
Off-chain routing, build to find the most suitable routes across the pools. Building block for `TradeRouter`.
|
|
37
69
|
|
|
38
|
-
#### API
|
|
70
|
+
#### API Reference
|
|
71
|
+
|
|
72
|
+
| Method | Description |
|
|
73
|
+
| :----- | :----------- |
|
|
74
|
+
| `getPools(): PoolBase[]` | Returns the current list of available pools. |
|
|
75
|
+
| `getAllPaths(tokenIn: string, tokenOut: string): Hop[][]` | Computes possible routes between two assets. |
|
|
76
|
+
| `getAllAssets(): PoolBase[]` | Lists all assets that are tradeable through the router. |
|
|
77
|
+
| `getAssetPairs(token: string): Asset[]` | Lists all assets given token is tradeable with. |
|
|
78
|
+
|
|
79
|
+
➡️ For type definitions visit [types.ts](src/sor/types.ts)<br />
|
|
80
|
+
|
|
81
|
+
#### Example
|
|
82
|
+
|
|
83
|
+
List all tradable assets available in the current pool context.
|
|
39
84
|
|
|
40
85
|
```typescript
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
86
|
+
import { ApiPromise, WsProvider } from '@polkadot/api';
|
|
87
|
+
import { TradeRouter, PoolService, PoolType } from '@galacticcouncil/sdk';
|
|
88
|
+
|
|
89
|
+
const wsProvider = new WsProvider('wss://rpc.hydradx.cloud');
|
|
90
|
+
const api = await ApiPromise.create({ provider: wsProvider });
|
|
91
|
+
|
|
92
|
+
const poolService = new PoolService(api);
|
|
93
|
+
const router = new Router(poolService);
|
|
94
|
+
|
|
95
|
+
const assets = await router.getAllAssets();
|
|
96
|
+
console.log(assets);
|
|
97
|
+
|
|
98
|
+
// Don't forget to cleanup the resources
|
|
99
|
+
poolService.destroy();
|
|
100
|
+
api.disconnect();
|
|
45
101
|
```
|
|
46
102
|
|
|
47
103
|
### TradeRouter
|
|
48
104
|
|
|
49
105
|
Off-chain optimization of orders across pools for best price execution. TradeRouter does not perform any on-chain transations.
|
|
50
106
|
|
|
51
|
-
####
|
|
107
|
+
#### Api Reference
|
|
52
108
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
getBestSell(tokenIn: string, tokenOut: string, amountIn:
|
|
56
|
-
getBestBuy(tokenIn: string, tokenOut: string, amountOut:
|
|
57
|
-
getBuy(tokenIn: string, tokenOut: string, amountOut:
|
|
58
|
-
getSell(tokenIn: string, tokenOut: string, amountIn:
|
|
59
|
-
|
|
109
|
+
| Method | Description |
|
|
110
|
+
| :----- | :----------- |
|
|
111
|
+
| `getBestSell(tokenIn: string, tokenOut: string, amountIn: bigint \| string): Trade` | Find the best sell trade for given input amount. |
|
|
112
|
+
| `getBestBuy(tokenIn: string, tokenOut: string, amountOut: bigint \| string): Trade` | Find the best buy trade for given output amount. |
|
|
113
|
+
| `getBuy(tokenIn: string, tokenOut: string, amountOut: bigint \| string, route?: Hop[]): Trade` | Calculate a buy using a specific route (optional). |
|
|
114
|
+
| `getSell(tokenIn: string, tokenOut: string, amountIn: bigint \| string, route?: Hop[]): Trade` | Calculate a sell using a specific route (optional). |
|
|
115
|
+
| `getSpotPrice(tokenIn: string, tokenOut: string): Amount` | Get the current spot price between two tokens. |
|
|
116
|
+
| `getMostLiquidRoute(tokenIn: string, tokenOut: string): Hop[]` | Find the route with the highest liquidity between two tokens. |
|
|
60
117
|
|
|
61
|
-
For type
|
|
118
|
+
➡️ For type definitions visit [types.ts](src/sor/types.ts)<br />
|
|
62
119
|
|
|
63
|
-
####
|
|
120
|
+
#### Example
|
|
121
|
+
|
|
122
|
+
Calculate sell of 1 DOT for HDX & build tx with 5% slippage (default to 1% if not specified)
|
|
64
123
|
|
|
65
124
|
```typescript
|
|
66
|
-
// Import
|
|
67
125
|
import { ApiPromise, WsProvider } from '@polkadot/api';
|
|
68
126
|
import { TradeRouter, PoolService, PoolType } from '@galacticcouncil/sdk';
|
|
69
127
|
|
|
70
|
-
// Initialize Polkadot API
|
|
71
128
|
const wsProvider = new WsProvider('wss://rpc.hydradx.cloud');
|
|
72
129
|
const api = await ApiPromise.create({ provider: wsProvider });
|
|
73
130
|
|
|
74
|
-
// Initialize Trade Router
|
|
75
131
|
const poolService = new PoolService(api);
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
console.log(
|
|
83
|
-
|
|
84
|
-
|
|
132
|
+
const txUtils = new TradeUtils(api);
|
|
133
|
+
|
|
134
|
+
const router = new TradeRouter(poolService);
|
|
135
|
+
|
|
136
|
+
const sell = await router.getBestSell("5", "0", "1");
|
|
137
|
+
const tx = await utils.buildSellTx(sell, 5);
|
|
138
|
+
console.log(sell.toHuman());
|
|
139
|
+
console.log('Transaction hash: ' + transaction.hex);
|
|
140
|
+
|
|
141
|
+
// Don't forget to cleanup the resources
|
|
142
|
+
poolService.destroy();
|
|
143
|
+
api.disconnect();
|
|
85
144
|
```
|
|
86
145
|
|
|
87
146
|
## Examples
|
|
88
147
|
|
|
89
|
-
|
|
148
|
+
To demonstrate more full working examples on real chain see [script](test/script/examples) section.
|
|
90
149
|
|
|
91
|
-
###
|
|
150
|
+
### Execution
|
|
92
151
|
|
|
93
152
|
Run: `$ npx tsx ./test/script/examples/<examplePackage>/<exampleName>.ts` with valid example package & name.
|
|
94
153
|
|
|
95
|
-
To demonstrate full working examples on real chain see [script](test/script/examples) section.
|
|
96
|
-
|
|
97
154
|
## Roadmap
|
|
98
155
|
|
|
99
156
|
Component list and current status ⬇️
|
|
@@ -116,3 +173,4 @@ Component list and current status ⬇️
|
|
|
116
173
|
| Stable | Pool | 🧪 |
|
|
117
174
|
| XYK | Math | 🧪 |
|
|
118
175
|
| XYK | Pool | 🧪 |
|
|
176
|
+
| Aave | Pool | 🧪 |
|
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Me=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var xt=Object.prototype.hasOwnProperty;var vt=(l,e)=>{for(var t in e)Me(l,t,{get:e[t],enumerable:!0})},Bt=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of St(e))!xt.call(l,r)&&r!==t&&Me(l,r,{get:()=>e[r],enumerable:!(s=yt(e,r))||s.enumerable});return l};var wt=l=>Bt(Me({},"__esModule",{value:!0}),l);var Ht={};vt(Ht,{AMOUNT_MAX:()=>ft,AavePool:()=>Se,AavePoolClient:()=>ue,AssetClient:()=>j,AssetNotFound:()=>$e,BASILISK_PARACHAIN_ID:()=>Tt,BalanceClient:()=>Y,BigNumber:()=>v.BigNumber,CachingPoolService:()=>De,DECIMAL_PLACES:()=>ct,DENOMINATOR:()=>we,FarmClient:()=>ke,HUB_ASSET_ID:()=>ae,HYDRADX_OMNIPOOL_ADDRESS:()=>Nt,HYDRADX_PARACHAIN_ID:()=>At,HYDRADX_SS58_PREFIX:()=>$,INFINITY:()=>Ct,LbpMath:()=>H,LbpPool:()=>Pe,LbpPoolClient:()=>ce,ONE:()=>_,OmniMath:()=>B,OmniPool:()=>fe,OmniPoolClient:()=>me,PolkadotApiClient:()=>G,PoolConfigNotFound:()=>Xe,PoolError:()=>J,PoolFactory:()=>re,PoolNotFound:()=>he,PoolService:()=>se,PoolType:()=>E,ProviderConfigNotFound:()=>Ke,RUNTIME_DECIMALS:()=>V,RouteNotFound:()=>K,Router:()=>Z,SYSTEM_ASSET_DECIMALS:()=>It,SYSTEM_ASSET_ID:()=>C,StableMath:()=>R,StableSwap:()=>be,StableSwapClient:()=>ge,StorageConfigNotFound:()=>Je,SubscriptionNotSupported:()=>je,TRADEABLE_DEFAULT:()=>Q,TradeRouter:()=>xe,TradeType:()=>Ge,XykMath:()=>X,XykPool:()=>ye,XykPoolClient:()=>pe,ZERO:()=>P,bnFormatter:()=>_t,bnum:()=>p,buildRoute:()=>de,calculateBuyFee:()=>Ve,calculateDiffToAvg:()=>qt,calculateDiffToRef:()=>ie,calculateSellFee:()=>Ze,findNestedKey:()=>qe,findNestedObj:()=>Ft,scale:()=>O});module.exports=wt(Ht);var ve=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Ot=5,ne=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new ve,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(o==null||o.length>Ot)return r;let a=o[o.length-1];(s===null||a[0]===s)&&r.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),i.enqueue(m)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,n]of t){let o=parseInt(i),a=parseInt(n);s.get(o)?.push([a,r])}return s}};function Ce(l){let e={};for(let t of l){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let n=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(n)}}}return e}var oe=class{getProposals(e,t,s){let r=Ce(s),i=Object.keys(r),n=i.map(c=>r[c]).flat(),o=new ne,a=o.buildAndPopulateGraph(i,n),u=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(u)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let n=s[i],o=s[i+1];if(o==null)break;r.push(this.toEdge(n,o))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Be=(l,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=l(t)),s)};var pt=require("@polkadot/util-crypto"),gt=require("@polkadot/util"),dt=require("viem");var Qe=[{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 et=require("@polkadot/util-crypto"),tt=require("@polkadot/util"),V=18,Q=15,C="0",It=12,ae="1",At=2034,$=63,Tt=2090,we=1e3,Nt=(0,et.encodeAddress)((0,tt.stringToU8a)("modlomnipool".padEnd(32,"\0")),$);var E=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(E||{}),J=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(J||{}),Ge=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ge||{});var Oe=class{static encodeEvmAddress(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static decodeEvmAddress(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};function qe(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Ft(l,e,t){let s;return JSON.stringify(l,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var _t=(l,e)=>typeof e=="bigint"?e.toString():e;var le=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var Ie=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Rt=Ie(()=>"illegal argument(s)"),st=l=>{throw new Rt(l)};var Et=Ie(()=>"index out of bounds"),He=l=>{throw new Et(l)},Ae=(l,e,t)=>(l<e||l>=t)&&He(l);var rt=23283064365386963e-26,Te=class{float(e=1){return this.int()*rt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*rt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var Ne=class extends Te{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var it=new Ne(Math.random);var nt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var ot=Object.getPrototypeOf({}),Fe="function",at="string",ee=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===Fe)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===Fe)return e.equiv(l)}else return l==e;return typeof l===at||typeof e===at?!1:(t=Object.getPrototypeOf(l),(t==null||t===ot)&&(t=Object.getPrototypeOf(e),t==null||t===ot)?Mt(l,e):typeof l!==Fe&&l.length!==void 0&&typeof e!==Fe&&e.length!==void 0?kt(l,e):l instanceof Set&&e instanceof Set?Lt(l,e):l instanceof Map&&e instanceof Map?Dt(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},kt=(l,e,t=ee)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},Lt=(l,e,t=ee)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),Dt=(l,e,t=ee)=>l.size===e.size&&t([...l].sort(),[...e].sort()),Mt=(l,e,t=ee)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var ze=class{value;constructor(e){this.value=e}deref(){return this.value}};var lt=l=>l instanceof ze;var _e=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return ut("next",this._head)}reverseIterator(){return ut("prev",this.tail)}clear(){this.release()}compare(e,t=le){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,n=0;for(;s-- >0&&n===0;)n=t(r.value,i.value),r=r.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof l||nt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!ee(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||le;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!lt(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&He(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*ut(l,e){for(;e;)yield e.value,e=e[l]}var Re=class l extends _e{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new l}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(Ae(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(Ae(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==r&&n.next?i(n.next):void 0}});return s?i(s):void 0}shuffle(e,t=it){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&st("invalid indices: ${from} / ${to}");let i=new l,n=this.nthCell(s);for(;n&&++s<=r;)i.push(n.value),n=n.next;return i}sort(e=le){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(s.value,i.value)<=0?(a=s,s=s.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),Ae(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new l;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let n of s)this.insertBefore(r,n);else for(let n of s)this.push(n);return i}};var te=class l{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new Re,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Ee=class l extends te{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new l(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let s=this.map.get(e);if(s){if(s.value.t>=Date.now())return this.resetEntry(s);this.removeEntry(s)}return t}set(e,t,s=this.opts.ttl){let r=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,r-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,r,s):this._size-=n,t}async getSet(e,t,s=this.opts.ttl){let r=this.get(e);return r!==void 0?r:this.set(e,await t(),s)}prune(){let e=Date.now(),t=this.items.head,s=0;for(;t;)t.value.t<e&&(this.removeEntry(t),s++),t=t.next;return s}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,s=Date.now(),r=this.items.head;for(;r&&(this._size>t||this.length>=e);)r.value.t<s&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(e,t,s,r,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var zs=require("@galacticcouncil/api-augment/hydradx"),Us=require("@galacticcouncil/api-augment/basilisk"),G=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var j=class extends G{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==C){let m=this.api.consts.balances.existentialDeposit;return{id:C,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:u,decimals:c}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:u,decimals:c,icon:u,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[i,n]=r,{assetType:o,isSufficient:a,existentialDeposit:u}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,s),h=n.toNumber(),g=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",g.format(h)].join(" ");return{id:e,name:d,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,s,r){let{assets:i}=r,{name:n,symbol:o,assetType:a,isSufficient:u,existentialDeposit:c}=t,h=i.map(f=>f.toString()).map(f=>{let{symbol:y}=this.getToken(f,t,s);return[f,y]}),g=Object.fromEntries(h),d=Object.values(g);return{id:e,name:d.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:d.join("/"),type:a.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:g}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),n=s?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:n}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),u=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},h])=>{let g=h.unwrap(),d=r.get(m.toString()),{assetType:f}=g;switch(f.toString()){case"Bond":let y=n.get(m.toString());return this.getBond(m.toString(),g,u,y);case"StableSwap":let x=i.get(m.toString());return this.getShares(m.toString(),g,u,x);case"External":return this.getExternal(m.toString(),g,t,d);default:return this.getToken(m.toString(),g,u,d)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var v=require("bignumber.js"),ct=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:ct});var P=p(0),_=p(1),Ct=p("Infinity");function O(l,e){let t=new v.BigNumber(e.toString()),s=new v.BigNumber(10).pow(t);return l.times(s)}function p(l){return new v.BigNumber(l.toString())}var Y=class extends G{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===C?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(C,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(n=>n.type!=="Erc20").filter(n=>n.id!==C).map(n=>[e,n.id]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,u)=>{let c=this.calculateFreeBalance(a),m=i[u][1];o.push([m,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(n=>n.type==="Erc20"),i=async()=>{let n=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,u])=>{n.push([a,u])}),s(n)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,n=new v.BigNumber(t),o=new v.BigNumber(s||i),a=new v.BigNumber(r||0n),u=o.gt(a)?o:a;return n.minus(u)}};var Ue=require("@polkadot/util-crypto"),We=require("@galacticcouncil/math-liquidity-mining");var mt=require("@polkadot/types"),Ye=require("@polkadot/util"),ke=class extends G{balanceClient;constructor(e){super(e),this.balanceClient=new Y(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),g=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),d=u.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:f.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),g=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),d=u.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:f.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),u;return Number(t)<Number(s)?u=(0,We.fixed_from_rational)(o,a):u=(0,We.fixed_from_rational)(a,o),u}getGlobalRewardPerPeriod(e,t,s,r){let n=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return n.gte(s)?s:n}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return(0,Ye.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",i=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new mt.GenericAccountId32(e,this.padEndU8a((0,Ye.u8aConcat)(r,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Ue.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Ue.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:u,potBalance:c})=>{let m=new v.BigNumber(a.totalSharesZ.toString()),h=a.plannedYieldingPeriods.toString(),g=new v.BigNumber(a.yieldPerPeriod.toString()),d=new v.BigNumber(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),y=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new v.BigNumber(s).times(f)),S;if(m.isZero())S=g.times(y).times(x);else{let M=this.getGlobalRewardPerPeriod(m,g,d,u);S=this.getPoolYieldPerPeriod(M,y,m,u).times(x)}let N=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),F=d.times(h),U=c?N.plus(c):F;return N.div(U).gte(.999)?P:S.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),P).toString():void 0}};var q=class extends Y{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Ee(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Be(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let i=this.subscribePoolChange(t);s.push(i)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);s.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);s.push(i)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,i])=>{let n=e.tokens.findIndex(o=>o.id==r);n>=0&&t(e,r)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var Gt=["Supply","Withdraw","Repay","Borrow"],ue=class extends q{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:i})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return(0,pt.encodeAddress)((0,gt.stringToU8a)(s.padEnd(32,"\0")),$)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(i=>{i.forEach(n=>{let{event:o}=n,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:u,assetOut:c}=o.data.toHuman(),m=u.replace(/,/g,""),h=c.replace(/,/g,"");(m===s.id||h===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${h}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:u}=o.data.toHuman();try{let{eventName:c,args:m}=(0,dt.decodeEventLog)({abi:Qe,topics:u.topics,data:u.data});Gt.includes(c)&&m.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?r.toString():i.toString();return{...n,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?qe(e.location,"accountKey20").accountKey20.key:Oe.encodeEvmAddress(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var z=require("@galacticcouncil/math-lbp"),H=class{static getSpotPrice(e,t,s,r,i){return(0,z.get_spot_price)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return(0,z.calculate_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return(0,z.calculate_out_given_in)(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return(0,z.calculate_linear_weights)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,z.calculate_pool_trade_fee)(e,t,s)}};var ce=class extends q{MAX_FINAL_WEIGHT=O(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,n])=>this.isActivePool(n.unwrap(),s)).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(i.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let n=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:u,feeCollector:c}=t,m=H.calculateLinearWeights(r.toString(),i.toString(),o.toString(),a.toString(),s),[h,g]=n,d=h.toString(),f=p(m),y=g.toString(),x=this.MAX_FINAL_WEIGHT.minus(p(f)),[S,N,F]=await Promise.all([this.isRepayFeeApplied(d,u.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,y)]);return{repayFeeApply:S,tokens:[{id:d,weight:f,balance:N.toString()},{id:y,weight:x,balance:F.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=p(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ht=require("@polkadot/util-crypto"),Pt=require("@polkadot/util");function k(l,e){return l.shiftedBy(-1*e).toString()}function T(l){return l[0]/l[1]*100}function D(l){return l[0]/l[1]}function L(l){return[l/we,we]}var b=require("@galacticcouncil/math-omnipool");var B=class{static calculateSpotPrice(e,t,s,r){return(0,b.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,b.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,n,o,a,u){return(0,b.calculate_in_given_out)(e,t,s,r,i,n,o,a,u)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,b.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,n,o,a,u){return(0,b.calculate_out_given_in)(e,t,s,r,i,n,o,a,u)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,b.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,b.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,b.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,n,o,a){return(0,b.calculate_liquidity_out)(e,t,s,r,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,i,n,o,a){return(0,b.calculate_liquidity_lrna_out)(e,t,s,r,i,n,o,a)}static calculateCapDifference(e,t,s,r){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),o=(0,v.BigNumber)(r),u=(0,v.BigNumber)(s).shiftedBy(-18);if(i.div(o).lt(u)){let m=u.times(o).minus(i).times(n),h=i.times((0,v.BigNumber)(1).minus(u));return m.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return(0,b.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,b.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,b.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,b.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,b.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,s,r,i,n,o,a,u,c,m){return(0,b.recalculate_asset_fee)(e,t,s,r,i,n,o,a,u,c,m)}static recalculateProtocolFee(e,t,s,r,i,n,o,a,u,c,m){return(0,b.recalculate_protocol_fee)(e,t,s,r,i,n,o,a,u,c,m)}static verifyAssetCap(e,t,s,r){return(0,b.verify_asset_cap)(e,t,s,r)}};var me=class extends q{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=s.map(async([{args:[a]},u])=>{let{hubReserve:c,shares:m,tradable:h,cap:g,protocolShares:d}=u.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:f.toString(),cap:p(g.toString()),protocolShares:p(d.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,i="omnipool",n="Short",o=F=>F===C?[C,ae]:[ae,F],[a,u,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(i,o(s),n),this.api.query.emaOracle.oracles(i,o(r),n)]),[h,g,d]=this.getAssetFee(e,a.toNumber(),u,c),[f,y,x]=r===ae?[0,0,0]:this.getProtocolFee(e,a.toNumber(),u,m),S=h+f,N=d+x;return{assetFee:L(g),protocolFee:L(y),min:L(S),max:L(N)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let n=e.tokens[i];if(r.isNone)return n;let o=r.unwrap();return this.updateTokenState(n,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:p(s.toString()),shares:p(r.toString()),cap:p(n.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:i,balanceOut:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=L(o.toNumber()),h=L(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[g]=r.unwrap(),{assetFee:d,timestamp:f}=s.unwrap(),y=t-f.toNumber(),x=g.volume.bIn.toString(),S=g.volume.bOut.toString(),N=g.liquidity.b.toString();i===C&&(x=g.volume.aIn.toString(),S=g.volume.aOut.toString(),N=g.liquidity.a.toString());let F=L(d.toNumber()),U=B.recalculateAssetFee(x,S,N,"9",n.toString(),T(F).toString(),y.toString(),T(m).toString(),T(h).toString(),u.toString(),c.toString());return[o.toNumber(),Number(U)*1e4,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:i,balanceIn:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=L(o.toNumber()),h=L(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[g]=r.unwrap(),{protocolFee:d,timestamp:f}=s.unwrap(),y=t-f.toNumber(),x=g.volume.bIn.toString(),S=g.volume.bOut.toString(),N=g.liquidity.b.toString();i===C&&(x=g.volume.aIn.toString(),S=g.volume.aOut.toString(),N=g.liquidity.a.toString());let F=L(d.toNumber()),U=B.recalculateProtocolFee(x,S,N,"9",n.toString(),T(F).toString(),y.toString(),T(m).toString(),T(h).toString(),u.toString(),c.toString());return[o.toNumber(),Number(U)*1e4,a.toNumber()]}getPoolId(){return(0,ht.encodeAddress)((0,Pt.stringToU8a)("modlomnipool".padEnd(32,"\0")),$)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var pe=class extends q{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[n,o]=r.unwrap(),[a,u]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Le=require("@polkadot/util-crypto");var I=require("@galacticcouncil/math-stableswap"),R=class{static getPoolAddress(e){return(0,I.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,i){return(0,I.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,n,o){return(0,I.calculate_in_given_out)(e,t,s,r,i,n,o)}static calculateAddOneAsset(e,t,s,r,i,n,o){return(0,I.calculate_add_one_asset)(e,t,s,r,i,n,o)}static calculateSharesForAmount(e,t,s,r,i,n,o){return(0,I.calculate_shares_for_amount)(e,t,s,r,i,n,o)}static calculateOutGivenIn(e,t,s,r,i,n,o){return(0,I.calculate_out_given_in)(e,t,s,r,i,n,o)}static calculateLiquidityOutOneAsset(e,t,s,r,i,n,o){return(0,I.calculate_liquidity_out_one_asset)(e,t,s,r,i,n,o)}static calculateShares(e,t,s,r,i,n){return(0,I.calculate_shares)(e,t,s,r,i,n)}static calculateSpotPriceWithFee(e,t,s,r,i,n,o,a){return(0,I.calculate_spot_price_with_fee)(e,t,s,r,i,n,o,a)}static calculatePoolTradeFee(e,t,s){return(0,I.calculate_pool_trade_fee)(e,t,s)}static recalculatePegs(e,t,s,r,i){let n=(0,I.recalculate_peg)(e,t,s,r,i);return JSON.parse(n)}};var ft=340282366920938463463374607431768211455n,ge=class extends q{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=this.getPoolAddress(a),[c,m,h]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(u,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(u,o),{address:u,id:a,type:"Stableswap",fee:L(o.fee.toNumber()),tokens:m,...c,...h,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[i,n]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,i,n)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=R.calculateAmplification(r.toString(),i.toString(),n.toString(),o.toString(),s),u=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:u.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async o=>{let[a,u]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:u.toString()}}),n=await Promise.all(i);return n.push({id:t,tradeable:Q,balance:ft.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,s=R.defaultPegs(e.assets.length);return{pegsFee:L(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let i=r.unwrap(),n=await this.getLatestPegs(t,i,s),o=this.getRecentPegs(i),a=i.maxPegUpdate.toHuman(),u=t.fee.toHuman(),[c,m]=R.recalculatePegs(JSON.stringify(o),JSON.stringify(n),s,a.replace(/%/g,""),u.replace(/%/g,"")),h=Number(c)*1e4;return{pegsFee:L(h),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(i=>i.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=r.map(async(o,a)=>{if(o.isOracle){let[u,c,m]=o.asOracle,h=[m.toString(),i[a]].map(S=>Number(S)).sort((S,N)=>S-N),g=await this.api.query.emaOracle.oracles(u,h,c),[{price:d,updatedAt:f}]=g.unwrap(),y=d.n.toString(),x=d.d.toString();return m.toString()===h[0].toString()?[[y,x],f.toString()]:[[x,y],f.toString()]}else return[o.asValue.map(u=>u.toString()),s]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),s=R.getPoolAddress(t);return(0,Le.encodeAddress)((0,Le.blake2AsHex)(s),$)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function de(l){return l.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var he=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Xe=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},K=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},$e=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Je=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},je=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ke=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var se=class extends G{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Be(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new j(this.api),this.aaveClient=new ue(this.api),this.xykClient=new pe(this.api),this.omniClient=new me(this.api),this.lbpClient=new ce(this.api),this.stableClient=new ge(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}unsubscribe(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new he(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}buildBuyTx(e,t,s,r,i){let n;return this.isDirectOmnipoolTrade(i)?n=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):n=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),de(i)),{hex:n.toHex(),name:"RouterBuy",get:()=>n,dryRun:o=>this.dryRun(o,n)}}buildSellTx(e,t,s,r,i){let n;return this.isDirectOmnipoolTrade(i)?n=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):n=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),de(i)),{hex:n.toHex(),name:"RouterSell",get:()=>n,dryRun:o=>this.dryRun(o,n)}}buildSellAllTx(e,t,s,r){let i=this.api.tx.router.sellAll(e,t,s.toFixed(),de(r));return{hex:i.toHex(),name:"RouterSellAll",get:()=>i,dryRun:n=>this.dryRun(n,i)}}};var De=class extends se{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new te(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){this.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Pe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,n,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=T(this.repayFeeApply?s.repayFee:s.exchangeFee),u=t.plus(o),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),u=T(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:u,errors:i}}}calculateInGivenOut(e,t){let s=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),O(_,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),O(_,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let s=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(s)}};var fe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=i.minus(r),o=r===P?P:n.div(r).multipliedBy(100).decimalPlaces(2),a=[],u=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),o=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),a=[],u=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?D(s.assetFee).toString():P.toString(),s?D(s.protocolFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?D(s.assetFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?D(s.assetFee).toString():P.toString(),s?D(s.protocolFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?D(s.assetFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(V-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(V-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(V-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(V-e.decimalsIn)).decimalPlaces(0,1)}};var be=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,i,n,o,a,u,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=n,this.id=o,this.fee=a,this.totalIssuance=u,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?Q:r.tradeable,tradeableOut:this.id===t?Q:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=T(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),u=B.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),n=T(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),u=B.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n,errors:o}}calculateIn(e,t,s){let r=R.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateAddOneAsset(e,t,s){let r=R.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateSharesForAmount(e,t,s){let r=R.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=R.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let r=O(_,e.decimalsIn-e.decimalsOut);return p(t).div(r)}let s=O(_,18-e.decimalsIn);return p(t).div(s)}calculateOut(e,t,s){let r=R.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateWithdrawOneAsset(e,t,s){let r=R.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateShares(e,t,s){let r=R.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=R.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let r=O(_,e.decimalsOut-e.decimalsIn);return p(t).div(r)}let s=O(_,18-e.decimalsOut);return p(t).div(s)}calculateTradeFee(e,t){let s=R.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var A=require("@galacticcouncil/math-xyk"),X=class{static getSpotPrice(e,t,s){return(0,A.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,A.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,A.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,A.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,A.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,A.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,A.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,A.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,A.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,A.calculate_liquidity_out_asset_b)(e,t,s,r)}};var ye=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),n=T(s.exchangeFee),o=r.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),n=T(s.exchangeFee),o=r.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let s=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=X.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=O(_,18-e.decimalsOut);return p(t).div(s)}spotPriceOutGivenIn(e){let t=X.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=O(_,18-e.decimalsIn);return p(t).div(s)}calculateTradeFee(e,t){let s=X.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(s)}};var Se=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:P,assetOutED:P}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=[];return t.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=[];return r.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return O(_,e.decimalsOut)}spotPriceOutGivenIn(e){return O(_,e.decimalsIn)}calculateTradeFee(e,t){return P}};var re=class{static get(e){switch(e.type){case"Aave":return Se.fromPool(e);case"Xyk":return ye.fromPool(e);case"Omnipool":return fe.fromPool(e);case"Lbp":return Pe.fromPool(e);case"Stableswap":return be.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Z=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new oe,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),n=this.getPaths(e,null,r,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(n)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,re.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let n=t.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function qt(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ie(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ze(l,e){return _.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function Ve(l,e){return e.div(l).minus(_).multipliedBy(100).decimalPlaces(2)}var xe=class extends Z{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,n=r[r.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,r]}}getPoolFeeRange(e){let t=e.min?T(e.min):void 0,s=e.max?T(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new K(e,t);let a;if(r)a=await this.toSellSwaps(s,r,n);else{let w=o.map(async W=>await this.toSellSwaps(s,W,n)),M=await Promise.all(w);a=this.findBestSellRoute(M)}let u=a[0],c=a[a.length-1],m=this.isDirectTrade(a),h=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,M)=>w.multipliedBy(M)),g=O(h,c.assetOutDecimals),d=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,a,n),f=c.amountOut,y=m?c.tradeFeePct:Ze(d,f).toNumber(),x=d.minus(f),S=this.getRouteFeeRange(a),N=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(g),F=ie(d,N),U=(w,M=!1)=>{let W=a.map(bt=>bt);return M?this.poolService.buildSellAllTx(e,t,w,W):this.poolService.buildSellTx(e,t,u.amountIn,w,W)};return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:g,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F.toNumber(),swaps:a,toTx:U,toHuman(){return{type:"Sell",amountIn:k(u.amountIn,u.assetInDecimals),amountOut:k(c.amountOut,c.assetOutDecimals),spotPrice:k(g,c.assetOutDecimals),tradeFee:k(x,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F.toNumber(),swaps:a.map(w=>w.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1]:u=e;let c=o.calculateOutGivenIn(a,u);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1].amountOut:u=O(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:h,feePct:g,errors:d}=o.validateAndSell(a,u,c),f=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),x=u.shiftedBy(-1*a.decimalsIn).multipliedBy(y),S=ie(h,x);r.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,calculatedOut:h,amountOut:m,spotPrice:y,tradeFeePct:g,tradeFeeRange:f,priceImpactPct:S.toNumber(),errors:d,toHuman(){return{...n,amountIn:k(u,a.decimalsIn),calculatedOut:k(h,a.decimalsOut),amountOut:k(m,a.decimalsOut),spotPrice:k(y,a.decimalsOut),tradeFeePct:g,tradeFeeRange:f,priceImpactPct:S.toNumber(),errors:d}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)throw new K(e,t);let u=s.filter(g=>g.tokens.some(d=>d.id===e&&d.id!==g.id)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(d=>d.id===e)).map(g=>g.map(d=>p(d.balance).shiftedBy(-1*d.decimals)).reduce((d,f)=>d.plus(f))).sort((g,d)=>d.isLessThan(g)?-1:1)[0].div(100).multipliedBy(.1),c=i.map(async g=>await this.toSellSwaps(u,g,r)),m=await Promise.all(c);return this.findBestSellRoute(m).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut}))}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,r),a=o.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,h)=>m.multipliedBy(h)),u=o[o.length-1].assetOutDecimals;return{amount:O(a,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,n=r[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new K(e,t);let a;if(r)a=await this.toBuySwaps(s,r,n);else{let w=o.map(async W=>await this.toBuySwaps(s,W,n)),M=await Promise.all(w);a=this.findBestBuyRoute(M)}let u=a[a.length-1],c=a[0],m=this.isDirectTrade(a),h=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,M)=>w.multipliedBy(M)),g=O(h,c.assetInDecimals),d=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,a,n),f=c.amountIn,y=m?c.tradeFeePct:Ve(d,f).toNumber(),x=f.minus(d),S=this.getRouteFeeRange(a),N=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(g),F;d.isZero()?F=-100:F=ie(N,d).toNumber();let U=w=>{let M=a.map(W=>W);return this.poolService.buildBuyTx(e,t,u.amountOut,w,M)};return{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:g,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F,swaps:a,toTx:U,toHuman(){return{type:"Buy",amountOut:k(u.amountOut,u.assetOutDecimals),amountIn:k(c.amountIn,c.assetInDecimals),spotPrice:k(g,c.assetInDecimals),tradeFee:k(x,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F,swaps:a.map(w=>w.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=e:u=r[0];let c=o.calculateInGivenOut(a,u);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=O(p(e),a.decimalsOut).decimalPlaces(0,1):u=r[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:h,feePct:g,errors:d}=o.validateAndBuy(a,u,c),f=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),x=u.shiftedBy(-1*a.decimalsOut).multipliedBy(y),S;h.isZero()?S=-100:S=ie(x,h).toNumber(),r.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:u,calculatedIn:h,amountIn:m,spotPrice:y,tradeFeePct:g,tradeFeeRange:f,priceImpactPct:S,errors:d,toHuman(){return{...n,amountOut:k(u,a.decimalsOut),calculatedIn:k(h,a.decimalsIn),amountIn:k(m,a.decimalsIn),spotPrice:k(y,a.decimalsIn),tradeFeePct:g,tradeFeeRange:f,priceImpactPct:S,errors:d}}})}return r}};0&&(module.exports={AMOUNT_MAX,AavePool,AavePoolClient,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HUB_ASSET_ID,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
|
|
1
|
+
"use strict";var Ye=Object.defineProperty;var Dt=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var qt=Object.prototype.hasOwnProperty;var Ht=(l,e)=>{for(var t in e)Ye(l,t,{get:e[t],enumerable:!0})},zt=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gt(e))!qt.call(l,r)&&r!==t&&Ye(l,r,{get:()=>e[r],enumerable:!(s=Dt(e,r))||s.enumerable});return l};var Ut=l=>zt(Ye({},"__esModule",{value:!0}),l);var rs={};Ht(rs,{AAVE_ABI:()=>pe,AAVE_GAS_LIMIT:()=>rt,AAVE_PROXY:()=>st,AAVE_ROUNDING_THRESHOLD:()=>Fe,AAVE_UINT_256_MAX:()=>it,AMOUNT_MAX:()=>_t,AavePool:()=>he,AavePoolClient:()=>Pe,AssetClient:()=>Q,AssetNotFound:()=>Ze,BASILISK_PARACHAIN_ID:()=>ns,BalanceClient:()=>U,BigNumber:()=>v.BigNumber,CachingPoolService:()=>qe,DECIMAL_PLACES:()=>dt,DENOMINATOR:()=>$e,ERC20:()=>Z,EvmClient:()=>de,FarmClient:()=>Te,H160:()=>Ae,HUB_ASSET_ID:()=>le,HYDRADX_PARACHAIN_ID:()=>os,HYDRADX_SS58_PREFIX:()=>Y,INFINITY:()=>Wt,LbpMath:()=>H,LbpPool:()=>fe,LbpPoolClient:()=>be,ONE:()=>_,OmniMath:()=>O,OmniPool:()=>ye,OmniPoolClient:()=>Se,PoolConfigNotFound:()=>Ve,PoolError:()=>V,PoolFactory:()=>re,PoolNotFound:()=>me,PoolService:()=>se,PoolType:()=>R,ProviderConfigNotFound:()=>tt,RUNTIME_DECIMALS:()=>ue,RouteNotFound:()=>K,Router:()=>ie,SYSTEM_ASSET_DECIMALS:()=>as,SYSTEM_ASSET_ID:()=>M,StableMath:()=>E,StableSwap:()=>ve,StableSwapClient:()=>Oe,StorageConfigNotFound:()=>Qe,SubscriptionNotSupported:()=>et,TRADEABLE_DEFAULT:()=>ce,TradeRouter:()=>Ue,TradeType:()=>ze,TradeUtils:()=>We,XykMath:()=>X,XykPool:()=>xe,XykPoolClient:()=>we,ZERO:()=>f,bnFormatter:()=>Zt,bnum:()=>d,calculateBuyFee:()=>mt,calculateDiffToAvg:()=>ss,calculateDiffToRef:()=>ne,calculateSellFee:()=>ct,evmMainnet:()=>nt,findNestedKey:()=>lt,findNestedObj:()=>Vt,getFraction:()=>oe,isEvmAccount:()=>Rt,isEvmAddress:()=>kt,isSs58Address:()=>Lt,scale:()=>B});module.exports=Ut(rs);var ns=2090,$e=1e3,le="1",os=2034,Y=63,ue=18,M="0",as=12,ce=15;var us=require("@galacticcouncil/api-augment/hydradx"),cs=require("@galacticcouncil/api-augment/basilisk"),D=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var Q=class extends D{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==M){let m=this.api.consts.balances.existentialDeposit;return{id:M,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:u,decimals:c}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:u,decimals:c,icon:u,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[i,n]=r,{assetType:o,isSufficient:a,existentialDeposit:u}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,s),g=n.toNumber(),p=new Intl.DateTimeFormat("en-GB"),h=[c,"Bond",p.format(g)].join(" ");return{id:e,name:h,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:i.toString(),maturity:g}}getShares(e,t,s,r){let{assets:i}=r,{name:n,symbol:o,assetType:a,isSufficient:u,existentialDeposit:c}=t,g=i.map(P=>P.toString()).map(P=>{let{symbol:y}=this.getToken(P,t,s);return[P,y]}),p=Object.fromEntries(g),h=Object.values(p);return{id:e,name:h.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:h.join("/"),type:a.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:p}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),n=s?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:n}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),u=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},g])=>{let p=g.unwrap(),h=r.get(m.toString()),{assetType:P}=p;switch(P.toString()){case"Bond":let y=n.get(m.toString());return this.getBond(m.toString(),p,u,y);case"StableSwap":let x=i.get(m.toString());return this.getShares(m.toString(),p,u,x);case"External":return this.getExternal(m.toString(),p,t,h);default:return this.getToken(m.toString(),p,u,h)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var v=require("bignumber.js"),dt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:dt});var f=d(0),_=d(1),Wt=d("Infinity");function B(l,e){let t=new v.BigNumber(e.toString()),s=new v.BigNumber(10).pow(t);return l.times(s)}function d(l){return new v.BigNumber(l.toString())}var U=class extends D{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===M?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(M,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(n=>n.type!=="Erc20").filter(n=>n.id!==M).map(n=>[e,n.id]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,u)=>{let c=this.calculateFreeBalance(a),m=i[u][1];o.push([m,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(n=>n.type==="Erc20"),i=async()=>{let n=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,u])=>{n.push([a,u])}),s(n)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,n=new v.BigNumber(t),o=new v.BigNumber(s||i),a=new v.BigNumber(r||0n),u=o.gt(a)?o:a;return n.minus(u)}};var Je=require("@galacticcouncil/math-liquidity-mining"),gt=require("@polkadot/types"),je=require("@polkadot/util"),Ke=require("@polkadot/util-crypto");var Te=class extends D{balanceClient;constructor(e){super(e),this.balanceClient=new U(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),p=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),h=u.rewardCurrency.toString(),P=await this.balanceClient.getTokenBalanceData(p,h);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:P.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),p=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),h=u.rewardCurrency.toString(),P=await this.balanceClient.getTokenBalanceData(p,h);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:P.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),u;return Number(t)<Number(s)?u=(0,Je.fixed_from_rational)(o,a):u=(0,Je.fixed_from_rational)(a,o),u}getGlobalRewardPerPeriod(e,t,s,r){let n=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return n.gte(s)?s:n}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return(0,je.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",i=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new gt.GenericAccountId32(e,this.padEndU8a((0,je.u8aConcat)(r,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Ke.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Ke.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:u,potBalance:c})=>{let m=new v.BigNumber(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),p=new v.BigNumber(a.yieldPerPeriod.toString()),h=new v.BigNumber(a.maxRewardPerPeriod.toString()),P=a.blocksPerPeriod.toString(),y=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new v.BigNumber(s).times(P)),S;if(m.isZero())S=p.times(y).times(x);else{let j=this.getGlobalRewardPerPeriod(m,p,h,u);S=this.getPoolYieldPerPeriod(j,y,m,u).times(x)}let A=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),T=h.times(g),w=c?A.plus(c):T;return A.div(w).gte(.999)?f:S.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),f).toString():void 0}};var me=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ve=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},K=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Ze=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Qe=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},et=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},tt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};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"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var st="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",rt=1000000n,Fe=5,it=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ft=require("viem"),ht=["https://rpc.hydradx.cloud","https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Pt=["wss://rpc.hydradx.cloud","wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],nt=(0,ft.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:ht,webSocket:Pt},default:{http:ht,webSocket:Pt}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var q=require("viem");var de=class{chain;constructor(e){this.chain=e||nt}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,q.createPublicClient)({chain:this.chain,transport:(0,q.http)()})}getWsProvider(){return(0,q.createPublicClient)({chain:this.chain,transport:(0,q.webSocket)()})}getSigner(e){return(0,q.createWalletClient)({account:e,chain:this.chain,transport:(0,q.custom)(window.ethereum)})}};var ge=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var Ne=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Xt=Ne(()=>"illegal argument(s)"),bt=l=>{throw new Xt(l)};var Yt=Ne(()=>"index out of bounds"),ot=l=>{throw new Yt(l)},_e=(l,e,t)=>(l<e||l>=t)&&ot(l);var yt=23283064365386963e-26,Ee=class{float(e=1){return this.int()*yt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*yt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var Re=class extends Ee{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var St=new Re(Math.random);var xt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var wt=Object.getPrototypeOf({}),ke="function",vt="string",ee=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===ke)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===ke)return e.equiv(l)}else return l==e;return typeof l===vt||typeof e===vt?!1:(t=Object.getPrototypeOf(l),(t==null||t===wt)&&(t=Object.getPrototypeOf(e),t==null||t===wt)?Kt(l,e):typeof l!==ke&&l.length!==void 0&&typeof e!==ke&&e.length!==void 0?$t(l,e):l instanceof Set&&e instanceof Set?Jt(l,e):l instanceof Map&&e instanceof Map?jt(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},$t=(l,e,t=ee)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},Jt=(l,e,t=ee)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),jt=(l,e,t=ee)=>l.size===e.size&&t([...l].sort(),[...e].sort()),Kt=(l,e,t=ee)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var at=class{value;constructor(e){this.value=e}deref(){return this.value}};var Ot=l=>l instanceof at;var Le=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Bt("next",this._head)}reverseIterator(){return Bt("prev",this.tail)}clear(){this.release()}compare(e,t=ge){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,n=0;for(;s-- >0&&n===0;)n=t(r.value,i.value),r=r.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof l||xt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!ee(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||ge;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!Ot(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&ot(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*Bt(l,e){for(;e;)yield e.value,e=e[l]}var Ce=class l extends Le{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new l}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(_e(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(_e(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==r&&n.next?i(n.next):void 0}});return s?i(s):void 0}shuffle(e,t=St){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&bt("invalid indices: ${from} / ${to}");let i=new l,n=this.nthCell(s);for(;n&&++s<=r;)i.push(n.value),n=n.next;return i}sort(e=ge){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(s.value,i.value)<=0?(a=s,s=s.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),_e(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new l;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let n of s)this.insertBefore(r,n);else for(let n of s)this.push(n);return i}};var te=class l{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new Ce,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Me=class l extends te{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new l(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let s=this.map.get(e);if(s){if(s.value.t>=Date.now())return this.resetEntry(s);this.removeEntry(s)}return t}set(e,t,s=this.opts.ttl){let r=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,r-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,r,s):this._size-=n,t}async getSet(e,t,s=this.opts.ttl){let r=this.get(e);return r!==void 0?r:this.set(e,await t(),s)}prune(){let e=Date.now(),t=this.items.head,s=0;for(;t;)t.value.t<e&&(this.removeEntry(t),s++),t=t.next;return s}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,s=Date.now(),r=this.items.head;for(;r&&(this._size>t||this.length>=e);)r.value.t<s&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(e,t,s,r,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var De=(l,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=l(t)),s)};var R=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(R||{}),V=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(V||{});var he=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=d(r.balance),o=d(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:f,assetOutED:f}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=[];return t.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=[];return r.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return B(_,e.decimalsOut)}spotPriceOutGivenIn(e){return B(_,e.decimalsIn)}calculateTradeFee(e,t){return f}};var It=require("@polkadot/util-crypto"),At=require("@polkadot/util"),Tt=require("viem");var Z=class{static fromAssetId(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};function lt(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Vt(l,e,t){let s;return JSON.stringify(l,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var Zt=(l,e)=>typeof e=="bigint"?e.toString():e;var G=class extends U{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Me(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=De(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let i=this.subscribePoolChange(t);s.push(i)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);s.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);s.push(i)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,i])=>{let n=e.tokens.findIndex(o=>o.id==r);n>=0&&t(e,r)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var Qt=["Supply","Withdraw","Repay","Borrow"],Pe=class extends G{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:i})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return(0,It.encodeAddress)((0,At.stringToU8a)(s.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(i=>{i.forEach(n=>{let{event:o}=n,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:u,assetOut:c}=o.data.toHuman(),m=u.replace(/,/g,""),g=c.replace(/,/g,"");(m===s.id||g===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:u}=o.data.toHuman();try{let{eventName:c,args:m}=(0,Tt.decodeEventLog)({abi:pe,topics:u.topics,data:u.data});Qt.includes(c)&&m.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?r.toString():i.toString();return{...n,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?lt(e.location,"accountKey20").accountKey20.key:Z.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var W=require("@galacticcouncil/math-lbp"),H=class{static getSpotPrice(e,t,s,r,i){return(0,W.get_spot_price)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return(0,W.calculate_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return(0,W.calculate_out_given_in)(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return(0,W.calculate_linear_weights)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,W.calculate_pool_trade_fee)(e,t,s)}};function k(l,e){return l.shiftedBy(-1*e).toString()}function N(l){return l[0]/l[1]*100}function C(l){return l[0]/l[1]}function L(l){return[l/1e3,1e3]}var fe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,n,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=d(r.balance),o=d(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=N(this.repayFeeApply?s.repayFee:s.exchangeFee),u=t.plus(o),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),u=N(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:u,errors:i}}}calculateInGivenOut(e,t){let s=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=d(s);return r.isNegative()?f:r}calculateOutGivenIn(e,t){let s=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=d(s);return r.isNegative()?f:r}spotPriceInGivenOut(e){let t=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),B(_,e.decimalsOut).toString());return d(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),B(_,e.decimalsIn).toString());return d(t)}calculateTradeFee(e,t){let s=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return d(s)}};var be=class extends G{MAX_FINAL_WEIGHT=B(d(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,n])=>this.isActivePool(n.unwrap(),s)).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(i.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let n=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:u,feeCollector:c}=t,m=H.calculateLinearWeights(r.toString(),i.toString(),o.toString(),a.toString(),s),[g,p]=n,h=g.toString(),P=d(m),y=p.toString(),x=this.MAX_FINAL_WEIGHT.minus(d(P)),[S,A,T]=await Promise.all([this.isRepayFeeApplied(h,u.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,y)]);return{repayFeeApply:S,tokens:[{id:h,weight:P,balance:A.toString()},{id:y,weight:x,balance:T.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=d(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var b=require("@galacticcouncil/math-omnipool");var O=class{static calculateSpotPrice(e,t,s,r){return(0,b.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,b.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,n,o,a,u){return(0,b.calculate_in_given_out)(e,t,s,r,i,n,o,a,u)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,b.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,n,o,a,u){return(0,b.calculate_out_given_in)(e,t,s,r,i,n,o,a,u)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,b.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,b.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,b.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,n,o,a){return(0,b.calculate_liquidity_out)(e,t,s,r,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,i,n,o,a){return(0,b.calculate_liquidity_lrna_out)(e,t,s,r,i,n,o,a)}static calculateCapDifference(e,t,s,r){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),o=(0,v.BigNumber)(r),u=(0,v.BigNumber)(s).shiftedBy(-18);if(i.div(o).lt(u)){let m=u.times(o).minus(i).times(n),g=i.times((0,v.BigNumber)(1).minus(u));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return(0,b.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,b.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,b.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,b.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,b.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,s,r,i,n,o,a,u,c,m){return(0,b.recalculate_asset_fee)(e,t,s,r,i,n,o,a,u,c,m)}static recalculateProtocolFee(e,t,s,r,i,n,o,a,u,c,m){return(0,b.recalculate_protocol_fee)(e,t,s,r,i,n,o,a,u,c,m)}static verifyAssetCap(e,t,s,r){return(0,b.verify_asset_cap)(e,t,s,r)}};var ye=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=d(r.balance),o=d(i.balance),a=d(r.existentialDeposit),u=d(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=i.minus(r),o=r===f?f:n.div(r).multipliedBy(100).decimalPlaces(2),a=[],u=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),o=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),a=[],u=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=O.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?C(s.assetFee).toString():f.toString(),s?C(s.protocolFee).toString():f.toString()),i=d(r);return i.isNegative()?f:i}calculateLrnaInGivenOut(e,t,s){let r=O.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?C(s.assetFee).toString():f.toString()),i=d(r);return i.isNegative()?f:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=O.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?C(s.assetFee).toString():f.toString(),s?C(s.protocolFee).toString():f.toString()),i=d(r);return i.isNegative()?f:i}calculateOutGivenLrnaIn(e,t,s){let r=O.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?C(s.assetFee).toString():f.toString()),i=d(r);return i.isNegative()?f:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=O.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return d(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=O.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return d(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=O.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return d(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=O.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return d(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var Ft=require("@polkadot/util-crypto"),Nt=require("@polkadot/util");var Se=class extends G{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=s.map(async([{args:[a]},u])=>{let{hubReserve:c,shares:m,tradable:g,cap:p,protocolShares:h}=u.unwrap(),P=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:d(c.toString()),shares:d(m.toString()),tradeable:g.bits.toNumber(),balance:P.toString(),cap:d(p.toString()),protocolShares:d(h.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,i="omnipool",n="Short",o=T=>T===M?[M,le]:[le,T],[a,u,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(i,o(s),n),this.api.query.emaOracle.oracles(i,o(r),n)]),[g,p,h]=this.getAssetFee(e,a.toNumber(),u,c),[P,y,x]=r===le?[0,0,0]:this.getProtocolFee(e,a.toNumber(),u,m),S=g+P,A=h+x;return{assetFee:L(p),protocolFee:L(y),min:L(S),max:L(A)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let n=e.tokens[i];if(r.isNone)return n;let o=r.unwrap();return this.updateTokenState(n,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:d(s.toString()),shares:d(r.toString()),cap:d(n.toString()),protocolShares:d(o.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:i,balanceOut:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=L(o.toNumber()),g=L(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[p]=r.unwrap(),{assetFee:h,timestamp:P}=s.unwrap(),y=t-P.toNumber(),x=p.volume.bIn.toString(),S=p.volume.bOut.toString(),A=p.liquidity.b.toString();i===M&&(x=p.volume.aIn.toString(),S=p.volume.aOut.toString(),A=p.liquidity.a.toString());let T=L(h.toNumber()),w=O.recalculateAssetFee(x,S,A,"9",n.toString(),N(T).toString(),y.toString(),N(m).toString(),N(g).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e4,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:i,balanceIn:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=L(o.toNumber()),g=L(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[p]=r.unwrap(),{protocolFee:h,timestamp:P}=s.unwrap(),y=t-P.toNumber(),x=p.volume.bIn.toString(),S=p.volume.bOut.toString(),A=p.liquidity.b.toString();i===M&&(x=p.volume.aIn.toString(),S=p.volume.aOut.toString(),A=p.liquidity.a.toString());let T=L(h.toNumber()),w=O.recalculateProtocolFee(x,S,A,"9",n.toString(),N(T).toString(),y.toString(),N(m).toString(),N(g).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e4,a.toNumber()]}getPoolId(){return(0,Ft.encodeAddress)((0,Nt.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var F=require("@galacticcouncil/math-xyk"),X=class{static getSpotPrice(e,t,s){return(0,F.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,F.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,F.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,F.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,F.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,F.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,F.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,F.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,F.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,F.calculate_liquidity_out_asset_b)(e,t,s,r)}};var xe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=d(r.balance),o=d(i.balance),a=d(r.existentialDeposit),u=d(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),n=N(s.exchangeFee),o=r.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),n=N(s.exchangeFee),o=r.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let s=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=d(s);return r.isNegative()?f:r}calculateOutGivenIn(e,t){let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=d(s);return r.isNegative()?f:r}spotPriceInGivenOut(e){let t=X.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=B(_,18-e.decimalsOut);return d(t).div(s)}spotPriceOutGivenIn(e){let t=X.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=B(_,18-e.decimalsIn);return d(t).div(s)}calculateTradeFee(e,t){let s=X.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return d(s)}};var we=class extends G{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[n,o]=r.unwrap(),[a,u]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var I=require("@galacticcouncil/math-stableswap"),E=class{static getPoolAddress(e){return(0,I.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,i){return(0,I.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,n,o){return(0,I.calculate_in_given_out)(e,t,s,r,i,n,o)}static calculateAddOneAsset(e,t,s,r,i,n,o){return(0,I.calculate_add_one_asset)(e,t,s,r,i,n,o)}static calculateSharesForAmount(e,t,s,r,i,n,o){return(0,I.calculate_shares_for_amount)(e,t,s,r,i,n,o)}static calculateOutGivenIn(e,t,s,r,i,n,o){return(0,I.calculate_out_given_in)(e,t,s,r,i,n,o)}static calculateLiquidityOutOneAsset(e,t,s,r,i,n,o){return(0,I.calculate_liquidity_out_one_asset)(e,t,s,r,i,n,o)}static calculateShares(e,t,s,r,i,n){return(0,I.calculate_shares)(e,t,s,r,i,n)}static calculateSpotPriceWithFee(e,t,s,r,i,n,o,a){return(0,I.calculate_spot_price_with_fee)(e,t,s,r,i,n,o,a)}static calculatePoolTradeFee(e,t,s){return(0,I.calculate_pool_trade_fee)(e,t,s)}static recalculatePegs(e,t,s,r,i){let n=(0,I.recalculate_peg)(e,t,s,r,i);return JSON.parse(n)}};var ve=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,i,n,o,a,u,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=n,this.id=o,this.fee=a,this.totalIssuance=u,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=d(r.balance),o=d(i.balance),a=d(r.existentialDeposit),u=d(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=N(s.fee),o=[],a=O.isSellAllowed(e.tradeableIn),u=O.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),n=N(s.fee),o=[],a=O.isSellAllowed(e.tradeableIn),u=O.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n,errors:o}}calculateIn(e,t,s){let r=E.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?C(s.fee).toString():f.toString(),this.getPegs()),i=d(r);return i.isNegative()?f:i}calculateAddOneAsset(e,t,s){let r=E.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?C(s.fee).toString():f.toString(),this.getPegs()),i=d(r);return i.isNegative()?f:i}calculateSharesForAmount(e,t,s){let r=E.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?C(s.fee).toString():f.toString(),this.getPegs()),i=d(r);return i.isNegative()?f:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=E.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return d(t);if(e.assetIn==this.id){let r=B(_,e.decimalsIn-e.decimalsOut);return d(t).div(r)}let s=B(_,18-e.decimalsIn);return d(t).div(s)}calculateOut(e,t,s){let r=E.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?C(s.fee).toString():f.toString(),this.getPegs()),i=d(r);return i.isNegative()?f:i}calculateWithdrawOneAsset(e,t,s){let r=E.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?C(s.fee).toString():f.toString(),this.getPegs()),i=d(r);return i.isNegative()?f:i}calculateShares(e,t,s){let r=E.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?C(s.fee).toString():f.toString(),this.getPegs()),i=d(r);return i.isNegative()?f:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=E.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return d(t);if(e.assetOut==this.id){let r=B(_,e.decimalsOut-e.decimalsIn);return d(t).div(r)}let s=B(_,18-e.decimalsOut);return d(t).div(s)}calculateTradeFee(e,t){let s=E.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return d(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var Ge=require("@polkadot/util-crypto");var _t=340282366920938463463374607431768211455n,Oe=class extends G{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=this.getPoolAddress(a),[c,m,g]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(u,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(u,o),{address:u,id:a,type:"Stableswap",fee:L(o.fee.toNumber()),tokens:m,...c,...g,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[i,n]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,i,n)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=E.calculateAmplification(r.toString(),i.toString(),n.toString(),o.toString(),s),u=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:u.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async o=>{let[a,u]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:u.toString()}}),n=await Promise.all(i);return n.push({id:t,tradeable:15,balance:_t.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,s=E.defaultPegs(e.assets.length);return{pegsFee:L(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let i=r.unwrap(),n=await this.getLatestPegs(t,i,s),o=this.getRecentPegs(i),a=i.maxPegUpdate.toHuman(),u=t.fee.toHuman(),[c,m]=E.recalculatePegs(JSON.stringify(o),JSON.stringify(n),s,a.replace(/%/g,""),u.replace(/%/g,"")),g=Number(c)*1e4;return{pegsFee:L(g),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(i=>i.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=r.map(async(o,a)=>{if(o.isOracle){let[u,c,m]=o.asOracle,g=[m.toString(),i[a]].map(S=>Number(S)).sort((S,A)=>S-A),p=await this.api.query.emaOracle.oracles(u,g,c),[{price:h,updatedAt:P}]=p.unwrap(),y=h.n.toString(),x=h.d.toString();return m.toString()===g[0].toString()?[[y,x],P.toString()]:[[x,y],P.toString()]}else return[o.asValue.map(u=>u.toString()),s]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),s=E.getPoolAddress(t);return(0,Ge.encodeAddress)((0,Ge.blake2AsHex)(s),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var se=class extends D{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=De(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new Q(this.api),this.aaveClient=new Pe(this.api),this.xykClient=new we(this.api),this.omniClient=new Se(this.api),this.lbpClient=new be(this.api),this.stableClient=new Oe(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new me(t.type)}}};var qe=class extends se{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new te(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){this.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var re=class{static get(e){switch(e.type){case"Aave":return he.fromPool(e);case"Xyk":return xe.fromPool(e);case"Omnipool":return ye.fromPool(e);case"Lbp":return fe.fromPool(e);case"Stableswap":return ve.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var He=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var es=5,Be=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new He,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(o==null||o.length>es)return r;let a=o[o.length-1];(s===null||a[0]===s)&&r.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),i.enqueue(m)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,n]of t){let o=parseInt(i),a=parseInt(n);s.get(o)?.push([a,r])}return s}};function ut(l){let e={};for(let t of l){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let n=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(n)}}}return e}var Ie=class{getProposals(e,t,s){let r=ut(s),i=Object.keys(r),n=i.map(c=>r[c]).flat(),o=new Be,a=o.buildAndPopulateGraph(i,n),u=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(u)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let n=s[i],o=s[i+1];if(o==null)break;r.push(this.toEdge(n,o))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ie=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ie,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),n=this.getPaths(e,null,r,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(n)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,re.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let n=t.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};var ts=d("100");function ss(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ne(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function ct(l,e){return _.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function mt(l,e){return e.div(l).minus(_).multipliedBy(100).decimalPlaces(2)}function oe(l,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),l.div(ts).multipliedBy(e).decimalPlaces(0,1)}var ze=(t=>(t.Buy="Buy",t.Sell="Sell",t))(ze||{});var Ue=class extends ie{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,n=r[r.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,r]}}getPoolFeeRange(e){let t=e.min?N(e.min):void 0,s=e.max?N(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new K(e,t);let a;if(r)a=await this.toSellSwaps(s,r,n);else{let w=o.map(async j=>await this.toSellSwaps(s,j,n)),z=await Promise.all(w);a=this.findBestSellRoute(z)}let u=a[0],c=a[a.length-1],m=this.isDirectTrade(a),g=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,z)=>w.multipliedBy(z)),p=B(g,c.assetOutDecimals),h=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,a,n),P=c.amountOut,y=m?c.tradeFeePct:ct(h,P).toNumber(),x=h.minus(P),S=this.getRouteFeeRange(a),A=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(p),T=ne(h,A);return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:p,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:T.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:k(u.amountIn,u.assetInDecimals),amountOut:k(c.amountOut,c.assetOutDecimals),spotPrice:k(p,c.assetOutDecimals),tradeFee:k(x,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:T.toNumber(),swaps:a.map(w=>w.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1]:u=e;let c=o.calculateOutGivenIn(a,u);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1].amountOut:u=B(d(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:g,feePct:p,errors:h}=o.validateAndSell(a,u,c),P=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),x=u.shiftedBy(-1*a.decimalsIn).multipliedBy(y),S=ne(g,x);r.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,calculatedOut:g,amountOut:m,spotPrice:y,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:S.toNumber(),errors:h,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:k(u,a.decimalsIn),calculatedOut:k(g,a.decimalsOut),amountOut:k(m,a.decimalsOut),spotPrice:k(y,a.decimalsOut),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:S.toNumber(),errors:h}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)throw new K(e,t);let u=s.filter(p=>p.tokens.some(h=>h.id===e&&h.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(h=>h.id===e)).map(p=>p.map(h=>d(h.balance).shiftedBy(-1*h.decimals)).reduce((h,P)=>h.plus(P))).sort((p,h)=>h.isLessThan(p)?-1:1)[0].div(100).multipliedBy(.1),c=i.map(async p=>await this.toSellSwaps(u,p,r)),m=await Promise.all(c);return this.findBestSellRoute(m).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.assetOut}))}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,r),a=o.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,g)=>m.multipliedBy(g)),u=o[o.length-1].assetOutDecimals;return{amount:B(a,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,n=r[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new K(e,t);let a;if(r)a=await this.toBuySwaps(s,r,n);else{let w=o.map(async j=>await this.toBuySwaps(s,j,n)),z=await Promise.all(w);a=this.findBestBuyRoute(z)}let u=a[a.length-1],c=a[0],m=this.isDirectTrade(a),g=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,z)=>w.multipliedBy(z)),p=B(g,c.assetInDecimals),h=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,a,n),P=c.amountIn,y=m?c.tradeFeePct:mt(h,P).toNumber(),x=P.minus(h),S=this.getRouteFeeRange(a),A=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(p),T;return h.isZero()?T=-100:T=ne(A,h).toNumber(),{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:p,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:T,swaps:a,toHuman(){return{type:"Buy",amountOut:k(u.amountOut,u.assetOutDecimals),amountIn:k(c.amountIn,c.assetInDecimals),spotPrice:k(p,c.assetInDecimals),tradeFee:k(x,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:T,swaps:a.map(w=>w.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=e:u=r[0];let c=o.calculateInGivenOut(a,u);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=B(d(e),a.decimalsOut).decimalPlaces(0,1):u=r[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:g,feePct:p,errors:h}=o.validateAndBuy(a,u,c),P=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),x=u.shiftedBy(-1*a.decimalsOut).multipliedBy(y),S;g.isZero()?S=-100:S=ne(x,g).toNumber(),r.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:u,calculatedIn:g,amountIn:m,spotPrice:y,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:S,errors:h,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountOut:k(u,a.decimalsOut),calculatedIn:k(g,a.decimalsIn),amountIn:k(m,a.decimalsIn),spotPrice:k(y,a.decimalsIn),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:S,errors:h}}})}return r}};var Ct=require("viem");var J=require("@polkadot/util-crypto"),ae=require("@polkadot/util"),$=require("buffer");var Et=$.Buffer.from("ETH\0");function Rt(l){if(!l)return!1;try{let e=(0,J.decodeAddress)(l,!0);return $.Buffer.from(e.subarray(0,Et.length)).equals(Et)}catch{return!1}}function kt(l){return!!/^0x[a-fA-F0-9]{40}$/.test(l)}function Lt(l){try{let e=(0,ae.isHex)(l)?(0,ae.hexToU8a)(l):(0,J.decodeAddress)(l);return(0,J.encodeAddress)(e),!0}catch{return!1}}var Ae=class l{static prefixBytes=$.Buffer.from("ETH\0");static toAccount=e=>{let t=$.Buffer.from(e.slice(2),"hex");return(0,J.encodeAddress)(new Uint8Array($.Buffer.concat([l.prefixBytes,t,$.Buffer.alloc(8)])),63)};static fromAccount=e=>{let s=(0,J.decodeAddress)(e).slice(l.prefixBytes.length,-8);return"0x"+$.Buffer.from(s).toString("hex")};static fromSS58=e=>{let s=(0,J.decodeAddress)(e).slice(0,20);return(0,ae.u8aToHex)(s)};static fromAny=e=>{if(kt(e))return e;if(Rt(e))return l.fromAccount(e);if(Lt(e))return l.fromSS58(e);throw new Error("Unknown address type")}};var We=class extends D{balanceClient;evmClient;constructor(e){super(e),this.balanceClient=new U(e),this.evmClient=new de}buildBuyTx(e,t=1){if(e.type!=="Buy")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:i}=e,n=i[0],o=i[i.length-1],a=oe(s,t),u=n.assetIn,c=o.assetOut,m=s.plus(a),g;return this.isDirectOmnipoolTrade(i)?g=this.api.tx.omnipool.buy(c,u,r.toFixed(),m.toFixed()):g=this.api.tx.router.buy(u,c,r.toFixed(),m.toFixed(),this.buildRoute(i)),{hex:g.toHex(),name:"RouterBuy",get:()=>g,dryRun:p=>this.dryRun(p,g)}}buildSellTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:i}=e,n=i[0],o=i[i.length-1],a=oe(r,t),u=n.assetIn,c=o.assetOut,m=r.minus(a),g;return this.isDirectOmnipoolTrade(i)?g=this.api.tx.omnipool.sell(u,c,s.toFixed(),m.toFixed()):g=this.api.tx.router.sell(u,c,s.toFixed(),m.toFixed(),this.buildRoute(i)),{hex:g.toHex(),name:"RouterSell",get:()=>g,dryRun:p=>this.dryRun(p,g)}}buildSellAllTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountOut:s,swaps:r}=e,i=r[0],n=r[r.length-1],o=oe(s,t),a=i.assetIn,u=n.assetOut,c=s.minus(o),m=this.api.tx.router.sellAll(a,u,c.toFixed(),this.buildRoute(r));return{hex:m.toHex(),name:"RouterSellAll",get:()=>m,dryRun:g=>this.dryRun(g,m)}}async buildWithdrawAndSellReserveTx(e,t,s=1){let{amountIn:r,amountOut:i,swaps:n}=t,o=n[0],a=n[n.length-1];if(!o.isWithdraw())throw new Error("Not permitted");let u=o.assetIn,c=o.assetOut,[m,g]=await Promise.all([this.evmClient.getProvider().getGasPrice(),this.balanceClient.getBalance(e,u)]),p=r.isGreaterThanOrEqualTo(g.minus(5)),h=m*10n/100n,P=Ae.fromAny(e),y=p?it:BigInt(r.toFixed()),x=Z.fromAssetId(c),S=(0,Ct.encodeFunctionData)({abi:pe,functionName:"withdraw",args:[x,y,P]}),A=this.api.tx.evm.call(P,st,S,0n,rt,m+h,m+h,null,[]),T=oe(i,s),w=c,z=a.assetOut,j=i.minus(T),pt=this.api.tx.router.sell(w,z,r.minus(5).toFixed(),j.toFixed(),this.buildRoute(n.slice(1))),Xe=this.api.tx.utility.batchAll([A,pt]);return{hex:Xe.toHex(),name:"WithdrawAndRouterReserveSell",get:()=>Xe,dryRun:Mt=>this.dryRun(Mt,Xe)}}buildRoute(e){return e.map(({assetIn:t,assetOut:s,pool:r,poolId:i})=>r==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:s}:{pool:r,assetIn:t,assetOut:s})}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};0&&(module.exports={AAVE_ABI,AAVE_GAS_LIMIT,AAVE_PROXY,AAVE_ROUNDING_THRESHOLD,AAVE_UINT_256_MAX,AMOUNT_MAX,AavePool,AavePoolClient,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,TradeUtils,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,evmMainnet,findNestedKey,findNestedObj,getFraction,isEvmAccount,isEvmAddress,isSs58Address,scale});
|