@galacticcouncil/sdk-next 1.0.1 → 1.1.0-pr319-25f3a93

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 CHANGED
@@ -13,6 +13,8 @@ Table of contents:
13
13
  - [client](#client)
14
14
  - [ctx](#ctx)
15
15
  - [tx](#tx)
16
+ - [Historical queries (`at`)](#historical-queries-at)
17
+ - [Offline routing (snapshots)](#offline-routing-snapshots)
16
18
  - [API Reference](#api-reference)
17
19
  - [AaveUtils](#aaveutils)
18
20
  - [TradeRouter](#traderouter)
@@ -70,6 +72,8 @@ It handles all necessary setup under the hood. Just plug in your PolkadotClient,
70
72
  - XYK pools
71
73
  - LBP pools
72
74
 
75
+ - `pool: SnapshotPoolCtxProvider` — Stateless, offline pool context built from a static `SnapshotPoolCtx`. Drop-in replacement for `PoolContextProvider` when you do not have (or do not want) a live chain subscription. See [Offline routing (snapshots)](#offline-routing-snapshots).
76
+
73
77
  ### `tx`
74
78
 
75
79
  - `TxBuilderFactory` — Factory for generating submittable transaction using fluent APIs.
@@ -78,6 +82,50 @@ It handles all necessary setup under the hood. Just plug in your PolkadotClient,
78
82
 
79
83
  Gracefully cleans up SDK resources. Always call before exiting to avoid memory leaks or stale subscriptions.
80
84
 
85
+ ## Historical queries (`at`)
86
+
87
+ By default the SDK reads chain state at the `best` block. Pass an `at` option to `createSdkContext` to pin all queries (pool state, balances, fees, oracles) to a specific block — useful for historical pricing, replay, or auditing.
88
+
89
+ ```ts
90
+ import { createSdkContext } from '@galacticcouncil/sdk-next';
91
+
92
+ const sdk = await createSdkContext(client, {
93
+ at: '0xabc…', // block hash
94
+ });
95
+ ```
96
+
97
+ Accepted values:
98
+
99
+ - `'best'` (default) — reads at best block, **subscribes** to live updates.
100
+ - `'finalized'` — reads at finalized block, **subscribes** to live updates.
101
+ - `'0x…'` (block hash) — reads pinned to that block, **no subscriptions**. State is one-shot; the context will not refresh.
102
+
103
+ ## Offline routing (snapshots)
104
+
105
+ `SnapshotPoolCtxProvider` is a stateless, offline alternative to `PoolContextProvider`. It implements the same `IPoolCtxProvider` interface, so any consumer (e.g. `TradeRouter`) works without changes. Use it for indexers, workers, replays, simulations, or tests — anywhere a live RPC subscription is undesirable.
106
+
107
+ You provide a `SnapshotPoolCtx` (pools + state + block) and pass the provider into the router:
108
+
109
+ ```ts
110
+ import {
111
+ SnapshotPoolCtx,
112
+ SnapshotPoolCtxProvider,
113
+ TradeRouter,
114
+ } from '@galacticcouncil/sdk-next';
115
+
116
+ const snapshot: SnapshotPoolCtx = { /* pools, states, block */ };
117
+
118
+ const ctx = new SnapshotPoolCtxProvider(snapshot);
119
+ const router = new TradeRouter(ctx);
120
+
121
+ const trade = await router.getBestSell(5, 10, 10_000_000_000n);
122
+ console.log(trade.toHuman());
123
+ ```
124
+
125
+ No `destroy()` needed — the provider holds no subscriptions.
126
+
127
+ ➡️ For the snapshot shape see [SnapshotPoolCtxProvider.ts](src/pool/SnapshotPoolCtxProvider.ts).
128
+
81
129
  ## API Reference
82
130
 
83
131
  ### AaveUtils
@@ -144,7 +192,7 @@ All examples assume SDK has been initialized, [see](#usage)
144
192
 
145
193
  ### TradeRouter
146
194
 
147
- Calculate sell of 1 DOT for HDX & build tx with 5% slippage (default to 1% if not specified)
195
+ Calculate sell of 1 DOT for USDT & build tx with 5% slippage (default to 1% if not specified)
148
196
 
149
197
  ```typescript
150
198
  const { api, tx } = sdk;
@@ -1,10 +1,12 @@
1
1
  import { PolkadotClient, TypedApi } from 'polkadot-api';
2
2
  import { hydration, hydrationNext } from '@galacticcouncil/descriptors';
3
3
  import { Watcher } from './Watcher';
4
+ export type BlockAt = 'best' | 'finalized' | (string & {});
4
5
  export declare abstract class Papi {
5
6
  readonly client: PolkadotClient;
6
7
  readonly api: TypedApi<typeof hydration>;
7
8
  readonly apiNext: TypedApi<typeof hydrationNext>;
8
9
  readonly watcher: Watcher;
9
- constructor(client: PolkadotClient);
10
+ readonly at: BlockAt;
11
+ constructor(client: PolkadotClient, at?: BlockAt);
10
12
  }
@@ -1,10 +1,10 @@
1
1
  import { PolkadotClient } from 'polkadot-api';
2
2
  import { type Observable } from 'rxjs';
3
- import { Papi } from '../api';
3
+ import { BlockAt, Papi } from '../api';
4
4
  import { AssetBalance, Balance } from '../types';
5
5
  export declare class BalanceClient extends Papi {
6
6
  private erc20Ids;
7
- constructor(client: PolkadotClient);
7
+ constructor(client: PolkadotClient, at?: BlockAt);
8
8
  getBalance(account: string, assetId: number): Promise<Balance>;
9
9
  getSystemBalance(account: string): Promise<Balance>;
10
10
  getTokenBalance(account: string, assetId: number): Promise<Balance>;
@@ -1 +1 @@
1
- "use strict";var E=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var L=Object.prototype.hasOwnProperty;var R=(p,e)=>{for(var t in e)E(p,t,{get:e[t],enumerable:!0})},N=(p,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of I(e))!L.call(p,n)&&n!==t&&E(p,n,{get:()=>e[n],enumerable:!(s=O(e,n))||s.enumerable});return p};var H=p=>N(E({},"__esModule",{value:!0}),p);var $={};R($,{AssetClient:()=>k,BalanceClient:()=>x,ChainParams:()=>_});module.exports=H($);var w=require("polkadot-api");var S=require("@galacticcouncil/descriptors");var C=require("@galacticcouncil/common"),B=require("rxjs");var b=require("rxjs"),c=require("rxjs/operators");function v(p,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let s=()=>(0,b.defer)(()=>(0,b.from)(p._request("system_health",[]))).pipe((0,c.timeout)({first:t}),(0,c.map)(()=>"online"),(0,c.catchError)(()=>(0,b.of)("offline")));return(0,b.of)({state:"offline",delayMs:0}).pipe((0,c.expand)(a=>(0,b.timer)(a.delayMs).pipe((0,c.switchMap)(s),(0,c.map)(r=>({state:r,delayMs:e})))),(0,c.skip)(1),(0,c.map)(a=>a.state),(0,c.distinctUntilChanged)(),(0,c.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:V}=C.log,P=class p{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,B.map)(({value:t})=>t))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",v(e))}static getInstance(e){return this.instance||(this.instance=new p(e)),this.instance}watched(e,t){return t.pipe((0,B.tap)({error:s=>V.error(e,s)}),(0,B.shareReplay)({bufferSize:1,refCount:!0}))}};var h=class{client;api;apiNext;watcher;constructor(e){this.client=e,this.api=this.client.getTypedApi(S.hydration),this.apiNext=this.client.getTypedApi(S.hydrationNext),this.watcher=P.getInstance(this.client)}};var W=require("polkadot-api/ws"),z=require("polkadot-api/logs-provider");var k=class extends h{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:s})=>{let{asset_type:n}=s;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async mapToken(e,t,s,n){let{name:a,asset_type:r,is_sufficient:i,existential_deposit:m}=t,{symbol:l,decimals:u}=s.get(e)??{};return{id:e,name:a?w.Binary.toText(a):void 0,symbol:l,decimals:u,icon:l,type:r.type,isSufficient:i,location:n,existentialDeposit:m}}async mapBond(e,t,s,n){let[a,r]=n,{asset_type:i,is_sufficient:m,existential_deposit:l}=t,{symbol:u,decimals:A}=await this.mapToken(a,t,s),f=Number(r),y=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",y.format(f)].join(" ");return{id:e,name:g,symbol:u+"b",decimals:A,icon:u,type:i.type,isSufficient:m,existentialDeposit:l,underlyingAssetId:a,maturity:f}}async mapShares(e,t,s,n){let{assets:a}=n,{name:r,symbol:i,asset_type:m,is_sufficient:l,existential_deposit:u}=t,A=await Promise.all(a.map(async g=>{let{symbol:M}=await this.mapToken(g,t,s);return[g,M]})),f=Object.fromEntries(A),y=Object.values(f);return{id:e,name:y.join(", "),symbol:i&&w.Binary.toText(i)||r&&w.Binary.toText(r),decimals:18,icon:y.join("/"),type:m.type,isSufficient:l,existentialDeposit:u,meta:f}}async mapExternal(e,t,s,n){let a=await this.mapToken(e,t,new Map,n),r=s?.find(i=>i.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(e){return new Map(Array.from(e,([t,s])=>[t,{symbol:s.symbol?w.Binary.toText(s.symbol):void 0,decimals:s.decimals}]))}async getSupported(e,t){let[s,n,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),i=this.parseMetadata(s),m=[];for(let[l,u]of Array.from(s)){let A=n.get(l),{asset_type:f}=u,y;switch(f.type){case"Bond":let g=r.get(l);y=await this.mapBond(l,u,i,g);break;case"StableSwap":let M=a.get(l);y=await this.mapShares(l,u,i,M);break;case"External":y=await this.mapExternal(l,u,t,A);break;default:y=await this.mapToken(l,u,i,A)}m.push(y)}return e?m:m.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};var D=require("@galacticcouncil/common"),d=require("rxjs"),o=require("rxjs/operators");var{logger:T}=D.log,x=class extends h{erc20Ids=null;constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:s}=await t.getValue(e,{at:"best"});return this.getBreakdown(s)}async getTokenBalance(e,t){let n=await this.api.query.Tokens.Accounts.getValue(e,t,{at:"best"});return this.getBreakdown(n)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return(0,d.defer)(()=>{let t=this.watchSystemBalance(e),s=this.watchTokensBalance(e),n=this.watchErc20Balance(e);return(0,d.combineLatest)([t,s,n]).pipe((0,o.connect)(a=>(0,d.concat)(a.pipe((0,o.take)(1)),a.pipe((0,o.skip)(1),(0,o.debounceTime)(250)))))}).pipe((0,o.map)(t=>t.flat()),(0,o.startWith)([]),(0,o.bufferCount)(2,1),(0,o.map)(([t,s],n)=>n===0?s:this.getDeltas(t,s))).pipe((0,o.tap)({subscribe:()=>T.debug("balance: subscribe",e),error:t=>T.error("balance",t)}),(0,o.retry)({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return(0,d.defer)(()=>t.watchValue(e,{at:"best"})).pipe((0,o.map)(({value:s})=>({id:0,balance:this.getBreakdown(s.data)})),(0,o.tap)({error:s=>T.error("balance(system)",s)}))}watchTokenBalance(e,t){let s=this.api.query.Tokens.Accounts;return(0,d.defer)(()=>s.watchValue(e,t,{at:"best"})).pipe((0,o.map)(({value:n})=>({id:t,balance:this.getBreakdown(n)})),(0,o.tap)({error:n=>T.error("balance(token)",n)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return(0,d.defer)(()=>t.watchEntries(e,{at:"best"})).pipe((0,o.distinctUntilChanged)((s,n)=>!n.deltas),(0,o.map)(({deltas:s})=>{let n=[];return s?.deleted.forEach(a=>{let[r,i]=a.args;n.push({id:i,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),s?.upserted.forEach(a=>{let[r,i]=a.args;n.push({id:i,balance:this.getBreakdown(a.value)})}),n}),(0,o.tap)({error:s=>T.error("balance(tokens)",s)}))}watchErc20Balance(e,t){let s=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[i]=r;return i}),this.erc20Ids},n=async a=>(await Promise.all(a.map(async i=>[i,await this.getBalanceData(e,i)]))).map(([i,m])=>({id:i,balance:m}));return(0,d.defer)(()=>(0,d.from)(t?Promise.resolve(t):s()).pipe((0,o.switchMap)(a=>this.watcher.bestBlock$.pipe((0,o.switchMap)(()=>(0,d.from)(n(a))))),(0,o.startWith)([]),(0,o.bufferCount)(2,1),(0,o.map)(([a,r],i)=>i===0?r.filter(m=>m.balance.total>0n):this.getDeltas(a,r)),(0,o.distinctUntilChanged)((a,r)=>r.length===0),(0,o.tap)({error:a=>T.error("balance(erc20)",a)})))}async getBalanceData(e,t){let s=await this.api.apis.CurrenciesApi.account(t,e,{at:"best"});return this.getBreakdown(s)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,s=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:s,transferable:t}}getDeltas(e,t){let s=(a,r)=>a!==void 0&&r!==void 0&&a.transferable===r.transferable&&a.total===r.total,n=e.reduce((a,r)=>(a.set(r.id,r.balance),a),new Map);return t.filter(a=>!s(a.balance,n.get(a.id)))}};var _=class extends h{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};0&&(module.exports={AssetClient,BalanceClient,ChainParams});
1
+ "use strict";var E=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var L=Object.prototype.hasOwnProperty;var R=(p,e)=>{for(var t in e)E(p,t,{get:e[t],enumerable:!0})},N=(p,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of I(e))!L.call(p,n)&&n!==t&&E(p,n,{get:()=>e[n],enumerable:!(s=O(e,n))||s.enumerable});return p};var z=p=>N(E({},"__esModule",{value:!0}),p);var $={};R($,{AssetClient:()=>S,BalanceClient:()=>x,ChainParams:()=>_});module.exports=z($);var w=require("polkadot-api");var P=require("@galacticcouncil/descriptors");var C=require("@galacticcouncil/common"),g=require("rxjs");var b=require("rxjs"),c=require("rxjs/operators");function v(p,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let s=()=>(0,b.defer)(()=>(0,b.from)(p._request("system_health",[]))).pipe((0,c.timeout)({first:t}),(0,c.map)(()=>"online"),(0,c.catchError)(()=>(0,b.of)("offline")));return(0,b.of)({state:"offline",delayMs:0}).pipe((0,c.expand)(a=>(0,b.timer)(a.delayMs).pipe((0,c.switchMap)(s),(0,c.map)(r=>({state:r,delayMs:e})))),(0,c.skip)(1),(0,c.map)(a=>a.state),(0,c.distinctUntilChanged)(),(0,c.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:H}=C.log,k=class p{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,g.map)(({value:t})=>t))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",v(e))}static getInstance(e){return this.instance||(this.instance=new p(e)),this.instance}watched(e,t){return t.pipe((0,g.tap)({error:s=>H.error(e,s)}),(0,g.shareReplay)({bufferSize:1,refCount:!0}))}};var h=class{client;api;apiNext;watcher;at;constructor(e,t){this.client=e,this.api=this.client.getTypedApi(P.hydration),this.apiNext=this.client.getTypedApi(P.hydrationNext),this.watcher=k.getInstance(this.client),this.at=t??"best"}};var V=require("polkadot-api/ws"),W=require("polkadot-api/logs-provider");var S=class extends h{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:s})=>{let{asset_type:n}=s;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async mapToken(e,t,s,n){let{name:a,asset_type:r,is_sufficient:i,existential_deposit:m}=t,{symbol:l,decimals:u}=s.get(e)??{};return{id:e,name:a?w.Binary.toText(a):void 0,symbol:l,decimals:u,icon:l,type:r.type,isSufficient:i,location:n,existentialDeposit:m}}async mapBond(e,t,s,n){let[a,r]=n,{asset_type:i,is_sufficient:m,existential_deposit:l}=t,{symbol:u,decimals:A}=await this.mapToken(a,t,s),f=Number(r),y=new Intl.DateTimeFormat("en-GB"),B=[u,"Bond",y.format(f)].join(" ");return{id:e,name:B,symbol:u+"b",decimals:A,icon:u,type:i.type,isSufficient:m,existentialDeposit:l,underlyingAssetId:a,maturity:f}}async mapShares(e,t,s,n){let{assets:a}=n,{name:r,symbol:i,asset_type:m,is_sufficient:l,existential_deposit:u}=t,A=await Promise.all(a.map(async B=>{let{symbol:M}=await this.mapToken(B,t,s);return[B,M]})),f=Object.fromEntries(A),y=Object.values(f);return{id:e,name:y.join(", "),symbol:i&&w.Binary.toText(i)||r&&w.Binary.toText(r),decimals:18,icon:y.join("/"),type:m.type,isSufficient:l,existentialDeposit:u,meta:f}}async mapExternal(e,t,s,n){let a=await this.mapToken(e,t,new Map,n),r=s?.find(i=>i.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(e){return new Map(Array.from(e,([t,s])=>[t,{symbol:s.symbol?w.Binary.toText(s.symbol):void 0,decimals:s.decimals}]))}async getSupported(e,t){let[s,n,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),i=this.parseMetadata(s),m=[];for(let[l,u]of Array.from(s)){let A=n.get(l),{asset_type:f}=u,y;switch(f.type){case"Bond":let B=r.get(l);y=await this.mapBond(l,u,i,B);break;case"StableSwap":let M=a.get(l);y=await this.mapShares(l,u,i,M);break;case"External":y=await this.mapExternal(l,u,t,A);break;default:y=await this.mapToken(l,u,i,A)}m.push(y)}return e?m:m.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};var D=require("@galacticcouncil/common"),d=require("rxjs"),o=require("rxjs/operators");var{logger:T}=D.log,x=class extends h{erc20Ids=null;constructor(e,t){super(e,t)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:s}=await t.getValue(e,{at:this.at});return this.getBreakdown(s)}async getTokenBalance(e,t){let n=await this.api.query.Tokens.Accounts.getValue(e,t,{at:this.at});return this.getBreakdown(n)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return(0,d.defer)(()=>{let t=this.watchSystemBalance(e),s=this.watchTokensBalance(e),n=this.watchErc20Balance(e);return(0,d.combineLatest)([t,s,n]).pipe((0,o.connect)(a=>(0,d.concat)(a.pipe((0,o.take)(1)),a.pipe((0,o.skip)(1),(0,o.debounceTime)(250)))))}).pipe((0,o.map)(t=>t.flat()),(0,o.startWith)([]),(0,o.bufferCount)(2,1),(0,o.map)(([t,s],n)=>n===0?s:this.getDeltas(t,s))).pipe((0,o.tap)({subscribe:()=>T.debug("balance: subscribe",e),error:t=>T.error("balance",t)}),(0,o.retry)({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return(0,d.defer)(()=>t.watchValue(e,{at:"best"})).pipe((0,o.map)(({value:s})=>({id:0,balance:this.getBreakdown(s.data)})),(0,o.tap)({error:s=>T.error("balance(system)",s)}))}watchTokenBalance(e,t){let s=this.api.query.Tokens.Accounts;return(0,d.defer)(()=>s.watchValue(e,t,{at:"best"})).pipe((0,o.map)(({value:n})=>({id:t,balance:this.getBreakdown(n)})),(0,o.tap)({error:n=>T.error("balance(token)",n)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return(0,d.defer)(()=>t.watchEntries(e,{at:"best"})).pipe((0,o.distinctUntilChanged)((s,n)=>!n.deltas),(0,o.map)(({deltas:s})=>{let n=[];return s?.deleted.forEach(a=>{let[r,i]=a.args;n.push({id:i,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),s?.upserted.forEach(a=>{let[r,i]=a.args;n.push({id:i,balance:this.getBreakdown(a.value)})}),n}),(0,o.tap)({error:s=>T.error("balance(tokens)",s)}))}watchErc20Balance(e,t){let s=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[i]=r;return i}),this.erc20Ids},n=async a=>(await Promise.all(a.map(async i=>[i,await this.getBalanceData(e,i)]))).map(([i,m])=>({id:i,balance:m}));return(0,d.defer)(()=>(0,d.from)(t?Promise.resolve(t):s()).pipe((0,o.switchMap)(a=>this.watcher.bestBlock$.pipe((0,o.switchMap)(()=>(0,d.from)(n(a))))),(0,o.startWith)([]),(0,o.bufferCount)(2,1),(0,o.map)(([a,r],i)=>i===0?r.filter(m=>m.balance.total>0n):this.getDeltas(a,r)),(0,o.distinctUntilChanged)((a,r)=>r.length===0),(0,o.tap)({error:a=>T.error("balance(erc20)",a)})))}async getBalanceData(e,t){let s=await this.api.apis.CurrenciesApi.account(t,e,{at:this.at});return this.getBreakdown(s)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,s=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:s,transferable:t}}getDeltas(e,t){let s=(a,r)=>a!==void 0&&r!==void 0&&a.transferable===r.transferable&&a.total===r.total,n=e.reduce((a,r)=>(a.set(r.id,r.balance),a),new Map);return t.filter(a=>!s(a.balance,n.get(a.id)))}};var _=class extends h{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};0&&(module.exports={AssetClient,BalanceClient,ChainParams});
@@ -1 +1 @@
1
- import I from"buffer";typeof window<"u"&&(window.Buffer=I.Buffer);import{Binary as w}from"polkadot-api";import{hydration as J,hydrationNext as K}from"@galacticcouncil/descriptors";import{log as Y}from"@galacticcouncil/common";import{map as j,shareReplay as F,tap as G}from"rxjs";import{defer as L,from as R,of as _,timer as N}from"rxjs";import{catchError as H,distinctUntilChanged as V,expand as W,map as P,shareReplay as z,skip as $,switchMap as Q,timeout as U}from"rxjs/operators";function M(u,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let s=()=>L(()=>R(u._request("system_health",[]))).pipe(U({first:t}),P(()=>"online"),H(()=>_("offline")));return _({state:"offline",delayMs:0}).pipe(W(a=>N(a.delayMs).pipe(Q(s),P(r=>({state:r,delayMs:e})))),$(1),P(a=>a.state),V(),z({bufferSize:1,refCount:!0}))}var{logger:X}=Y,B=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(j(({value:t})=>t))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",M(e))}static getInstance(e){return this.instance||(this.instance=new u(e)),this.instance}watched(e,t){return t.pipe(G({error:s=>X.error(e,s)}),F({bufferSize:1,refCount:!0}))}};var m=class{client;api;apiNext;watcher;constructor(e){this.client=e,this.api=this.client.getTypedApi(J),this.apiNext=this.client.getTypedApi(K),this.watcher=B.getInstance(this.client)}};import{getWsProvider as Se}from"polkadot-api/ws";import{withLogsRecorder as xe}from"polkadot-api/logs-provider";var S=class extends m{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:s})=>{let{asset_type:n}=s;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async mapToken(e,t,s,n){let{name:a,asset_type:r,is_sufficient:o,existential_deposit:c}=t,{symbol:i,decimals:l}=s.get(e)??{};return{id:e,name:a?w.toText(a):void 0,symbol:i,decimals:l,icon:i,type:r.type,isSufficient:o,location:n,existentialDeposit:c}}async mapBond(e,t,s,n){let[a,r]=n,{asset_type:o,is_sufficient:c,existential_deposit:i}=t,{symbol:l,decimals:y}=await this.mapToken(a,t,s),d=Number(r),p=new Intl.DateTimeFormat("en-GB"),b=[l,"Bond",p.format(d)].join(" ");return{id:e,name:b,symbol:l+"b",decimals:y,icon:l,type:o.type,isSufficient:c,existentialDeposit:i,underlyingAssetId:a,maturity:d}}async mapShares(e,t,s,n){let{assets:a}=n,{name:r,symbol:o,asset_type:c,is_sufficient:i,existential_deposit:l}=t,y=await Promise.all(a.map(async b=>{let{symbol:T}=await this.mapToken(b,t,s);return[b,T]})),d=Object.fromEntries(y),p=Object.values(d);return{id:e,name:p.join(", "),symbol:o&&w.toText(o)||r&&w.toText(r),decimals:18,icon:p.join("/"),type:c.type,isSufficient:i,existentialDeposit:l,meta:d}}async mapExternal(e,t,s,n){let a=await this.mapToken(e,t,new Map,n),r=s?.find(o=>o.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(e){return new Map(Array.from(e,([t,s])=>[t,{symbol:s.symbol?w.toText(s.symbol):void 0,decimals:s.decimals}]))}async getSupported(e,t){let[s,n,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),o=this.parseMetadata(s),c=[];for(let[i,l]of Array.from(s)){let y=n.get(i),{asset_type:d}=l,p;switch(d.type){case"Bond":let b=r.get(i);p=await this.mapBond(i,l,o,b);break;case"StableSwap":let T=a.get(i);p=await this.mapShares(i,l,o,T);break;case"External":p=await this.mapExternal(i,l,t,y);break;default:p=await this.mapToken(i,l,o,y)}c.push(p)}return e?c:c.filter(i=>this.isValidAsset(i))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};import{log as Z}from"@galacticcouncil/common";import{combineLatest as ee,concat as te,defer as A,from as v}from"rxjs";import{bufferCount as C,distinctUntilChanged as q,debounceTime as se,map as f,retry as ae,startWith as D,switchMap as O,tap as g,take as ne,skip as re,connect as oe}from"rxjs/operators";var{logger:h}=Z,k=class extends m{erc20Ids=null;constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:s}=await t.getValue(e,{at:"best"});return this.getBreakdown(s)}async getTokenBalance(e,t){let n=await this.api.query.Tokens.Accounts.getValue(e,t,{at:"best"});return this.getBreakdown(n)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return A(()=>{let t=this.watchSystemBalance(e),s=this.watchTokensBalance(e),n=this.watchErc20Balance(e);return ee([t,s,n]).pipe(oe(a=>te(a.pipe(ne(1)),a.pipe(re(1),se(250)))))}).pipe(f(t=>t.flat()),D([]),C(2,1),f(([t,s],n)=>n===0?s:this.getDeltas(t,s))).pipe(g({subscribe:()=>h.debug("balance: subscribe",e),error:t=>h.error("balance",t)}),ae({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return A(()=>t.watchValue(e,{at:"best"})).pipe(f(({value:s})=>({id:0,balance:this.getBreakdown(s.data)})),g({error:s=>h.error("balance(system)",s)}))}watchTokenBalance(e,t){let s=this.api.query.Tokens.Accounts;return A(()=>s.watchValue(e,t,{at:"best"})).pipe(f(({value:n})=>({id:t,balance:this.getBreakdown(n)})),g({error:n=>h.error("balance(token)",n)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return A(()=>t.watchEntries(e,{at:"best"})).pipe(q((s,n)=>!n.deltas),f(({deltas:s})=>{let n=[];return s?.deleted.forEach(a=>{let[r,o]=a.args;n.push({id:o,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),s?.upserted.forEach(a=>{let[r,o]=a.args;n.push({id:o,balance:this.getBreakdown(a.value)})}),n}),g({error:s=>h.error("balance(tokens)",s)}))}watchErc20Balance(e,t){let s=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[o]=r;return o}),this.erc20Ids},n=async a=>(await Promise.all(a.map(async o=>[o,await this.getBalanceData(e,o)]))).map(([o,c])=>({id:o,balance:c}));return A(()=>v(t?Promise.resolve(t):s()).pipe(O(a=>this.watcher.bestBlock$.pipe(O(()=>v(n(a))))),D([]),C(2,1),f(([a,r],o)=>o===0?r.filter(c=>c.balance.total>0n):this.getDeltas(a,r)),q((a,r)=>r.length===0),g({error:a=>h.error("balance(erc20)",a)})))}async getBalanceData(e,t){let s=await this.api.apis.CurrenciesApi.account(t,e,{at:"best"});return this.getBreakdown(s)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,s=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:s,transferable:t}}getDeltas(e,t){let s=(a,r)=>a!==void 0&&r!==void 0&&a.transferable===r.transferable&&a.total===r.total,n=e.reduce((a,r)=>(a.set(r.id,r.balance),a),new Map);return t.filter(a=>!s(a.balance,n.get(a.id)))}};var x=class extends m{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};export{S as AssetClient,k as BalanceClient,x as ChainParams};
1
+ import I from"buffer";typeof window<"u"&&(window.Buffer=I.Buffer);import{Binary as w}from"polkadot-api";import{hydration as J,hydrationNext as K}from"@galacticcouncil/descriptors";import{log as Y}from"@galacticcouncil/common";import{map as j,shareReplay as F,tap as G}from"rxjs";import{defer as L,from as R,of as _,timer as N}from"rxjs";import{catchError as z,distinctUntilChanged as H,expand as V,map as k,shareReplay as W,skip as $,switchMap as Q,timeout as U}from"rxjs/operators";function M(u,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let s=()=>L(()=>R(u._request("system_health",[]))).pipe(U({first:t}),k(()=>"online"),z(()=>_("offline")));return _({state:"offline",delayMs:0}).pipe(V(a=>N(a.delayMs).pipe(Q(s),k(r=>({state:r,delayMs:e})))),$(1),k(a=>a.state),H(),W({bufferSize:1,refCount:!0}))}var{logger:X}=Y,g=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(j(({value:t})=>t))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",M(e))}static getInstance(e){return this.instance||(this.instance=new u(e)),this.instance}watched(e,t){return t.pipe(G({error:s=>X.error(e,s)}),F({bufferSize:1,refCount:!0}))}};var m=class{client;api;apiNext;watcher;at;constructor(e,t){this.client=e,this.api=this.client.getTypedApi(J),this.apiNext=this.client.getTypedApi(K),this.watcher=g.getInstance(this.client),this.at=t??"best"}};import{getWsProvider as Pe}from"polkadot-api/ws";import{withLogsRecorder as xe}from"polkadot-api/logs-provider";var P=class extends m{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:s})=>{let{asset_type:n}=s;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async mapToken(e,t,s,n){let{name:a,asset_type:r,is_sufficient:o,existential_deposit:c}=t,{symbol:i,decimals:l}=s.get(e)??{};return{id:e,name:a?w.toText(a):void 0,symbol:i,decimals:l,icon:i,type:r.type,isSufficient:o,location:n,existentialDeposit:c}}async mapBond(e,t,s,n){let[a,r]=n,{asset_type:o,is_sufficient:c,existential_deposit:i}=t,{symbol:l,decimals:y}=await this.mapToken(a,t,s),d=Number(r),p=new Intl.DateTimeFormat("en-GB"),b=[l,"Bond",p.format(d)].join(" ");return{id:e,name:b,symbol:l+"b",decimals:y,icon:l,type:o.type,isSufficient:c,existentialDeposit:i,underlyingAssetId:a,maturity:d}}async mapShares(e,t,s,n){let{assets:a}=n,{name:r,symbol:o,asset_type:c,is_sufficient:i,existential_deposit:l}=t,y=await Promise.all(a.map(async b=>{let{symbol:T}=await this.mapToken(b,t,s);return[b,T]})),d=Object.fromEntries(y),p=Object.values(d);return{id:e,name:p.join(", "),symbol:o&&w.toText(o)||r&&w.toText(r),decimals:18,icon:p.join("/"),type:c.type,isSufficient:i,existentialDeposit:l,meta:d}}async mapExternal(e,t,s,n){let a=await this.mapToken(e,t,new Map,n),r=s?.find(o=>o.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(e){return new Map(Array.from(e,([t,s])=>[t,{symbol:s.symbol?w.toText(s.symbol):void 0,decimals:s.decimals}]))}async getSupported(e,t){let[s,n,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),o=this.parseMetadata(s),c=[];for(let[i,l]of Array.from(s)){let y=n.get(i),{asset_type:d}=l,p;switch(d.type){case"Bond":let b=r.get(i);p=await this.mapBond(i,l,o,b);break;case"StableSwap":let T=a.get(i);p=await this.mapShares(i,l,o,T);break;case"External":p=await this.mapExternal(i,l,t,y);break;default:p=await this.mapToken(i,l,o,y)}c.push(p)}return e?c:c.filter(i=>this.isValidAsset(i))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};import{log as Z}from"@galacticcouncil/common";import{combineLatest as ee,concat as te,defer as A,from as v}from"rxjs";import{bufferCount as C,distinctUntilChanged as q,debounceTime as se,map as h,retry as ae,startWith as D,switchMap as O,tap as B,take as ne,skip as re,connect as oe}from"rxjs/operators";var{logger:f}=Z,S=class extends m{erc20Ids=null;constructor(e,t){super(e,t)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:s}=await t.getValue(e,{at:this.at});return this.getBreakdown(s)}async getTokenBalance(e,t){let n=await this.api.query.Tokens.Accounts.getValue(e,t,{at:this.at});return this.getBreakdown(n)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return A(()=>{let t=this.watchSystemBalance(e),s=this.watchTokensBalance(e),n=this.watchErc20Balance(e);return ee([t,s,n]).pipe(oe(a=>te(a.pipe(ne(1)),a.pipe(re(1),se(250)))))}).pipe(h(t=>t.flat()),D([]),C(2,1),h(([t,s],n)=>n===0?s:this.getDeltas(t,s))).pipe(B({subscribe:()=>f.debug("balance: subscribe",e),error:t=>f.error("balance",t)}),ae({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return A(()=>t.watchValue(e,{at:"best"})).pipe(h(({value:s})=>({id:0,balance:this.getBreakdown(s.data)})),B({error:s=>f.error("balance(system)",s)}))}watchTokenBalance(e,t){let s=this.api.query.Tokens.Accounts;return A(()=>s.watchValue(e,t,{at:"best"})).pipe(h(({value:n})=>({id:t,balance:this.getBreakdown(n)})),B({error:n=>f.error("balance(token)",n)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return A(()=>t.watchEntries(e,{at:"best"})).pipe(q((s,n)=>!n.deltas),h(({deltas:s})=>{let n=[];return s?.deleted.forEach(a=>{let[r,o]=a.args;n.push({id:o,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),s?.upserted.forEach(a=>{let[r,o]=a.args;n.push({id:o,balance:this.getBreakdown(a.value)})}),n}),B({error:s=>f.error("balance(tokens)",s)}))}watchErc20Balance(e,t){let s=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[o]=r;return o}),this.erc20Ids},n=async a=>(await Promise.all(a.map(async o=>[o,await this.getBalanceData(e,o)]))).map(([o,c])=>({id:o,balance:c}));return A(()=>v(t?Promise.resolve(t):s()).pipe(O(a=>this.watcher.bestBlock$.pipe(O(()=>v(n(a))))),D([]),C(2,1),h(([a,r],o)=>o===0?r.filter(c=>c.balance.total>0n):this.getDeltas(a,r)),q((a,r)=>r.length===0),B({error:a=>f.error("balance(erc20)",a)})))}async getBalanceData(e,t){let s=await this.api.apis.CurrenciesApi.account(t,e,{at:this.at});return this.getBreakdown(s)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,s=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:s,transferable:t}}getDeltas(e,t){let s=(a,r)=>a!==void 0&&r!==void 0&&a.transferable===r.transferable&&a.total===r.total,n=e.reduce((a,r)=>(a.set(r.id,r.balance),a),new Map);return t.filter(a=>!s(a.balance,n.get(a.id)))}};var x=class extends m{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};export{P as AssetClient,S as BalanceClient,x as ChainParams};
@@ -1,4 +1,5 @@
1
1
  import { PolkadotClient } from 'polkadot-api';
2
+ import { BlockAt } from './api';
2
3
  import { AaveUtils } from './aave';
3
4
  import { AssetClient, BalanceClient } from './client';
4
5
  import { EvmClient } from './evm';
@@ -7,6 +8,9 @@ import { PoolContextProvider } from './pool';
7
8
  import { TradeRouter, TradeScheduler } from './sor';
8
9
  import { StakingApi } from './staking';
9
10
  import { TxBuilderFactory } from './tx';
11
+ export type SdkOptions = {
12
+ at?: BlockAt;
13
+ };
10
14
  export type SdkCtx = {
11
15
  api: {
12
16
  aave: AaveUtils;
@@ -26,4 +30,4 @@ export type SdkCtx = {
26
30
  tx: TxBuilderFactory;
27
31
  destroy: () => void;
28
32
  };
29
- export declare function createSdkContext(client: PolkadotClient): Promise<SdkCtx>;
33
+ export declare function createSdkContext(client: PolkadotClient, options?: SdkOptions): Promise<SdkCtx>;
@@ -1 +1 @@
1
- "use strict";var ht=Object.create;var M=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var Z=(a,t)=>{for(var e in t)M(a,e,{get:t[e],enumerable:!0})},tt=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of St(t))!vt.call(a,i)&&i!==e&&M(a,i,{get:()=>t[i],enumerable:!(r=_t(t,i))||r.enumerable});return a};var B=(a,t,e)=>(e=a!=null?ht(wt(a)):{},tt(t||!a||!a.__esModule?M(e,"default",{value:a,enumerable:!0}):e,a)),At=a=>tt(M({},"__esModule",{value:!0}),a);var qt={};Z(qt,{LiquidityMiningApi:()=>W,LiquidityMiningClient:()=>j});module.exports=At(qt);var it=require("polkadot-api"),m=B(require("big.js")),h=require("@galacticcouncil/common"),K=require("@galacticcouncil/math-liquidity-mining");var It=require("@galacticcouncil/common");var F={};Z(F,{FeeUtils:()=>q,shiftNeg:()=>Ot});var et=B(require("big.js"));var q=class a{static toPct(t){let[e,r]=t;return a.safeDivide(e*100,r)}static toRaw(t){let[e,r]=t;return a.safeDivide(e,r)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,r=12){let i=10**r;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ot(a,t){let e=(0,et.default)(typeof a=="bigint"?a.toString():a);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Mt=B(require("big.js"));var C=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let r=0;r<t.length;++r){let[i,n]=t[r];this.result.set(this.getKey(n,i),e[r].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,r,i){let n=this.getKey(t,e),o=this.getKey(t,r),c=this.result.get(n)??0n,s=this.result.get(o)??0n;if(c<i)throw new Error("Attempting to transfer more than is present");this.result.set(n,c+i),this.result.set(o,s+i)}};var S=B(require("big.js")),b=require("@galacticcouncil/math-liquidity-mining");var k=B(require("big.js")),z=(0,k.default)(10).pow(18),rt=BigInt((0,k.default)(1).pow(18).toString()),nt=6e3;var Et="1000000000000000000",E=class{constructor(t,e,r){this.getAccount=t;this.getAsset=e;this.multiCurrency=r}async syncGlobalFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let i=await this.getAsset(t.reward_currency),n=e-t.updated_at,o=this.getAccount(t.id),c=i?.existential_deposit;if(!c)throw new Error("Missing reward currency asset list");let s=this.multiCurrency.freeBalance(t.reward_currency,o),d=(0,S.default)(c.toString()),g=(0,S.default)(s.toString()).minus(d.lt(s.toString())?c.toString():s.toString()),l=(0,S.default)((0,b.calculate_global_farm_rewards)(t.total_shares_z.toString(),r.toString(),(0,S.default)(t.yield_per_period.toString()).mul(z).round(0,S.default.roundDown).toFixed(),t.max_reward_per_period.toString(),n.toFixed()));if(g.lt(l)&&(l=g),l.eq(0))return t;let f=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,o,f,BigInt(l.toFixed())),{...t,accumulated_rpz:BigInt((0,b.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),l.toFixed()))}}syncYieldFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===r)return t;if(t.total_valued_shares===0n)return{...t,updated_at:r};let i=(0,b.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(i),updated_at:r}}getLoyaltyMultiplier(t,e){let r=(0,S.default)(1).mul(z).round(0,S.default.roundDown).toString();if(!e)return r;let{initial_reward_percentage:i,scale_coef:n}=e;return(0,b.calculate_loyalty_multiplier)(t.toFixed(),i.toString(),n.toFixed())}async claimRewards(t,e,r,i,n){if(e.state.type==="Terminated")return null;let o=Math.floor(i/t.blocks_per_period);if(r.updated_at===o)return null;let c=await this.syncGlobalFarm(t,o,n);if(!c)return null;let s=this.syncYieldFarm(e,c,o);if(!s)return null;let d=s.total_stopped-r.stopped_at_creation,g=s.updated_at-r.entered_at-d,l=this.getLoyaltyMultiplier(g,s.loyalty_curve),f=BigInt((0,b.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),s.accumulated_rpvs.toString(),l)),p=BigInt((0,b.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),s.accumulated_rpvs.toString(),Et));return{reward:f,maxReward:p,assetId:c.reward_currency,yieldFarmId:s.id,isActiveFarm:s.state.type==="Active"}}};var Lt=(0,m.default)(365.2425).times(24).times(60).times(60),W=class{balance;client;options;constructor(t,e,r={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:r.blockTime??nt})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let r=[t,e].sort((n,o)=>n-o);if(t===e)return rt;let i=await this.client.getOraclePrice(r);if(i){let{n,d:o}=i[0].price,c;return t<e?c=(0,K.fixed_from_rational)(n.toString(),o.toString()):c=(0,K.fixed_from_rational)(o.toString(),n.toString()),BigInt(c)}}getFarmAddress=(t,e)=>{let r=Buffer.from("modl","utf-8"),i=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),n=Buffer.from([t]),o=Buffer.concat([r,i,n]),s="0x"+Buffer.concat([o,Buffer.alloc(32-o.length)]).toString("hex");return(0,it.AccountId)(h.HYDRATION_SS58_PREFIX).dec(s)};getGlobalRewardPerPeriod(t,e,r,i){let n=(0,m.default)(i).times(t.toString()).times(e.toString()).div(Math.pow(10,h.RUNTIME_DECIMALS));return n.gte(r.toString())?r.toString():n.toString()}getPoolYieldPerPeriod(t,e,r,i){let n=(0,m.default)(t.toString()).times(e),o=(0,m.default)(r.toString()).times(i);return n.div(o.toString()).toString()}farmData(t,e,r){let{yieldFarm:i,globalFarm:n,priceAdjustment:o,balance:c,id:s}=t,{multiplier:d,loyalty_curve:g}=i,{blocks_per_period:l,yield_per_period:f,total_shares_z:p,max_reward_per_period:y,pending_rewards:w,accumulated_paid_rewards:v,planned_yielding_periods:P,updated_at:x,incentivized_asset:at,reward_currency:ct,price_adjustment:lt,min_deposit:ut}=n,N=F.shiftNeg(o??lt,h.RUNTIME_DECIMALS),U=F.shiftNeg(d,h.RUNTIME_DECIMALS),H=F.shiftNeg(g?.initial_reward_percentage??0,h.RUNTIME_DECIMALS),V=Lt.div((0,m.default)(this.blockTime).div(1e3).times(l)).toString(),A;if(p<=0)A=(0,m.default)(U).times(f.toString()).times(V).div(Math.pow(10,h.RUNTIME_DECIMALS)).toString();else{let bt=this.getGlobalRewardPerPeriod(p,f,y,N),yt=this.getPoolYieldPerPeriod(bt,U,p,N);A=(0,m.default)(yt).times(V).toString()}let T=w+v,dt=y*BigInt(P),D=c.transferable+T,mt=D-T,$=(0,m.default)(mt.toString()).div(y.toString()),X=(0,m.default)(e).div(l.toString()).toString(),J=(p>=0?$.plus(x):$.plus(X)).toString(),gt=(0,m.default)(J).times(l).toString(),pt=(0,m.default)(p.toString()).div((0,m.default)(y.toString()).div(f.toString())).div(Math.pow(10,h.RUNTIME_DECIMALS)).times(100).times(N).toFixed(2),Q=(0,m.default)(T.toString()).div(D.toString()).gte(.999);A=Q?"0":(0,m.default)(A).div(r?2:1).times(100).toString();let ft=H?(0,m.default)(A).times(H).toString():void 0;return{apr:A,minApr:ft,isDistributed:Q,estimatedEndPeriod:J,estimatedEndBlock:gt,maxRewards:dt,incentivizedAsset:at,rewardCurrency:ct,loyaltyCurve:g,currentPeriod:X,potMaxRewards:D,fullness:pt,yieldFarmId:i.id,globalFarmId:n.id,poolId:s,distributedRewards:T,plannedYieldingPeriods:P,minDeposit:ut,blocksPerPeriod:l}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((i,n)=>i.includes(n.keyArgs[0].toString())?i:[...i,n.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async i=>{let n=await this.getOmnipoolFarms(i);if(n)return[i,n]}));return Object.fromEntries(r.filter(i=>!!i))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),r=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:n,value:o})=>{let[,c]=n,s=o,d=await this.client.getOmnipoolGlobalFarm(c),g=await this.client.getOmnipoolYieldFarm(Number(t),c,s);if(!d||!g)return;let l=d.reward_currency,f=d.incentivized_asset,p=this.getFarmAddress(c),y=await this.getOraclePrice(l,f),w=await this.balance.getBalance(p,l);return{id:t,globalFarm:d,yieldFarm:g,priceAdjustment:y,balance:w}}));return r?i.map(n=>n?this.farmData(n,r):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((i,n)=>i.includes(n.keyArgs[0].toString())?i:[...i,n.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async i=>{let n=await this.getIsolatedFarms(i);if(n)return[i,n]}));return Object.fromEntries(r.filter(i=>!!i))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),r=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:n,value:o})=>{let[,c]=n,s=o,d=await this.client.getIsolatedGlobalFarm(c),g=await this.client.getIsolatedYieldFarm(t,c,s);if(!d||!g)return;let l=d.reward_currency,f=d.incentivized_asset,p=this.getFarmAddress(c,!0),y=await this.getOraclePrice(l,f),w=await this.balance.getBalance(p,l);return{id:t,globalFarm:d,yieldFarm:g,priceAdjustment:y,balance:w,farmAddress:p}}));return r?i.map(n=>n?this.farmData(n,r,!0):void 0):[]}async getDepositReward(t,e,r,i){let n=e.global_farm_id,o=e.yield_farm_id,c=r?await this.client.getIsolatedYieldFarm(t,n,o):await this.client.getOmnipoolYieldFarm(Number(t),n,o),s=r?await this.client.getIsolatedGlobalFarm(n):await this.client.getOmnipoolGlobalFarm(n);if(!s||!c)return;let d=s.reward_currency,g=s.incentivized_asset,l=[[this.getFarmAddress(0,r),s.reward_currency],[this.getFarmAddress(s.id,r),s.reward_currency]],f=await this.getAccountAssetBalances(l),p=await this.getOraclePrice(d,g),y=new C(l,f),v=await new E(x=>this.getFarmAddress(x),x=>this.client.getAsset(x),y).claimRewards(s,c,e,i,p??s.price_adjustment);if(!v)return;let P=await this.client.getAsset(v.assetId);if(P&&!(v.reward<=P.existential_deposit))return v}async getAccountAssetBalances(t){let[e,r]=await Promise.all([Promise.all(t.filter(([n,o])=>o!==0).map(([n,o])=>this.balance.getTokenBalance(n,o))),Promise.all(t.filter(([n,o])=>o===0).map(([n])=>this.balance.getSystemBalance(n)))]),i=[];for(let n=0,o=0;n+o<t.length;){let c=n+o,[,s]=t[c];s===0?(i.push(r[o]),o+=1):(i.push(e[n]),n+=1)}return i}};var Y=require("@galacticcouncil/descriptors");var st=require("@galacticcouncil/common"),I=require("rxjs");var _=require("rxjs"),u=require("rxjs/operators");function ot(a,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>(0,_.defer)(()=>(0,_.from)(a._request("system_health",[]))).pipe((0,u.timeout)({first:e}),(0,u.map)(()=>"online"),(0,u.catchError)(()=>(0,_.of)("offline")));return(0,_.of)({state:"offline",delayMs:0}).pipe((0,u.expand)(n=>(0,_.timer)(n.delayMs).pipe((0,u.switchMap)(r),(0,u.map)(o=>({state:o,delayMs:t})))),(0,u.skip)(1),(0,u.map)(n=>n.state),(0,u.distinctUntilChanged)(),(0,u.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Rt}=st.log,L=class a{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,I.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ot(t))}static getInstance(t){return this.instance||(this.instance=new a(t)),this.instance}watched(t,e){return e.pipe((0,I.tap)({error:r=>Rt.error(t,r)}),(0,I.shareReplay)({bufferSize:1,refCount:!0}))}};var R=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(Y.hydration),this.apiNext=this.client.getTypedApi(Y.hydrationNext),this.watcher=L.getInstance(this.client)}};var Yt=require("polkadot-api/ws"),Nt=require("polkadot-api/logs-provider");var O=require("polkadot-api"),Dt=O.Binary.toHex(O.Binary.fromText("omnipool")),j=class extends R{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Dt,t,(0,O.Enum)("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,r){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,r){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};0&&(module.exports={LiquidityMiningApi,LiquidityMiningClient});
1
+ "use strict";var ht=Object.create;var M=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var Z=(a,t)=>{for(var e in t)M(a,e,{get:t[e],enumerable:!0})},tt=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of St(t))!vt.call(a,i)&&i!==e&&M(a,i,{get:()=>t[i],enumerable:!(r=_t(t,i))||r.enumerable});return a};var B=(a,t,e)=>(e=a!=null?ht(wt(a)):{},tt(t||!a||!a.__esModule?M(e,"default",{value:a,enumerable:!0}):e,a)),At=a=>tt(M({},"__esModule",{value:!0}),a);var kt={};Z(kt,{LiquidityMiningApi:()=>W,LiquidityMiningClient:()=>j});module.exports=At(kt);var it=require("polkadot-api"),m=B(require("big.js")),h=require("@galacticcouncil/common"),K=require("@galacticcouncil/math-liquidity-mining");var It=require("@galacticcouncil/common");var F={};Z(F,{FeeUtils:()=>k,shiftNeg:()=>Ot});var et=B(require("big.js"));var k=class a{static toPct(t){let[e,r]=t;return a.safeDivide(e*100,r)}static toRaw(t){let[e,r]=t;return a.safeDivide(e,r)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,r=12){let i=10**r;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ot(a,t){let e=(0,et.default)(typeof a=="bigint"?a.toString():a);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Mt=B(require("big.js"));var C=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let r=0;r<t.length;++r){let[i,n]=t[r];this.result.set(this.getKey(n,i),e[r].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,r,i){let n=this.getKey(t,e),o=this.getKey(t,r),c=this.result.get(n)??0n,s=this.result.get(o)??0n;if(c<i)throw new Error("Attempting to transfer more than is present");this.result.set(n,c+i),this.result.set(o,s+i)}};var S=B(require("big.js")),b=require("@galacticcouncil/math-liquidity-mining");var q=B(require("big.js")),z=(0,q.default)(10).pow(18),rt=BigInt((0,q.default)(1).pow(18).toString()),nt=6e3;var Et="1000000000000000000",E=class{constructor(t,e,r){this.getAccount=t;this.getAsset=e;this.multiCurrency=r}async syncGlobalFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let i=await this.getAsset(t.reward_currency),n=e-t.updated_at,o=this.getAccount(t.id),c=i?.existential_deposit;if(!c)throw new Error("Missing reward currency asset list");let s=this.multiCurrency.freeBalance(t.reward_currency,o),d=(0,S.default)(c.toString()),g=(0,S.default)(s.toString()).minus(d.lt(s.toString())?c.toString():s.toString()),l=(0,S.default)((0,b.calculate_global_farm_rewards)(t.total_shares_z.toString(),r.toString(),(0,S.default)(t.yield_per_period.toString()).mul(z).round(0,S.default.roundDown).toFixed(),t.max_reward_per_period.toString(),n.toFixed()));if(g.lt(l)&&(l=g),l.eq(0))return t;let f=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,o,f,BigInt(l.toFixed())),{...t,accumulated_rpz:BigInt((0,b.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),l.toFixed()))}}syncYieldFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===r)return t;if(t.total_valued_shares===0n)return{...t,updated_at:r};let i=(0,b.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(i),updated_at:r}}getLoyaltyMultiplier(t,e){let r=(0,S.default)(1).mul(z).round(0,S.default.roundDown).toString();if(!e)return r;let{initial_reward_percentage:i,scale_coef:n}=e;return(0,b.calculate_loyalty_multiplier)(t.toFixed(),i.toString(),n.toFixed())}async claimRewards(t,e,r,i,n){if(e.state.type==="Terminated")return null;let o=Math.floor(i/t.blocks_per_period);if(r.updated_at===o)return null;let c=await this.syncGlobalFarm(t,o,n);if(!c)return null;let s=this.syncYieldFarm(e,c,o);if(!s)return null;let d=s.total_stopped-r.stopped_at_creation,g=s.updated_at-r.entered_at-d,l=this.getLoyaltyMultiplier(g,s.loyalty_curve),f=BigInt((0,b.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),s.accumulated_rpvs.toString(),l)),p=BigInt((0,b.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),s.accumulated_rpvs.toString(),Et));return{reward:f,maxReward:p,assetId:c.reward_currency,yieldFarmId:s.id,isActiveFarm:s.state.type==="Active"}}};var Lt=(0,m.default)(365.2425).times(24).times(60).times(60),W=class{balance;client;options;constructor(t,e,r={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:r.blockTime??nt})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let r=[t,e].sort((n,o)=>n-o);if(t===e)return rt;let i=await this.client.getOraclePrice(r);if(i){let{n,d:o}=i[0].price,c;return t<e?c=(0,K.fixed_from_rational)(n.toString(),o.toString()):c=(0,K.fixed_from_rational)(o.toString(),n.toString()),BigInt(c)}}getFarmAddress=(t,e)=>{let r=Buffer.from("modl","utf-8"),i=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),n=Buffer.from([t]),o=Buffer.concat([r,i,n]),s="0x"+Buffer.concat([o,Buffer.alloc(32-o.length)]).toString("hex");return(0,it.AccountId)(h.HYDRATION_SS58_PREFIX).dec(s)};getGlobalRewardPerPeriod(t,e,r,i){let n=(0,m.default)(i).times(t.toString()).times(e.toString()).div(Math.pow(10,h.RUNTIME_DECIMALS));return n.gte(r.toString())?r.toString():n.toString()}getPoolYieldPerPeriod(t,e,r,i){let n=(0,m.default)(t.toString()).times(e),o=(0,m.default)(r.toString()).times(i);return n.div(o.toString()).toString()}farmData(t,e,r){let{yieldFarm:i,globalFarm:n,priceAdjustment:o,balance:c,id:s}=t,{multiplier:d,loyalty_curve:g}=i,{blocks_per_period:l,yield_per_period:f,total_shares_z:p,max_reward_per_period:y,pending_rewards:w,accumulated_paid_rewards:v,planned_yielding_periods:P,updated_at:x,incentivized_asset:at,reward_currency:ct,price_adjustment:lt,min_deposit:ut}=n,N=F.shiftNeg(o??lt,h.RUNTIME_DECIMALS),U=F.shiftNeg(d,h.RUNTIME_DECIMALS),H=F.shiftNeg(g?.initial_reward_percentage??0,h.RUNTIME_DECIMALS),V=Lt.div((0,m.default)(this.blockTime).div(1e3).times(l)).toString(),A;if(p<=0)A=(0,m.default)(U).times(f.toString()).times(V).div(Math.pow(10,h.RUNTIME_DECIMALS)).toString();else{let bt=this.getGlobalRewardPerPeriod(p,f,y,N),yt=this.getPoolYieldPerPeriod(bt,U,p,N);A=(0,m.default)(yt).times(V).toString()}let T=w+v,dt=y*BigInt(P),D=c.transferable+T,mt=D-T,$=(0,m.default)(mt.toString()).div(y.toString()),X=(0,m.default)(e).div(l.toString()).toString(),J=(p>=0?$.plus(x):$.plus(X)).toString(),gt=(0,m.default)(J).times(l).toString(),pt=(0,m.default)(p.toString()).div((0,m.default)(y.toString()).div(f.toString())).div(Math.pow(10,h.RUNTIME_DECIMALS)).times(100).times(N).toFixed(2),Q=(0,m.default)(T.toString()).div(D.toString()).gte(.999);A=Q?"0":(0,m.default)(A).div(r?2:1).times(100).toString();let ft=H?(0,m.default)(A).times(H).toString():void 0;return{apr:A,minApr:ft,isDistributed:Q,estimatedEndPeriod:J,estimatedEndBlock:gt,maxRewards:dt,incentivizedAsset:at,rewardCurrency:ct,loyaltyCurve:g,currentPeriod:X,potMaxRewards:D,fullness:pt,yieldFarmId:i.id,globalFarmId:n.id,poolId:s,distributedRewards:T,plannedYieldingPeriods:P,minDeposit:ut,blocksPerPeriod:l}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((i,n)=>i.includes(n.keyArgs[0].toString())?i:[...i,n.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async i=>{let n=await this.getOmnipoolFarms(i);if(n)return[i,n]}));return Object.fromEntries(r.filter(i=>!!i))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),r=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:n,value:o})=>{let[,c]=n,s=o,d=await this.client.getOmnipoolGlobalFarm(c),g=await this.client.getOmnipoolYieldFarm(Number(t),c,s);if(!d||!g)return;let l=d.reward_currency,f=d.incentivized_asset,p=this.getFarmAddress(c),y=await this.getOraclePrice(l,f),w=await this.balance.getBalance(p,l);return{id:t,globalFarm:d,yieldFarm:g,priceAdjustment:y,balance:w}}));return r?i.map(n=>n?this.farmData(n,r):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((i,n)=>i.includes(n.keyArgs[0].toString())?i:[...i,n.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async i=>{let n=await this.getIsolatedFarms(i);if(n)return[i,n]}));return Object.fromEntries(r.filter(i=>!!i))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),r=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:n,value:o})=>{let[,c]=n,s=o,d=await this.client.getIsolatedGlobalFarm(c),g=await this.client.getIsolatedYieldFarm(t,c,s);if(!d||!g)return;let l=d.reward_currency,f=d.incentivized_asset,p=this.getFarmAddress(c,!0),y=await this.getOraclePrice(l,f),w=await this.balance.getBalance(p,l);return{id:t,globalFarm:d,yieldFarm:g,priceAdjustment:y,balance:w,farmAddress:p}}));return r?i.map(n=>n?this.farmData(n,r,!0):void 0):[]}async getDepositReward(t,e,r,i){let n=e.global_farm_id,o=e.yield_farm_id,c=r?await this.client.getIsolatedYieldFarm(t,n,o):await this.client.getOmnipoolYieldFarm(Number(t),n,o),s=r?await this.client.getIsolatedGlobalFarm(n):await this.client.getOmnipoolGlobalFarm(n);if(!s||!c)return;let d=s.reward_currency,g=s.incentivized_asset,l=[[this.getFarmAddress(0,r),s.reward_currency],[this.getFarmAddress(s.id,r),s.reward_currency]],f=await this.getAccountAssetBalances(l),p=await this.getOraclePrice(d,g),y=new C(l,f),v=await new E(x=>this.getFarmAddress(x),x=>this.client.getAsset(x),y).claimRewards(s,c,e,i,p??s.price_adjustment);if(!v)return;let P=await this.client.getAsset(v.assetId);if(P&&!(v.reward<=P.existential_deposit))return v}async getAccountAssetBalances(t){let[e,r]=await Promise.all([Promise.all(t.filter(([n,o])=>o!==0).map(([n,o])=>this.balance.getTokenBalance(n,o))),Promise.all(t.filter(([n,o])=>o===0).map(([n])=>this.balance.getSystemBalance(n)))]),i=[];for(let n=0,o=0;n+o<t.length;){let c=n+o,[,s]=t[c];s===0?(i.push(r[o]),o+=1):(i.push(e[n]),n+=1)}return i}};var Y=require("@galacticcouncil/descriptors");var st=require("@galacticcouncil/common"),I=require("rxjs");var _=require("rxjs"),u=require("rxjs/operators");function ot(a,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>(0,_.defer)(()=>(0,_.from)(a._request("system_health",[]))).pipe((0,u.timeout)({first:e}),(0,u.map)(()=>"online"),(0,u.catchError)(()=>(0,_.of)("offline")));return(0,_.of)({state:"offline",delayMs:0}).pipe((0,u.expand)(n=>(0,_.timer)(n.delayMs).pipe((0,u.switchMap)(r),(0,u.map)(o=>({state:o,delayMs:t})))),(0,u.skip)(1),(0,u.map)(n=>n.state),(0,u.distinctUntilChanged)(),(0,u.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Rt}=st.log,L=class a{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,I.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ot(t))}static getInstance(t){return this.instance||(this.instance=new a(t)),this.instance}watched(t,e){return e.pipe((0,I.tap)({error:r=>Rt.error(t,r)}),(0,I.shareReplay)({bufferSize:1,refCount:!0}))}};var R=class{client;api;apiNext;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(Y.hydration),this.apiNext=this.client.getTypedApi(Y.hydrationNext),this.watcher=L.getInstance(this.client),this.at=e??"best"}};var Yt=require("polkadot-api/ws"),Nt=require("polkadot-api/logs-provider");var O=require("polkadot-api"),Dt=O.Binary.toHex(O.Binary.fromText("omnipool")),j=class extends R{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Dt,t,(0,O.Enum)("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,r){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,r){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};0&&(module.exports={LiquidityMiningApi,LiquidityMiningClient});
@@ -1 +1 @@
1
- var ct=Object.defineProperty;var ut=(c,t)=>{for(var e in t)ct(c,e,{get:t[e],enumerable:!0})};import dt from"buffer";typeof window<"u"&&(window.Buffer=dt.Buffer);import{AccountId as At}from"polkadot-api";import m from"big.js";import{HYDRATION_SS58_PREFIX as xt,RUNTIME_DECIMALS as w}from"@galacticcouncil/common";import{fixed_from_rational as V}from"@galacticcouncil/math-liquidity-mining";import{RUNTIME_DECIMALS as Zt}from"@galacticcouncil/common";var S={};ut(S,{FeeUtils:()=>T,shiftNeg:()=>yt});import bt from"big.js";var T=class c{static toPct(t){let[e,r]=t;return c.safeDivide(e*100,r)}static toRaw(t){let[e,r]=t;return c.safeDivide(e,r)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,r=12){let n=10**r;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function yt(c,t){let e=bt(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import ae from"big.js";import{TLRUCache as ce}from"@thi.ng/cache";var A=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let r=0;r<t.length;++r){let[n,i]=t[r];this.result.set(this.getKey(i,n),e[r].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,r,n){let i=this.getKey(t,e),o=this.getKey(t,r),s=this.result.get(i)??0n,a=this.result.get(o)??0n;if(s<n)throw new Error("Attempting to transfer more than is present");this.result.set(i,s+n),this.result.set(o,a+n)}};import b from"big.js";import{calculate_accumulated_rps as St,calculate_global_farm_rewards as wt,calculate_loyalty_multiplier as Ft,calculate_user_reward as H,calculate_yield_farm_delta_rpvs as vt}from"@galacticcouncil/math-liquidity-mining";import z from"big.js";var Y=z(10).pow(18),W=BigInt(z(1).pow(18).toString()),K=6e3;var It="1000000000000000000",x=class{constructor(t,e,r){this.getAccount=t;this.getAsset=e;this.multiCurrency=r}async syncGlobalFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let n=await this.getAsset(t.reward_currency),i=e-t.updated_at,o=this.getAccount(t.id),s=n?.existential_deposit;if(!s)throw new Error("Missing reward currency asset list");let a=this.multiCurrency.freeBalance(t.reward_currency,o),u=b(s.toString()),d=b(a.toString()).minus(u.lt(a.toString())?s.toString():a.toString()),l=b(wt(t.total_shares_z.toString(),r.toString(),b(t.yield_per_period.toString()).mul(Y).round(0,b.roundDown).toFixed(),t.max_reward_per_period.toString(),i.toFixed()));if(d.lt(l)&&(l=d),l.eq(0))return t;let g=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,o,g,BigInt(l.toFixed())),{...t,accumulated_rpz:BigInt(St(t.accumulated_rpz.toString(),t.total_shares_z.toString(),l.toFixed()))}}syncYieldFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===r)return t;if(t.total_valued_shares===0n)return{...t,updated_at:r};let n=vt(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(n),updated_at:r}}getLoyaltyMultiplier(t,e){let r=b(1).mul(Y).round(0,b.roundDown).toString();if(!e)return r;let{initial_reward_percentage:n,scale_coef:i}=e;return Ft(t.toFixed(),n.toString(),i.toFixed())}async claimRewards(t,e,r,n,i){if(e.state.type==="Terminated")return null;let o=Math.floor(n/t.blocks_per_period);if(r.updated_at===o)return null;let s=await this.syncGlobalFarm(t,o,i);if(!s)return null;let a=this.syncYieldFarm(e,s,o);if(!a)return null;let u=a.total_stopped-r.stopped_at_creation,d=a.updated_at-r.entered_at-u,l=this.getLoyaltyMultiplier(d,a.loyalty_curve),g=BigInt(H(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),a.accumulated_rpvs.toString(),l)),p=BigInt(H(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),a.accumulated_rpvs.toString(),It));return{reward:g,maxReward:p,assetId:s.reward_currency,yieldFarmId:a.id,isActiveFarm:a.state.type==="Active"}}};var Pt=m(365.2425).times(24).times(60).times(60),j=class{balance;client;options;constructor(t,e,r={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:r.blockTime??K})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let r=[t,e].sort((i,o)=>i-o);if(t===e)return W;let n=await this.client.getOraclePrice(r);if(n){let{n:i,d:o}=n[0].price,s;return t<e?s=V(i.toString(),o.toString()):s=V(o.toString(),i.toString()),BigInt(s)}}getFarmAddress=(t,e)=>{let r=Buffer.from("modl","utf-8"),n=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),i=Buffer.from([t]),o=Buffer.concat([r,n,i]),a="0x"+Buffer.concat([o,Buffer.alloc(32-o.length)]).toString("hex");return At(xt).dec(a)};getGlobalRewardPerPeriod(t,e,r,n){let i=m(n).times(t.toString()).times(e.toString()).div(Math.pow(10,w));return i.gte(r.toString())?r.toString():i.toString()}getPoolYieldPerPeriod(t,e,r,n){let i=m(t.toString()).times(e),o=m(r.toString()).times(n);return i.div(o.toString()).toString()}farmData(t,e,r){let{yieldFarm:n,globalFarm:i,priceAdjustment:o,balance:s,id:a}=t,{multiplier:u,loyalty_curve:d}=n,{blocks_per_period:l,yield_per_period:g,total_shares_z:p,max_reward_per_period:f,pending_rewards:y,accumulated_paid_rewards:h,planned_yielding_periods:F,updated_at:v,incentivized_asset:J,reward_currency:Z,price_adjustment:tt,min_deposit:et}=i,B=S.shiftNeg(o??tt,w),R=S.shiftNeg(u,w),E=S.shiftNeg(d?.initial_reward_percentage??0,w),D=Pt.div(m(this.blockTime).div(1e3).times(l)).toString(),_;if(p<=0)_=m(R).times(g.toString()).times(D).div(Math.pow(10,w)).toString();else{let st=this.getGlobalRewardPerPeriod(p,g,f,B),lt=this.getPoolYieldPerPeriod(st,R,p,B);_=m(lt).times(D).toString()}let I=y+h,rt=f*BigInt(F),M=s.transferable+I,it=M-I,N=m(it.toString()).div(f.toString()),k=m(e).div(l.toString()).toString(),q=(p>=0?N.plus(v):N.plus(k)).toString(),nt=m(q).times(l).toString(),ot=m(p.toString()).div(m(f.toString()).div(g.toString())).div(Math.pow(10,w)).times(100).times(B).toFixed(2),G=m(I.toString()).div(M.toString()).gte(.999);_=G?"0":m(_).div(r?2:1).times(100).toString();let at=E?m(_).times(E).toString():void 0;return{apr:_,minApr:at,isDistributed:G,estimatedEndPeriod:q,estimatedEndBlock:nt,maxRewards:rt,incentivizedAsset:J,rewardCurrency:Z,loyaltyCurve:d,currentPeriod:k,potMaxRewards:M,fullness:ot,yieldFarmId:n.id,globalFarmId:i.id,poolId:a,distributedRewards:I,plannedYieldingPeriods:F,minDeposit:et,blocksPerPeriod:l}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((n,i)=>n.includes(i.keyArgs[0].toString())?n:[...n,i.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async n=>{let i=await this.getOmnipoolFarms(n);if(i)return[n,i]}));return Object.fromEntries(r.filter(n=>!!n))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),r=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:i,value:o})=>{let[,s]=i,a=o,u=await this.client.getOmnipoolGlobalFarm(s),d=await this.client.getOmnipoolYieldFarm(Number(t),s,a);if(!u||!d)return;let l=u.reward_currency,g=u.incentivized_asset,p=this.getFarmAddress(s),f=await this.getOraclePrice(l,g),y=await this.balance.getBalance(p,l);return{id:t,globalFarm:u,yieldFarm:d,priceAdjustment:f,balance:y}}));return r?n.map(i=>i?this.farmData(i,r):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((n,i)=>n.includes(i.keyArgs[0].toString())?n:[...n,i.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async n=>{let i=await this.getIsolatedFarms(n);if(i)return[n,i]}));return Object.fromEntries(r.filter(n=>!!n))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),r=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:i,value:o})=>{let[,s]=i,a=o,u=await this.client.getIsolatedGlobalFarm(s),d=await this.client.getIsolatedYieldFarm(t,s,a);if(!u||!d)return;let l=u.reward_currency,g=u.incentivized_asset,p=this.getFarmAddress(s,!0),f=await this.getOraclePrice(l,g),y=await this.balance.getBalance(p,l);return{id:t,globalFarm:u,yieldFarm:d,priceAdjustment:f,balance:y,farmAddress:p}}));return r?n.map(i=>i?this.farmData(i,r,!0):void 0):[]}async getDepositReward(t,e,r,n){let i=e.global_farm_id,o=e.yield_farm_id,s=r?await this.client.getIsolatedYieldFarm(t,i,o):await this.client.getOmnipoolYieldFarm(Number(t),i,o),a=r?await this.client.getIsolatedGlobalFarm(i):await this.client.getOmnipoolGlobalFarm(i);if(!a||!s)return;let u=a.reward_currency,d=a.incentivized_asset,l=[[this.getFarmAddress(0,r),a.reward_currency],[this.getFarmAddress(a.id,r),a.reward_currency]],g=await this.getAccountAssetBalances(l),p=await this.getOraclePrice(u,d),f=new A(l,g),h=await new x(v=>this.getFarmAddress(v),v=>this.client.getAsset(v),f).claimRewards(a,s,e,n,p??a.price_adjustment);if(!h)return;let F=await this.client.getAsset(h.assetId);if(F&&!(h.reward<=F.existential_deposit))return h}async getAccountAssetBalances(t){let[e,r]=await Promise.all([Promise.all(t.filter(([i,o])=>o!==0).map(([i,o])=>this.balance.getTokenBalance(i,o))),Promise.all(t.filter(([i,o])=>o===0).map(([i])=>this.balance.getSystemBalance(i)))]),n=[];for(let i=0,o=0;i+o<t.length;){let s=i+o,[,a]=t[s];a===0?(n.push(r[o]),o+=1):(n.push(e[i]),i+=1)}return n}};import{hydration as Wt,hydrationNext as Kt}from"@galacticcouncil/descriptors";import{log as Nt}from"@galacticcouncil/common";import{map as kt,shareReplay as qt,tap as Gt}from"rxjs";import{defer as Ot,from as Bt,of as U,timer as Mt}from"rxjs";import{catchError as Tt,distinctUntilChanged as Yt,expand as Lt,map as C,shareReplay as Ct,skip as Rt,switchMap as Et,timeout as Dt}from"rxjs/operators";function $(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>Ot(()=>Bt(c._request("system_health",[]))).pipe(Dt({first:e}),C(()=>"online"),Tt(()=>U("offline")));return U({state:"offline",delayMs:0}).pipe(Lt(i=>Mt(i.delayMs).pipe(Et(r),C(o=>({state:o,delayMs:t})))),Rt(1),C(i=>i.state),Yt(),Ct({bufferSize:1,refCount:!0}))}var{logger:zt}=Nt,P=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(kt(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",$(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe(Gt({error:r=>zt.error(t,r)}),qt({bufferSize:1,refCount:!0}))}};var O=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(Wt),this.apiNext=this.client.getTypedApi(Kt),this.watcher=P.getInstance(this.client)}};import{getWsProvider as Ze}from"polkadot-api/ws";import{withLogsRecorder as er}from"polkadot-api/logs-provider";import{Binary as X,Enum as Ht}from"polkadot-api";var Vt=X.toHex(X.fromText("omnipool")),Q=class extends O{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Vt,t,Ht("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,r){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,r){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};export{j as LiquidityMiningApi,Q as LiquidityMiningClient};
1
+ var ct=Object.defineProperty;var ut=(c,t)=>{for(var e in t)ct(c,e,{get:t[e],enumerable:!0})};import dt from"buffer";typeof window<"u"&&(window.Buffer=dt.Buffer);import{AccountId as It}from"polkadot-api";import m from"big.js";import{HYDRATION_SS58_PREFIX as xt,RUNTIME_DECIMALS as w}from"@galacticcouncil/common";import{fixed_from_rational as V}from"@galacticcouncil/math-liquidity-mining";import{RUNTIME_DECIMALS as Zt}from"@galacticcouncil/common";var S={};ut(S,{FeeUtils:()=>T,shiftNeg:()=>yt});import bt from"big.js";var T=class c{static toPct(t){let[e,r]=t;return c.safeDivide(e*100,r)}static toRaw(t){let[e,r]=t;return c.safeDivide(e,r)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,r=12){let n=10**r;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function yt(c,t){let e=bt(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import ae from"big.js";import{TLRUCache as ce}from"@thi.ng/cache";var I=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let r=0;r<t.length;++r){let[n,i]=t[r];this.result.set(this.getKey(i,n),e[r].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,r,n){let i=this.getKey(t,e),o=this.getKey(t,r),s=this.result.get(i)??0n,a=this.result.get(o)??0n;if(s<n)throw new Error("Attempting to transfer more than is present");this.result.set(i,s+n),this.result.set(o,a+n)}};import b from"big.js";import{calculate_accumulated_rps as St,calculate_global_farm_rewards as wt,calculate_loyalty_multiplier as Ft,calculate_user_reward as H,calculate_yield_farm_delta_rpvs as vt}from"@galacticcouncil/math-liquidity-mining";import G from"big.js";var Y=G(10).pow(18),W=BigInt(G(1).pow(18).toString()),K=6e3;var At="1000000000000000000",x=class{constructor(t,e,r){this.getAccount=t;this.getAsset=e;this.multiCurrency=r}async syncGlobalFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let n=await this.getAsset(t.reward_currency),i=e-t.updated_at,o=this.getAccount(t.id),s=n?.existential_deposit;if(!s)throw new Error("Missing reward currency asset list");let a=this.multiCurrency.freeBalance(t.reward_currency,o),u=b(s.toString()),d=b(a.toString()).minus(u.lt(a.toString())?s.toString():a.toString()),l=b(wt(t.total_shares_z.toString(),r.toString(),b(t.yield_per_period.toString()).mul(Y).round(0,b.roundDown).toFixed(),t.max_reward_per_period.toString(),i.toFixed()));if(d.lt(l)&&(l=d),l.eq(0))return t;let g=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,o,g,BigInt(l.toFixed())),{...t,accumulated_rpz:BigInt(St(t.accumulated_rpz.toString(),t.total_shares_z.toString(),l.toFixed()))}}syncYieldFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===r)return t;if(t.total_valued_shares===0n)return{...t,updated_at:r};let n=vt(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(n),updated_at:r}}getLoyaltyMultiplier(t,e){let r=b(1).mul(Y).round(0,b.roundDown).toString();if(!e)return r;let{initial_reward_percentage:n,scale_coef:i}=e;return Ft(t.toFixed(),n.toString(),i.toFixed())}async claimRewards(t,e,r,n,i){if(e.state.type==="Terminated")return null;let o=Math.floor(n/t.blocks_per_period);if(r.updated_at===o)return null;let s=await this.syncGlobalFarm(t,o,i);if(!s)return null;let a=this.syncYieldFarm(e,s,o);if(!a)return null;let u=a.total_stopped-r.stopped_at_creation,d=a.updated_at-r.entered_at-u,l=this.getLoyaltyMultiplier(d,a.loyalty_curve),g=BigInt(H(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),a.accumulated_rpvs.toString(),l)),p=BigInt(H(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),a.accumulated_rpvs.toString(),At));return{reward:g,maxReward:p,assetId:s.reward_currency,yieldFarmId:a.id,isActiveFarm:a.state.type==="Active"}}};var Pt=m(365.2425).times(24).times(60).times(60),j=class{balance;client;options;constructor(t,e,r={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:r.blockTime??K})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let r=[t,e].sort((i,o)=>i-o);if(t===e)return W;let n=await this.client.getOraclePrice(r);if(n){let{n:i,d:o}=n[0].price,s;return t<e?s=V(i.toString(),o.toString()):s=V(o.toString(),i.toString()),BigInt(s)}}getFarmAddress=(t,e)=>{let r=Buffer.from("modl","utf-8"),n=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),i=Buffer.from([t]),o=Buffer.concat([r,n,i]),a="0x"+Buffer.concat([o,Buffer.alloc(32-o.length)]).toString("hex");return It(xt).dec(a)};getGlobalRewardPerPeriod(t,e,r,n){let i=m(n).times(t.toString()).times(e.toString()).div(Math.pow(10,w));return i.gte(r.toString())?r.toString():i.toString()}getPoolYieldPerPeriod(t,e,r,n){let i=m(t.toString()).times(e),o=m(r.toString()).times(n);return i.div(o.toString()).toString()}farmData(t,e,r){let{yieldFarm:n,globalFarm:i,priceAdjustment:o,balance:s,id:a}=t,{multiplier:u,loyalty_curve:d}=n,{blocks_per_period:l,yield_per_period:g,total_shares_z:p,max_reward_per_period:f,pending_rewards:y,accumulated_paid_rewards:h,planned_yielding_periods:F,updated_at:v,incentivized_asset:J,reward_currency:Z,price_adjustment:tt,min_deposit:et}=i,B=S.shiftNeg(o??tt,w),R=S.shiftNeg(u,w),E=S.shiftNeg(d?.initial_reward_percentage??0,w),D=Pt.div(m(this.blockTime).div(1e3).times(l)).toString(),_;if(p<=0)_=m(R).times(g.toString()).times(D).div(Math.pow(10,w)).toString();else{let st=this.getGlobalRewardPerPeriod(p,g,f,B),lt=this.getPoolYieldPerPeriod(st,R,p,B);_=m(lt).times(D).toString()}let A=y+h,rt=f*BigInt(F),M=s.transferable+A,it=M-A,N=m(it.toString()).div(f.toString()),k=m(e).div(l.toString()).toString(),q=(p>=0?N.plus(v):N.plus(k)).toString(),nt=m(q).times(l).toString(),ot=m(p.toString()).div(m(f.toString()).div(g.toString())).div(Math.pow(10,w)).times(100).times(B).toFixed(2),z=m(A.toString()).div(M.toString()).gte(.999);_=z?"0":m(_).div(r?2:1).times(100).toString();let at=E?m(_).times(E).toString():void 0;return{apr:_,minApr:at,isDistributed:z,estimatedEndPeriod:q,estimatedEndBlock:nt,maxRewards:rt,incentivizedAsset:J,rewardCurrency:Z,loyaltyCurve:d,currentPeriod:k,potMaxRewards:M,fullness:ot,yieldFarmId:n.id,globalFarmId:i.id,poolId:a,distributedRewards:A,plannedYieldingPeriods:F,minDeposit:et,blocksPerPeriod:l}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((n,i)=>n.includes(i.keyArgs[0].toString())?n:[...n,i.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async n=>{let i=await this.getOmnipoolFarms(n);if(i)return[n,i]}));return Object.fromEntries(r.filter(n=>!!n))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),r=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:i,value:o})=>{let[,s]=i,a=o,u=await this.client.getOmnipoolGlobalFarm(s),d=await this.client.getOmnipoolYieldFarm(Number(t),s,a);if(!u||!d)return;let l=u.reward_currency,g=u.incentivized_asset,p=this.getFarmAddress(s),f=await this.getOraclePrice(l,g),y=await this.balance.getBalance(p,l);return{id:t,globalFarm:u,yieldFarm:d,priceAdjustment:f,balance:y}}));return r?n.map(i=>i?this.farmData(i,r):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((n,i)=>n.includes(i.keyArgs[0].toString())?n:[...n,i.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async n=>{let i=await this.getIsolatedFarms(n);if(i)return[n,i]}));return Object.fromEntries(r.filter(n=>!!n))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),r=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:i,value:o})=>{let[,s]=i,a=o,u=await this.client.getIsolatedGlobalFarm(s),d=await this.client.getIsolatedYieldFarm(t,s,a);if(!u||!d)return;let l=u.reward_currency,g=u.incentivized_asset,p=this.getFarmAddress(s,!0),f=await this.getOraclePrice(l,g),y=await this.balance.getBalance(p,l);return{id:t,globalFarm:u,yieldFarm:d,priceAdjustment:f,balance:y,farmAddress:p}}));return r?n.map(i=>i?this.farmData(i,r,!0):void 0):[]}async getDepositReward(t,e,r,n){let i=e.global_farm_id,o=e.yield_farm_id,s=r?await this.client.getIsolatedYieldFarm(t,i,o):await this.client.getOmnipoolYieldFarm(Number(t),i,o),a=r?await this.client.getIsolatedGlobalFarm(i):await this.client.getOmnipoolGlobalFarm(i);if(!a||!s)return;let u=a.reward_currency,d=a.incentivized_asset,l=[[this.getFarmAddress(0,r),a.reward_currency],[this.getFarmAddress(a.id,r),a.reward_currency]],g=await this.getAccountAssetBalances(l),p=await this.getOraclePrice(u,d),f=new I(l,g),h=await new x(v=>this.getFarmAddress(v),v=>this.client.getAsset(v),f).claimRewards(a,s,e,n,p??a.price_adjustment);if(!h)return;let F=await this.client.getAsset(h.assetId);if(F&&!(h.reward<=F.existential_deposit))return h}async getAccountAssetBalances(t){let[e,r]=await Promise.all([Promise.all(t.filter(([i,o])=>o!==0).map(([i,o])=>this.balance.getTokenBalance(i,o))),Promise.all(t.filter(([i,o])=>o===0).map(([i])=>this.balance.getSystemBalance(i)))]),n=[];for(let i=0,o=0;i+o<t.length;){let s=i+o,[,a]=t[s];a===0?(n.push(r[o]),o+=1):(n.push(e[i]),i+=1)}return n}};import{hydration as Wt,hydrationNext as Kt}from"@galacticcouncil/descriptors";import{log as Nt}from"@galacticcouncil/common";import{map as kt,shareReplay as qt,tap as zt}from"rxjs";import{defer as Ot,from as Bt,of as U,timer as Mt}from"rxjs";import{catchError as Tt,distinctUntilChanged as Yt,expand as Lt,map as C,shareReplay as Ct,skip as Rt,switchMap as Et,timeout as Dt}from"rxjs/operators";function $(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>Ot(()=>Bt(c._request("system_health",[]))).pipe(Dt({first:e}),C(()=>"online"),Tt(()=>U("offline")));return U({state:"offline",delayMs:0}).pipe(Lt(i=>Mt(i.delayMs).pipe(Et(r),C(o=>({state:o,delayMs:t})))),Rt(1),C(i=>i.state),Yt(),Ct({bufferSize:1,refCount:!0}))}var{logger:Gt}=Nt,P=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(kt(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",$(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe(zt({error:r=>Gt.error(t,r)}),qt({bufferSize:1,refCount:!0}))}};var O=class{client;api;apiNext;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(Wt),this.apiNext=this.client.getTypedApi(Kt),this.watcher=P.getInstance(this.client),this.at=e??"best"}};import{getWsProvider as Ze}from"polkadot-api/ws";import{withLogsRecorder as er}from"polkadot-api/logs-provider";import{Binary as X,Enum as Ht}from"polkadot-api";var Vt=X.toHex(X.fromText("omnipool")),Q=class extends O{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Vt,t,Ht("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,r){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,r){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};export{j as LiquidityMiningApi,Q as LiquidityMiningClient};