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.37 kB
import{Decimal as t,ONE as e,DecToBn as n,BnToDec as r}from"../numerics/index.js";function i(e){return e>0n?t.log2(e.toString()).add(1).floor().toNumber():0}const o=r=>{const o=new t(e.toString()),a=n(r.sqrt().mul(o).floor()),s=i(a/e);return a>>BigInt(s)<<BigInt(s)},a=n=>{const r=new t(e.toString());return n.div(r).pow(2)},s=a(new t(1)),g=t=>{const n=i(t/e),r=t>>BigInt(n);return e*BigInt(n)|r},l=t=>t%e<<BigInt(Number(t/e)),w=([e,n])=>{const r=new t(e.liquidity),i=new t(e.lowestRate),o=new t(e.highestRate),a=new t(n.liquidity),s=new t(n.lowestRate),g=new t(n.highestRate);return r.eq(0)&&a.gt(0)&&s.gt(0)&&g.gt(0)?[u(e,c(n)),u(n)]:a.eq(0)&&r.gt(0)&&i.gt(0)&&o.gt(0)?[u(e),u(n,c(e))]:[u(e),u(n)]},h=t=>{try{return u(t),!0}catch{return!1}},R=(e,n)=>{const r=new t(e),i=new t(n);return o(r)===o(i)},u=(e,r)=>{const i=new t(e.liquidity),a=new t(e.lowestRate),s=new t(e.highestRate),l=new t(e.marginalRate),w=n(i),h=o(a),R=o(s),u=o(l);if(0n===h&&(0n!==R||0n!==u))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 = ${a}, highestRate = ${s}, marginalRate = ${l}\nL = ${h}, H = ${R}, M = ${u}`);if(!(R>=u&&u>h||R===u&&u===h||R>u&&u===h&&0n===w))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 = ${a}), liquidity = ${i}`);return{y:w,z:void 0!==r?r:R===u||0n===w?w:w*(R-h)/(u-h),A:g(R-h),B:g(h)}},d=t=>{const e=r(t.y),n=r(t.z),i=r(l(t.A)),o=r(l(t.B));return{liquidity:e.toString(),lowestRate:a(o).toString(),highestRate:a(o.add(i)).toString(),marginalRate:a(e.eq(n)?o.add(i):o.add(i.mul(e).div(n))).toString()}},m=(e,n)=>{const r=c(e),i=o(new t(n.lowestRate)),a=o(new t(n.highestRate));return(r*(o(new t(n.marginalRate))-i)/(a-i)).toString()},c=e=>{const i=r(u(e).z),o=new t(e.lowestRate),a=new t(e.highestRate),s=o.mul(a).sqrt();return n(i.div(s).floor())};export{R as areScaledRatesEqual,c as calculateCorrelatedZ,m as calculateRequiredLiquidity,l as decodeFloat,d as decodeOrder,a as decodeRate,g as encodeFloat,u as encodeOrder,w as encodeOrders,o as encodeRate,h as isOrderEncodable,s as lowestPossibleRate};