UNPKG

@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.12 kB
import{DecToBn as t,ONE as e,Decimal as r,BnToDec as n}from"../numerics/index.js";import{BigNumber as i}from"@ethersproject/bignumber";function o(t){return t.gt(0)?r.log2(t.toString()).add(1).floor().toNumber():0}const a=r=>{const n=t(r.sqrt().mul(e).floor()),i=o(n.div(e));return n.shr(i).shl(i)},s=t=>t.div(e).pow(2),l=t=>{const r=o(t.div(e)),n=t.shr(r);return i.from(e).mul(r).or(n)},g=t=>t.mod(e).shl(t.div(e).toNumber()),u=([t,e])=>{const n=new r(t.liquidity),i=new r(t.lowestRate),o=new r(t.highestRate),a=new r(e.liquidity),s=new r(e.lowestRate),l=new r(e.highestRate);return n.eq(0)&&a.gt(0)&&s.gt(0)&&l.gt(0)?[R(t,q(e)),R(e)]:a.eq(0)&&n.gt(0)&&i.gt(0)&&o.gt(0)?[R(t),R(e,q(t))]:[R(t),R(e)]},w=t=>{try{return R(t),!0}catch{return!1}},h=(t,e)=>{const n=new r(t),i=new r(e),o=a(n),s=a(i);return o.eq(s)},R=(e,n)=>{const i=new r(e.liquidity),o=new r(e.lowestRate),s=new r(e.highestRate),g=new r(e.marginalRate),u=t(i),w=a(o),h=a(s),R=a(g);if(!(h.gte(R)&&R.gt(w)||h.eq(R)&&R.eq(w)||h.gt(R)&&R.eq(w)&&u.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 = ${g}, lowestRate = ${o}), liquidity = ${i}`);return{y:u,z:void 0!==n?n:h.eq(R)||u.isZero()?u:u.mul(h.sub(w)).div(R.sub(w)),A:l(h.sub(w)),B:l(w)}},d=t=>{const e=n(t.y),r=n(t.z),i=n(g(t.A)),o=n(g(t.B));return{liquidity:e.toString(),lowestRate:s(o).toString(),highestRate:s(o.add(i)).toString(),marginalRate:s(e.eq(r)?o.add(i):o.add(i.mul(e).div(r))).toString()}},m=(t,e)=>{const n=q(t),i=a(new r(e.lowestRate)),o=a(new r(e.highestRate)),s=a(new r(e.marginalRate));return n.mul(s.sub(i)).div(o.sub(i)).toString()},q=e=>{const i=n(R(e).z),o=new r(e.lowestRate),a=new r(e.highestRate),s=o.mul(a).sqrt();return t(i.div(s).floor())};export{h as areScaledRatesEqual,q as calculateCorrelatedZ,m as calculateRequiredLiquidity,g as decodeFloat,d as decodeOrder,s as decodeRate,l as encodeFloat,R as encodeOrder,u as encodeOrders,a as encodeRate,w as isOrderEncodable};