@galacticcouncil/sdk-next 0.41.0 → 0.42.0-pr311-837d8d4

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
@@ -156,7 +156,7 @@ const tradeTx = await tx.trade(trade)
156
156
  .build();
157
157
  const tradeCall = await tradeTx.get().getEncodedData();
158
158
  console.log(trade.toHuman());
159
- console.log('Transaction hash:', tradeCall.asHex());
159
+ console.log('Transaction hash:', Binary.toHex(tradeCall));
160
160
  ```
161
161
 
162
162
  **Note:** For convenience, the router amount can be specified either as a native bigint or as a human-readable string.
@@ -2,7 +2,7 @@ import type { PolkadotClient } from 'polkadot-api';
2
2
  import { Observable } from 'rxjs';
3
3
  export declare class Watcher {
4
4
  private static instance;
5
- readonly bestBlock$: Observable<any>;
5
+ readonly bestBlock$: Observable<number>;
6
6
  readonly finalizedBlock$: Observable<import("polkadot-api").BlockInfo>;
7
7
  readonly connection$: Observable<"online" | "offline">;
8
8
  private constructor();
@@ -1 +1 @@
1
- export declare function getSm(chainSpec: string): Promise<import("@polkadot-api/json-rpc-provider").JsonRpcProvider>;
1
+ export declare function getSm(chainSpec: string): Promise<import("polkadot-api").JsonRpcProvider>;
@@ -1,4 +1,4 @@
1
- import { getWsProvider } from 'polkadot-api/ws-provider';
1
+ import { getWsProvider } from 'polkadot-api/ws';
2
2
  type WsProviderConfig = Parameters<typeof getWsProvider>[1];
3
3
  export declare const getWs: (wsUrl: string | string[], config?: WsProviderConfig) => import("@polkadot-api/ws-provider").WsJsonRpcProvider;
4
4
  export {};
@@ -1 +1 @@
1
- "use strict";var E=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var L=Object.prototype.hasOwnProperty;var I=(p,e)=>{for(var t in e)E(p,t,{get:e[t],enumerable:!0})},R=(p,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of O(e))!L.call(p,n)&&n!==t&&E(p,n,{get:()=>e[n],enumerable:!(s=D(e,n))||s.enumerable});return p};var N=p=>R(E({},"__esModule",{value:!0}),p);var Q={};I(Q,{AssetClient:()=>S,BalanceClient:()=>k,ChainParams:()=>x});module.exports=N(Q);var P=require("@galacticcouncil/descriptors");var v=require("@galacticcouncil/common"),w=require("rxjs");var b=require("rxjs"),c=require("rxjs/operators");function M(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}=v.log,T=class p{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue("best")),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 p(e)),this.instance}watched(e,t){return t.pipe((0,w.tap)({error:s=>H.error(e,s)}),(0,w.shareReplay)({bufferSize:1,refCount:!0}))}};var h=class{client;api;apiNext;watcher;constructor(e){this.client=e,this.api=this.client.getTypedApi(P.hydration),this.apiNext=this.client.getTypedApi(P.hydrationNext),this.watcher=T.getInstance(this.client)}};var V=require("polkadot-api/ws-provider"),W=require("polkadot-api/logs-provider"),z=require("@polkadot-api/legacy-provider");var $=require("polkadot-api/sm-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?.asText(),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:_}=await this.mapToken(g,t,s);return[g,_]})),f=Object.fromEntries(A),y=Object.values(f);return{id:e,name:y.join(", "),symbol:i?.asText()||r?.asText(),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?.asText(),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 _=a.get(l);y=await this.mapShares(l,u,i,_);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 q=require("@galacticcouncil/common"),d=require("rxjs"),o=require("rxjs/operators");var{logger:B}=q.log,k=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:()=>B.debug("balance: subscribe",e),error:t=>B.error("balance",t)}),(0,o.retry)({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return(0,d.defer)(()=>t.watchValue(e,"best")).pipe((0,o.map)(s=>({id:0,balance:this.getBreakdown(s.data)})),(0,o.tap)({error:s=>B.error("balance(system)",s)}))}watchTokenBalance(e,t){let s=this.api.query.Tokens.Accounts;return(0,d.defer)(()=>s.watchValue(e,t,"best")).pipe((0,o.map)(n=>({id:t,balance:this.getBreakdown(n)})),(0,o.tap)({error:n=>B.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=>B.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=>B.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 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 H=p=>N(E({},"__esModule",{value:!0}),p);var Q={};R(Q,{AssetClient:()=>k,BalanceClient:()=>x,ChainParams:()=>_});module.exports=H(Q);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 $=require("polkadot-api/sm-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 +1 @@
1
- import O from"buffer";typeof window<"u"&&(window.Buffer=O.Buffer);import{hydration as G,hydrationNext as X}from"@galacticcouncil/descriptors";import{log as U}from"@galacticcouncil/common";import{shareReplay as Y,tap as j}from"rxjs";import{defer as L,from as I,of as x,timer as R}from"rxjs";import{catchError as N,distinctUntilChanged as H,expand as V,map as T,shareReplay as W,skip as z,switchMap as $,timeout as Q}from"rxjs/operators";function _(u,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let s=()=>L(()=>I(u._request("system_health",[]))).pipe(Q({first:t}),T(()=>"online"),N(()=>x("offline")));return x({state:"offline",delayMs:0}).pipe(V(a=>R(a.delayMs).pipe($(s),T(r=>({state:r,delayMs:e})))),z(1),T(a=>a.state),H(),W({bufferSize:1,refCount:!0}))}var{logger:F}=U,B=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",_(e))}static getInstance(e){return this.instance||(this.instance=new u(e)),this.instance}watched(e,t){return t.pipe(j({error:s=>F.error(e,s)}),Y({bufferSize:1,refCount:!0}))}};var m=class{client;api;apiNext;watcher;constructor(e){this.client=e,this.api=this.client.getTypedApi(G),this.apiNext=this.client.getTypedApi(X),this.watcher=B.getInstance(this.client)}};import{getWsProvider as Te}from"polkadot-api/ws-provider";import{withLogsRecorder as Se}from"polkadot-api/logs-provider";import{withLegacy as xe}from"@polkadot-api/legacy-provider";import{getSmProvider as ve}from"polkadot-api/sm-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?.asText(),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:w}=await this.mapToken(b,t,s);return[b,w]})),d=Object.fromEntries(y),p=Object.values(d);return{id:e,name:p.join(", "),symbol:o?.asText()||r?.asText(),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?.asText(),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 w=a.get(i);p=await this.mapShares(i,l,o,w);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 J}from"@galacticcouncil/common";import{combineLatest as K,concat as Z,defer as A,from as M}from"rxjs";import{bufferCount as v,distinctUntilChanged as C,debounceTime as ee,map as h,retry as te,startWith as q,switchMap as D,tap as g,take as se,skip as ae,connect as ne}from"rxjs/operators";var{logger:f}=J,S=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 K([t,s,n]).pipe(ne(a=>Z(a.pipe(se(1)),a.pipe(ae(1),ee(250)))))}).pipe(h(t=>t.flat()),q([]),v(2,1),h(([t,s],n)=>n===0?s:this.getDeltas(t,s))).pipe(g({subscribe:()=>f.debug("balance: subscribe",e),error:t=>f.error("balance",t)}),te({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return A(()=>t.watchValue(e,"best")).pipe(h(s=>({id:0,balance:this.getBreakdown(s.data)})),g({error:s=>f.error("balance(system)",s)}))}watchTokenBalance(e,t){let s=this.api.query.Tokens.Accounts;return A(()=>s.watchValue(e,t,"best")).pipe(h(n=>({id:t,balance:this.getBreakdown(n)})),g({error:n=>f.error("balance(token)",n)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return A(()=>t.watchEntries(e,{at:"best"})).pipe(C((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}),g({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(()=>M(t?Promise.resolve(t):s()).pipe(D(a=>this.watcher.bestBlock$.pipe(D(()=>M(n(a))))),q([]),v(2,1),h(([a,r],o)=>o===0?r.filter(c=>c.balance.total>0n):this.getDeltas(a,r)),C((a,r)=>r.length===0),g({error:a=>f.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 k=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,k 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 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";import{getSmProvider as ve}from"polkadot-api/sm-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 +1 @@
1
- "use strict";var d=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var w=(i,t)=>{for(var e in t)d(i,e,{get:t[e],enumerable:!0})},v=(i,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of P(t))!k.call(i,r)&&r!==e&&d(i,r,{get:()=>t[r],enumerable:!(a=x(t,r))||a.enumerable});return i};var E=i=>v(d({},"__esModule",{value:!0}),i);var R={};w(R,{EvmClient:()=>h,EvmRpcAdapter:()=>c,createChain:()=>u});module.exports=E(R);var o=require("polkadot-api"),m=require("@galacticcouncil/descriptors"),s=require("viem"),A=10000000n,c=class{api;constructor(t){this.api=t.getTypedApi(m.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,a=e.timestamp/1000n,[r]=e.number;return{timestamp:a,number:r}}readContract=(async t=>{let{abi:e,address:a,functionName:r,args:C}=t,f=(0,s.encodeFunctionData)({abi:e,functionName:r,args:C}),l=await this.api.apis.EthereumRuntimeRPCApi.call(o.FixedSizeBinary.fromText(""),o.FixedSizeBinary.fromHex(a),o.Binary.fromHex(f),[0n,0n,0n,0n],[A,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!l.success)throw console.error(r,l.value.type),new Error("Contract read failure");let{exit_reason:p,value:b,used_gas:g}=l.value;if(console.log(g),p.type==="Succeed")return(0,s.decodeFunctionResult)({abi:e,functionName:r,data:b.asHex()});throw console.log(r,p.type,p.value.type),new Error("Contract read error")})};var y=require("viem"),H=["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"],u=()=>(0,y.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:H}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var n=require("viem");var h=class{client;chain;constructor(t){this.client=t,this.chain=u()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,n.createPublicClient)({chain:this.chain,transport:(0,n.http)()})}getWsProvider(){return(0,n.createPublicClient)({transport:(0,n.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,n.createWalletClient)({account:t,chain:this.chain,transport:(0,n.custom)(window.ethereum)})}getRPCAdapter(){return new c(this.client)}};0&&(module.exports={EvmClient,EvmRpcAdapter,createChain});
1
+ "use strict";var p=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var w=(i,t)=>{for(var e in t)p(i,e,{get:t[e],enumerable:!0})},v=(i,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of P(t))!k.call(i,r)&&r!==e&&p(i,r,{get:()=>t[r],enumerable:!(a=x(t,r))||a.enumerable});return i};var H=i=>v(p({},"__esModule",{value:!0}),i);var R={};w(R,{EvmClient:()=>h,EvmRpcAdapter:()=>o,createChain:()=>u});module.exports=H(R);var d=require("polkadot-api"),m=require("@galacticcouncil/descriptors"),c=require("viem"),E=10000000n,o=class{api;constructor(t){this.api=t.getTypedApi(m.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,a=e.timestamp/1000n,[r]=e.number;return{timestamp:a,number:r}}readContract=(async t=>{let{abi:e,address:a,functionName:r,args:C}=t,f=(0,c.encodeFunctionData)({abi:e,functionName:r,args:C}),s=await this.api.apis.EthereumRuntimeRPCApi.call("0x0000000000000000000000000000000000000000",a,d.Binary.fromHex(f),[0n,0n,0n,0n],[E,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!s.success)throw console.error(r,s.value.type),new Error("Contract read failure");let{exit_reason:l,value:b,used_gas:g}=s.value;if(console.log(g),l.type==="Succeed")return(0,c.decodeFunctionResult)({abi:e,functionName:r,data:d.Binary.toHex(b)});throw console.log(r,l.type,l.value.type),new Error("Contract read error")})};var y=require("viem"),A=["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"],u=()=>(0,y.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:A}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var n=require("viem");var h=class{client;chain;constructor(t){this.client=t,this.chain=u()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,n.createPublicClient)({chain:this.chain,transport:(0,n.http)()})}getWsProvider(){return(0,n.createPublicClient)({transport:(0,n.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,n.createWalletClient)({account:t,chain:this.chain,transport:(0,n.custom)(window.ethereum)})}getRPCAdapter(){return new o(this.client)}};0&&(module.exports={EvmClient,EvmRpcAdapter,createChain});
@@ -1 +1 @@
1
- import C from"buffer";typeof window<"u"&&(window.Buffer=C.Buffer);import{Binary as g,FixedSizeBinary as s}from"polkadot-api";import{hydration as b}from"@galacticcouncil/descriptors";import{encodeFunctionData as x,decodeFunctionResult as P}from"viem";var w=10000000n,n=class{api;constructor(t){this.api=t.getTypedApi(b)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,i=e.timestamp/1000n,[r]=e.number;return{timestamp:i,number:r}}readContract=(async t=>{let{abi:e,address:i,functionName:r,args:h}=t,m=x({abi:e,functionName:r,args:h}),a=await this.api.apis.EthereumRuntimeRPCApi.call(s.fromText(""),s.fromHex(i),g.fromHex(m),[0n,0n,0n,0n],[w,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!a.success)throw console.error(r,a.value.type),new Error("Contract read failure");let{exit_reason:o,value:f,used_gas:y}=a.value;if(console.log(y),o.type==="Succeed")return P({abi:e,functionName:r,data:f.asHex()});throw console.log(r,o.type,o.value.type),new Error("Contract read error")})};import{defineChain as k}from"viem";var v=["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"],c=()=>k({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:v}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});import{createPublicClient as l,createWalletClient as E,custom as p,http as A}from"viem";var d=class{client;chain;constructor(t){this.client=t,this.chain=c()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return l({chain:this.chain,transport:A()})}getWsProvider(){return l({transport:p({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return E({account:t,chain:this.chain,transport:p(window.ethereum)})}getRPCAdapter(){return new n(this.client)}};export{d as EvmClient,n as EvmRpcAdapter,c as createChain};
1
+ import C from"buffer";typeof window<"u"&&(window.Buffer=C.Buffer);import{Binary as s}from"polkadot-api";import{hydration as g}from"@galacticcouncil/descriptors";import{encodeFunctionData as b,decodeFunctionResult as x}from"viem";var P=10000000n,n=class{api;constructor(t){this.api=t.getTypedApi(g)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,i=e.timestamp/1000n,[r]=e.number;return{timestamp:i,number:r}}readContract=(async t=>{let{abi:e,address:i,functionName:r,args:h}=t,m=b({abi:e,functionName:r,args:h}),a=await this.api.apis.EthereumRuntimeRPCApi.call("0x0000000000000000000000000000000000000000",i,s.fromHex(m),[0n,0n,0n,0n],[P,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!a.success)throw console.error(r,a.value.type),new Error("Contract read failure");let{exit_reason:o,value:y,used_gas:f}=a.value;if(console.log(f),o.type==="Succeed")return x({abi:e,functionName:r,data:s.toHex(y)});throw console.log(r,o.type,o.value.type),new Error("Contract read error")})};import{defineChain as w}from"viem";var k=["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"],c=()=>w({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:k}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});import{createPublicClient as l,createWalletClient as v,custom as d,http as E}from"viem";var p=class{client;chain;constructor(t){this.client=t,this.chain=c()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return l({chain:this.chain,transport:E()})}getWsProvider(){return l({transport:d({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return v({account:t,chain:this.chain,transport:d(window.ethereum)})}getRPCAdapter(){return new n(this.client)}};export{p as EvmClient,n as EvmRpcAdapter,c as createChain};
@@ -1,5 +1,5 @@
1
1
  import { Papi } from '../api';
2
- import { Binary, Enum } from 'polkadot-api';
2
+ import { Enum } from 'polkadot-api';
3
3
  export declare class LiquidityMiningClient extends Papi {
4
4
  protected omnipoolAssetIds: string[];
5
5
  getOraclePrice(orderedAssets: [number, number]): Promise<[{
@@ -128,9 +128,9 @@ export declare class LiquidityMiningClient extends Papi {
128
128
  total_stopped: number;
129
129
  } | undefined>;
130
130
  getAsset(id: number): Promise<{
131
- symbol: Binary | undefined;
131
+ symbol: Uint8Array<ArrayBufferLike> | undefined;
132
132
  decimals: number | undefined;
133
- name: Binary | undefined;
133
+ name: Uint8Array<ArrayBufferLike> | undefined;
134
134
  asset_type: Enum<{
135
135
  Token: undefined;
136
136
  XYK: undefined;
@@ -1 +1 @@
1
- "use strict";var ht=Object.create;var O=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)O(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&&O(a,i,{get:()=>t[i],enumerable:!(r=_t(t,i))||r.enumerable});return a};var x=(a,t,e)=>(e=a!=null?ht(wt(a)):{},tt(t||!a||!a.__esModule?O(e,"default",{value:a,enumerable:!0}):e,a)),Ft=a=>tt(O({},"__esModule",{value:!0}),a);var kt={};Z(kt,{LiquidityMiningApi:()=>W,LiquidityMiningClient:()=>j});module.exports=Ft(kt);var it=require("polkadot-api"),d=x(require("big.js")),h=require("@galacticcouncil/common"),K=require("@galacticcouncil/math-liquidity-mining");var It=require("@galacticcouncil/common");var A={};Z(A,{FeeUtils:()=>q,shiftNeg:()=>Ot});var et=x(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=x(require("big.js"));var T=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=x(require("big.js")),b=require("@galacticcouncil/math-liquidity-mining");var k=x(require("big.js")),z=(0,k.default)(10).pow(18),rt=BigInt((0,k.default)(1).pow(18).toString()),nt=6e3;var Et="1000000000000000000",M=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),m=(0,S.default)(c.toString()),g=(0,S.default)(s.toString()).minus(m.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 null;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 m=s.total_stopped-r.stopped_at_creation,g=s.updated_at-r.entered_at-m,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,d.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,d.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,d.default)(t.toString()).times(e),o=(0,d.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:m,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:I,updated_at:P,incentivized_asset:at,reward_currency:ct,price_adjustment:lt,min_deposit:ut}=n,N=A.shiftNeg(o??lt,h.RUNTIME_DECIMALS),U=A.shiftNeg(m,h.RUNTIME_DECIMALS),V=A.shiftNeg(g?.initial_reward_percentage??0,h.RUNTIME_DECIMALS),$=Lt.div((0,d.default)(this.blockTime).div(1e3).times(l)).toString(),F;if(p<=0)F=(0,d.default)(U).times(f.toString()).times($).div(Math.pow(10,h.RUNTIME_DECIMALS)).toString();else{let bt=this.getGlobalRewardPerPeriod(p,f,y,N),yt=this.getPoolYieldPerPeriod(bt,U,p,N);F=(0,d.default)(yt).times($).toString()}let B=w+v,mt=y*BigInt(I),D=c.transferable+B,dt=D-B,H=(0,d.default)(dt.toString()).div(y.toString()),X=(0,d.default)(e).div(l.toString()).toString(),J=(p>=0?H.plus(P):H.plus(X)).toString(),gt=(0,d.default)(J).times(l).toString(),pt=(0,d.default)(p.toString()).div((0,d.default)(y.toString()).div(f.toString())).div(Math.pow(10,h.RUNTIME_DECIMALS)).times(100).times(N).toFixed(2),Q=(0,d.default)(B.toString()).div(D.toString()).gte(.999);F=Q?"0":(0,d.default)(F).div(r?2:1).times(100).toString();let ft=V?(0,d.default)(F).times(V).toString():void 0;return{apr:F,minApr:ft,isDistributed:Q,estimatedEndPeriod:J,estimatedEndBlock:gt,maxRewards:mt,incentivizedAsset:at,rewardCurrency:ct,loyaltyCurve:g,currentPeriod:X,potMaxRewards:D,fullness:pt,yieldFarmId:i.id,globalFarmId:n.id,poolId:s,distributedRewards:B,plannedYieldingPeriods:I,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,m=await this.client.getOmnipoolGlobalFarm(c),g=await this.client.getOmnipoolYieldFarm(Number(t),c,s);if(!m||!g)return;let l=m.reward_currency,f=m.incentivized_asset,p=this.getFarmAddress(c),y=await this.getOraclePrice(l,f),w=await this.balance.getBalance(p,l);return{id:t,globalFarm:m,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,m=await this.client.getIsolatedGlobalFarm(c),g=await this.client.getIsolatedYieldFarm(t,c,s);if(!m||!g)return;let l=m.reward_currency,f=m.incentivized_asset,p=this.getFarmAddress(c,!0),y=await this.getOraclePrice(l,f),w=await this.balance.getBalance(p,l);return{id:t,globalFarm:m,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 m=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(m,g),y=new T(l,f),v=await new M(P=>this.getFarmAddress(P),P=>this.client.getAsset(P),y).claimRewards(s,c,e,i,p??s.price_adjustment);if(!v)return;let I=await this.client.getAsset(v.assetId);if(I&&!(v.reward<=I.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 R=require("@galacticcouncil/descriptors");var st=require("@galacticcouncil/common"),E=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,C=class a{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),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,E.tap)({error:r=>Rt.error(t,r)}),(0,E.shareReplay)({bufferSize:1,refCount:!0}))}};var L=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(R.hydration),this.apiNext=this.client.getTypedApi(R.hydrationNext),this.watcher=C.getInstance(this.client)}};var Yt=require("polkadot-api/ws-provider"),Nt=require("polkadot-api/logs-provider"),Dt=require("@polkadot-api/legacy-provider");var qt=require("polkadot-api/sm-provider");var Y=require("polkadot-api"),j=class extends L{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Y.Binary.fromText("omnipool"),t,(0,Y.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)),Ft=a=>tt(M({},"__esModule",{value:!0}),a);var kt={};Z(kt,{LiquidityMiningApi:()=>W,LiquidityMiningClient:()=>j});module.exports=Ft(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 A={};Z(A,{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 null;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=A.shiftNeg(o??lt,h.RUNTIME_DECIMALS),U=A.shiftNeg(d,h.RUNTIME_DECIMALS),H=A.shiftNeg(g?.initial_reward_percentage??0,h.RUNTIME_DECIMALS),V=Lt.div((0,m.default)(this.blockTime).div(1e3).times(l)).toString(),F;if(p<=0)F=(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);F=(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);F=Q?"0":(0,m.default)(F).div(r?2:1).times(100).toString();let ft=H?(0,m.default)(F).times(H).toString():void 0;return{apr:F,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 Dt=require("polkadot-api/sm-provider");var O=require("polkadot-api"),qt=O.Binary.toHex(O.Binary.fromText("omnipool")),j=class extends R{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(qt,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 lt=Object.defineProperty;var ct=(c,t)=>{for(var e in t)lt(c,e,{get:t[e],enumerable:!0})};import ut from"buffer";typeof window<"u"&&(window.Buffer=ut.Buffer);import{AccountId as It}from"polkadot-api";import m from"big.js";import{HYDRATION_SS58_PREFIX as At,RUNTIME_DECIMALS as w}from"@galacticcouncil/common";import{fixed_from_rational as j}from"@galacticcouncil/math-liquidity-mining";import{RUNTIME_DECIMALS as Qt}from"@galacticcouncil/common";var S={};ct(S,{FeeUtils:()=>T,shiftNeg:()=>bt});import ft 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 bt(c,t){let e=ft(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import ne from"big.js";import{TLRUCache as se}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 _t,calculate_global_farm_rewards as St,calculate_loyalty_multiplier as wt,calculate_user_reward as V,calculate_yield_farm_delta_rpvs as Ft}from"@galacticcouncil/math-liquidity-mining";import W from"big.js";var Y=W(10).pow(18),z=BigInt(W(1).pow(18).toString()),K=6e3;var vt="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(St(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(_t(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 null;if(t.total_valued_shares===0n)return{...t,updated_at:r};let n=Ft(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 wt(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(V(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),a.accumulated_rpvs.toString(),l)),p=BigInt(V(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),a.accumulated_rpvs.toString(),vt));return{reward:g,maxReward:p,assetId:s.reward_currency,yieldFarmId:a.id,isActiveFarm:a.state.type==="Active"}}};var xt=m(365.2425).times(24).times(60).times(60),H=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 z;let n=await this.client.getOraclePrice(r);if(n){let{n:i,d:o}=n[0].price,s;return t<e?s=j(i.toString(),o.toString()):s=j(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(At).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:Q,reward_currency:J,price_adjustment:Z,min_deposit:tt}=i,B=S.shiftNeg(o??Z,w),E=S.shiftNeg(u,w),R=S.shiftNeg(d?.initial_reward_percentage??0,w),D=xt.div(m(this.blockTime).div(1e3).times(l)).toString(),_;if(p<=0)_=m(E).times(g.toString()).times(D).div(Math.pow(10,w)).toString();else{let at=this.getGlobalRewardPerPeriod(p,g,f,B),st=this.getPoolYieldPerPeriod(at,E,p,B);_=m(st).times(D).toString()}let I=y+h,et=f*BigInt(F),M=s.transferable+I,rt=M-I,N=m(rt.toString()).div(f.toString()),k=m(e).div(l.toString()).toString(),q=(p>=0?N.plus(v):N.plus(k)).toString(),it=m(q).times(l).toString(),nt=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 ot=R?m(_).times(R).toString():void 0;return{apr:_,minApr:ot,isDistributed:G,estimatedEndPeriod:q,estimatedEndBlock:it,maxRewards:et,incentivizedAsset:Q,rewardCurrency:J,loyaltyCurve:d,currentPeriod:k,potMaxRewards:M,fullness:nt,yieldFarmId:n.id,globalFarmId:i.id,poolId:a,distributedRewards:I,plannedYieldingPeriods:F,minDeposit:tt,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 Gt,hydrationNext as Wt}from"@galacticcouncil/descriptors";import{log as Dt}from"@galacticcouncil/common";import{shareReplay as Nt,tap as kt}from"rxjs";import{defer as Pt,from as Ot,of as U,timer as Bt}from"rxjs";import{catchError as Mt,distinctUntilChanged as Tt,expand as Yt,map as C,shareReplay as Lt,skip as Ct,switchMap as Et,timeout as Rt}from"rxjs/operators";function $(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>Pt(()=>Ot(c._request("system_health",[]))).pipe(Rt({first:e}),C(()=>"online"),Mt(()=>U("offline")));return U({state:"offline",delayMs:0}).pipe(Yt(i=>Bt(i.delayMs).pipe(Et(r),C(o=>({state:o,delayMs:t})))),Ct(1),C(i=>i.state),Tt(),Lt({bufferSize:1,refCount:!0}))}var{logger:qt}=Dt,P=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),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(kt({error:r=>qt.error(t,r)}),Nt({bufferSize:1,refCount:!0}))}};var O=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(Gt),this.apiNext=this.client.getTypedApi(Wt),this.watcher=P.getInstance(this.client)}};import{getWsProvider as Qe}from"polkadot-api/ws-provider";import{withLogsRecorder as Ze}from"polkadot-api/logs-provider";import{withLegacy as er}from"@polkadot-api/legacy-provider";import{getSmProvider as or}from"polkadot-api/sm-provider";import{Binary as zt,Enum as Kt}from"polkadot-api";var X=class extends O{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(zt.fromText("omnipool"),t,Kt("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{H as LiquidityMiningApi,X 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 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 null;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{getSmProvider as or}from"polkadot-api/sm-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};