@bancor/carbon-sdk
Version:
The SDK is a READ-ONLY tool, intended to facilitate working with Carbon contracts. It's a convenient wrapper around our matching algorithm, allowing programs and users get a ready to use transaction data that will allow them to manage strategies and fulfi
2 lines (1 loc) • 2.47 kB
JavaScript
import{Decimal as t,ONE as e,DecToBn as r,BnToDec as o}from"../numerics/index.js";import{BigNumber as n}from"@ethersproject/bignumber";function i(e){return e.gt(0)?t.log2(e.toString()).add(1).floor().toNumber():0}const a=t=>{const o=r(t.sqrt().mul(e).floor()),n=i(o.div(e));return o.shr(n).shl(n)},s=t=>t.div(e).pow(2),l=s(new t(1)),g=t=>{const r=i(t.div(e)),o=t.shr(r);return n.from(e).mul(r).or(o)},h=t=>t.mod(e).shl(t.div(e).toNumber()),u=([e,r])=>{const o=new t(e.liquidity),n=new t(e.lowestRate),i=new t(e.highestRate),a=new t(r.liquidity),s=new t(r.lowestRate),l=new t(r.highestRate);return o.eq(0)&&a.gt(0)&&s.gt(0)&&l.gt(0)?[d(e,q(r)),d(r)]:a.eq(0)&&o.gt(0)&&n.gt(0)&&i.gt(0)?[d(e),d(r,q(e))]:[d(e),d(r)]},w=t=>{try{return d(t),!0}catch{return!1}},R=(e,r)=>{const o=new t(e),n=new t(r),i=a(o),s=a(n);return i.eq(s)},d=(e,o)=>{const n=new t(e.liquidity),i=new t(e.lowestRate),s=new t(e.highestRate),l=new t(e.marginalRate),h=r(n),u=a(i),w=a(s),R=a(l);if(u.isZero()&&(!w.isZero()||!R.isZero()))throw new Error(`Encoded lowest rate cannot be zero unless the highest and marginal rates are also zero. This may be the result of passing a rate that is zero or too close to zero:\nlowestRate = ${i}, highestRate = ${s}, marginalRate = ${l}\nL = ${u}, H = ${w}, M = ${R}`);if(!(w.gte(R)&&R.gt(u)||w.eq(R)&&R.eq(u)||w.gt(R)&&R.eq(u)&&h.isZero()))throw new Error(`Either one of the following must hold:\n- highestRate >= marginalRate > lowestRate\n- highestRate == marginalRate == lowestRate\n- (highestRate > marginalRate == lowestRate) AND liquidity == 0\n(highestRate = ${s}, marginalRate = ${l}, lowestRate = ${i}), liquidity = ${n}`);return{y:h,z:void 0!==o?o:w.eq(R)||h.isZero()?h:h.mul(w.sub(u)).div(R.sub(u)),A:g(w.sub(u)),B:g(u)}},m=t=>{const e=o(t.y),r=o(t.z),n=o(h(t.A)),i=o(h(t.B));return{liquidity:e.toString(),lowestRate:s(i).toString(),highestRate:s(i.add(n)).toString(),marginalRate:s(e.eq(r)?i.add(n):i.add(n.mul(e).div(r))).toString()}},c=(e,r)=>{const o=q(e),n=a(new t(r.lowestRate)),i=a(new t(r.highestRate)),s=a(new t(r.marginalRate));return o.mul(s.sub(n)).div(i.sub(n)).toString()},q=e=>{const n=o(d(e).z),i=new t(e.lowestRate),a=new t(e.highestRate),s=i.mul(a).sqrt();return r(n.div(s).floor())};export{R as areScaledRatesEqual,q as calculateCorrelatedZ,c as calculateRequiredLiquidity,h as decodeFloat,m as decodeOrder,s as decodeRate,g as encodeFloat,d as encodeOrder,u as encodeOrders,a as encodeRate,w as isOrderEncodable,l as lowestPossibleRate};