@galacticcouncil/sdk-next 0.41.0 → 0.41.1-pr314-bdb1f07

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.
@@ -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 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 t;if(t.total_valued_shares===0n)return{...t,updated_at:r};let i=(0,b.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(i),updated_at:r}}getLoyaltyMultiplier(t,e){let r=(0,S.default)(1).mul(z).round(0,S.default.roundDown).toString();if(!e)return r;let{initial_reward_percentage:i,scale_coef:n}=e;return(0,b.calculate_loyalty_multiplier)(t.toFixed(),i.toString(),n.toFixed())}async claimRewards(t,e,r,i,n){if(e.state.type==="Terminated")return null;let o=Math.floor(i/t.blocks_per_period);if(r.updated_at===o)return null;let c=await this.syncGlobalFarm(t,o,n);if(!c)return null;let s=this.syncYieldFarm(e,c,o);if(!s)return null;let 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 +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 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 t;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};