UNPKG

goosefx-amm-sdk

Version:

SDK for the GooseFx AMM

2 lines 2.78 kB
import o from"bn.js";import N from"decimal.js-light";import P from"bn.js";var h=new P(0);function k(p,e){if(e.isZero())throw Error("rhs is zero");let t=p.div(e);return t.isZero()?[t,e]:p.sub(t.mul(e)).isZero()?[t,e]:[t.add(new P(1)),e]}function d(p,e){return p.gt(e)?p.sub(e):new P(0)}var q=new o(100),v=new o(1e6),E=100,D=new o(3600),y=new o(1e5),C=new o(3e5),x=class{static calculateDynamicFee(e,t,r,a,m,i,u){let c=this.calculateDynamicFeeRate(t,r,a,m,i,u),[l,b]=k(e.mul(c),v);return l}static calculatePreDynamicFee(e,t,r,a,m,i,u){let c=this.calculateDynamicFeeRate(t,r,a,m,i,u);if(c.isZero())return e;let l=v.sub(c);if(l.isZero())throw new Error("Fee rate equals denominator, causing division by zero");return e.mul(v).add(l).sub(new o(1)).div(l)}static calculateDynamicFeeRate(e,t,r,a,m,i){switch(r){case"volatility":return this.calculateVolatileFee(e,t,a,m,i)}}static calculateVolatileFee(e,t,r,a,m){let{minPrice:i,maxPrice:u,twapPrice:c}=this.getPriceRange(t,e,D);if(i.eqn(0)||u.eqn(0)||c.eqn(0)||c.eqn(1))return r;let l=new N(u.toString()).ln(),b=new N(i.toString()).ln(),n=new N(c.toString()).ln(),s=l.sub(b),B=n.abs();if(B.eq(0))return r;let w=s.div(B),T=a.eqn(0)?C:a,F=new N(T.toString()).mul(w),f=new N(r.toString()).add(F),O=new o(f.lessThan(new N(y.toString()))?f.toString():y.toString());if(m){let g=d(O,q);return r.gt(g)?r:g}else return O}static getPriceRange(e,t,r){let a=new o(1).ushln(128).subn(1),m=new o(0),i=e.observations.map((n,s)=>({observation:n,idx:s})).filter(({observation:n})=>{n.blockTimestamp.eqn(0)&&!n.cumulativeToken0PriceX32.eqn(0)&&!n.cumulativeToken1PriceX32.eqn(0)&&t.sub(n.blockTimestamp)<=r}).map(({observation:n,idx:s})=>({index:s,observation:n}));if(i.length<2)return{minPrice:new o(0),maxPrice:new o(0),twapPrice:new o(0)};i.sort((n,s)=>s.observation.blockTimestamp.cmp(n.observation.blockTimestamp));let u=i[0],c=i[i.length-1],l=d(u.observation.blockTimestamp,c.observation.blockTimestamp);if(l.eqn(0))return{minPrice:new o(0),maxPrice:new o(0),twapPrice:new o(0)};let b=u.observation.cumulativeToken0PriceX32.sub(c.observation.cumulativeToken0PriceX32).div(l);for(let n of i){let s;if(n.index==0?s=e.observations[E-1]:s=e.observations[n.index-1],s.blockTimestamp.eqn(0))continue;if(s.blockTimestamp>n.observation.blockTimestamp)break;let B=n.observation,w=d(B.blockTimestamp,s.blockTimestamp);if(w.eqn(0))continue;let T=B.cumulativeToken0PriceX32.sub(s.cumulativeToken0PriceX32).div(w);a=o.min(a,T),m=o.max(m,T)}return{minPrice:a,maxPrice:m,twapPrice:b}}static calculatePreFeeAmount(e,t,r,a,m,i,u){let c=this.calculateDynamicFeeRate(e,r,a,m,i,u);if(c.eqn(0))return t;{let l=t.mul(v),b=v.sub(c);return l.add(b).subn(1).div(b)}}};export{x as DynamicFee,v as FEE_RATE_DENOMINATOR_VALUE,q as ONE_BASIS_POINT}; //# sourceMappingURL=fee.mjs.map