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