@bancor/carbon-sdk
Advanced tools
Comparing version 0.0.98-DEV to 0.0.99-DEV
@@ -1,1 +0,1 @@ | ||
import{formatUnits as e,parseUnits as t,tenPow as a,BigNumberMax as r,mulDiv as i}from"../../utils/numerics/index.js";import{MatchType as s}from"../../common/types/index.js";import{Decimals as o}from"../../utils/decimals/index.js";import{matchByTargetAmount as c,matchBySourceAmount as d}from"../../trade-matcher/match/index.js";import{getEncodedTradeSourceAmount as n}from"../../trade-matcher/trade/index.js";import{getDepths as g,getMinRate as l,getMaxRate as u}from"../stats/index.js";import{Logger as m}from"../../common/logger/index.js";import{decodeStrategy as y,parseStrategy as h,addFee as p,subtractFee as f,calculateOverlappingSellBudget as B,calculateOverlappingBuyBudget as S,buildStrategyObject as b,encodeStrategy as w,normalizeRate as P}from"../utils/index.js";import{decodeOrder as _}from"../../utils/encoders/index.js";import{ordersMapStrToBN as D,matchActionBNToStr as T,ordersMapBNToStr as v,tradeActionStrToBN as A,encodedStrategyStrToBN as x}from"../../utils/serializers/index.js";import{BigNumber as O}from"../../node_modules/@ethersproject/bignumber/lib.esm/bignumber/index.js";import{Decimal as j}from"../../node_modules/decimal.js/decimal/index.js";const M=new m("Toolkit.ts");var R;function k(e){return void 0!==e&&e!==R.reset&&e!==R.maintain}!function(e){e.reset="RESET",e.maintain="MAINTAIN"}(R||(R={}));class q{_api;_decimals;_cache;constructor(e,t,a){M.debug("SDK class constructor called with",arguments),this._api=e,this._cache=t;this._decimals=new o((async e=>await(a?.(e))??await this._api.reader.getDecimalsByAddress(e)))}static getMatchActions(e,t,a,r=s.Fast,i){const o=D(a);let n;return n=t?c(O.from(e),o,[r],i):d(O.from(e),o,[r],i),n[r]?.map(T)??[]}async hasLiquidityByPair(e,t){M.debug("hasLiquidityByPair called",arguments);const a=await this._cache.getOrdersByPair(e,t);return M.debug("hasLiquidityByPair info:",{orders:a}),Object.keys(a).length>0}async getLiquidityByPair(t,a){M.debug("getLiquidityByPair called",arguments);const r=await this._cache.getOrdersByPair(t,a),i=Object.values(r).reduce(((e,{y:t})=>e.add(t)),O.from(0)),s=await this._decimals.fetchDecimals(a),o=e(i,s);return M.debug("getLiquidityByPair info:",{orders:r,liquidityWei:i,targetToken:a,decimals:s,liquidity:o}),o}async getMaxSourceAmountByPair(t,a){M.debug("getMaxSourceAmountByPair called",arguments);const r=await this._cache.getOrdersByPair(t,a),i=Object.values(r).reduce(((e,t)=>e.add(n(t.y,t))),O.from(0)),s=await this._decimals.fetchDecimals(t),o=e(i,s);return M.debug("getMaxSourceAmountByPair info:",{orders:r,maxSourceAmountWei:i,sourceToken:t,decimals:s,maxSourceAmount:o}),o}async getStrategyById(e){let t;M.debug("getStrategyById called",arguments),this._cache&&(t=await this._cache.getStrategyById(e)),t?M.debug("getStrategyById fetched from cache"):(M.debug("getStrategyById fetching from chain"),t=await this._api.reader.strategy(O.from(e)));const a=y(t),r=await h(a,this._decimals);return M.debug("getStrategyById info:",{id:e,encodedStrategy:t,decodedStrategy:a,strategy:r}),r}async getStrategiesByPair(e,t){let a;M.debug("getStrategiesByPair called",arguments),this._cache&&(a=await this._cache.getStrategiesByPair(e,t)),a?M.debug("getStrategiesByPair fetched from cache"):(M.debug("getStrategiesByPair fetching from chain"),a=await this._api.reader.strategiesByPair(e,t));const r=a.map(y),i=await Promise.all(r.map((async e=>await h(e,this._decimals))));return M.debug("getStrategiesByPair info:",{token0:e,token1:t,encodedStrategies:a,decodedStrategies:r,strategies:i}),i}async getUserStrategies(e){M.debug("getUserStrategies called",arguments);const t=await this._api.reader.tokensByOwner(e);let a=[],r=t;if(this._cache&&(r=t.reduce(((e,t)=>{const r=this._cache.getStrategyById(t);return r?a.push(r):e.push(t),e}),[])),r.length>0){const e=await this._api.reader.strategies(r);a=[...a,...e]}const i=a.map(y),s=await Promise.all(i.map((async e=>await h(e,this._decimals))));return M.debug("getUserStrategies info:",{ids:t,encodedStrategies:a,decodedStrategies:i,strategies:s}),s}async getMatchParams(e,a,r,i){M.debug("getMatchParams called",arguments);const s=this._decimals,o=await s.fetchDecimals(e),c=await s.fetchDecimals(a),d=await this._cache.getOrdersByPair(e,a),n=t(r,i?c:o);return{orders:v(d),amountWei:n.toString(),sourceDecimals:o,targetDecimals:c}}async getTradeData(e,t,a,r,i=s.Fast,o){M.debug("getTradeData called",arguments);const{orders:c,amountWei:d}=await this.getMatchParams(e,t,a,r),n=q.getMatchActions(d,r,c,i,o),g=await this.getTradeDataFromActions(e,t,r,n);return M.debug("getTradeData info:",{orders:c,amount:a,amountWei:d,res:g}),g}async getTradeDataFromActions(t,r,i,s){M.debug("getTradeDataFromActions called",arguments);const o=await this._cache.getTradingFeePPMByPair(t,r);if(void 0===o)throw new Error(`tradingFeePPM is undefined for this pair: ${t}-${r}`);const c=this._decimals,d=await c.fetchDecimals(t),n=await c.fetchDecimals(r),g=[],l=[];let u,m,y,h=O.from(0),B=O.from(0);if(s.forEach((t=>{g.push({strategyId:t.id,amount:t.input}),i?l.push({id:t.id,sourceAmount:e(p(t.output,o).floor().toFixed(0),d),targetAmount:e(t.input,n)}):l.push({id:t.id,sourceAmount:e(t.input,d),targetAmount:e(f(t.output,o).floor().toFixed(0),n)}),B=B.add(t.input),h=h.add(t.output)})),i?(u=p(h,o).floor().toFixed(0),m=B.toString()):(u=B.toString(),m=f(h,o).floor().toFixed(0)),new j(u).isZero()||new j(m).isZero())y={tradeActions:g,actionsTokenRes:l,totalSourceAmount:"0",totalTargetAmount:"0",effectiveRate:"0",actionsWei:s};else{const t=new j(m).div(u).times(a(d,n)).toString();y={tradeActions:g,actionsTokenRes:l,totalSourceAmount:e(u,d),totalTargetAmount:e(m,n),effectiveRate:t,actionsWei:s}}return M.debug("getTradeDataFromActions info:",{sourceDecimals:d,targetDecimals:n,actionsWei:s,totalInput:B,totalOutput:h,tradingFeePPM:o,res:y}),y}async composeTradeByTargetTransaction(e,a,r,i,s,o){M.debug("composeTradeByTargetTransaction called",arguments);const c=await this._decimals.fetchDecimals(e);return this._api.composer.tradeByTargetAmount(e,a,r.map(A),i,t(s,c),o)}async composeTradeBySourceTransaction(e,a,r,i,s,o){M.debug("composeTradeBySourceTransaction called",arguments);const c=await this._decimals.fetchDecimals(a);return this._api.composer.tradeBySourceAmount(e,a,r.map(A),i,t(s,c),o)}async calculateOverlappingStrategySellBudget(e,t,a,r,i,s,o){M.debug("calculateOverlappingStrategySellBudget called",arguments);const c=this._decimals,d=await c.fetchDecimals(e),n=await c.fetchDecimals(t),g=B(d,n,a,r,i,s,o);return M.debug("calculateOverlappingStrategySellBudget info:",{baseDecimals:d,budget:g}),g}async calculateOverlappingStrategyBuyBudget(e,t,a,r,i,s,o){M.debug("calculateOverlappingStrategyBuyBudget called",arguments);const c=this._decimals,d=await c.fetchDecimals(e),n=await c.fetchDecimals(t),g=S(d,n,a,r,i,s,o);return M.debug("calculateOverlappingStrategyBuyBudget info:",{quoteDecimals:n,budget:g}),g}async createBuySellStrategy(e,t,a,r,i,s,o,c,d,n,g){M.debug("createBuySellStrategy called",arguments);const l=this._decimals,u=await l.fetchDecimals(e),m=await l.fetchDecimals(t),y=b(e,t,u,m,a,r,i,s,o,c,d,n),h=w(y);return M.debug("createBuySellStrategy info:",{strategy:y,encStrategy:h}),this._api.composer.createStrategy(h.token0,h.token1,h.order0,h.order1,g)}async updateStrategy(e,t,{buyPriceLow:a,buyPriceHigh:s,buyBudget:o,sellPriceLow:c,sellPriceHigh:d,sellBudget:n},g,l,u){M.debug("updateStrategy called",arguments);const m=y(x(t)),p=await h(m,this._decimals),f=this._decimals,B=await f.fetchDecimals(p.baseToken),S=await f.fetchDecimals(p.quoteToken),P=b(p.baseToken,p.quoteToken,B,S,a??p.buyPriceLow,k(g)?g:s??p.buyPriceHigh,s??p.buyPriceHigh,o??p.buyBudget,c??p.sellPriceLow,k(l)?l:c??p.sellPriceLow,d??p.sellPriceHigh,n??p.sellBudget),_=w(P),D=x(t);return void 0===o&&(_.order1.y=D.order1.y),void 0===n&&(_.order0.y=D.order0.y),void 0===a&&void 0===s&&(_.order1.A=D.order1.A,_.order1.B=D.order1.B),void 0===c&&void 0===d&&(_.order0.A=D.order0.A,_.order0.B=D.order0.B),void 0!==o&&(k(g)||(g===R.maintain?D.order1.y.isZero()?_.order1.z=r(D.order1.z,_.order1.y):_.order1.z=i(D.order1.z,_.order1.y,D.order1.y):_.order1.z=_.order1.y)),void 0!==n&&(k(l)||(l===R.maintain?D.order0.y.isZero()?_.order0.z=r(D.order0.z,_.order0.y):_.order0.z=i(D.order0.z,_.order0.y,D.order0.y):_.order0.z=_.order0.y)),void 0===a&&void 0===s||g!==R.reset&&void 0!==g||(_.order1.z=_.order1.y),void 0===c&&void 0===d||l!==R.reset&&void 0!==l||(_.order0.z=_.order0.y),M.debug("updateStrategy info:",{baseDecimals:B,quoteDecimals:S,decodedOriginal:m,originalStrategy:p,newStrategy:P,newEncodedStrategy:_}),this._api.composer.updateStrategy(O.from(e),_.token0,_.token1,[D.order0,D.order1],[_.order0,_.order1],u)}async deleteStrategy(e){return M.debug("deleteStrategy called",arguments),this._api.composer.deleteStrategy(O.from(e))}async getRateLiquidityDepthsByPair(t,a,r){M.debug("getRateLiquidityDepthByPair called",arguments);const i=Object.values(await this._cache.getOrdersByPair(t,a)).map(_),s=this._decimals,o=await s.fetchDecimals(t),c=await s.fetchDecimals(a),d=r.map((e=>new j(P(e,c,o)))),n=g(i,d).map((e=>e.floor().toFixed(0))),l=n.map((t=>e(t,c)));return M.debug("getRateLiquidityDepthByPair info:",{orders:i,depthsWei:n,targetDecimals:c,depthsInTargetDecimals:l}),l}async getMinRateByPair(e,t){M.debug("getMinRateByPair called",arguments);const a=Object.values(await this._cache.getOrdersByPair(e,t)).map(_),r=l(a).toString(),i=this._decimals,s=await i.fetchDecimals(e),o=await i.fetchDecimals(t),c=P(r,s,o);return M.debug("getMinRateByPair info:",{orders:a,minRate:r,sourceDecimals:s,targetDecimals:o,normalizedRate:c}),c}async getMaxRateByPair(e,t){M.debug("getMaxRateByPair called",arguments);const a=Object.values(await this._cache.getOrdersByPair(e,t)).map(_),r=u(a).toString(),i=this._decimals,s=await i.fetchDecimals(e),o=await i.fetchDecimals(t),c=P(r,s,o);return M.debug("getMaxRateByPair info:",{orders:a,maxRate:r,sourceDecimals:s,targetDecimals:o,normalizedRate:c}),c}}export{R as MarginalPriceOptions,q as Toolkit,k as isMarginalPriceValue}; | ||
import{formatUnits as e,parseUnits as t,tenPow as a,BigNumberMax as r,mulDiv as i}from"../../utils/numerics/index.js";import{MatchType as o}from"../../common/types/index.js";import{Decimals as s}from"../../utils/decimals/index.js";import{matchByTargetAmount as d,matchBySourceAmount as c}from"../../trade-matcher/match/index.js";import{getEncodedTradeSourceAmount as n}from"../../trade-matcher/trade/index.js";import{getDepths as g,getMinRate as l,getMaxRate as u}from"../stats/index.js";import{Logger as m}from"../../common/logger/index.js";import{decodeStrategy as y,parseStrategy as h,addFee as p,subtractFee as f,calculateOverlappingSellBudget as B,calculateOverlappingBuyBudget as S,buildStrategyObject as b,encodeStrategy as w,normalizeRate as P}from"../utils/index.js";import{decodeOrder as _}from"../../utils/encoders/index.js";import{ordersMapStrToBN as D,matchActionBNToStr as v,ordersMapBNToStr as A,tradeActionStrToBN as T,encodedStrategyStrToBN as x}from"../../utils/serializers/index.js";import{BigNumber as O}from"../../node_modules/@ethersproject/bignumber/lib.esm/bignumber/index.js";import{Decimal as j}from"../../node_modules/decimal.js/decimal/index.js";const z=new m("Toolkit.ts");var M;function R(e){return void 0!==e&&e!==M.reset&&e!==M.maintain}!function(e){e.reset="RESET",e.maintain="MAINTAIN"}(M||(M={}));class k{_api;_decimals;_cache;constructor(e,t,a){z.debug("SDK class constructor called with",arguments),this._api=e,this._cache=t;this._decimals=new s((async e=>await(a?.(e))??await this._api.reader.getDecimalsByAddress(e)))}static getMatchActions(e,t,a,r=o.Fast,i){const s=D(a);let n;return n=t?d(O.from(e),s,[r],i):c(O.from(e),s,[r],i),n[r]?.map(v)??[]}async hasLiquidityByPair(e,t){z.debug("hasLiquidityByPair called",arguments);const a=await this._cache.getOrdersByPair(e,t);return z.debug("hasLiquidityByPair info:",{orders:a}),Object.keys(a).length>0}async getLiquidityByPair(t,a){z.debug("getLiquidityByPair called",arguments);const r=await this._cache.getOrdersByPair(t,a),i=Object.values(r).reduce(((e,{y:t})=>e.add(t)),O.from(0)),o=await this._decimals.fetchDecimals(a),s=e(i,o);return z.debug("getLiquidityByPair info:",{orders:r,liquidityWei:i,targetToken:a,decimals:o,liquidity:s}),s}async getMaxSourceAmountByPair(t,a){z.debug("getMaxSourceAmountByPair called",arguments);const r=await this._cache.getOrdersByPair(t,a),i=Object.values(r).reduce(((e,t)=>e.add(n(t.y,t))),O.from(0)),o=await this._decimals.fetchDecimals(t),s=e(i,o);return z.debug("getMaxSourceAmountByPair info:",{orders:r,maxSourceAmountWei:i,sourceToken:t,decimals:o,maxSourceAmount:s}),s}async getStrategyById(e){let t;z.debug("getStrategyById called",arguments),this._cache&&(t=await this._cache.getStrategyById(e)),t?z.debug("getStrategyById fetched from cache"):(z.debug("getStrategyById fetching from chain"),t=await this._api.reader.strategy(O.from(e)));const a=y(t),r=await h(a,this._decimals);return z.debug("getStrategyById info:",{id:e,encodedStrategy:t,decodedStrategy:a,strategy:r}),r}async getStrategiesByPair(e,t){let a;z.debug("getStrategiesByPair called",arguments),this._cache&&(a=await this._cache.getStrategiesByPair(e,t)),a?z.debug("getStrategiesByPair fetched from cache"):(z.debug("getStrategiesByPair fetching from chain"),a=await this._api.reader.strategiesByPair(e,t));const r=a.map(y),i=await Promise.all(r.map((async e=>await h(e,this._decimals))));return z.debug("getStrategiesByPair info:",{token0:e,token1:t,encodedStrategies:a,decodedStrategies:r,strategies:i}),i}async getUserStrategies(e){z.debug("getUserStrategies called",arguments);const t=await this._api.reader.tokensByOwner(e);let a=[],r=t;if(this._cache&&(r=t.reduce(((e,t)=>{const r=this._cache.getStrategyById(t);return r?a.push(r):e.push(t),e}),[])),r.length>0){const e=await this._api.reader.strategies(r);a=[...a,...e]}const i=a.map(y),o=await Promise.all(i.map((async e=>await h(e,this._decimals))));return z.debug("getUserStrategies info:",{ids:t,encodedStrategies:a,decodedStrategies:i,strategies:o}),o}async getMatchParams(e,a,r,i){z.debug("getMatchParams called",arguments);const o=this._decimals,s=await o.fetchDecimals(e),d=await o.fetchDecimals(a),c=await this._cache.getOrdersByPair(e,a),n=t(r,i?d:s);return{orders:A(c),amountWei:n.toString(),sourceDecimals:s,targetDecimals:d}}async getTradeData(e,t,a,r,i=o.Fast,s){z.debug("getTradeData called",arguments);const{orders:d,amountWei:c}=await this.getMatchParams(e,t,a,r),n=k.getMatchActions(c,r,d,i,s),g=await this.getTradeDataFromActions(e,t,r,n);return z.debug("getTradeData info:",{orders:d,amount:a,amountWei:c,res:g}),g}async getTradeDataFromActions(t,r,i,o){z.debug("getTradeDataFromActions called",arguments);const s=await this._cache.getTradingFeePPMByPair(t,r);if(void 0===s)throw new Error(`tradingFeePPM is undefined for this pair: ${t}-${r}`);const d=this._decimals,c=await d.fetchDecimals(t),n=await d.fetchDecimals(r),g=[],l=[];let u,m,y,h=O.from(0),B=O.from(0);if(o.forEach((t=>{g.push({strategyId:t.id,amount:t.input}),i?l.push({id:t.id,sourceAmount:e(p(t.output,s).floor().toFixed(0),c),targetAmount:e(t.input,n)}):l.push({id:t.id,sourceAmount:e(t.input,c),targetAmount:e(f(t.output,s).floor().toFixed(0),n)}),B=B.add(t.input),h=h.add(t.output)})),i?(u=p(h,s).floor().toFixed(0),m=B.toString()):(u=B.toString(),m=f(h,s).floor().toFixed(0)),new j(u).isZero()||new j(m).isZero())y={tradeActions:g,actionsTokenRes:l,totalSourceAmount:"0",totalTargetAmount:"0",effectiveRate:"0",actionsWei:o};else{const t=new j(m).div(u).times(a(c,n)).toString();y={tradeActions:g,actionsTokenRes:l,totalSourceAmount:e(u,c),totalTargetAmount:e(m,n),effectiveRate:t,actionsWei:o}}return z.debug("getTradeDataFromActions info:",{sourceDecimals:c,targetDecimals:n,actionsWei:o,totalInput:B,totalOutput:h,tradingFeePPM:s,res:y}),y}async composeTradeByTargetTransaction(e,a,r,i,o,s){z.debug("composeTradeByTargetTransaction called",arguments);const d=await this._decimals.fetchDecimals(e);return this._api.composer.tradeByTargetAmount(e,a,r.map(T),i,t(o,d),s)}async composeTradeBySourceTransaction(e,a,r,i,o,s){z.debug("composeTradeBySourceTransaction called",arguments);const d=await this._decimals.fetchDecimals(a);return this._api.composer.tradeBySourceAmount(e,a,r.map(T),i,t(o,d),s)}async calculateOverlappingStrategySellBudget(e,t,a,r,i,o,s){z.debug("calculateOverlappingStrategySellBudget called",arguments);const d=this._decimals,c=await d.fetchDecimals(e),n=await d.fetchDecimals(t),g=B(c,n,a,r,i,o,s);return z.debug("calculateOverlappingStrategySellBudget info:",{baseDecimals:c,budget:g}),g}async calculateOverlappingStrategyBuyBudget(e,t,a,r,i,o,s){z.debug("calculateOverlappingStrategyBuyBudget called",arguments);const d=this._decimals,c=await d.fetchDecimals(e),n=await d.fetchDecimals(t),g=S(c,n,a,r,i,o,s);return z.debug("calculateOverlappingStrategyBuyBudget info:",{quoteDecimals:n,budget:g}),g}async createBuySellStrategy(e,t,a,r,i,o,s,d,c,n,g){z.debug("createBuySellStrategy called",arguments);const l=this._decimals,u=await l.fetchDecimals(e),m=await l.fetchDecimals(t),y=b(e,t,u,m,a,r,i,o,s,d,c,n),h=w(y);return z.debug("createBuySellStrategy info:",{strategy:y,encStrategy:h}),this._api.composer.createStrategy(h.token0,h.token1,h.order0,h.order1,g)}async updateStrategy(e,t,{buyPriceLow:a,buyPriceHigh:o,buyBudget:s,sellPriceLow:d,sellPriceHigh:c,sellBudget:n},g,l,u){z.debug("updateStrategy called",arguments);const m=y(x(t)),p=await h(m,this._decimals),f=this._decimals,B=await f.fetchDecimals(p.baseToken),S=await f.fetchDecimals(p.quoteToken),P=b(p.baseToken,p.quoteToken,B,S,a??p.buyPriceLow,R(g)?g:o??p.buyPriceHigh,o??p.buyPriceHigh,s??p.buyBudget,d??p.sellPriceLow,R(l)?l:d??p.sellPriceLow,c??p.sellPriceHigh,n??p.sellBudget),_=w(P),D=x(t);return void 0===s&&void 0===a&&void 0===o&&void 0===g&&(_.order1.y=D.order1.y,_.order1.z=D.order1.z,_.order1.A=D.order1.A,_.order1.B=D.order1.B),void 0===n&&void 0===d&&void 0===c&&void 0===l&&(_.order0.y=D.order0.y,_.order0.z=D.order0.z,_.order0.A=D.order0.A,_.order0.B=D.order0.B),void 0===s&&(_.order1.y=D.order1.y),void 0===n&&(_.order0.y=D.order0.y),void 0===a&&void 0===o&&(_.order1.A=D.order1.A,_.order1.B=D.order1.B),void 0===d&&void 0===c&&(_.order0.A=D.order0.A,_.order0.B=D.order0.B),void 0!==s&&(R(g)||(g===M.maintain?D.order1.y.isZero()?_.order1.z=r(D.order1.z,_.order1.y):_.order1.z=i(D.order1.z,_.order1.y,D.order1.y):_.order1.z=_.order1.y)),void 0!==n&&(R(l)||(l===M.maintain?D.order0.y.isZero()?_.order0.z=r(D.order0.z,_.order0.y):_.order0.z=i(D.order0.z,_.order0.y,D.order0.y):_.order0.z=_.order0.y)),void 0===a&&void 0===o||g!==M.reset&&void 0!==g||(_.order1.z=_.order1.y),void 0===d&&void 0===c||l!==M.reset&&void 0!==l||(_.order0.z=_.order0.y),z.debug("updateStrategy info:",{baseDecimals:B,quoteDecimals:S,decodedOriginal:m,originalStrategy:p,newStrategy:P,newEncodedStrategy:_}),this._api.composer.updateStrategy(O.from(e),_.token0,_.token1,[D.order0,D.order1],[_.order0,_.order1],u)}async deleteStrategy(e){return z.debug("deleteStrategy called",arguments),this._api.composer.deleteStrategy(O.from(e))}async getRateLiquidityDepthsByPair(t,a,r){z.debug("getRateLiquidityDepthByPair called",arguments);const i=Object.values(await this._cache.getOrdersByPair(t,a)).map(_),o=this._decimals,s=await o.fetchDecimals(t),d=await o.fetchDecimals(a),c=r.map((e=>new j(P(e,d,s)))),n=g(i,c).map((e=>e.floor().toFixed(0))),l=n.map((t=>e(t,d)));return z.debug("getRateLiquidityDepthByPair info:",{orders:i,depthsWei:n,targetDecimals:d,depthsInTargetDecimals:l}),l}async getMinRateByPair(e,t){z.debug("getMinRateByPair called",arguments);const a=Object.values(await this._cache.getOrdersByPair(e,t)).map(_),r=l(a).toString(),i=this._decimals,o=await i.fetchDecimals(e),s=await i.fetchDecimals(t),d=P(r,o,s);return z.debug("getMinRateByPair info:",{orders:a,minRate:r,sourceDecimals:o,targetDecimals:s,normalizedRate:d}),d}async getMaxRateByPair(e,t){z.debug("getMaxRateByPair called",arguments);const a=Object.values(await this._cache.getOrdersByPair(e,t)).map(_),r=u(a).toString(),i=this._decimals,o=await i.fetchDecimals(e),s=await i.fetchDecimals(t),d=P(r,o,s);return z.debug("getMaxRateByPair info:",{orders:a,maxRate:r,sourceDecimals:o,targetDecimals:s,normalizedRate:d}),d}}export{M as MarginalPriceOptions,k as Toolkit,R as isMarginalPriceValue}; |
import { BigNumber, Decimal } from './numerics'; | ||
import { DecodedOrder, EncodedOrder } from '../common/types'; | ||
export declare const encodeRate: (value: Decimal) => Decimal; | ||
export declare const encodeRate: (value: Decimal) => BigNumber; | ||
export declare const decodeRate: (value: Decimal) => Decimal; | ||
@@ -11,2 +11,10 @@ export declare const encodeFloat: (value: BigNumber) => BigNumber; | ||
]; | ||
export declare const isOrderEncodable: (order: DecodedOrder) => boolean; | ||
/** | ||
* Checks if the rates are equal after scaling them | ||
* @param {string} x - the first rate | ||
* @param {string} y - the second rate | ||
* @returns {boolean} - true if the rates are equal after scaling, false otherwise | ||
*/ | ||
export declare const areScaledRatesEqual: (x: string, y: string) => boolean; | ||
export declare const encodeOrder: (order: DecodedOrder, z?: BigNumber) => EncodedOrder; | ||
@@ -13,0 +21,0 @@ export declare const decodeOrder: (order: EncodedOrder) => DecodedOrder; |
@@ -1,1 +0,1 @@ | ||
import{DecToBn as t,ONE as e,BnToDec as i}from"../numerics/index.js";import{BigNumber as n}from"../../node_modules/@ethersproject/bignumber/lib.esm/bignumber/index.js";import{Decimal as o}from"../../node_modules/decimal.js/decimal/index.js";function r(t){return t.gt(0)?o.log2(t.toString()).add(1).floor().toNumber():0}const s=n=>{const o=t(n.sqrt().mul(e).floor()),s=r(o.div(e));return i(o.shr(s).shl(s))},a=t=>t.div(e).pow(2),l=t=>{const i=r(t.div(e)),o=t.shr(i);return n.from(e).mul(i).or(o)},g=t=>t.mod(e).shl(t.div(e).toNumber()),d=([t,e])=>{const i=new o(t.liquidity),n=new o(t.lowestRate),r=new o(t.highestRate),s=new o(e.liquidity),a=new o(e.lowestRate),l=new o(e.highestRate);return i.eq(0)&&s.gt(0)&&a.gt(0)&&l.gt(0)?[u(t,w(e)),u(e)]:s.eq(0)&&i.gt(0)&&n.gt(0)&&r.gt(0)?[u(t),u(e,w(t))]:[u(t),u(e)]},u=(e,i)=>{const n=new o(e.liquidity),r=new o(e.lowestRate),a=new o(e.highestRate),g=new o(e.marginalRate);if(!(a.gte(g)&&g.gt(r)||a.eq(g)&&g.eq(r)||a.gt(g)&&g.eq(r)&&n.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 = ${a}, marginalRate = ${g}, lowestRate = ${r}), liquidity = ${n}`);const d=t(n),u=t(s(r)),m=t(s(a)),h=t(s(g));return{y:d,z:void 0!==i?i:m.eq(h)||d.isZero()?d:d.mul(m.sub(u)).div(h.sub(u)),A:l(m.sub(u)),B:l(u)}},m=t=>{const e=i(t.y),n=i(t.z),o=i(g(t.A)),r=i(g(t.B));return{liquidity:e.toString(),lowestRate:a(r).toString(),highestRate:a(r.add(o)).toString(),marginalRate:a(e.eq(n)?r.add(o):r.add(o.mul(e).div(n))).toString()}},h=(e,i)=>{const n=w(e),r=t(s(new o(i.lowestRate))),a=t(s(new o(i.highestRate))),l=t(s(new o(i.marginalRate)));return n.mul(l.sub(r)).div(a.sub(r)).toString()},w=e=>{const n=i(u(e).z),r=new o(e.lowestRate),s=new o(e.highestRate),a=r.mul(s).sqrt();return t(n.div(a).floor())};export{w as calculateCorrelatedZ,h as calculateRequiredLiquidity,g as decodeFloat,m as decodeOrder,a as decodeRate,l as encodeFloat,u as encodeOrder,d as encodeOrders,s as encodeRate}; | ||
import{DecToBn as t,ONE as e,BnToDec as i}from"../numerics/index.js";import{BigNumber as n}from"../../node_modules/@ethersproject/bignumber/lib.esm/bignumber/index.js";import{Decimal as r}from"../../node_modules/decimal.js/decimal/index.js";function o(t){return t.gt(0)?r.log2(t.toString()).add(1).floor().toNumber():0}const s=i=>{const n=t(i.sqrt().mul(e).floor()),r=o(n.div(e));return n.shr(r).shl(r)},a=t=>t.div(e).pow(2),l=t=>{const i=o(t.div(e)),r=t.shr(i);return n.from(e).mul(i).or(r)},g=t=>t.mod(e).shl(t.div(e).toNumber()),u=([t,e])=>{const i=new r(t.liquidity),n=new r(t.lowestRate),o=new r(t.highestRate),s=new r(e.liquidity),a=new r(e.lowestRate),l=new r(e.highestRate);return i.eq(0)&&s.gt(0)&&a.gt(0)&&l.gt(0)?[w(t,c(e)),w(e)]:s.eq(0)&&i.gt(0)&&n.gt(0)&&o.gt(0)?[w(t),w(e,c(t))]:[w(t),w(e)]},d=t=>{try{return w(t),!0}catch(t){return!1}},m=(t,e)=>{const i=new r(t),n=new r(e),o=s(i),a=s(n);return o.eq(a)},w=(e,i)=>{const n=new r(e.liquidity),o=new r(e.lowestRate),a=new r(e.highestRate),g=new r(e.marginalRate),u=t(n),d=s(o),m=s(a),w=s(g);if(!(m.gte(w)&&w.gt(d)||m.eq(w)&&w.eq(d)||m.gt(w)&&w.eq(d)&&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 = ${a}, marginalRate = ${g}, lowestRate = ${o}), liquidity = ${n}`);return{y:u,z:void 0!==i?i:m.eq(w)||u.isZero()?u:u.mul(m.sub(d)).div(w.sub(d)),A:l(m.sub(d)),B:l(d)}},h=t=>{const e=i(t.y),n=i(t.z),r=i(g(t.A)),o=i(g(t.B));return{liquidity:e.toString(),lowestRate:a(o).toString(),highestRate:a(o.add(r)).toString(),marginalRate:a(e.eq(n)?o.add(r):o.add(r.mul(e).div(n))).toString()}},R=(t,e)=>{const i=c(t),n=s(new r(e.lowestRate)),o=s(new r(e.highestRate)),a=s(new r(e.marginalRate));return i.mul(a.sub(n)).div(o.sub(n)).toString()},c=e=>{const n=i(w(e).z),o=new r(e.lowestRate),s=new r(e.highestRate),a=o.mul(s).sqrt();return t(n.div(a).floor())};export{m as areScaledRatesEqual,c as calculateCorrelatedZ,R as calculateRequiredLiquidity,g as decodeFloat,h as decodeOrder,a as decodeRate,l as encodeFloat,w as encodeOrder,u as encodeOrders,s as encodeRate,d as isOrderEncodable}; |
@@ -1,1 +0,1 @@ | ||
export{Decimals}from"./decimals/index.js";export{calculateCorrelatedZ,calculateRequiredLiquidity,decodeFloat,decodeOrder,decodeRate,encodeFloat,encodeOrder,encodeOrders,encodeRate}from"./encoders/index.js";export{encodedOrderBNToStr,encodedOrderStrToBN,encodedStrategyBNToStr,encodedStrategyStrToBN,matchActionBNToStr,ordersMapBNToStr,ordersMapStrToBN,replaceBigNumbersWithStrings,tradeActionStrToBN}from"./serializers/index.js";export{BigNumberMax,BigNumberMin,BnToDec,DecToBn,ONE,TEN,formatUnits,mulDiv,parseUnits,tenPow,trimDecimal}from"./numerics/index.js";export{Decimal}from"../node_modules/decimal.js/decimal/index.js";export{BigNumber}from"../node_modules/@ethersproject/bignumber/lib.esm/bignumber/index.js"; | ||
export{Decimals}from"./decimals/index.js";export{areScaledRatesEqual,calculateCorrelatedZ,calculateRequiredLiquidity,decodeFloat,decodeOrder,decodeRate,encodeFloat,encodeOrder,encodeOrders,encodeRate,isOrderEncodable}from"./encoders/index.js";export{encodedOrderBNToStr,encodedOrderStrToBN,encodedStrategyBNToStr,encodedStrategyStrToBN,matchActionBNToStr,ordersMapBNToStr,ordersMapStrToBN,replaceBigNumbersWithStrings,tradeActionStrToBN}from"./serializers/index.js";export{BigNumberMax,BigNumberMin,BnToDec,DecToBn,ONE,TEN,formatUnits,mulDiv,parseUnits,tenPow,trimDecimal}from"./numerics/index.js";export{Decimal}from"../node_modules/decimal.js/decimal/index.js";export{BigNumber}from"../node_modules/@ethersproject/bignumber/lib.esm/bignumber/index.js"; |
@@ -5,3 +5,3 @@ { | ||
"source": "src/index.ts", | ||
"version": "0.0.98-DEV", | ||
"version": "0.0.99-DEV", | ||
"description": "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 fulfill trades", | ||
@@ -96,12 +96,12 @@ "main": "dist/index.cjs", | ||
"@rollup/plugin-node-resolve": "^15.2.3", | ||
"@rollup/plugin-typescript": "^11.1.5", | ||
"@typechain/ethers-v5": "^11.1.1", | ||
"@types/chai": "^4.3.10", | ||
"@rollup/plugin-typescript": "^11.1.6", | ||
"@typechain/ethers-v5": "^11.1.2", | ||
"@types/chai": "^4.3.11", | ||
"@types/mocha": "^10.0.0", | ||
"@types/node": "^18.18.8", | ||
"@types/node": "^18.19.17", | ||
"@types/sinon": "^10.0.15", | ||
"@typescript-eslint/eslint-plugin": "^6.12.0", | ||
"@typescript-eslint/eslint-plugin": "^6.21.0", | ||
"@typescript-eslint/parser": "^6.12.0", | ||
"chai": "^4.3.10", | ||
"eslint": "^8.46.0", | ||
"eslint": "^8.57.0", | ||
"mocha": "^10.1.0", | ||
@@ -111,6 +111,6 @@ "rollup": "^4.5.0", | ||
"sinon": "^16.0.0", | ||
"ts-node": "^10.9.1", | ||
"tslib": "^2.6.2", | ||
"typechain": "^8.3.1", | ||
"typescript": "^5.2.2" | ||
"ts-node": "^10.9.2", | ||
"tslib": "^2.7.0", | ||
"typechain": "^8.3.2", | ||
"typescript": "^5.5.4" | ||
}, | ||
@@ -117,0 +117,0 @@ "dependencies": { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 2 instances in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 2 instances in 1 package
923687
7737