@bancor/carbon-sdk
Advanced tools
Comparing version 0.0.94-DEV to 0.0.95-DEV
@@ -1,1 +0,1 @@ | ||
export{MarginalPriceOptions,Toolkit,isMarginalPriceValue}from"./Toolkit/index.js";export{PPM_RESOLUTION,addFee,buildStrategyObject,calculateOverlappingBuyBudget,calculateOverlappingPriceRanges,calculateOverlappingSellBudget,createFromBuyOrder,createFromSellOrder,createOrders,decodeStrategy,encodeStrategy,enforcePriceRange,normalizeInvertedRate,normalizeRate,parseStrategy,subtractFee}from"./utils/index.js"; | ||
export{MarginalPriceOptions,Toolkit,isMarginalPriceValue}from"./Toolkit/index.js";export{PPM_RESOLUTION,addFee,buildStrategyObject,calculateOverlappingBuyBudget,calculateOverlappingPrices,calculateOverlappingSellBudget,createFromBuyOrder,createFromSellOrder,createOrders,decodeStrategy,encodeStrategy,enforcePriceRange,normalizeInvertedRate,normalizeRate,parseStrategy,subtractFee}from"./utils/index.js"; |
@@ -243,29 +243,2 @@ import { PopulatedTransaction } from '@ethersproject/contracts'; | ||
/** | ||
* Calculate the overlapping strategy prices. Returns it with correct decimals | ||
* | ||
* @param {string} quoteToken - The address of the quote token. | ||
* @param {string} buyPriceLow - The minimum buy price for the strategy, in in `quoteToken` per 1 `baseToken`, as a string. | ||
* @param {string} sellPriceHigh - The maximum sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. | ||
* @param {string} marketPrice - The market price, in `quoteToken` per 1 `baseToken`, as a string. | ||
* @param {string} spreadPercentage - The spread percentage, e.g. for 10%, enter `10`. | ||
* @return {Promise<{ | ||
* buyPriceLow: string; | ||
* buyPriceHigh: string; | ||
* buyPriceMarginal: string; | ||
* sellPriceLow: string; | ||
* sellPriceHigh: string; | ||
* sellPriceMarginal: string; | ||
* marketPrice: string; | ||
* }>} The calculated overlapping strategy prices. | ||
*/ | ||
calculateOverlappingStrategyPrices(quoteToken: string, buyPriceLow: string, sellPriceHigh: string, marketPrice: string, spreadPercentage: string): Promise<{ | ||
buyPriceLow: string; | ||
buyPriceHigh: string; | ||
buyPriceMarginal: string; | ||
sellPriceLow: string; | ||
sellPriceHigh: string; | ||
sellPriceMarginal: string; | ||
marketPrice: string; | ||
}>; | ||
/** | ||
* Calculates the sell budget given a buy budget of an overlapping strategy. | ||
@@ -272,0 +245,0 @@ * |
@@ -1,1 +0,1 @@ | ||
import{formatUnits as e,parseUnits as t,tenPow as a,trimDecimal as r,BigNumberMax as i,mulDiv as s}from"../../utils/numerics/index.js";import{MatchType as c}from"../../common/types/index.js";import{Decimals as o}from"../../utils/decimals/index.js";import{matchByTargetAmount as d,matchBySourceAmount as n}from"../../trade-matcher/match/index.js";import{getEncodedTradeSourceAmount as l}from"../../trade-matcher/trade/index.js";import{getDepths as u,getMinRate as g,getMaxRate as m}from"../stats/index.js";import{Logger as y}from"../../common/logger/index.js";import{decodeStrategy as h,parseStrategy as p,addFee as f,subtractFee as P,calculateOverlappingPriceRanges as b,calculateOverlappingSellBudget as w,calculateOverlappingBuyBudget as B,buildStrategyObject as S,encodeStrategy as D,normalizeRate as _}from"../utils/index.js";import{decodeOrder as v}from"../../utils/encoders/index.js";import{ordersMapStrToBN as T,matchActionBNToStr as A,ordersMapBNToStr as x,tradeActionStrToBN as O,encodedStrategyStrToBN as M}from"../../utils/serializers/index.js";import{BigNumber as j}from"../../node_modules/@ethersproject/bignumber/lib.esm/bignumber/index.js";import{Decimal as k}from"../../node_modules/decimal.js/decimal/index.js";const R=new y("Toolkit.ts");var L;function q(e){return void 0!==e&&e!==L.reset&&e!==L.maintain}!function(e){e.reset="RESET",e.maintain="MAINTAIN"}(L||(L={}));class z{_api;_decimals;_cache;constructor(e,t,a){R.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=c.Fast,i){const s=T(a);let o;return o=t?d(j.from(e),s,[r],i):n(j.from(e),s,[r],i),o[r]?.map(A)??[]}async hasLiquidityByPair(e,t){R.debug("hasLiquidityByPair called",arguments);const a=await this._cache.getOrdersByPair(e,t);return R.debug("hasLiquidityByPair info:",{orders:a}),Object.keys(a).length>0}async getLiquidityByPair(t,a){R.debug("getLiquidityByPair called",arguments);const r=await this._cache.getOrdersByPair(t,a),i=Object.values(r).reduce(((e,{y:t})=>e.add(t)),j.from(0)),s=await this._decimals.fetchDecimals(a),c=e(i,s);return R.debug("getLiquidityByPair info:",{orders:r,liquidityWei:i,targetToken:a,decimals:s,liquidity:c}),c}async getMaxSourceAmountByPair(t,a){R.debug("getMaxSourceAmountByPair called",arguments);const r=await this._cache.getOrdersByPair(t,a),i=Object.values(r).reduce(((e,t)=>e.add(l(t.y,t))),j.from(0)),s=await this._decimals.fetchDecimals(t),c=e(i,s);return R.debug("getMaxSourceAmountByPair info:",{orders:r,maxSourceAmountWei:i,sourceToken:t,decimals:s,maxSourceAmount:c}),c}async getStrategiesByPair(e,t){let a;R.debug("getStrategiesByPair called",arguments),this._cache&&(a=await this._cache.getStrategiesByPair(e,t)),a?R.debug("getStrategiesByPair fetched from cache"):(R.debug("getStrategiesByPair fetching from chain"),a=await this._api.reader.strategiesByPair(e,t));const r=a.map(h),i=await Promise.all(r.map((async e=>await p(e,this._decimals))));return R.debug("getStrategiesByPair info:",{token0:e,token1:t,encodedStrategies:a,decodedStrategies:r,strategies:i}),i}async getUserStrategies(e){R.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(h),s=await Promise.all(i.map((async e=>await p(e,this._decimals))));return R.debug("getUserStrategies info:",{ids:t,encodedStrategies:a,decodedStrategies:i,strategies:s}),s}async getMatchParams(e,a,r,i){R.debug("getMatchParams called",arguments);const s=this._decimals,c=await s.fetchDecimals(e),o=await s.fetchDecimals(a),d=await this._cache.getOrdersByPair(e,a),n=t(r,i?o:c);return{orders:x(d),amountWei:n.toString(),sourceDecimals:c,targetDecimals:o}}async getTradeData(e,t,a,r,i=c.Fast,s){R.debug("getTradeData called",arguments);const{orders:o,amountWei:d}=await this.getMatchParams(e,t,a,r),n=z.getMatchActions(d,r,o,i,s),l=await this.getTradeDataFromActions(e,t,r,n);return R.debug("getTradeData info:",{orders:o,amount:a,amountWei:d,res:l}),l}async getTradeDataFromActions(t,r,i,s){R.debug("getTradeDataFromActions called",arguments);const c=await this._cache.getTradingFeePPMByPair(t,r);if(void 0===c)throw new Error(`tradingFeePPM is undefined for this pair: ${t}-${r}`);const o=this._decimals,d=await o.fetchDecimals(t),n=await o.fetchDecimals(r),l=[],u=[];let g,m,y,h=j.from(0),p=j.from(0);if(s.forEach((t=>{l.push({strategyId:t.id,amount:t.input}),i?u.push({id:t.id,sourceAmount:e(f(t.output,c).floor().toFixed(0),d),targetAmount:e(t.input,n)}):u.push({id:t.id,sourceAmount:e(t.input,d),targetAmount:e(P(t.output,c).floor().toFixed(0),n)}),p=p.add(t.input),h=h.add(t.output)})),i?(g=f(h,c).floor().toFixed(0),m=p.toString()):(g=p.toString(),m=P(h,c).floor().toFixed(0)),new k(g).isZero()||new k(m).isZero())y={tradeActions:l,actionsTokenRes:u,totalSourceAmount:"0",totalTargetAmount:"0",effectiveRate:"0",actionsWei:s};else{const t=new k(m).div(g).times(a(d,n)).toString();y={tradeActions:l,actionsTokenRes:u,totalSourceAmount:e(g,d),totalTargetAmount:e(m,n),effectiveRate:t,actionsWei:s}}return R.debug("getTradeDataFromActions info:",{sourceDecimals:d,targetDecimals:n,actionsWei:s,totalInput:p,totalOutput:h,tradingFeePPM:c,res:y}),y}async composeTradeByTargetTransaction(e,a,r,i,s,c){R.debug("composeTradeByTargetTransaction called",arguments);const o=await this._decimals.fetchDecimals(e);return this._api.composer.tradeByTargetAmount(e,a,r.map(O),i,t(s,o),c)}async composeTradeBySourceTransaction(e,a,r,i,s,c){R.debug("composeTradeBySourceTransaction called",arguments);const o=await this._decimals.fetchDecimals(a);return this._api.composer.tradeBySourceAmount(e,a,r.map(O),i,t(s,o),c)}async calculateOverlappingStrategyPrices(e,t,a,i,s){R.debug("calculateOverlappingStrategyPrices called",arguments);const c=this._decimals,o=await c.fetchDecimals(e),d=b(t,a,i,s),n={buyPriceLow:r(t,o),buyPriceHigh:r(d.buyPriceHigh,o),buyPriceMarginal:r(d.buyPriceMarginal,o),sellPriceLow:r(d.sellPriceLow,o),sellPriceHigh:r(a,o),sellPriceMarginal:r(d.sellPriceMarginal,o),marketPrice:r(i,o)};return R.debug("calculateOverlappingStrategyPrices info:",{quoteDecimals:o,result:n}),n}async calculateOverlappingStrategySellBudget(e,t,a,r,i,s,c){R.debug("calculateOverlappingStrategySellBudget called",arguments);const o=this._decimals,d=await o.fetchDecimals(e),n=await o.fetchDecimals(t),l=w(d,n,a,r,i,s,c);return R.debug("calculateOverlappingStrategySellBudget info:",{baseDecimals:d,budget:l}),l}async calculateOverlappingStrategyBuyBudget(e,t,a,r,i,s,c){R.debug("calculateOverlappingStrategyBuyBudget called",arguments);const o=this._decimals,d=await o.fetchDecimals(e),n=await o.fetchDecimals(t),l=B(d,n,a,r,i,s,c);return R.debug("calculateOverlappingStrategyBuyBudget info:",{quoteDecimals:n,budget:l}),l}async createBuySellStrategy(e,t,a,r,i,s,c,o,d,n,l){R.debug("createBuySellStrategy called",arguments);const u=this._decimals,g=await u.fetchDecimals(e),m=await u.fetchDecimals(t),y=S(e,t,g,m,a,r,i,s,c,o,d,n),h=D(y);return R.debug("createBuySellStrategy info:",{strategy:y,encStrategy:h}),this._api.composer.createStrategy(h.token0,h.token1,h.order0,h.order1,l)}async updateStrategy(e,t,{buyPriceLow:a,buyPriceHigh:r,buyBudget:c,sellPriceLow:o,sellPriceHigh:d,sellBudget:n},l,u,g){R.debug("updateStrategy called",arguments);const m=h(M(t)),y=await p(m,this._decimals),f=this._decimals,P=await f.fetchDecimals(y.baseToken),b=await f.fetchDecimals(y.quoteToken),w=S(y.baseToken,y.quoteToken,P,b,a??y.buyPriceLow,q(l)?l:r??y.buyPriceHigh,r??y.buyPriceHigh,c??y.buyBudget,o??y.sellPriceLow,q(u)?u:o??y.sellPriceLow,d??y.sellPriceHigh,n??y.sellBudget),B=D(w),_=M(t);return void 0===c&&(B.order1.y=_.order1.y),void 0===n&&(B.order0.y=_.order0.y),void 0===a&&void 0===r&&(B.order1.A=_.order1.A,B.order1.B=_.order1.B),void 0===o&&void 0===d&&(B.order0.A=_.order0.A,B.order0.B=_.order0.B),void 0!==c&&(q(l)||(l===L.maintain?_.order1.y.isZero()?B.order1.z=i(_.order1.z,B.order1.y):B.order1.z=s(_.order1.z,B.order1.y,_.order1.y):B.order1.z=B.order1.y)),void 0!==n&&(q(u)||(u===L.maintain?_.order0.y.isZero()?B.order0.z=i(_.order0.z,B.order0.y):B.order0.z=s(_.order0.z,B.order0.y,_.order0.y):B.order0.z=B.order0.y)),void 0===a&&void 0===r||l!==L.reset&&void 0!==l||(B.order1.z=B.order1.y),void 0===o&&void 0===d||u!==L.reset&&void 0!==u||(B.order0.z=B.order0.y),R.debug("updateStrategy info:",{baseDecimals:P,quoteDecimals:b,decodedOriginal:m,originalStrategy:y,newStrategy:w,newEncodedStrategy:B}),this._api.composer.updateStrategy(j.from(e),B.token0,B.token1,[_.order0,_.order1],[B.order0,B.order1],g)}async deleteStrategy(e){return R.debug("deleteStrategy called",arguments),this._api.composer.deleteStrategy(j.from(e))}async getRateLiquidityDepthsByPair(t,a,r){R.debug("getRateLiquidityDepthByPair called",arguments);const i=Object.values(await this._cache.getOrdersByPair(t,a)).map(v),s=this._decimals,c=await s.fetchDecimals(t),o=await s.fetchDecimals(a),d=r.map((e=>new k(_(e,o,c)))),n=u(i,d).map((e=>e.floor().toFixed(0))),l=n.map((t=>e(t,o)));return R.debug("getRateLiquidityDepthByPair info:",{orders:i,depthsWei:n,targetDecimals:o,depthsInTargetDecimals:l}),l}async getMinRateByPair(e,t){R.debug("getMinRateByPair called",arguments);const a=Object.values(await this._cache.getOrdersByPair(e,t)).map(v),r=g(a).toString(),i=this._decimals,s=await i.fetchDecimals(e),c=await i.fetchDecimals(t),o=_(r,s,c);return R.debug("getMinRateByPair info:",{orders:a,minRate:r,sourceDecimals:s,targetDecimals:c,normalizedRate:o}),o}async getMaxRateByPair(e,t){R.debug("getMaxRateByPair called",arguments);const a=Object.values(await this._cache.getOrdersByPair(e,t)).map(v),r=m(a).toString(),i=this._decimals,s=await i.fetchDecimals(e),c=await i.fetchDecimals(t),o=_(r,s,c);return R.debug("getMaxRateByPair info:",{orders:a,maxRate:r,sourceDecimals:s,targetDecimals:c,normalizedRate:o}),o}}export{L as MarginalPriceOptions,z as Toolkit,q 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 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 l,getMinRate as u,getMaxRate as g}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 w,buildStrategyObject as b,encodeStrategy as S,normalizeRate as P}from"../utils/index.js";import{decodeOrder as D}from"../../utils/encoders/index.js";import{ordersMapStrToBN as _,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=_(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 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),l=await this.getTradeDataFromActions(e,t,r,n);return M.debug("getTradeData info:",{orders:c,amount:a,amountWei:d,res:l}),l}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),l=[],u=[];let g,m,y,h=O.from(0),B=O.from(0);if(s.forEach((t=>{l.push({strategyId:t.id,amount:t.input}),i?u.push({id:t.id,sourceAmount:e(p(t.output,o).floor().toFixed(0),d),targetAmount:e(t.input,n)}):u.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?(g=p(h,o).floor().toFixed(0),m=B.toString()):(g=B.toString(),m=f(h,o).floor().toFixed(0)),new j(g).isZero()||new j(m).isZero())y={tradeActions:l,actionsTokenRes:u,totalSourceAmount:"0",totalTargetAmount:"0",effectiveRate:"0",actionsWei:s};else{const t=new j(m).div(g).times(a(d,n)).toString();y={tradeActions:l,actionsTokenRes:u,totalSourceAmount:e(g,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),l=B(d,n,a,r,i,s,o);return M.debug("calculateOverlappingStrategySellBudget info:",{baseDecimals:d,budget:l}),l}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),l=w(d,n,a,r,i,s,o);return M.debug("calculateOverlappingStrategyBuyBudget info:",{quoteDecimals:n,budget:l}),l}async createBuySellStrategy(e,t,a,r,i,s,o,c,d,n,l){M.debug("createBuySellStrategy called",arguments);const u=this._decimals,g=await u.fetchDecimals(e),m=await u.fetchDecimals(t),y=b(e,t,g,m,a,r,i,s,o,c,d,n),h=S(y);return M.debug("createBuySellStrategy info:",{strategy:y,encStrategy:h}),this._api.composer.createStrategy(h.token0,h.token1,h.order0,h.order1,l)}async updateStrategy(e,t,{buyPriceLow:a,buyPriceHigh:s,buyBudget:o,sellPriceLow:c,sellPriceHigh:d,sellBudget:n},l,u,g){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),w=await f.fetchDecimals(p.quoteToken),P=b(p.baseToken,p.quoteToken,B,w,a??p.buyPriceLow,k(l)?l:s??p.buyPriceHigh,s??p.buyPriceHigh,o??p.buyBudget,c??p.sellPriceLow,k(u)?u:c??p.sellPriceLow,d??p.sellPriceHigh,n??p.sellBudget),D=S(P),_=x(t);return void 0===o&&(D.order1.y=_.order1.y),void 0===n&&(D.order0.y=_.order0.y),void 0===a&&void 0===s&&(D.order1.A=_.order1.A,D.order1.B=_.order1.B),void 0===c&&void 0===d&&(D.order0.A=_.order0.A,D.order0.B=_.order0.B),void 0!==o&&(k(l)||(l===R.maintain?_.order1.y.isZero()?D.order1.z=r(_.order1.z,D.order1.y):D.order1.z=i(_.order1.z,D.order1.y,_.order1.y):D.order1.z=D.order1.y)),void 0!==n&&(k(u)||(u===R.maintain?_.order0.y.isZero()?D.order0.z=r(_.order0.z,D.order0.y):D.order0.z=i(_.order0.z,D.order0.y,_.order0.y):D.order0.z=D.order0.y)),void 0===a&&void 0===s||l!==R.reset&&void 0!==l||(D.order1.z=D.order1.y),void 0===c&&void 0===d||u!==R.reset&&void 0!==u||(D.order0.z=D.order0.y),M.debug("updateStrategy info:",{baseDecimals:B,quoteDecimals:w,decodedOriginal:m,originalStrategy:p,newStrategy:P,newEncodedStrategy:D}),this._api.composer.updateStrategy(O.from(e),D.token0,D.token1,[_.order0,_.order1],[D.order0,D.order1],g)}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(D),s=this._decimals,o=await s.fetchDecimals(t),c=await s.fetchDecimals(a),d=r.map((e=>new j(P(e,c,o)))),n=l(i,d).map((e=>e.floor().toFixed(0))),u=n.map((t=>e(t,c)));return M.debug("getRateLiquidityDepthByPair info:",{orders:i,depthsWei:n,targetDecimals:c,depthsInTargetDecimals:u}),u}async getMinRateByPair(e,t){M.debug("getMinRateByPair called",arguments);const a=Object.values(await this._cache.getOrdersByPair(e,t)).map(D),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("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(D),r=g(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}; |
@@ -40,10 +40,27 @@ import { BigNumber, BigNumberish, Decimal } from '../utils/numerics'; | ||
export declare function enforcePriceRange(minPrice: Decimal, maxPrice: Decimal, marginalPrice: Decimal): Decimal; | ||
export declare function calculateOverlappingPriceRanges(buyPriceLow: string, // in quote tkn per 1 base tkn | ||
sellPriceHigh: string, // in quote tkn per 1 base tkn | ||
marketPrice: string, // in quote tkn per 1 base tkn | ||
spreadPercentage: string): { | ||
/** | ||
* Calculate the overlapping strategy prices. Returns it with correct decimals | ||
* | ||
* @param {string} buyPriceLow - The minimum buy price for the strategy, in in `quoteToken` per 1 `baseToken`, as a string. | ||
* @param {string} sellPriceHigh - The maximum sell price for the strategy, in `quoteToken` per 1 `baseToken`, as a string. | ||
* @param {string} marketPrice - The market price, in `quoteToken` per 1 `baseToken`, as a string. | ||
* @param {string} spreadPercentage - The spread percentage, e.g. for 10%, enter `10`. | ||
* @return {{ | ||
* buyPriceLow: string; | ||
* buyPriceHigh: string; | ||
* buyPriceMarginal: string; | ||
* sellPriceLow: string; | ||
* sellPriceHigh: string; | ||
* sellPriceMarginal: string; | ||
* marketPrice: string; | ||
* }} The calculated overlapping strategy prices. | ||
*/ | ||
export declare function calculateOverlappingPrices(buyPriceLow: string, sellPriceHigh: string, marketPrice: string, spreadPercentage: string): { | ||
buyPriceLow: string; | ||
buyPriceHigh: string; | ||
buyPriceMarginal: string; | ||
sellPriceLow: string; | ||
sellPriceHigh: string; | ||
sellPriceMarginal: string; | ||
marketPrice: string; | ||
}; | ||
@@ -50,0 +67,0 @@ export declare function calculateOverlappingSellBudget(baseTokenDecimals: number, quoteTokenDecimals: number, buyPriceLow: string, // in quote tkn per 1 base tkn |
@@ -1,1 +0,1 @@ | ||
import{tenPow as e,formatUnits as r,parseUnits as t}from"../../utils/numerics/index.js";import{Logger as n}from"../../common/logger/index.js";import{encodeOrders as i,decodeOrder as o,calculateRequiredLiquidity as l}from"../../utils/encoders/index.js";import{encodedStrategyBNToStr as a}from"../../utils/serializers/index.js";import{Decimal as d}from"../../node_modules/decimal.js/decimal/index.js";const c=new n("utils.ts");function u(r,t,n){return new d(r.toString()).times(e(t,n)).toFixed()}function g(r,t,n){return 0==+r.toString()?"0":new d(1).div(r.toString()).times(e(n,t)).toFixed()}const s=e=>{const[r,t]=i([e.order0,e.order1]);return{token0:e.token0,token1:e.token1,order0:r,order1:t}},w=e=>({id:e.id,token0:e.token0,token1:e.token1,order0:o(e.order0),order1:o(e.order1),encoded:e});async function b(e,t){c.debug("parseStrategy called",arguments);const{id:n,token0:i,token1:o,order0:l,order1:d,encoded:s}=e,w=await t.fetchDecimals(i),b=await t.fetchDecimals(o),m=u(d.lowestRate,w,b),f=u(d.marginalRate,w,b),y=u(d.highestRate,w,b),h=g(l.highestRate,b,w),P=g(l.marginalRate,b,w),k=g(l.lowestRate,b,w),S=r(l.liquidity,w),v=r(d.liquidity,b),p=n.toString(),R=a(s);return c.debug("parseStrategy info:",{id:p,token0:i,token1:o,order0:l,order1:d,decimals0:w,decimals1:b,baseToken:i,quoteToken:o,buyPriceLow:m,buyPriceMarginal:f,buyPriceHigh:y,buyBudget:v,sellPriceLow:h,sellPriceMarginal:P,sellPriceHigh:k,sellBudget:S,encoded:R}),{id:p,baseToken:i,quoteToken:o,buyPriceLow:m,buyPriceMarginal:f,buyPriceHigh:y,buyBudget:v,sellPriceLow:h,sellPriceMarginal:P,sellPriceHigh:k,sellBudget:S,encoded:R}}function m(e,r,t,n,i,o,l,a,u,g,s,w){if(c.debug("buildStrategyObject called",arguments),new d(i).isNegative()||new d(o).isNegative()||new d(l).isNegative()||new d(u).isNegative()||new d(g).isNegative()||new d(s).isNegative())throw new Error("prices cannot be negative");if(new d(i).gt(o)||new d(i).gt(l)||new d(o).gt(l)||new d(u).gt(g)||new d(u).gt(s)||new d(g).gt(s))throw new Error("low/marginal price must be lower than or equal to marginal/high price");if(new d(a).isNegative()||new d(w).isNegative())throw new Error("budgets cannot be negative");const{order0:b,order1:m}=h(t,n,i,o,l,a,u,g,s,w);return c.debug("buildStrategyObject info:",{token0:e,token1:r,order0:b,order1:m}),{token0:e,token1:r,order0:b,order1:m}}function f(e,r,n,i,o,l){c.debug("createFromBuyOrder called",arguments);const a=t(l,r),d=u(n,r,e),g=u(i,r,e),s=u(o,r,e),w={liquidity:a.toString(),lowestRate:d,highestRate:s,marginalRate:g};return c.debug("createFromBuyOrder info:",{order:w}),w}function y(e,r,n,i,o,l){c.debug("createFromSellOrder called",arguments);const a=t(l,e),d=g(o,r,e),u=g(i,r,e),s=g(n,r,e),w={liquidity:a.toString(),lowestRate:d,highestRate:s,marginalRate:u};return c.debug("createFromSellOrder info:",{order:w}),w}function h(e,r,t,n,i,o,l,a,d,u){c.debug("createOrders called",arguments);const g=y(e,r,l,a,d,u),s=f(e,r,t,n,i,o);return c.debug("createOrders info:",{order0:g,order1:s}),{order0:g,order1:s}}const P=1e6;function k(e,r){return new d(e.toString()).mul(P).div(P-r).ceil()}function S(e,r){return new d(e.toString()).mul(P-r).div(P).floor()}function v(e,r,t){return t.lte(e)?e:t.gte(r)?r:t}function p(e,r,t,n){const i=new d(n).div(100).plus(1),o=new d(r).div(i),l=new d(e).mul(i),a=v(new d(e),o,new d(t).div(i.sqrt())),c=v(l,new d(r),new d(t).mul(i.sqrt()));return{buyPriceHigh:o.toString(),buyPriceMarginal:a.toString(),sellPriceLow:l.toString(),sellPriceMarginal:c.toString()}}function R(e,t,n,i,o,a,c){if("0"===c)return"0";const{buyPriceHigh:u,sellPriceLow:g,sellPriceMarginal:s,buyPriceMarginal:w}=p(n,i,o,a);if(new d(s).gte(i))return"0";if(new d(w).lte(n))throw new Error("calculateOverlappingSellBudget called with zero buy range and non zero buy budget");const b=f(e,t,n,w,u,c),m=y(e,t,g,s,i,"0"),h=l(b,m);return r(h,e)}function M(e,t,n,i,o,a,c){if("0"===c)return"0";const{sellPriceLow:u,buyPriceHigh:g,sellPriceMarginal:s,buyPriceMarginal:w}=p(n,i,o,a);if(new d(w).lte(n))return"0";if(new d(s).gte(i))throw new Error("calculateOverlappingBuyBudget called with zero sell range and non zero sell budget");const b=f(e,t,n,w,g,"0"),m=y(e,t,u,s,i,c),h=l(m,b);return r(h,t)}export{P as PPM_RESOLUTION,k as addFee,m as buildStrategyObject,M as calculateOverlappingBuyBudget,p as calculateOverlappingPriceRanges,R as calculateOverlappingSellBudget,f as createFromBuyOrder,y as createFromSellOrder,h as createOrders,w as decodeStrategy,s as encodeStrategy,v as enforcePriceRange,g as normalizeInvertedRate,u as normalizeRate,b as parseStrategy,S as subtractFee}; | ||
import{tenPow as e,formatUnits as r,parseUnits as t}from"../../utils/numerics/index.js";import{Logger as i}from"../../common/logger/index.js";import{encodeOrders as n,decodeOrder as o,calculateRequiredLiquidity as l}from"../../utils/encoders/index.js";import{encodedStrategyBNToStr as a}from"../../utils/serializers/index.js";import{Decimal as u}from"../../node_modules/decimal.js/decimal/index.js";const c=new i("utils.ts");function d(r,t,i){return new u(r.toString()).times(e(t,i)).toFixed()}function g(r,t,i){return 0==+r.toString()?"0":new u(1).div(r.toString()).times(e(i,t)).toFixed()}const s=e=>{const[r,t]=n([e.order0,e.order1]);return{token0:e.token0,token1:e.token1,order0:r,order1:t}},w=e=>({id:e.id,token0:e.token0,token1:e.token1,order0:o(e.order0),order1:o(e.order1),encoded:e});async function b(e,t){c.debug("parseStrategy called",arguments);const{id:i,token0:n,token1:o,order0:l,order1:u,encoded:s}=e,w=await t.fetchDecimals(n),b=await t.fetchDecimals(o),f=d(u.lowestRate,w,b),m=d(u.marginalRate,w,b),y=d(u.highestRate,w,b),p=g(l.highestRate,b,w),P=g(l.marginalRate,b,w),h=g(l.lowestRate,b,w),v=r(l.liquidity,w),k=r(u.liquidity,b),S=i.toString(),B=a(s);return c.debug("parseStrategy info:",{id:S,token0:n,token1:o,order0:l,order1:u,decimals0:w,decimals1:b,baseToken:n,quoteToken:o,buyPriceLow:f,buyPriceMarginal:m,buyPriceHigh:y,buyBudget:k,sellPriceLow:p,sellPriceMarginal:P,sellPriceHigh:h,sellBudget:v,encoded:B}),{id:S,baseToken:n,quoteToken:o,buyPriceLow:f,buyPriceMarginal:m,buyPriceHigh:y,buyBudget:k,sellPriceLow:p,sellPriceMarginal:P,sellPriceHigh:h,sellBudget:v,encoded:B}}function f(e,r,t,i,n,o,l,a,d,g,s,w){if(c.debug("buildStrategyObject called",arguments),new u(n).isNegative()||new u(o).isNegative()||new u(l).isNegative()||new u(d).isNegative()||new u(g).isNegative()||new u(s).isNegative())throw new Error("prices cannot be negative");if(new u(n).gt(o)||new u(n).gt(l)||new u(o).gt(l)||new u(d).gt(g)||new u(d).gt(s)||new u(g).gt(s))throw new Error("low/marginal price must be lower than or equal to marginal/high price");if(new u(a).isNegative()||new u(w).isNegative())throw new Error("budgets cannot be negative");const{order0:b,order1:f}=p(t,i,n,o,l,a,d,g,s,w);return c.debug("buildStrategyObject info:",{token0:e,token1:r,order0:b,order1:f}),{token0:e,token1:r,order0:b,order1:f}}function m(e,r,i,n,o,l){c.debug("createFromBuyOrder called",arguments);const a=t(l,r),u=d(i,r,e),g=d(n,r,e),s=d(o,r,e),w={liquidity:a.toString(),lowestRate:u,highestRate:s,marginalRate:g};return c.debug("createFromBuyOrder info:",{order:w}),w}function y(e,r,i,n,o,l){c.debug("createFromSellOrder called",arguments);const a=t(l,e),u=g(o,r,e),d=g(n,r,e),s=g(i,r,e),w={liquidity:a.toString(),lowestRate:u,highestRate:s,marginalRate:d};return c.debug("createFromSellOrder info:",{order:w}),w}function p(e,r,t,i,n,o,l,a,u,d){c.debug("createOrders called",arguments);const g=y(e,r,l,a,u,d),s=m(e,r,t,i,n,o);return c.debug("createOrders info:",{order0:g,order1:s}),{order0:g,order1:s}}const P=1e6;function h(e,r){return new u(e.toString()).mul(P).div(P-r).ceil()}function v(e,r){return new u(e.toString()).mul(P-r).div(P).floor()}function k(e,r,t){return t.lte(e)?e:t.gte(r)?r:t}function S(e,r,t,i){c.debug("calculateOverlappingPrices called",arguments);const n=new u(i).div(100).plus(1),o=new u(r).div(n),l=new u(e).mul(n),a=k(new u(e),o,new u(t).div(n.sqrt())),d=k(l,new u(r),new u(t).mul(n.sqrt())),g={buyPriceHigh:o.toString(),buyPriceMarginal:a.toString(),sellPriceLow:l.toString(),sellPriceMarginal:d.toString(),buyPriceLow:e,sellPriceHigh:r,marketPrice:t};return c.debug("calculateOverlappingPrices info:",{prices:g}),g}function B(e,t,i,n,o,a,d){if(c.debug("calculateOverlappingSellBudget called",arguments),"0"===d)return"0";const{buyPriceHigh:g,sellPriceLow:s,sellPriceMarginal:w,buyPriceMarginal:b}=S(i,n,o,a);if(new u(w).gte(n))return"0";if(new u(b).lte(i))throw new Error("calculateOverlappingSellBudget called with zero buy range and non zero buy budget");const f=m(e,t,i,b,g,d),p=y(e,t,s,w,n,"0"),P=l(f,p),h=r(P,e);return c.debug("calculateOverlappingSellBudget info:",{sellBudget:h}),h}function O(e,t,i,n,o,a,d){if(c.debug("calculateOverlappingBuyBudget called",arguments),"0"===d)return"0";const{sellPriceLow:g,buyPriceHigh:s,sellPriceMarginal:w,buyPriceMarginal:b}=S(i,n,o,a);if(new u(b).lte(i))return"0";if(new u(w).gte(n))throw new Error("calculateOverlappingBuyBudget called with zero sell range and non zero sell budget");const f=m(e,t,i,b,s,"0"),p=y(e,t,g,w,n,d),P=l(p,f),h=r(P,t);return c.debug("calculateOverlappingBuyBudget info:",{buyBudget:h}),h}export{P as PPM_RESOLUTION,h as addFee,f as buildStrategyObject,O as calculateOverlappingBuyBudget,S as calculateOverlappingPrices,B as calculateOverlappingSellBudget,m as createFromBuyOrder,y as createFromSellOrder,p as createOrders,w as decodeStrategy,s as encodeStrategy,k as enforcePriceRange,g as normalizeInvertedRate,d as normalizeRate,b as parseStrategy,v as subtractFee}; |
@@ -5,3 +5,3 @@ { | ||
"source": "src/index.ts", | ||
"version": "0.0.94-DEV", | ||
"version": "0.0.95-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", | ||
@@ -8,0 +8,0 @@ "main": "dist/index.cjs", |
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 1 instance 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 1 instance in 1 package
918308
7696