@drift-labs/common 1.0.54 → 1.0.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;AAAA,yCAuByB;AAKzB,mDAA0E;AAGnE,MAAM,SAAS,GAAG,CAAC,KAAU,EAAE,KAAK,EAAE,EAAE;IAC9C,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACxD,CAAC,CAAC;AAFW,QAAA,SAAS,aAEpB;AAEF,SAAS,SAAS,CAAC,OAAe;IACjC,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAE/B,OAAO;QACN,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,EAAE,EAAE;KACnB,CAAC;AACH,CAAC;AAED,SAAS,SAAS,CAAC,OAA4B;;IAC9C,OAAO,MAAA,MAAM,CAAC,IAAI,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,0CAAG,CAAC,CAAC,CAAC;AACxC,CAAC;AAEY,QAAA,UAAU,GAAG;IACzB,KAAK,EAAE,iBAAS;IAChB,KAAK,EAAE,SAAS;IAChB,KAAK,EAAE,SAAS;CAChB,CAAC;AAEK,KAAK,UAAU,KAAK,CAAC,EAAE;IAC7B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC1D,CAAC;AAFD,sBAEC;AACD,MAAM,2BAA2B,GAAG,CAAC,KAAU,EAAiB,EAAE;IACjE,QAAQ;IACR,kLAAkL;IAClL,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,2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PRICE_PRECISION_EXP,\n\tBASE_PRECISION_EXP,\n\tBigNum,\n\tMarketType,\n\tDriftClient,\n\tSPOT_MARKET_RATE_PRECISION_EXP,\n\tcalculateDepositRate,\n\tcalculateBorrowRate,\n\tgetTokenAmount,\n\tSpotBalanceType,\n\tSpotMarketConfig,\n} from '@drift-labs/sdk';\nimport {\n\tUIMatchedOrderRecordAndAction,\n\tUISerializableOrderActionRecord,\n} from '../serializableTypes';\nimport { getIfStakingVaultApr, getIfVaultBalance } from './insuranceFund';\nimport { AccountInfo, Connection } from '@solana/web3.js';\n\nexport const matchEnum = (enum1: any, enum2) => {\n\treturn JSON.stringify(enum1) === JSON.stringify(enum2);\n};\n\nfunction enumToObj(enumStr: string) {\n\tif (!enumStr) return undefined;\n\n\treturn {\n\t\t[enumStr ?? '']: {},\n\t};\n}\n\nfunction enumToStr(enumStr: Record<string, any>) {\n\treturn Object.keys(enumStr ?? {})?.[0];\n}\n\nexport const ENUM_UTILS = {\n\tmatch: matchEnum,\n\ttoObj: enumToObj,\n\ttoStr: enumToStr,\n};\n\nexport async function sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\nconst getStringifiableObjectEntry = (value: any): [any, string] => {\n\t// If BN\n\t// if (value instanceof BN) { /* This method would be much safer but don't think it's possible to ensure that instances of classes match when they're in different npm packages */\n\tif (Object.keys(value).sort().join(',') === 'length,negative,red,words') {\n\t\treturn [value.toString(), '_bgnm_'];\n\t}\n\n\t// If PublicKey\n\t// if (value instanceof PublicKey) { { /* This method would be much safer but don't think it's possible to ensure that instances of classes match when they're in different npm packages */\n\tif (Object.keys(value).sort().join(',') === '_bn') {\n\t\treturn [value.toString(), '_pbky_'];\n\t}\n\n\tif (typeof value === 'object') {\n\t\treturn [encodeStringifiableObject(value), ''];\n\t}\n\n\treturn [value, ''];\n};\n\n/**\n * Converts an objects with potential Pubkeys and BNs in it into a form that can be JSON stringified. When pubkeys get converted a _pbky_ suffix will be added to their key, and _bgnm_ for BNs.\n *\n * e.g.\n * input : {\n * QuoteAmount: BN\n * }\n *\n * output: {\n * _bgnm_QuoteAmount: string\n * }\n * @param value\n * @returns\n */\nexport const encodeStringifiableObject = (value: any) => {\n\tif (typeof value !== 'object') return value;\n\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => encodeStringifiableObject(entry));\n\t}\n\n\tconst buildJsonObject = {};\n\n\tif (!value) return value;\n\n\tObject.entries(value).forEach(([key, val]) => {\n\t\tconst [convertedVal, keyTag] = getStringifiableObjectEntry(val);\n\t\tbuildJsonObject[`${keyTag}${key}`] = convertedVal;\n\t});\n\n\treturn buildJsonObject;\n};\n\n/**\n * Converts a parsed object with potential Pubkeys and BNs in it (in string form) to their proper form. Pubkey values must have a key starting in _pbky_ and BN values must have a key starting in _bnnm_\n *\n * * e.g.\n * input : {\n * _bgnm_QuoteAmount: string\n * }\n *\n * output: {\n * QuoteAmount: BN\n * }\n * @param value\n * @returns\n */\nexport const decodeStringifiableObject = (value: any) => {\n\tif (typeof value !== 'object') return value;\n\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => decodeStringifiableObject(entry));\n\t}\n\n\tconst buildJsonObject = {};\n\n\tObject.entries(value)\n\t\t.filter((val) => val != undefined && val != null)\n\t\t.forEach(([key, val]) => {\n\t\t\tif (key.match(/^_pbky_/)) {\n\t\t\t\tbuildJsonObject[key.replace('_pbky_', '')] = new PublicKey(val);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (key.match(/^_bgnm_/)) {\n\t\t\t\tbuildJsonObject[key.replace('_bgnm_', '')] = new BN(val as string);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof val === 'object' && val != undefined && val != null) {\n\t\t\t\tbuildJsonObject[key] = decodeStringifiableObject(val);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbuildJsonObject[key] = val;\n\t\t});\n\n\treturn buildJsonObject;\n};\n\nconst getChronologicalValueForOrderAction = (action: OrderAction) => {\n\treturn matchEnum(action, OrderAction.PLACE)\n\t\t? 0\n\t\t: matchEnum(action, OrderAction.FILL)\n\t\t? 1\n\t\t: 2;\n};\n\n/**\n * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal\n * @param orderA\n * @param orderB\n * @returns\n */\nexport const getSortScoreForOrderRecords = (\n\torderA: { slot: number },\n\torderB: { slot: number }\n) => {\n\tif (orderA.slot !== orderB.slot) {\n\t\treturn orderA.slot > orderB.slot ? 1 : -1;\n\t}\n\n\treturn 0;\n};\n\nexport const getTradeInfoFromActionRecord = (\n\tactionRecord: PartialUISerializableOrderActionRecord\n) => {\n\treturn {\n\t\tts: actionRecord.ts,\n\t\tbaseAssetAmount: actionRecord.taker\n\t\t\t? actionRecord.takerOrderBaseAssetAmount\n\t\t\t: actionRecord.makerOrderBaseAssetAmount,\n\t\tbaseAssetAmountFilled: actionRecord.taker\n\t\t\t? actionRecord.takerOrderCumulativeBaseAssetAmountFilled\n\t\t\t: actionRecord.makerOrderCumulativeBaseAssetAmountFilled,\n\t\tquoteAssetAmountFilled: actionRecord.taker\n\t\t\t? actionRecord.takerOrderCumulativeQuoteAssetAmountFilled\n\t\t\t: actionRecord.makerOrderCumulativeQuoteAssetAmountFilled,\n\t};\n};\n\nexport type PartialOrderActionRecord =\n\t| PartialUISerializableOrderActionRecord\n\t| PartialOrderActionEventRecord;\n\nexport type PartialUISerializableOrderActionRecord = Pick<\n\tUISerializableOrderActionRecord,\n\t| 'quoteAssetAmountFilled'\n\t| 'baseAssetAmountFilled'\n\t| 'ts'\n\t| 'slot'\n\t| 'action'\n\t| 'fillRecordId'\n\t| 'taker'\n\t| 'takerOrderBaseAssetAmount'\n\t| 'makerOrderBaseAssetAmount'\n\t| 'takerOrderCumulativeBaseAssetAmountFilled'\n\t| 'makerOrderCumulativeBaseAssetAmountFilled'\n\t| 'takerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'makerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'oraclePrice'\n>;\n\nexport type PartialOrderActionEventRecord = Pick<\n\tEvent<OrderActionRecord>,\n\t| 'quoteAssetAmountFilled'\n\t| 'baseAssetAmountFilled'\n\t| 'ts'\n\t| 'slot'\n\t| 'action'\n\t| 'fillRecordId'\n\t| 'taker'\n\t| 'takerOrderBaseAssetAmount'\n\t| 'makerOrderBaseAssetAmount'\n\t| 'takerOrderCumulativeBaseAssetAmountFilled'\n\t| 'makerOrderCumulativeBaseAssetAmountFilled'\n\t| 'takerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'makerOrderCumulativeQuoteAssetAmountFilled'\n>;\n\n/**\n * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal\n * @param orderA\n * @param orderB\n * @returns\n */\nexport const getSortScoreForOrderActionRecords = (\n\torderA: PartialOrderActionRecord,\n\torderB: PartialOrderActionRecord\n) => {\n\tif (orderA.slot !== orderB.slot) {\n\t\treturn orderA.slot > orderB.slot ? 1 : -1;\n\t}\n\n\tif (!matchEnum(orderA.action, orderB.action)) {\n\t\t// @ts-ignore\n\t\tconst orderAActionVal = getChronologicalValueForOrderAction(orderA.action);\n\t\t// @ts-ignore\n\t\tconst orderBActionVal = getChronologicalValueForOrderAction(orderB.action);\n\n\t\treturn orderAActionVal > orderBActionVal ? 1 : -1;\n\t}\n\t// @ts-ignore\n\tif (orderA.fillRecordId && orderB.fillRecordId) {\n\t\tif (!orderA.fillRecordId.eq(orderB.fillRecordId)) {\n\t\t\t// @ts-ignore\n\t\t\treturn orderA.fillRecordId.gt(orderB.fillRecordId) ? 1 : -1;\n\t\t}\n\t}\n\n\treturn 0;\n};\n\nexport const sortUIMatchedOrderRecordAndAction = (\n\trecords: UIMatchedOrderRecordAndAction[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort((a, b) =>\n\t\tgetSortScoreForOrderActionRecords(a.actionRecord, b.actionRecord)\n\t);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortUIOrderActionRecords = (\n\trecords: PartialUISerializableOrderActionRecord[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderActionRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortUIOrderRecords = <T extends { slot: number }>(\n\trecords: T[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortOrderRecords = (\n\trecords: Event<OrderRecord>[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const getLatestOfTwoUIOrderRecords = <T extends { slot: number }>(\n\torderA: T,\n\torderB: T\n) => {\n\treturn getSortScoreForOrderRecords(orderA, orderB) === 1 ? orderA : orderB;\n};\n\nexport const getLatestOfTwoOrderRecords = <T extends { slot: number }>(\n\torderA: T,\n\torderB: T\n) => {\n\treturn getSortScoreForOrderRecords(orderA, orderB) === 1 ? orderA : orderB;\n};\n\nexport const getUIOrderRecordsLaterThanTarget = <T extends { slot: number }>(\n\ttarget: T,\n\trecords: T[]\n) =>\n\trecords.filter(\n\t\t(record) => getLatestOfTwoUIOrderRecords(record, target) === record\n\t);\n\n// Trade records are order records which have been filled\nexport const orderActionRecordIsTrade = (orderRecord: OrderActionRecord) =>\n\torderRecord.baseAssetAmountFilled.gt(ZERO) &&\n\t// @ts-ignore\n\tmatchEnum(orderRecord.action, OrderAction.FILL) &&\n\ttrue;\n\nexport const uiOrderActionRecordIsTrade = (\n\torderRecord: UISerializableOrderActionRecord\n) =>\n\torderRecord.baseAssetAmountFilled.gtZero() &&\n\tmatchEnum(orderRecord.action, OrderAction.FILL) &&\n\ttrue;\n\n// Trade records are order records which have been filled\nexport const filterTradeRecordsFromOrderActionRecords = (\n\torderRecords: OrderActionRecord[]\n): OrderActionRecord[] => orderRecords.filter(orderActionRecordIsTrade);\n\n// Trade records are order records which have been filled\nexport const filterTradeRecordsFromUIOrderRecords = (\n\torderRecords: UISerializableOrderActionRecord[]\n): UISerializableOrderActionRecord[] =>\n\torderRecords.filter(uiOrderActionRecordIsTrade);\n\n/**\n * Returns the average price for a given base amount and quote amount.\n * @param quoteAmount\n * @param baseAmount\n * @returns PRICE_PRECISION\n */\nexport const getPriceForBaseAndQuoteAmount = (\n\tquoteAmount: BN,\n\tbaseAmount: BN\n) => {\n\treturn quoteAmount\n\t\t.mul(PRICE_PRECISION)\n\t\t.mul(BASE_PRECISION)\n\t\t.div(QUOTE_PRECISION)\n\t\t.div(BigNum.from(baseAmount, BASE_PRECISION_EXP).val);\n};\n\nexport const getPriceForOrderRecord = (\n\torderRecord: Pick<\n\t\tOrderActionRecord,\n\t\t'quoteAssetAmountFilled' | 'baseAssetAmountFilled'\n\t>\n) => {\n\treturn getPriceForBaseAndQuoteAmount(\n\t\t// @ts-ignore\n\t\torderRecord.quoteAssetAmountFilled,\n\t\t// @ts-ignore\n\t\torderRecord.baseAssetAmountFilled\n\t);\n};\n\nexport const getPriceForUIOrderRecord = (\n\torderRecord: Pick<\n\t\tUISerializableOrderActionRecord,\n\t\t'quoteAssetAmountFilled' | 'baseAssetAmountFilled'\n\t>\n) => {\n\treturn orderRecord.quoteAssetAmountFilled\n\t\t.shiftTo(AMM_RESERVE_PRECISION_EXP)\n\t\t.shift(PRICE_PRECISION_EXP)\n\t\t.div(orderRecord.baseAssetAmountFilled.shiftTo(BASE_PRECISION_EXP))\n\t\t.shiftTo(PRICE_PRECISION_EXP);\n};\n\nexport const orderIsNull = (\n\torder: UISerializableOrderActionRecord | Event<OrderActionRecord>,\n\tside: 'taker' | 'maker'\n) => {\n\treturn side === 'taker' ? !order.taker : !order.maker;\n};\n\nexport const getAnchorEnumString = (enumVal: Record<string, unknown>) => {\n\treturn Object.keys(enumVal)[0];\n};\nexport class Ref<T> {\n\tpublic val: T;\n\n\tconstructor(val: T) {\n\t\tthis.val = val;\n\t}\n\n\tset(val: T) {\n\t\tthis.val = val;\n\t}\n\n\tget() {\n\t\treturn this.val;\n\t}\n}\n\nexport class Counter {\n\tprivate val = 0;\n\n\tget() {\n\t\treturn this.val;\n\t}\n\n\tincrement(value = 1) {\n\t\tthis.val += value;\n\t}\n\n\treset() {\n\t\tthis.val = 0;\n\t}\n}\n\n/**\n * A class which allows a group of switches to seperately turn a multiswitch on or off. The base state is the state of the \"multiswitch\" when all of the constituent switches are off. When any of the switches are \"on\" then the multiswitch flips to the opposite state\n *\n * If baseState is on => any switch being \"on\" will turn the multiswitch off.\n * If baseState is off => any switch being \"off\" will turn the multiswitch off.\n */\nexport class MultiSwitch {\n\tprivate switches: string[] = [];\n\tprivate switchValue = 0;\n\n\tconstructor(private baseState: 'on' | 'off' = 'off') {}\n\n\tprivate getSwitchKey(key: string) {\n\t\t// If first time using switch, add to list of switches\n\t\tif (!this.switches.includes(key)) {\n\t\t\tthis.switches.push(key);\n\t\t}\n\n\t\tconst switchIndex = this.switches.indexOf(key);\n\n\t\treturn 2 ** switchIndex;\n\t}\n\n\tpublic switchOn(key: string) {\n\t\tif (this.baseState === 'on') {\n\t\t\tthis._switchOff(key);\n\t\t\treturn;\n\t\t}\n\t\tthis._switchOn(key);\n\t}\n\n\tpublic switchOff(key: string) {\n\t\tif (this.baseState === 'on') {\n\t\t\tthis._switchOn(key);\n\t\t\treturn;\n\t\t}\n\t\tthis._switchOff(key);\n\t}\n\n\tprivate _switchOff(key: string) {\n\t\tconst switchKey = this.getSwitchKey(key);\n\n\t\tthis.switchValue &= ~switchKey;\n\t}\n\n\tprivate _switchOn(key: string) {\n\t\tconst switchKey = this.getSwitchKey(key);\n\n\t\tthis.switchValue |= switchKey;\n\t}\n\n\tpublic get isOn() {\n\t\t// When the base state is on, then if any switch is on the multi-switch is off\n\t\tif (this.baseState === 'on') {\n\t\t\treturn this.switchValue === 0;\n\t\t}\n\n\t\tif (this.baseState === 'off') {\n\t\t\treturn this.switchValue > 0;\n\t\t}\n\t}\n}\n\n/**\n * Returns the quote amount of the current open interest for a market, using the current oracle price\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getCurrentOpenInterestForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.PERP)) {\n\t\tconst market = driftClient.getPerpMarketAccount(marketIndex);\n\t\tconst OI = BigNum.from(\n\t\t\tmarket.amm.baseAssetAmountLong.add(market.amm.baseAssetAmountShort.abs()),\n\t\t\tBASE_PRECISION_EXP\n\t\t);\n\n\t\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\t\tmarket.amm.oracle,\n\t\t\tmarket.amm.oracleSource\n\t\t);\n\n\t\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\t\tconst quoteOIforMarket = price.toNum() * OI.toNum();\n\n\t\treturn quoteOIforMarket;\n\t} else {\n\t\tthrow new Error('Invalid market type for Open Interest calculation');\n\t}\n};\n\n/**\n * Gets the deposit APR for a spot market, in percent\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getDepositAprForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.SPOT)) {\n\t\tconst marketAccount = driftClient.getSpotMarketAccount(marketIndex);\n\n\t\tconst depositApr = BigNum.from(\n\t\t\tcalculateDepositRate(marketAccount),\n\t\t\tSPOT_MARKET_RATE_PRECISION_EXP\n\t\t);\n\n\t\tconst depositAprPct = depositApr.toNum() * 100;\n\n\t\treturn depositAprPct;\n\t} else {\n\t\tthrow new Error('Invalid market type for Deposit APR calculation');\n\t}\n};\n\n/**\n * Get's the borrow APR for a spot market, in percent\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getBorrowAprForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.SPOT)) {\n\t\tconst marketAccount = driftClient.getSpotMarketAccount(marketIndex);\n\n\t\tconst depositApr = BigNum.from(\n\t\t\tcalculateBorrowRate(marketAccount),\n\t\t\tSPOT_MARKET_RATE_PRECISION_EXP\n\t\t);\n\n\t\tconst depositAprPct = depositApr.toNum() * 100;\n\n\t\treturn depositAprPct;\n\t} else {\n\t\tthrow new Error('Invalid market type for Borrow APR calculation');\n\t}\n};\n\nconst getTotalBorrowsForMarket = (\n\tmarket: SpotMarketConfig,\n\tdriftClient: DriftClient\n) => {\n\tconst marketAccount = driftClient.getSpotMarketAccount(market.marketIndex);\n\n\tconst totalBorrowsTokenAmount = getTokenAmount(\n\t\tmarketAccount.borrowBalance,\n\t\tdriftClient.getSpotMarketAccount(marketAccount.marketIndex),\n\t\tSpotBalanceType.BORROW\n\t);\n\n\tconst totalBorrowsAmountBigNum = BigNum.from(\n\t\ttotalBorrowsTokenAmount,\n\t\tmarket.precisionExp\n\t);\n\n\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\tmarketAccount.oracle,\n\t\tmarketAccount.oracleSource\n\t);\n\n\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\tconst totalBorrowsQuote = price.toNum() * totalBorrowsAmountBigNum.toNum();\n\n\treturn Number(totalBorrowsQuote.toFixed(2));\n};\n\nconst getTotalDepositsForMarket = (\n\tmarket: SpotMarketConfig,\n\tdriftClient: DriftClient\n) => {\n\tconst marketAccount = driftClient.getSpotMarketAccount(market.marketIndex);\n\n\tconst totalDepositsTokenAmount = getTokenAmount(\n\t\tmarketAccount.depositBalance,\n\t\tmarketAccount,\n\t\tSpotBalanceType.DEPOSIT\n\t);\n\n\tconst totalDepositsTokenAmountBigNum = BigNum.from(\n\t\ttotalDepositsTokenAmount,\n\t\tmarket.precisionExp\n\t);\n\n\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\tmarketAccount.oracle,\n\t\tmarketAccount.oracleSource\n\t);\n\n\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\tconst totalDepositsBase = totalDepositsTokenAmountBigNum.toNum();\n\tconst totalDepositsQuote =\n\t\tprice.toNum() * totalDepositsTokenAmountBigNum.toNum();\n\n\treturn {\n\t\ttotalDepositsBase,\n\t\ttotalDepositsQuote,\n\t};\n};\n\n/**\n * Check if numbers divide exactly, accounting for floating point division annoyingness\n * @param numerator\n * @param denominator\n * @returns\n */\nconst dividesExactly = (numerator: number, denominator: number) => {\n\tconst division = numerator / denominator;\n\tconst remainder = division % 1;\n\n\tif (remainder === 0) return true;\n\n\t// Because of floating point weirdness, we're just going to assume that if the remainder after dividing is less than 1/10^6 then the numbers do divide exactly\n\tif (Math.abs(remainder - 1) < 1 / 10 ** 6) return true;\n\n\treturn false;\n};\n\nconst toSnakeCase = (str: string): string =>\n\tstr.replace(/[^\\w]/g, '_').toLowerCase();\n\nconst toCamelCase = (str: string): string => {\n\tconst words = str.split(/[_\\-\\s]+/); // split on underscores, hyphens, and spaces\n\tconst firstWord = words[0].toLowerCase();\n\tconst restWords = words\n\t\t.slice(1)\n\t\t.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());\n\treturn [firstWord, ...restWords].join('');\n};\n\nexport const aprFromApy = (apy: number, compoundsPerYear: number) => {\n\tconst compoundedAmount = 1 + apy * 0.01;\n\tconst estimatedApr =\n\t\t(Math.pow(compoundedAmount, 1 / compoundsPerYear) - 1) * compoundsPerYear;\n\n\treturn estimatedApr * 100;\n};\n\n/**\n * Helper utility to get a sort score for \"tiered\" parameters.\n *\n * Example: Want to sort students by Grade, but fall back to using Age if they are equal. This method will accept an array for each student of [grade, age] and return the appropriate sort score for each.\n *\n * @param aScores\n * @param bScores\n * @returns\n */\nexport const getTieredSortScore = (aScores: number[], bScores: number[]) => {\n\tconst maxIndex = Math.max(aScores.length, bScores.length);\n\n\tfor (let i = 0; i < maxIndex; i++) {\n\t\tconst aScore = aScores[i] ?? Number.MIN_SAFE_INTEGER;\n\t\tconst bScore = bScores[i] ?? Number.MIN_SAFE_INTEGER;\n\n\t\tif (aScore !== bScore) return aScore - bScore;\n\t}\n\n\treturn 0;\n};\n\nconst normalizeBaseAssetSymbol = (symbol: string) => {\n\treturn symbol.replace(/^1M/, '');\n};\n\n/**\n * Returns the number of standard deviations between a target value and the history of values to compare it to.\n * @param target\n * @param previousValues\n * @returns\n */\nconst calculateZScore = (target: number, previousValues: number[]): number => {\n\tconst meanValue = calculateMean(previousValues);\n\tconst standardDeviationValue = calculateStandardDeviation(\n\t\tpreviousValues,\n\t\tmeanValue\n\t);\n\n\tconst zScore = (target - meanValue) / standardDeviationValue;\n\treturn zScore;\n};\n\nconst calculateMean = (numbers: number[]): number => {\n\tconst sum = numbers.reduce((total, num) => total + num, 0);\n\treturn sum / numbers.length;\n};\n\nconst calculateMedian = (numbers: number[]): number => {\n\tconst sortedNumbers = numbers.sort();\n\tconst middleIndex = Math.floor(sortedNumbers.length / 2);\n\tif (sortedNumbers.length % 2 === 0) {\n\t\treturn (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2;\n\t} else {\n\t\treturn sortedNumbers[middleIndex];\n\t}\n};\n\nconst calculateStandardDeviation = (\n\tnumbers: number[],\n\tmean: number\n): number => {\n\tconst squaredDifferences = numbers.map((num) => Math.pow(num - mean, 2));\n\tconst sumSquaredDifferences = squaredDifferences.reduce(\n\t\t(total, diff) => total + diff,\n\t\t0\n\t);\n\tconst variance = sumSquaredDifferences / numbers.length;\n\treturn Math.sqrt(variance);\n};\n\nconst glueArray = <T>(size: number, elements: T[]): T[][] => {\n\tconst gluedElements: T[][] = [];\n\n\telements.forEach((element, index) => {\n\t\tconst gluedIndex = Math.floor(index / size);\n\t\tif (gluedElements[gluedIndex]) {\n\t\t\tgluedElements[gluedIndex].push(element);\n\t\t} else {\n\t\t\tgluedElements[gluedIndex] = [element];\n\t\t}\n\t});\n\n\treturn gluedElements;\n};\n\nconst bnMin = (numbers: BN[]): BN => {\n\tlet min = numbers[0];\n\tfor (let i = 1; i < numbers.length; i++) {\n\t\tif (numbers[i].lt(min)) {\n\t\t\tmin = numbers[i];\n\t\t}\n\t}\n\treturn min;\n};\n\nconst bnMax = (numbers: BN[]): BN => {\n\tlet max = numbers[0];\n\tfor (let i = 1; i < numbers.length; i++) {\n\t\tif (numbers[i].gt(max)) {\n\t\t\tmax = numbers[i];\n\t\t}\n\t}\n\treturn max;\n};\n\nconst bnMedian = (numbers: BN[]): BN => {\n\tconst sortedNumbers = numbers.sort((a, b) => a.cmp(b));\n\tconst middleIndex = Math.floor(sortedNumbers.length / 2);\n\tif (sortedNumbers.length % 2 === 0) {\n\t\treturn sortedNumbers[middleIndex - 1]\n\t\t\t.add(sortedNumbers[middleIndex])\n\t\t\t.div(new BN(2));\n\t} else {\n\t\treturn sortedNumbers[middleIndex];\n\t}\n};\n\nconst bnMean = (numbers: BN[]): BN => {\n\tlet sum = new BN(0);\n\tfor (let i = 0; i < numbers.length; i++) {\n\t\tsum = sum.add(numbers[i]);\n\t}\n\treturn sum.div(new BN(numbers.length));\n};\n\nconst timedPromise = async <T>(promise: T) => {\n\tconst start = Date.now();\n\tconst promiseResult = await promise;\n\n\treturn {\n\t\tpromiseTime: Date.now() - start,\n\t\tpromiseResult,\n\t};\n};\n\nconst chunks = <T>(array: readonly T[], size: number): T[][] => {\n\treturn new Array(Math.ceil(array.length / size))\n\t\t.fill(null)\n\t\t.map((_, index) => index * size)\n\t\t.map((begin) => array.slice(begin, begin + size));\n};\n\nconst getMultipleAccountsInfoChunked = async (\n\tconnection: Connection,\n\taccounts: PublicKey[]\n): Promise<(AccountInfo<Buffer> | null)[]> => {\n\tconst accountChunks = chunks(accounts, 100); // 100 is limit for getMultipleAccountsInfo\n\tconst responses = await Promise.all(\n\t\taccountChunks.map((chunk) => connection.getMultipleAccountsInfo(chunk))\n\t);\n\treturn responses.flat();\n};\n\nexport const COMMON_UTILS = {\n\tgetIfVaultBalance,\n\tgetIfStakingVaultApr,\n\tgetCurrentOpenInterestForMarket,\n\tgetDepositAprForMarket,\n\tgetBorrowAprForMarket,\n\tgetTotalBorrowsForMarket,\n\tgetTotalDepositsForMarket,\n\tdividesExactly,\n\ttoSnakeCase,\n\ttoCamelCase,\n\tgetTieredSortScore,\n\tnormalizeBaseAssetSymbol,\n\tcalculateZScore,\n\tglueArray,\n\ttimedPromise,\n\tchunks,\n\tgetMultipleAccountsInfoChunked,\n\tMATH: {\n\t\tNUM: {\n\t\t\tmean: calculateMean,\n\t\t\tmedian: calculateMedian,\n\t\t},\n\t\tBN: {\n\t\t\tbnMax,\n\t\t\tbnMin,\n\t\t\tbnMean,\n\t\t\tbnMedian,\n\t\t},\n\t},\n};\nexport { getSwiftConfirmationTimeoutMs } from './signedMsgs';\nexport { ResultSlotIncrementer } from './ResultSlotIncrementer';\nexport { MultiplexWebSocket } from './MultiplexWebSocket';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;AAAA,yCAuByB;AAKzB,mDAA0E;AAG1E,iCAA+C;AACtC,0FADA,gBAAS,OACA;AAAE,2FADA,iBAAU,OACA;AAEvB,KAAK,UAAU,KAAK,CAAC,EAAE;IAC7B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC1D,CAAC;AAFD,sBAEC;AACD,MAAM,2BAA2B,GAAG,CAAC,KAAU,EAAiB,EAAE;IACjE,QAAQ;IACR,kLAAkL;IAClL,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,2BAA2B,EAAE,CAAC;QACzE,OAAO,CAAC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IAAI,CAAC,CAAC,CAAC;AACpD,CAAC,CAAC;AAEF,MAAM,8BAA8B,GAAG,KAAK,EAC3C,UAAsB,EACtB,QAAqB,EACqB,EAAE;IAC5C,MAAM,aAAa,GAAG,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,2CAA2C;IACxF,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,GAAG,CAClC,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,uBAAuB,CAAC,KAAK,CAAC,CAAC,CACvE,CAAC;IACF,OAAO,SAAS,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC,CAAC;AAEW,QAAA,YAAY,GAAG;IAC3B,iBAAiB,EAAjB,iCAAiB;IACjB,oBAAoB,EAApB,oCAAoB;IACpB,+BAA+B;IAC/B,sBAAsB;IACtB,qBAAqB;IACrB,wBAAwB;IACxB,yBAAyB;IACzB,cAAc;IACd,WAAW;IACX,WAAW;IACX,kBAAkB,EAAlB,0BAAkB;IAClB,wBAAwB;IACxB,eAAe;IACf,SAAS;IACT,YAAY;IACZ,MAAM;IACN,8BAA8B;IAC9B,IAAI,EAAE;QACL,GAAG,EAAE;YACJ,IAAI,EAAE,aAAa;YACnB,MAAM,EAAE,eAAe;SACvB;QACD,EAAE,EAAE;YACH,KAAK;YACL,KAAK;YACL,MAAM;YACN,QAAQ;SACR;KACD;CACD,CAAC;AACF,2CAA6D;AAApD,2HAAA,6BAA6B,OAAA;AACtC,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAC9B,2DAA0D;AAAjD,wHAAA,kBAAkB,OAAA","sourcesContent":["import {\n\tAMM_RESERVE_PRECISION_EXP,\n\tBASE_PRECISION,\n\tBN,\n\tEvent,\n\tPRICE_PRECISION,\n\tOrderAction,\n\tOrderActionRecord,\n\tOrderRecord,\n\tPublicKey,\n\tQUOTE_PRECISION,\n\tZERO,\n\tPRICE_PRECISION_EXP,\n\tBASE_PRECISION_EXP,\n\tBigNum,\n\tMarketType,\n\tDriftClient,\n\tSPOT_MARKET_RATE_PRECISION_EXP,\n\tcalculateDepositRate,\n\tcalculateBorrowRate,\n\tgetTokenAmount,\n\tSpotBalanceType,\n\tSpotMarketConfig,\n} from '@drift-labs/sdk';\nimport {\n\tUIMatchedOrderRecordAndAction,\n\tUISerializableOrderActionRecord,\n} from '../serializableTypes';\nimport { getIfStakingVaultApr, getIfVaultBalance } from './insuranceFund';\nimport { AccountInfo, Connection } from '@solana/web3.js';\n\nimport { matchEnum, ENUM_UTILS } from './enum';\nexport { matchEnum, ENUM_UTILS };\n\nexport async function sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\nconst getStringifiableObjectEntry = (value: any): [any, string] => {\n\t// If BN\n\t// if (value instanceof BN) { /* This method would be much safer but don't think it's possible to ensure that instances of classes match when they're in different npm packages */\n\tif (Object.keys(value).sort().join(',') === 'length,negative,red,words') {\n\t\treturn [value.toString(), '_bgnm_'];\n\t}\n\n\t// If PublicKey\n\t// if (value instanceof PublicKey) { { /* This method would be much safer but don't think it's possible to ensure that instances of classes match when they're in different npm packages */\n\tif (Object.keys(value).sort().join(',') === '_bn') {\n\t\treturn [value.toString(), '_pbky_'];\n\t}\n\n\tif (typeof value === 'object') {\n\t\treturn [encodeStringifiableObject(value), ''];\n\t}\n\n\treturn [value, ''];\n};\n\n/**\n * Converts an objects with potential Pubkeys and BNs in it into a form that can be JSON stringified. When pubkeys get converted a _pbky_ suffix will be added to their key, and _bgnm_ for BNs.\n *\n * e.g.\n * input : {\n * QuoteAmount: BN\n * }\n *\n * output: {\n * _bgnm_QuoteAmount: string\n * }\n * @param value\n * @returns\n */\nexport const encodeStringifiableObject = (value: any) => {\n\tif (typeof value !== 'object') return value;\n\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => encodeStringifiableObject(entry));\n\t}\n\n\tconst buildJsonObject = {};\n\n\tif (!value) return value;\n\n\tObject.entries(value).forEach(([key, val]) => {\n\t\tconst [convertedVal, keyTag] = getStringifiableObjectEntry(val);\n\t\tbuildJsonObject[`${keyTag}${key}`] = convertedVal;\n\t});\n\n\treturn buildJsonObject;\n};\n\n/**\n * Converts a parsed object with potential Pubkeys and BNs in it (in string form) to their proper form. Pubkey values must have a key starting in _pbky_ and BN values must have a key starting in _bnnm_\n *\n * * e.g.\n * input : {\n * _bgnm_QuoteAmount: string\n * }\n *\n * output: {\n * QuoteAmount: BN\n * }\n * @param value\n * @returns\n */\nexport const decodeStringifiableObject = (value: any) => {\n\tif (typeof value !== 'object') return value;\n\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => decodeStringifiableObject(entry));\n\t}\n\n\tconst buildJsonObject = {};\n\n\tObject.entries(value)\n\t\t.filter((val) => val != undefined && val != null)\n\t\t.forEach(([key, val]) => {\n\t\t\tif (key.match(/^_pbky_/)) {\n\t\t\t\tbuildJsonObject[key.replace('_pbky_', '')] = new PublicKey(val);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (key.match(/^_bgnm_/)) {\n\t\t\t\tbuildJsonObject[key.replace('_bgnm_', '')] = new BN(val as string);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof val === 'object' && val != undefined && val != null) {\n\t\t\t\tbuildJsonObject[key] = decodeStringifiableObject(val);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbuildJsonObject[key] = val;\n\t\t});\n\n\treturn buildJsonObject;\n};\n\nconst getChronologicalValueForOrderAction = (action: OrderAction) => {\n\treturn matchEnum(action, OrderAction.PLACE)\n\t\t? 0\n\t\t: matchEnum(action, OrderAction.FILL)\n\t\t? 1\n\t\t: 2;\n};\n\n/**\n * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal\n * @param orderA\n * @param orderB\n * @returns\n */\nexport const getSortScoreForOrderRecords = (\n\torderA: { slot: number },\n\torderB: { slot: number }\n) => {\n\tif (orderA.slot !== orderB.slot) {\n\t\treturn orderA.slot > orderB.slot ? 1 : -1;\n\t}\n\n\treturn 0;\n};\n\nexport const getTradeInfoFromActionRecord = (\n\tactionRecord: PartialUISerializableOrderActionRecord\n) => {\n\treturn {\n\t\tts: actionRecord.ts,\n\t\tbaseAssetAmount: actionRecord.taker\n\t\t\t? actionRecord.takerOrderBaseAssetAmount\n\t\t\t: actionRecord.makerOrderBaseAssetAmount,\n\t\tbaseAssetAmountFilled: actionRecord.taker\n\t\t\t? actionRecord.takerOrderCumulativeBaseAssetAmountFilled\n\t\t\t: actionRecord.makerOrderCumulativeBaseAssetAmountFilled,\n\t\tquoteAssetAmountFilled: actionRecord.taker\n\t\t\t? actionRecord.takerOrderCumulativeQuoteAssetAmountFilled\n\t\t\t: actionRecord.makerOrderCumulativeQuoteAssetAmountFilled,\n\t};\n};\n\nexport type PartialOrderActionRecord =\n\t| PartialUISerializableOrderActionRecord\n\t| PartialOrderActionEventRecord;\n\nexport type PartialUISerializableOrderActionRecord = Pick<\n\tUISerializableOrderActionRecord,\n\t| 'quoteAssetAmountFilled'\n\t| 'baseAssetAmountFilled'\n\t| 'ts'\n\t| 'slot'\n\t| 'action'\n\t| 'fillRecordId'\n\t| 'taker'\n\t| 'takerOrderBaseAssetAmount'\n\t| 'makerOrderBaseAssetAmount'\n\t| 'takerOrderCumulativeBaseAssetAmountFilled'\n\t| 'makerOrderCumulativeBaseAssetAmountFilled'\n\t| 'takerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'makerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'oraclePrice'\n>;\n\nexport type PartialOrderActionEventRecord = Pick<\n\tEvent<OrderActionRecord>,\n\t| 'quoteAssetAmountFilled'\n\t| 'baseAssetAmountFilled'\n\t| 'ts'\n\t| 'slot'\n\t| 'action'\n\t| 'fillRecordId'\n\t| 'taker'\n\t| 'takerOrderBaseAssetAmount'\n\t| 'makerOrderBaseAssetAmount'\n\t| 'takerOrderCumulativeBaseAssetAmountFilled'\n\t| 'makerOrderCumulativeBaseAssetAmountFilled'\n\t| 'takerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'makerOrderCumulativeQuoteAssetAmountFilled'\n>;\n\n/**\n * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal\n * @param orderA\n * @param orderB\n * @returns\n */\nexport const getSortScoreForOrderActionRecords = (\n\torderA: PartialOrderActionRecord,\n\torderB: PartialOrderActionRecord\n) => {\n\tif (orderA.slot !== orderB.slot) {\n\t\treturn orderA.slot > orderB.slot ? 1 : -1;\n\t}\n\n\tif (!matchEnum(orderA.action, orderB.action)) {\n\t\t// @ts-ignore\n\t\tconst orderAActionVal = getChronologicalValueForOrderAction(orderA.action);\n\t\t// @ts-ignore\n\t\tconst orderBActionVal = getChronologicalValueForOrderAction(orderB.action);\n\n\t\treturn orderAActionVal > orderBActionVal ? 1 : -1;\n\t}\n\t// @ts-ignore\n\tif (orderA.fillRecordId && orderB.fillRecordId) {\n\t\tif (!orderA.fillRecordId.eq(orderB.fillRecordId)) {\n\t\t\t// @ts-ignore\n\t\t\treturn orderA.fillRecordId.gt(orderB.fillRecordId) ? 1 : -1;\n\t\t}\n\t}\n\n\treturn 0;\n};\n\nexport const sortUIMatchedOrderRecordAndAction = (\n\trecords: UIMatchedOrderRecordAndAction[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort((a, b) =>\n\t\tgetSortScoreForOrderActionRecords(a.actionRecord, b.actionRecord)\n\t);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortUIOrderActionRecords = (\n\trecords: PartialUISerializableOrderActionRecord[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderActionRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortUIOrderRecords = <T extends { slot: number }>(\n\trecords: T[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortOrderRecords = (\n\trecords: Event<OrderRecord>[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const getLatestOfTwoUIOrderRecords = <T extends { slot: number }>(\n\torderA: T,\n\torderB: T\n) => {\n\treturn getSortScoreForOrderRecords(orderA, orderB) === 1 ? orderA : orderB;\n};\n\nexport const getLatestOfTwoOrderRecords = <T extends { slot: number }>(\n\torderA: T,\n\torderB: T\n) => {\n\treturn getSortScoreForOrderRecords(orderA, orderB) === 1 ? orderA : orderB;\n};\n\nexport const getUIOrderRecordsLaterThanTarget = <T extends { slot: number }>(\n\ttarget: T,\n\trecords: T[]\n) =>\n\trecords.filter(\n\t\t(record) => getLatestOfTwoUIOrderRecords(record, target) === record\n\t);\n\n// Trade records are order records which have been filled\nexport const orderActionRecordIsTrade = (orderRecord: OrderActionRecord) =>\n\torderRecord.baseAssetAmountFilled.gt(ZERO) &&\n\t// @ts-ignore\n\tmatchEnum(orderRecord.action, OrderAction.FILL) &&\n\ttrue;\n\nexport const uiOrderActionRecordIsTrade = (\n\torderRecord: UISerializableOrderActionRecord\n) =>\n\torderRecord.baseAssetAmountFilled.gtZero() &&\n\tmatchEnum(orderRecord.action, OrderAction.FILL) &&\n\ttrue;\n\n// Trade records are order records which have been filled\nexport const filterTradeRecordsFromOrderActionRecords = (\n\torderRecords: OrderActionRecord[]\n): OrderActionRecord[] => orderRecords.filter(orderActionRecordIsTrade);\n\n// Trade records are order records which have been filled\nexport const filterTradeRecordsFromUIOrderRecords = (\n\torderRecords: UISerializableOrderActionRecord[]\n): UISerializableOrderActionRecord[] =>\n\torderRecords.filter(uiOrderActionRecordIsTrade);\n\n/**\n * Returns the average price for a given base amount and quote amount.\n * @param quoteAmount\n * @param baseAmount\n * @returns PRICE_PRECISION\n */\nexport const getPriceForBaseAndQuoteAmount = (\n\tquoteAmount: BN,\n\tbaseAmount: BN\n) => {\n\treturn quoteAmount\n\t\t.mul(PRICE_PRECISION)\n\t\t.mul(BASE_PRECISION)\n\t\t.div(QUOTE_PRECISION)\n\t\t.div(BigNum.from(baseAmount, BASE_PRECISION_EXP).val);\n};\n\nexport const getPriceForOrderRecord = (\n\torderRecord: Pick<\n\t\tOrderActionRecord,\n\t\t'quoteAssetAmountFilled' | 'baseAssetAmountFilled'\n\t>\n) => {\n\treturn getPriceForBaseAndQuoteAmount(\n\t\t// @ts-ignore\n\t\torderRecord.quoteAssetAmountFilled,\n\t\t// @ts-ignore\n\t\torderRecord.baseAssetAmountFilled\n\t);\n};\n\nexport const getPriceForUIOrderRecord = (\n\torderRecord: Pick<\n\t\tUISerializableOrderActionRecord,\n\t\t'quoteAssetAmountFilled' | 'baseAssetAmountFilled'\n\t>\n) => {\n\treturn orderRecord.quoteAssetAmountFilled\n\t\t.shiftTo(AMM_RESERVE_PRECISION_EXP)\n\t\t.shift(PRICE_PRECISION_EXP)\n\t\t.div(orderRecord.baseAssetAmountFilled.shiftTo(BASE_PRECISION_EXP))\n\t\t.shiftTo(PRICE_PRECISION_EXP);\n};\n\nexport const orderIsNull = (\n\torder: UISerializableOrderActionRecord | Event<OrderActionRecord>,\n\tside: 'taker' | 'maker'\n) => {\n\treturn side === 'taker' ? !order.taker : !order.maker;\n};\n\nexport const getAnchorEnumString = (enumVal: Record<string, unknown>) => {\n\treturn Object.keys(enumVal)[0];\n};\nexport class Ref<T> {\n\tpublic val: T;\n\n\tconstructor(val: T) {\n\t\tthis.val = val;\n\t}\n\n\tset(val: T) {\n\t\tthis.val = val;\n\t}\n\n\tget() {\n\t\treturn this.val;\n\t}\n}\n\nexport class Counter {\n\tprivate val = 0;\n\n\tget() {\n\t\treturn this.val;\n\t}\n\n\tincrement(value = 1) {\n\t\tthis.val += value;\n\t}\n\n\treset() {\n\t\tthis.val = 0;\n\t}\n}\n\n/**\n * A class which allows a group of switches to seperately turn a multiswitch on or off. The base state is the state of the \"multiswitch\" when all of the constituent switches are off. When any of the switches are \"on\" then the multiswitch flips to the opposite state\n *\n * If baseState is on => any switch being \"on\" will turn the multiswitch off.\n * If baseState is off => any switch being \"off\" will turn the multiswitch off.\n */\nexport class MultiSwitch {\n\tprivate switches: string[] = [];\n\tprivate switchValue = 0;\n\n\tconstructor(private baseState: 'on' | 'off' = 'off') {}\n\n\tprivate getSwitchKey(key: string) {\n\t\t// If first time using switch, add to list of switches\n\t\tif (!this.switches.includes(key)) {\n\t\t\tthis.switches.push(key);\n\t\t}\n\n\t\tconst switchIndex = this.switches.indexOf(key);\n\n\t\treturn 2 ** switchIndex;\n\t}\n\n\tpublic switchOn(key: string) {\n\t\tif (this.baseState === 'on') {\n\t\t\tthis._switchOff(key);\n\t\t\treturn;\n\t\t}\n\t\tthis._switchOn(key);\n\t}\n\n\tpublic switchOff(key: string) {\n\t\tif (this.baseState === 'on') {\n\t\t\tthis._switchOn(key);\n\t\t\treturn;\n\t\t}\n\t\tthis._switchOff(key);\n\t}\n\n\tprivate _switchOff(key: string) {\n\t\tconst switchKey = this.getSwitchKey(key);\n\n\t\tthis.switchValue &= ~switchKey;\n\t}\n\n\tprivate _switchOn(key: string) {\n\t\tconst switchKey = this.getSwitchKey(key);\n\n\t\tthis.switchValue |= switchKey;\n\t}\n\n\tpublic get isOn() {\n\t\t// When the base state is on, then if any switch is on the multi-switch is off\n\t\tif (this.baseState === 'on') {\n\t\t\treturn this.switchValue === 0;\n\t\t}\n\n\t\tif (this.baseState === 'off') {\n\t\t\treturn this.switchValue > 0;\n\t\t}\n\t}\n}\n\n/**\n * Returns the quote amount of the current open interest for a market, using the current oracle price\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getCurrentOpenInterestForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.PERP)) {\n\t\tconst market = driftClient.getPerpMarketAccount(marketIndex);\n\t\tconst OI = BigNum.from(\n\t\t\tmarket.amm.baseAssetAmountLong.add(market.amm.baseAssetAmountShort.abs()),\n\t\t\tBASE_PRECISION_EXP\n\t\t);\n\n\t\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\t\tmarket.amm.oracle,\n\t\t\tmarket.amm.oracleSource\n\t\t);\n\n\t\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\t\tconst quoteOIforMarket = price.toNum() * OI.toNum();\n\n\t\treturn quoteOIforMarket;\n\t} else {\n\t\tthrow new Error('Invalid market type for Open Interest calculation');\n\t}\n};\n\n/**\n * Gets the deposit APR for a spot market, in percent\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getDepositAprForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.SPOT)) {\n\t\tconst marketAccount = driftClient.getSpotMarketAccount(marketIndex);\n\n\t\tconst depositApr = BigNum.from(\n\t\t\tcalculateDepositRate(marketAccount),\n\t\t\tSPOT_MARKET_RATE_PRECISION_EXP\n\t\t);\n\n\t\tconst depositAprPct = depositApr.toNum() * 100;\n\n\t\treturn depositAprPct;\n\t} else {\n\t\tthrow new Error('Invalid market type for Deposit APR calculation');\n\t}\n};\n\n/**\n * Get's the borrow APR for a spot market, in percent\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getBorrowAprForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.SPOT)) {\n\t\tconst marketAccount = driftClient.getSpotMarketAccount(marketIndex);\n\n\t\tconst depositApr = BigNum.from(\n\t\t\tcalculateBorrowRate(marketAccount),\n\t\t\tSPOT_MARKET_RATE_PRECISION_EXP\n\t\t);\n\n\t\tconst depositAprPct = depositApr.toNum() * 100;\n\n\t\treturn depositAprPct;\n\t} else {\n\t\tthrow new Error('Invalid market type for Borrow APR calculation');\n\t}\n};\n\nconst getTotalBorrowsForMarket = (\n\tmarket: SpotMarketConfig,\n\tdriftClient: DriftClient\n) => {\n\tconst marketAccount = driftClient.getSpotMarketAccount(market.marketIndex);\n\n\tconst totalBorrowsTokenAmount = getTokenAmount(\n\t\tmarketAccount.borrowBalance,\n\t\tdriftClient.getSpotMarketAccount(marketAccount.marketIndex),\n\t\tSpotBalanceType.BORROW\n\t);\n\n\tconst totalBorrowsAmountBigNum = BigNum.from(\n\t\ttotalBorrowsTokenAmount,\n\t\tmarket.precisionExp\n\t);\n\n\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\tmarketAccount.oracle,\n\t\tmarketAccount.oracleSource\n\t);\n\n\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\tconst totalBorrowsQuote = price.toNum() * totalBorrowsAmountBigNum.toNum();\n\n\treturn Number(totalBorrowsQuote.toFixed(2));\n};\n\nconst getTotalDepositsForMarket = (\n\tmarket: SpotMarketConfig,\n\tdriftClient: DriftClient\n) => {\n\tconst marketAccount = driftClient.getSpotMarketAccount(market.marketIndex);\n\n\tconst totalDepositsTokenAmount = getTokenAmount(\n\t\tmarketAccount.depositBalance,\n\t\tmarketAccount,\n\t\tSpotBalanceType.DEPOSIT\n\t);\n\n\tconst totalDepositsTokenAmountBigNum = BigNum.from(\n\t\ttotalDepositsTokenAmount,\n\t\tmarket.precisionExp\n\t);\n\n\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\tmarketAccount.oracle,\n\t\tmarketAccount.oracleSource\n\t);\n\n\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\tconst totalDepositsBase = totalDepositsTokenAmountBigNum.toNum();\n\tconst totalDepositsQuote =\n\t\tprice.toNum() * totalDepositsTokenAmountBigNum.toNum();\n\n\treturn {\n\t\ttotalDepositsBase,\n\t\ttotalDepositsQuote,\n\t};\n};\n\n/**\n * Check if numbers divide exactly, accounting for floating point division annoyingness\n * @param numerator\n * @param denominator\n * @returns\n */\nconst dividesExactly = (numerator: number, denominator: number) => {\n\tconst division = numerator / denominator;\n\tconst remainder = division % 1;\n\n\tif (remainder === 0) return true;\n\n\t// Because of floating point weirdness, we're just going to assume that if the remainder after dividing is less than 1/10^6 then the numbers do divide exactly\n\tif (Math.abs(remainder - 1) < 1 / 10 ** 6) return true;\n\n\treturn false;\n};\n\nconst toSnakeCase = (str: string): string =>\n\tstr.replace(/[^\\w]/g, '_').toLowerCase();\n\nconst toCamelCase = (str: string): string => {\n\tconst words = str.split(/[_\\-\\s]+/); // split on underscores, hyphens, and spaces\n\tconst firstWord = words[0].toLowerCase();\n\tconst restWords = words\n\t\t.slice(1)\n\t\t.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());\n\treturn [firstWord, ...restWords].join('');\n};\n\nexport const aprFromApy = (apy: number, compoundsPerYear: number) => {\n\tconst compoundedAmount = 1 + apy * 0.01;\n\tconst estimatedApr =\n\t\t(Math.pow(compoundedAmount, 1 / compoundsPerYear) - 1) * compoundsPerYear;\n\n\treturn estimatedApr * 100;\n};\n\n/**\n * Helper utility to get a sort score for \"tiered\" parameters.\n *\n * Example: Want to sort students by Grade, but fall back to using Age if they are equal. This method will accept an array for each student of [grade, age] and return the appropriate sort score for each.\n *\n * @param aScores\n * @param bScores\n * @returns\n */\nexport const getTieredSortScore = (aScores: number[], bScores: number[]) => {\n\tconst maxIndex = Math.max(aScores.length, bScores.length);\n\n\tfor (let i = 0; i < maxIndex; i++) {\n\t\tconst aScore = aScores[i] ?? Number.MIN_SAFE_INTEGER;\n\t\tconst bScore = bScores[i] ?? Number.MIN_SAFE_INTEGER;\n\n\t\tif (aScore !== bScore) return aScore - bScore;\n\t}\n\n\treturn 0;\n};\n\nconst normalizeBaseAssetSymbol = (symbol: string) => {\n\treturn symbol.replace(/^1M/, '');\n};\n\n/**\n * Returns the number of standard deviations between a target value and the history of values to compare it to.\n * @param target\n * @param previousValues\n * @returns\n */\nconst calculateZScore = (target: number, previousValues: number[]): number => {\n\tconst meanValue = calculateMean(previousValues);\n\tconst standardDeviationValue = calculateStandardDeviation(\n\t\tpreviousValues,\n\t\tmeanValue\n\t);\n\n\tconst zScore = (target - meanValue) / standardDeviationValue;\n\treturn zScore;\n};\n\nconst calculateMean = (numbers: number[]): number => {\n\tconst sum = numbers.reduce((total, num) => total + num, 0);\n\treturn sum / numbers.length;\n};\n\nconst calculateMedian = (numbers: number[]): number => {\n\tconst sortedNumbers = numbers.sort();\n\tconst middleIndex = Math.floor(sortedNumbers.length / 2);\n\tif (sortedNumbers.length % 2 === 0) {\n\t\treturn (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2;\n\t} else {\n\t\treturn sortedNumbers[middleIndex];\n\t}\n};\n\nconst calculateStandardDeviation = (\n\tnumbers: number[],\n\tmean: number\n): number => {\n\tconst squaredDifferences = numbers.map((num) => Math.pow(num - mean, 2));\n\tconst sumSquaredDifferences = squaredDifferences.reduce(\n\t\t(total, diff) => total + diff,\n\t\t0\n\t);\n\tconst variance = sumSquaredDifferences / numbers.length;\n\treturn Math.sqrt(variance);\n};\n\nconst glueArray = <T>(size: number, elements: T[]): T[][] => {\n\tconst gluedElements: T[][] = [];\n\n\telements.forEach((element, index) => {\n\t\tconst gluedIndex = Math.floor(index / size);\n\t\tif (gluedElements[gluedIndex]) {\n\t\t\tgluedElements[gluedIndex].push(element);\n\t\t} else {\n\t\t\tgluedElements[gluedIndex] = [element];\n\t\t}\n\t});\n\n\treturn gluedElements;\n};\n\nconst bnMin = (numbers: BN[]): BN => {\n\tlet min = numbers[0];\n\tfor (let i = 1; i < numbers.length; i++) {\n\t\tif (numbers[i].lt(min)) {\n\t\t\tmin = numbers[i];\n\t\t}\n\t}\n\treturn min;\n};\n\nconst bnMax = (numbers: BN[]): BN => {\n\tlet max = numbers[0];\n\tfor (let i = 1; i < numbers.length; i++) {\n\t\tif (numbers[i].gt(max)) {\n\t\t\tmax = numbers[i];\n\t\t}\n\t}\n\treturn max;\n};\n\nconst bnMedian = (numbers: BN[]): BN => {\n\tconst sortedNumbers = numbers.sort((a, b) => a.cmp(b));\n\tconst middleIndex = Math.floor(sortedNumbers.length / 2);\n\tif (sortedNumbers.length % 2 === 0) {\n\t\treturn sortedNumbers[middleIndex - 1]\n\t\t\t.add(sortedNumbers[middleIndex])\n\t\t\t.div(new BN(2));\n\t} else {\n\t\treturn sortedNumbers[middleIndex];\n\t}\n};\n\nconst bnMean = (numbers: BN[]): BN => {\n\tlet sum = new BN(0);\n\tfor (let i = 0; i < numbers.length; i++) {\n\t\tsum = sum.add(numbers[i]);\n\t}\n\treturn sum.div(new BN(numbers.length));\n};\n\nconst timedPromise = async <T>(promise: T) => {\n\tconst start = Date.now();\n\tconst promiseResult = await promise;\n\n\treturn {\n\t\tpromiseTime: Date.now() - start,\n\t\tpromiseResult,\n\t};\n};\n\nconst chunks = <T>(array: readonly T[], size: number): T[][] => {\n\treturn new Array(Math.ceil(array.length / size))\n\t\t.fill(null)\n\t\t.map((_, index) => index * size)\n\t\t.map((begin) => array.slice(begin, begin + size));\n};\n\nconst getMultipleAccountsInfoChunked = async (\n\tconnection: Connection,\n\taccounts: PublicKey[]\n): Promise<(AccountInfo<Buffer> | null)[]> => {\n\tconst accountChunks = chunks(accounts, 100); // 100 is limit for getMultipleAccountsInfo\n\tconst responses = await Promise.all(\n\t\taccountChunks.map((chunk) => connection.getMultipleAccountsInfo(chunk))\n\t);\n\treturn responses.flat();\n};\n\nexport const COMMON_UTILS = {\n\tgetIfVaultBalance,\n\tgetIfStakingVaultApr,\n\tgetCurrentOpenInterestForMarket,\n\tgetDepositAprForMarket,\n\tgetBorrowAprForMarket,\n\tgetTotalBorrowsForMarket,\n\tgetTotalDepositsForMarket,\n\tdividesExactly,\n\ttoSnakeCase,\n\ttoCamelCase,\n\tgetTieredSortScore,\n\tnormalizeBaseAssetSymbol,\n\tcalculateZScore,\n\tglueArray,\n\ttimedPromise,\n\tchunks,\n\tgetMultipleAccountsInfoChunked,\n\tMATH: {\n\t\tNUM: {\n\t\t\tmean: calculateMean,\n\t\t\tmedian: calculateMedian,\n\t\t},\n\t\tBN: {\n\t\t\tbnMax,\n\t\t\tbnMin,\n\t\t\tbnMean,\n\t\t\tbnMedian,\n\t\t},\n\t},\n};\nexport { getSwiftConfirmationTimeoutMs } from './signedMsgs';\nexport { ResultSlotIncrementer } from './ResultSlotIncrementer';\nexport { MultiplexWebSocket } from './MultiplexWebSocket';\n"]}
@@ -1,4 +1,25 @@
1
- import { L2OrderBook } from '@drift-labs/sdk';
1
+ import { BigNum, L2OrderBook } from '@drift-labs/sdk';
2
+ export declare const TRADE_PRECISION = 6;
3
+ export declare const getPctCompletion: (start: number, end: number, current: number) => number;
4
+ export declare const sortBnAsc: (bnA: BN, bnB: BN) => 0 | 1 | -1;
5
+ export declare const sortBnDesc: (bnA: BN, bnB: BN) => 0 | 1 | -1;
6
+ export declare const getBigNumRoundedToStepSize: (baseSize: BigNum, stepSize: BN) => BigNum;
7
+ export declare const truncateInputToPrecision: (input: string, marketPrecisionExp: BN) => string;
8
+ export declare const roundToStepSize: (value: string, stepSize?: number) => string;
9
+ export declare const roundToStepSizeIfLargeEnough: (value: string, stepSize?: number) => string;
10
+ export declare const valueIsBelowStepSize: (value: string, stepSize: number) => boolean;
11
+ /**
12
+ * NOTE: Do not use modulo alone to check if numbers fit evenly.
13
+ * Due to floating point precision issues this can return incorrect results.
14
+ * i.e. 5.1 % 0.1 = 0.09999999999999959 (should be 0)
15
+ * tells me 5.1 / 0.1 = 50.99999999999999
16
+ */
17
+ export declare const numbersFitEvenly: (numberOne: number, numberTwo: number) => boolean;
18
+ export declare function roundToDecimal(value: number, decimals: number | undefined | null): number;
19
+ export declare const roundBigNumToDecimalPlace: (bignum: BigNum, decimalPlaces: number) => BigNum;
20
+ export declare const sortRecordsByTs: <T extends {
21
+ ts: BN;
22
+ }[]>(records: T | undefined, direction?: 'asc' | 'desc') => T[number][];
2
23
  export declare const COMMON_MATH: {
3
24
  calculateSpreadBidAskMark: (l2: Pick<L2OrderBook, 'bids' | 'asks'>, oraclePrice?: BN) => {
4
25
  bestBidPrice: BN;
package/lib/utils/math.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.COMMON_MATH = void 0;
3
+ exports.COMMON_MATH = exports.sortRecordsByTs = exports.roundBigNumToDecimalPlace = exports.roundToDecimal = exports.numbersFitEvenly = exports.valueIsBelowStepSize = exports.roundToStepSizeIfLargeEnough = exports.roundToStepSize = exports.truncateInputToPrecision = exports.getBigNumRoundedToStepSize = exports.sortBnDesc = exports.sortBnAsc = exports.getPctCompletion = exports.TRADE_PRECISION = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
5
  const calculateMarkPrice = (bestBidPrice, bestAskPrice, oraclePrice) => {
6
6
  const bid = bestBidPrice;
@@ -83,6 +83,98 @@ const calculateSpreadBidAskMark = (l2, oraclePrice) => {
83
83
  spreadQuote,
84
84
  };
85
85
  };
86
+ exports.TRADE_PRECISION = 6;
87
+ const getPctCompletion = (start, end, current) => {
88
+ const totalProgressSize = end - start;
89
+ const currentProgressSize = current - start;
90
+ return (currentProgressSize / totalProgressSize) * 100;
91
+ };
92
+ exports.getPctCompletion = getPctCompletion;
93
+ const sortBnAsc = (bnA, bnB) => {
94
+ if (bnA.gt(bnB))
95
+ return 1;
96
+ if (bnA.eq(bnB))
97
+ return 0;
98
+ if (bnA.lt(bnB))
99
+ return -1;
100
+ return 0;
101
+ };
102
+ exports.sortBnAsc = sortBnAsc;
103
+ const sortBnDesc = (bnA, bnB) => (0, exports.sortBnAsc)(bnB, bnA);
104
+ exports.sortBnDesc = sortBnDesc;
105
+ const getBigNumRoundedToStepSize = (baseSize, stepSize) => {
106
+ const baseSizeRounded = baseSize.div(stepSize).mul(stepSize);
107
+ return baseSizeRounded;
108
+ };
109
+ exports.getBigNumRoundedToStepSize = getBigNumRoundedToStepSize;
110
+ const truncateInputToPrecision = (input, marketPrecisionExp) => {
111
+ var _a, _b;
112
+ const decimalPlaces = (_b = (_a = input.split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
113
+ const maxDecimals = marketPrecisionExp.toNumber();
114
+ if (decimalPlaces > maxDecimals) {
115
+ return input.slice(0, input.length - (decimalPlaces - maxDecimals));
116
+ }
117
+ return input;
118
+ };
119
+ exports.truncateInputToPrecision = truncateInputToPrecision;
120
+ const roundToStepSize = (value, stepSize) => {
121
+ var _a, _b;
122
+ const stepSizeExp = (_b = (_a = stepSize === null || stepSize === void 0 ? void 0 : stepSize.toString().split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
123
+ const truncatedValue = (0, exports.truncateInputToPrecision)(value, new sdk_1.BN(stepSizeExp));
124
+ if (truncatedValue.charAt(truncatedValue.length - 1) === '.') {
125
+ return truncatedValue.slice(0, -1);
126
+ }
127
+ return truncatedValue;
128
+ };
129
+ exports.roundToStepSize = roundToStepSize;
130
+ const roundToStepSizeIfLargeEnough = (value, stepSize) => {
131
+ const parsedValue = parseFloat(value);
132
+ if (isNaN(parsedValue) || stepSize === 0 || !value || parsedValue === 0) {
133
+ return value;
134
+ }
135
+ return (0, exports.roundToStepSize)(value, stepSize);
136
+ };
137
+ exports.roundToStepSizeIfLargeEnough = roundToStepSizeIfLargeEnough;
138
+ const valueIsBelowStepSize = (value, stepSize) => {
139
+ const parsedValue = parseFloat(value);
140
+ if (isNaN(parsedValue))
141
+ return false;
142
+ return parsedValue < stepSize;
143
+ };
144
+ exports.valueIsBelowStepSize = valueIsBelowStepSize;
145
+ /**
146
+ * NOTE: Do not use modulo alone to check if numbers fit evenly.
147
+ * Due to floating point precision issues this can return incorrect results.
148
+ * i.e. 5.1 % 0.1 = 0.09999999999999959 (should be 0)
149
+ * tells me 5.1 / 0.1 = 50.99999999999999
150
+ */
151
+ const numbersFitEvenly = (numberOne, numberTwo) => {
152
+ if (isNaN(numberOne) || isNaN(numberTwo))
153
+ return false;
154
+ if (numberOne === 0 || numberTwo === 0)
155
+ return true;
156
+ return (Number.isInteger(Number((numberOne / numberTwo).toFixed(9))) ||
157
+ numberOne % numberTwo === 0);
158
+ };
159
+ exports.numbersFitEvenly = numbersFitEvenly;
160
+ function roundToDecimal(value, decimals) {
161
+ return decimals ? Math.round(value * 10 ** decimals) / 10 ** decimals : value;
162
+ }
163
+ exports.roundToDecimal = roundToDecimal;
164
+ const roundBigNumToDecimalPlace = (bignum, decimalPlaces) => {
165
+ const factor = Math.pow(10, decimalPlaces);
166
+ const newNum = Math.round(bignum.toNum() * factor) / factor;
167
+ return sdk_1.BigNum.fromPrint(newNum.toString(), bignum.precision);
168
+ };
169
+ exports.roundBigNumToDecimalPlace = roundBigNumToDecimalPlace;
170
+ const sortRecordsByTs = (records, direction = 'desc') => {
171
+ if (!records || !(records === null || records === void 0 ? void 0 : records.length))
172
+ return [];
173
+ return direction === 'desc'
174
+ ? [...records].sort((a, b) => b.ts.toNumber() - a.ts.toNumber())
175
+ : [...records].sort((a, b) => a.ts.toNumber() - b.ts.toNumber());
176
+ };
177
+ exports.sortRecordsByTs = sortRecordsByTs;
86
178
  exports.COMMON_MATH = {
87
179
  calculateSpreadBidAskMark,
88
180
  };
@@ -1 +1 @@
1
- {"version":3,"file":"math.js","sourceRoot":"","sources":["../../src/utils/math.ts"],"names":[],"mappings":";;;AAAA,yCAA8E;AAE9E,MAAM,kBAAkB,GAAG,CAC1B,YAAiB,EACjB,YAAiB,EACjB,WAAgB,EACf,EAAE;IACH,MAAM,GAAG,GAAG,YAAY,CAAC;IACzB,MAAM,GAAG,GAAG,YAAY,CAAC;IAEzB,IAAI,GAAO,CAAC;IAEZ,0GAA0G;IAC1G,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,CA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B,SAAS,EAAE,SAAS;YACpB,YAAY,EAAE,SAAS;YACvB,YAAY,EAAE,SAAS;SACvB,CAAC;IACH,CAAC;IAED,MAAM,EAAE,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,GAAG,2BAA2B,CAC5E,EAAE,EACF,WAAW,CACX,CAAC;IAEF,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,GAAG,eAAe,CACjD,YAAY,EACZ,YAAY,EACZ,SAAS,CACT,CAAC;IACF,OAAO;QACN,YAAY;QACZ,YAAY;QACZ,SAAS;QACT,SAAS;QACT,WAAW;KACX,CAAC;AACH,CAAC,CAAC;AAEW,QAAA,WAAW,GAAG;IAC1B,yBAAyB;CACzB,CAAC","sourcesContent":["import { BN, L2OrderBook, PERCENTAGE_PRECISION, ZERO } from '@drift-labs/sdk';\n\nconst calculateMarkPrice = (\n\tbestBidPrice?: BN,\n\tbestAskPrice?: BN,\n\toraclePrice?: BN\n) => {\n\tconst bid = bestBidPrice;\n\tconst ask = bestAskPrice;\n\n\tlet mid: BN;\n\n\t// if bid/ask cross, force it to be the one closer to oracle, if oracle is in the middle, use oracle price\n\tif (bid && ask && bid.gt(ask) && oraclePrice) {\n\t\tif (bid.gt(oraclePrice) && ask.gt(oraclePrice)) {\n\t\t\tmid = BN.min(bid, ask);\n\t\t} else if (bid.lt(oraclePrice) && ask.lt(oraclePrice)) {\n\t\t\tmid = BN.max(bid, ask);\n\t\t} else {\n\t\t\tmid = oraclePrice;\n\t\t}\n\t} else {\n\t\tif (bid && ask) {\n\t\t\tmid = bid.add(ask).divn(2);\n\t\t} else if (oraclePrice) {\n\t\t\tmid = oraclePrice;\n\t\t} else {\n\t\t\tmid = undefined;\n\t\t}\n\t}\n\n\treturn mid;\n};\n\nconst calculateBidAskAndmarkPrice = (l2: L2OrderBook, oraclePrice?: BN) => {\n\tconst bestBidPrice = l2.bids.reduce((previousMax, currentBid) => {\n\t\tif (!previousMax) return currentBid.price;\n\t\treturn BN.max(currentBid.price, previousMax);\n\t}, undefined as BN);\n\n\tconst bestAskPrice = l2.asks.reduce((previousMin, currentBid) => {\n\t\tif (!previousMin) return currentBid.price;\n\t\treturn BN.min(currentBid.price, previousMin);\n\t}, undefined as BN);\n\n\tconst markPrice = calculateMarkPrice(bestBidPrice, bestAskPrice, oraclePrice);\n\n\treturn {\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice,\n\t};\n};\n\nconst calculateSpreadQuote = (bestBidPrice: BN, bestAskPrice: BN) => {\n\treturn BN.max(bestAskPrice.sub(bestBidPrice), ZERO);\n};\n\nfunction calculateSpreadPct(markPricePrice: BN, spreadQuote: BN) {\n\treturn spreadQuote.muln(100).mul(PERCENTAGE_PRECISION).div(markPricePrice);\n}\n\nconst calculateSpread = (bestBidPrice: BN, bestAskPrice: BN, markPrice: BN) => {\n\tconst spreadQuote = calculateSpreadQuote(bestBidPrice, bestAskPrice);\n\tconst spreadPct = calculateSpreadPct(markPrice, spreadQuote);\n\n\treturn {\n\t\tspreadPct,\n\t\tspreadQuote,\n\t};\n};\n\nconst calculateSpreadBidAskMark = (\n\tl2: Pick<L2OrderBook, 'bids' | 'asks'>,\n\toraclePrice?: BN\n) => {\n\tif (l2.asks.length === 0 || l2.bids.length === 0) {\n\t\treturn {\n\t\t\tspreadQuote: undefined,\n\t\t\tspreadPct: undefined,\n\t\t\tmarkPrice: undefined,\n\t\t\tbestBidPrice: undefined,\n\t\t\tbestAskPrice: undefined,\n\t\t};\n\t}\n\n\tconst { bestBidPrice, bestAskPrice, markPrice } = calculateBidAskAndmarkPrice(\n\t\tl2,\n\t\toraclePrice\n\t);\n\n\tconst { spreadPct, spreadQuote } = calculateSpread(\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice\n\t);\n\treturn {\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice,\n\t\tspreadPct,\n\t\tspreadQuote,\n\t};\n};\n\nexport const COMMON_MATH = {\n\tcalculateSpreadBidAsk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CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC;QAChE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;AACnE,CAAC,CAAC;AATW,QAAA,eAAe,mBAS1B;AAEW,QAAA,WAAW,GAAG;IAC1B,yBAAyB;CACzB,CAAC","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tL2OrderBook,\n\tPERCENTAGE_PRECISION,\n\tSpotMarketConfig,\n\tZERO,\n} from '@drift-labs/sdk';\n\nconst calculateMarkPrice = (\n\tbestBidPrice?: BN,\n\tbestAskPrice?: BN,\n\toraclePrice?: BN\n) => {\n\tconst bid = bestBidPrice;\n\tconst ask = bestAskPrice;\n\n\tlet mid: BN;\n\n\t// if bid/ask cross, force it to be the one closer to oracle, if oracle is in the middle, use oracle price\n\tif (bid && ask && bid.gt(ask) && oraclePrice) {\n\t\tif (bid.gt(oraclePrice) && ask.gt(oraclePrice)) {\n\t\t\tmid = BN.min(bid, ask);\n\t\t} else if (bid.lt(oraclePrice) && ask.lt(oraclePrice)) {\n\t\t\tmid = BN.max(bid, ask);\n\t\t} else {\n\t\t\tmid = oraclePrice;\n\t\t}\n\t} else {\n\t\tif (bid && ask) {\n\t\t\tmid = bid.add(ask).divn(2);\n\t\t} else if (oraclePrice) {\n\t\t\tmid = oraclePrice;\n\t\t} else {\n\t\t\tmid = undefined;\n\t\t}\n\t}\n\n\treturn mid;\n};\n\nconst calculateBidAskAndmarkPrice = (l2: L2OrderBook, oraclePrice?: BN) => {\n\tconst bestBidPrice = l2.bids.reduce((previousMax, currentBid) => {\n\t\tif (!previousMax) return currentBid.price;\n\t\treturn BN.max(currentBid.price, previousMax);\n\t}, undefined as BN);\n\n\tconst bestAskPrice = l2.asks.reduce((previousMin, currentBid) => {\n\t\tif (!previousMin) return currentBid.price;\n\t\treturn BN.min(currentBid.price, previousMin);\n\t}, undefined as BN);\n\n\tconst markPrice = calculateMarkPrice(bestBidPrice, bestAskPrice, oraclePrice);\n\n\treturn {\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice,\n\t};\n};\n\nconst calculateSpreadQuote = (bestBidPrice: BN, bestAskPrice: BN) => {\n\treturn BN.max(bestAskPrice.sub(bestBidPrice), ZERO);\n};\n\nfunction calculateSpreadPct(markPricePrice: BN, spreadQuote: BN) {\n\treturn spreadQuote.muln(100).mul(PERCENTAGE_PRECISION).div(markPricePrice);\n}\n\nconst calculateSpread = (bestBidPrice: BN, bestAskPrice: BN, markPrice: BN) => {\n\tconst spreadQuote = calculateSpreadQuote(bestBidPrice, bestAskPrice);\n\tconst spreadPct = calculateSpreadPct(markPrice, spreadQuote);\n\n\treturn {\n\t\tspreadPct,\n\t\tspreadQuote,\n\t};\n};\n\nconst calculateSpreadBidAskMark = (\n\tl2: Pick<L2OrderBook, 'bids' | 'asks'>,\n\toraclePrice?: BN\n) => {\n\tif (l2.asks.length === 0 || l2.bids.length === 0) {\n\t\treturn {\n\t\t\tspreadQuote: undefined,\n\t\t\tspreadPct: undefined,\n\t\t\tmarkPrice: undefined,\n\t\t\tbestBidPrice: undefined,\n\t\t\tbestAskPrice: undefined,\n\t\t};\n\t}\n\n\tconst { bestBidPrice, bestAskPrice, markPrice } = calculateBidAskAndmarkPrice(\n\t\tl2,\n\t\toraclePrice\n\t);\n\n\tconst { spreadPct, spreadQuote } = calculateSpread(\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice\n\t);\n\treturn {\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice,\n\t\tspreadPct,\n\t\tspreadQuote,\n\t};\n};\n\nexport const TRADE_PRECISION = 6;\n\nexport const getPctCompletion = (\n\tstart: number,\n\tend: number,\n\tcurrent: number\n) => {\n\tconst totalProgressSize = end - start;\n\tconst currentProgressSize = current - start;\n\n\treturn (currentProgressSize / totalProgressSize) * 100;\n};\n\nexport const sortBnAsc = (bnA: BN, bnB: BN) => {\n\tif (bnA.gt(bnB)) return 1;\n\tif (bnA.eq(bnB)) return 0;\n\tif (bnA.lt(bnB)) return -1;\n\n\treturn 0;\n};\n\nexport const sortBnDesc = (bnA: BN, bnB: BN) => sortBnAsc(bnB, bnA);\n\nexport const getBigNumRoundedToStepSize = (baseSize: BigNum, stepSize: BN) => {\n\tconst baseSizeRounded = baseSize.div(stepSize).mul(stepSize);\n\treturn baseSizeRounded;\n};\n\nexport const truncateInputToPrecision = (\n\tinput: string,\n\tmarketPrecisionExp: SpotMarketConfig['precisionExp']\n) => {\n\tconst decimalPlaces = input.split('.')[1]?.length ?? 0;\n\tconst maxDecimals = marketPrecisionExp.toNumber();\n\n\tif (decimalPlaces > maxDecimals) {\n\t\treturn input.slice(0, input.length - (decimalPlaces - maxDecimals));\n\t}\n\n\treturn input;\n};\n\nexport const roundToStepSize = (value: string, stepSize?: number) => {\n\tconst stepSizeExp = stepSize?.toString().split('.')[1]?.length ?? 0;\n\tconst truncatedValue = truncateInputToPrecision(value, new BN(stepSizeExp));\n\n\tif (truncatedValue.charAt(truncatedValue.length - 1) === '.') {\n\t\treturn truncatedValue.slice(0, -1);\n\t}\n\n\treturn truncatedValue;\n};\n\nexport const roundToStepSizeIfLargeEnough = (\n\tvalue: string,\n\tstepSize?: number\n) => {\n\tconst parsedValue = parseFloat(value);\n\tif (isNaN(parsedValue) || stepSize === 0 || !value || parsedValue === 0) {\n\t\treturn value;\n\t}\n\n\treturn roundToStepSize(value, stepSize);\n};\n\nexport const valueIsBelowStepSize = (value: string, stepSize: number) => {\n\tconst parsedValue = parseFloat(value);\n\n\tif (isNaN(parsedValue)) return false;\n\n\treturn parsedValue < stepSize;\n};\n\n/**\n * NOTE: Do not use modulo alone to check if numbers fit evenly.\n * Due to floating point precision issues this can return incorrect results.\n * i.e. 5.1 % 0.1 = 0.09999999999999959 (should be 0)\n * tells me 5.1 / 0.1 = 50.99999999999999\n */\nexport const numbersFitEvenly = (\n\tnumberOne: number,\n\tnumberTwo: number\n): boolean => {\n\tif (isNaN(numberOne) || isNaN(numberTwo)) return false;\n\tif (numberOne === 0 || numberTwo === 0) return true;\n\n\treturn (\n\t\tNumber.isInteger(Number((numberOne / numberTwo).toFixed(9))) ||\n\t\tnumberOne % numberTwo === 0\n\t);\n};\n\nexport function roundToDecimal(\n\tvalue: number,\n\tdecimals: number | undefined | null\n) {\n\treturn decimals ? Math.round(value * 10 ** decimals) / 10 ** decimals : value;\n}\n\nexport const roundBigNumToDecimalPlace = (\n\tbignum: BigNum,\n\tdecimalPlaces: number\n): BigNum => {\n\tconst factor = Math.pow(10, decimalPlaces);\n\tconst newNum = Math.round(bignum.toNum() * factor) / factor;\n\treturn BigNum.fromPrint(newNum.toString(), bignum.precision);\n};\n\nexport const sortRecordsByTs = <T extends { ts: BN }[]>(\n\trecords: T | undefined,\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tif (!records || !records?.length) return [];\n\n\treturn direction === 'desc'\n\t\t? [...records].sort((a, b) => b.ts.toNumber() - a.ts.toNumber())\n\t\t: [...records].sort((a, b) => a.ts.toNumber() - b.ts.toNumber());\n};\n\nexport const COMMON_MATH = {\n\tcalculateSpreadBidAskMark,\n};\n"]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * There is a "millify" npm library but it is multiple kilobytes and opens space
3
+ * for security vulnerabilities. Easier to just roll our own as it's not complicated.
4
+ */
5
+ interface MillifyOptions {
6
+ precision?: number;
7
+ decimals?: number;
8
+ notation?: 'scientific' | 'financial';
9
+ trimEndingZeroes?: boolean;
10
+ }
11
+ export default function millify(value: number, options?: MillifyOptions): string;
12
+ export {};
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ /**
3
+ * There is a "millify" npm library but it is multiple kilobytes and opens space
4
+ * for security vulnerabilities. Easier to just roll our own as it's not complicated.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const FINANCIAL_UNITS = ['', 'K', 'M', 'B', 'T', 'Q'];
8
+ const SCIENTIFIC_UNITS = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
9
+ function millify(value, options) {
10
+ var _a, _b, _c;
11
+ const precision = (_a = options === null || options === void 0 ? void 0 : options.precision) !== null && _a !== void 0 ? _a : 6;
12
+ const trimEndingZeroes = (_b = options === null || options === void 0 ? void 0 : options.trimEndingZeroes) !== null && _b !== void 0 ? _b : false;
13
+ if (isNaN(value))
14
+ return '0';
15
+ const isNegative = value < 0;
16
+ const absoluteValue = Math.abs(value);
17
+ const units = ((_c = options === null || options === void 0 ? void 0 : options.notation) !== null && _c !== void 0 ? _c : 'financial') === 'financial'
18
+ ? FINANCIAL_UNITS
19
+ : SCIENTIFIC_UNITS;
20
+ if (absoluteValue < 1000) {
21
+ const formattedValue = absoluteValue.toPrecision(precision);
22
+ const trimmedValue = trimEndingZeroes
23
+ ? parseFloat(formattedValue).toString()
24
+ : formattedValue;
25
+ return `${isNegative ? '-' : ''}${trimmedValue}`;
26
+ }
27
+ const unitIndex = Math.min(Math.floor(Math.log10(absoluteValue) / 3), units.length - 1);
28
+ const scaledValue = absoluteValue / Math.pow(1000, unitIndex);
29
+ const valueWithDecimals = (options === null || options === void 0 ? void 0 : options.decimals) !== undefined
30
+ ? scaledValue.toFixed(options.decimals)
31
+ : scaledValue.toPrecision(precision);
32
+ const trimmedValue = trimEndingZeroes
33
+ ? parseFloat(valueWithDecimals).toString()
34
+ : valueWithDecimals;
35
+ return `${isNegative ? '-' : ''}${trimmedValue}${units[unitIndex]}`;
36
+ }
37
+ exports.default = millify;
38
+ //# sourceMappingURL=millify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"millify.js","sourceRoot":"","sources":["../../src/utils/millify.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AASH,MAAM,eAAe,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG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AAG,CAAC,CAAC,EACzC,KAAK,CAAC,MAAM,GAAG,CAAC,CAChB,CAAC;IAEF,MAAM,WAAW,GAAG,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IAC9D,MAAM,iBAAiB,GACtB,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,MAAK,SAAS;QAC9B,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC;QACvC,CAAC,CAAC,WAAW,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;IAEvC,MAAM,YAAY,GAAG,gBAAgB;QACpC,CAAC,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE;QAC1C,CAAC,CAAC,iBAAiB,CAAC;IAErB,OAAO,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,YAAY,GAAG,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;AACrE,CAAC;AAzCD,0BAyCC","sourcesContent":["/**\n * There is a \"millify\" npm library but it is multiple kilobytes and opens space\n * for security vulnerabilities. Easier to just roll our own as it's not complicated.\n */\n\ninterface MillifyOptions {\n\tprecision?: number;\n\tdecimals?: number;\n\tnotation?: 'scientific' | 'financial';\n\ttrimEndingZeroes?: boolean;\n}\n\nconst FINANCIAL_UNITS = ['', 'K', 'M', 'B', 'T', 'Q'];\nconst SCIENTIFIC_UNITS = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];\n\nexport default function millify(\n\tvalue: number,\n\toptions?: MillifyOptions\n): string {\n\tconst precision = options?.precision ?? 6;\n\tconst trimEndingZeroes = options?.trimEndingZeroes ?? false;\n\n\tif (isNaN(value)) return '0';\n\n\tconst isNegative = value < 0;\n\tconst absoluteValue = Math.abs(value);\n\n\tconst units =\n\t\t(options?.notation ?? 'financial') === 'financial'\n\t\t\t? FINANCIAL_UNITS\n\t\t\t: SCIENTIFIC_UNITS;\n\n\tif (absoluteValue < 1000) {\n\t\tconst formattedValue = absoluteValue.toPrecision(precision);\n\t\tconst trimmedValue = trimEndingZeroes\n\t\t\t? parseFloat(formattedValue).toString()\n\t\t\t: formattedValue;\n\t\treturn `${isNegative ? '-' : ''}${trimmedValue}`;\n\t}\n\n\tconst unitIndex = Math.min(\n\t\tMath.floor(Math.log10(absoluteValue) / 3),\n\t\tunits.length - 1\n\t);\n\n\tconst scaledValue = absoluteValue / Math.pow(1000, unitIndex);\n\tconst valueWithDecimals =\n\t\toptions?.decimals !== undefined\n\t\t\t? scaledValue.toFixed(options.decimals)\n\t\t\t: scaledValue.toPrecision(precision);\n\n\tconst trimmedValue = trimEndingZeroes\n\t\t? parseFloat(valueWithDecimals).toString()\n\t\t: valueWithDecimals;\n\n\treturn `${isNegative ? '-' : ''}${trimmedValue}${units[unitIndex]}`;\n}\n"]}
@@ -0,0 +1,34 @@
1
+ export declare const isValidBase58: (str: string) => boolean;
2
+ export declare function abbreviateAccountName(name: string, size?: number, opts?: {
3
+ ellipsisMiddle?: boolean;
4
+ }): string;
5
+ export declare function splitByCapitalLetters(word: string): string;
6
+ export declare function lowerCaseNonFirstWords(sentence: string): string;
7
+ export declare const disallowNegativeStringInput: (str: string) => string;
8
+ /**
9
+ * LastOrder status types from https://github.com/drift-labs/infrastructure-v3/blob/8ab1888eaaaed96228406b562d4a399729d042d7/packages/common/src/types/index.ts#L221
10
+ */
11
+ declare const LAST_ORDER_STATUS_LABELS: {
12
+ readonly open: "Open";
13
+ readonly filled: "Filled";
14
+ readonly partial_fill: "Partially Filled";
15
+ readonly cancelled: "Canceled";
16
+ readonly partial_fill_cancelled: "Partially Filled & Canceled";
17
+ readonly expired: "Expired";
18
+ readonly trigger: "Triggered";
19
+ };
20
+ export type LastOrderStatus = keyof typeof LAST_ORDER_STATUS_LABELS;
21
+ export type LastOrderStatusLabel = (typeof LAST_ORDER_STATUS_LABELS)[LastOrderStatus];
22
+ export declare function lastOrderStatusToNormalEng(status: string): LastOrderStatusLabel | string;
23
+ /**
24
+ * Recursively converts various types into printable strings.
25
+ */
26
+ export declare function toPrintableObject(obj: unknown,
27
+ /** Used to guard against circular refs during recursion. */
28
+ seen?: WeakSet<object>): unknown;
29
+ export declare function convertStringValuesToNumbers<T>(obj: T): T;
30
+ /**
31
+ * Returns an array of an object's string values (deep).
32
+ */
33
+ export declare function extractStringValuesFromObject(value: object): string[];
34
+ export {};
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extractStringValuesFromObject = exports.convertStringValuesToNumbers = exports.toPrintableObject = exports.lastOrderStatusToNormalEng = exports.disallowNegativeStringInput = exports.lowerCaseNonFirstWords = exports.splitByCapitalLetters = exports.abbreviateAccountName = exports.isValidBase58 = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const isValidBase58 = (str) => /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(str);
6
+ exports.isValidBase58 = isValidBase58;
7
+ function abbreviateAccountName(name, size = 8, opts) {
8
+ if (name.length <= size)
9
+ return name;
10
+ if (opts === null || opts === void 0 ? void 0 : opts.ellipsisMiddle) {
11
+ const length = name.length;
12
+ const sizeMid = Math.floor(size / 2);
13
+ return name.slice(0, sizeMid) + '...' + name.slice(length - sizeMid);
14
+ }
15
+ return name.slice(0, size) + '...';
16
+ }
17
+ exports.abbreviateAccountName = abbreviateAccountName;
18
+ function splitByCapitalLetters(word) {
19
+ return word.replace(/([A-Z])/g, ' $1').trim();
20
+ }
21
+ exports.splitByCapitalLetters = splitByCapitalLetters;
22
+ function lowerCaseNonFirstWords(sentence) {
23
+ const words = sentence.split(' ');
24
+ for (let i = 1; i < words.length; i++) {
25
+ words[i] = words[i].toLowerCase();
26
+ }
27
+ return words.join(' ');
28
+ }
29
+ exports.lowerCaseNonFirstWords = lowerCaseNonFirstWords;
30
+ const disallowNegativeStringInput = (str) => {
31
+ if (str && str.charAt(0) === '-') {
32
+ return '0';
33
+ }
34
+ return str;
35
+ };
36
+ exports.disallowNegativeStringInput = disallowNegativeStringInput;
37
+ /**
38
+ * LastOrder status types from https://github.com/drift-labs/infrastructure-v3/blob/8ab1888eaaaed96228406b562d4a399729d042d7/packages/common/src/types/index.ts#L221
39
+ */
40
+ const LAST_ORDER_STATUS_LABELS = {
41
+ open: 'Open',
42
+ filled: 'Filled',
43
+ partial_fill: 'Partially Filled',
44
+ cancelled: 'Canceled',
45
+ partial_fill_cancelled: 'Partially Filled & Canceled',
46
+ expired: 'Expired',
47
+ trigger: 'Triggered',
48
+ };
49
+ function lastOrderStatusToNormalEng(status) {
50
+ var _a;
51
+ return (_a = LAST_ORDER_STATUS_LABELS[status]) !== null && _a !== void 0 ? _a : status;
52
+ }
53
+ exports.lastOrderStatusToNormalEng = lastOrderStatusToNormalEng;
54
+ /**
55
+ * Recursively converts various types into printable strings.
56
+ */
57
+ function toPrintableObject(obj,
58
+ /** Used to guard against circular refs during recursion. */
59
+ seen = new WeakSet()) {
60
+ if (obj == null) {
61
+ return null;
62
+ }
63
+ if (obj instanceof sdk_1.BigNum || sdk_1.BN.isBN(obj) || typeof obj === 'bigint') {
64
+ return obj.toString();
65
+ }
66
+ if (obj instanceof Date) {
67
+ const time = obj.getTime();
68
+ if (Number.isNaN(time)) {
69
+ return 'Invalid Date';
70
+ }
71
+ return obj.toISOString();
72
+ }
73
+ if (typeof obj === 'object') {
74
+ if (seen.has(obj)) {
75
+ return '[Circular]';
76
+ }
77
+ seen.add(obj);
78
+ if (Array.isArray(obj)) {
79
+ return obj.map((value) => toPrintableObject(value, seen));
80
+ }
81
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [
82
+ key,
83
+ toPrintableObject(value, seen),
84
+ ]));
85
+ }
86
+ return obj;
87
+ }
88
+ exports.toPrintableObject = toPrintableObject;
89
+ function convertStringValuesToNumbers(obj) {
90
+ if (typeof obj === 'string' && !isNaN(Number(obj))) {
91
+ return Number(obj);
92
+ }
93
+ if (Array.isArray(obj)) {
94
+ return obj.map(convertStringValuesToNumbers);
95
+ }
96
+ if (obj !== null && typeof obj === 'object') {
97
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [
98
+ key,
99
+ convertStringValuesToNumbers(value),
100
+ ]));
101
+ }
102
+ return obj;
103
+ }
104
+ exports.convertStringValuesToNumbers = convertStringValuesToNumbers;
105
+ /**
106
+ * Returns an array of an object's string values (deep).
107
+ */
108
+ function extractStringValuesFromObject(value) {
109
+ if (typeof value === 'string') {
110
+ return [value];
111
+ }
112
+ if (Array.isArray(value)) {
113
+ return value.flatMap(extractStringValuesFromObject);
114
+ }
115
+ if (value && typeof value === 'object') {
116
+ return Object.values(value).flatMap(extractStringValuesFromObject);
117
+ }
118
+ return [];
119
+ }
120
+ exports.extractStringValuesFromObject = extractStringValuesFromObject;
121
+ //# sourceMappingURL=strings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strings.js","sourceRoot":"","sources":["../../src/utils/strings.ts"],"names":[],"mappings":";;;AAAA,yCAA6C;AAEtC,MAAM,aAAa,GAAG,CAAC,GAAW,EAAE,EAAE,CAC5C,+BAA+B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAD9B,QAAA,aAAa,iBACiB;AAE3C,SAAgB,qBAAqB,CACpC,IAAY,EACZ,IAAI,GAAG,CAAC,EACR,IAEC;IAED,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI;QAAE,OAAO,IAAI,CAAC;IAErC,IAAI,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,cAAc,EAAE,CAAC;QAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;QAErC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,OAAO,C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n\t/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(str);\n\nexport function abbreviateAccountName(\n\tname: string,\n\tsize = 8,\n\topts?: {\n\t\tellipsisMiddle?: boolean;\n\t}\n) {\n\tif (name.length <= size) return name;\n\n\tif (opts?.ellipsisMiddle) {\n\t\tconst length = name.length;\n\t\tconst sizeMid = Math.floor(size / 2);\n\n\t\treturn name.slice(0, sizeMid) + '...' + name.slice(length - sizeMid);\n\t}\n\n\treturn name.slice(0, size) + '...';\n}\n\nexport function splitByCapitalLetters(word: string) {\n\treturn word.replace(/([A-Z])/g, ' $1').trim();\n}\n\nexport function lowerCaseNonFirstWords(sentence: string): string {\n\tconst words = sentence.split(' ');\n\tfor (let i = 1; i < words.length; i++) {\n\t\twords[i] = words[i].toLowerCase();\n\t}\n\treturn words.join(' ');\n}\n\nexport const disallowNegativeStringInput = (str: string): string => {\n\tif (str && str.charAt(0) === '-') {\n\t\treturn '0';\n\t}\n\treturn str;\n};\n\n/**\n * LastOrder status types from https://github.com/drift-labs/infrastructure-v3/blob/8ab1888eaaaed96228406b562d4a399729d042d7/packages/common/src/types/index.ts#L221\n */\nconst LAST_ORDER_STATUS_LABELS = {\n\topen: 'Open',\n\tfilled: 'Filled',\n\tpartial_fill: 'Partially Filled',\n\tcancelled: 'Canceled',\n\tpartial_fill_cancelled: 'Partially Filled & Canceled',\n\texpired: 'Expired',\n\ttrigger: 'Triggered',\n} as const;\nexport type LastOrderStatus = keyof typeof LAST_ORDER_STATUS_LABELS;\nexport type LastOrderStatusLabel =\n\t(typeof LAST_ORDER_STATUS_LABELS)[LastOrderStatus];\n\nexport function lastOrderStatusToNormalEng(\n\tstatus: string\n): LastOrderStatusLabel | string {\n\treturn LAST_ORDER_STATUS_LABELS[status as LastOrderStatus] ?? status;\n}\n\n/**\n * Recursively converts various types into printable strings.\n */\nexport function toPrintableObject(\n\tobj: unknown,\n\t/** Used to guard against circular refs during recursion. */\n\tseen: WeakSet<object> = new WeakSet()\n): unknown {\n\tif (obj == null) {\n\t\treturn null;\n\t}\n\n\tif (obj instanceof BigNum || BN.isBN(obj) || typeof obj === 'bigint') {\n\t\treturn obj.toString();\n\t}\n\n\tif (obj instanceof Date) {\n\t\tconst time = obj.getTime();\n\n\t\tif (Number.isNaN(time)) {\n\t\t\treturn 'Invalid Date';\n\t\t}\n\n\t\treturn obj.toISOString();\n\t}\n\n\tif (typeof obj === 'object') {\n\t\tif (seen.has(obj)) {\n\t\t\treturn '[Circular]';\n\t\t}\n\n\t\tseen.add(obj);\n\n\t\tif (Array.isArray(obj)) {\n\t\t\treturn obj.map((value) => toPrintableObject(value, seen));\n\t\t}\n\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(obj).map(([key, value]) => [\n\t\t\t\tkey,\n\t\t\t\ttoPrintableObject(value, seen),\n\t\t\t])\n\t\t);\n\t}\n\n\treturn obj;\n}\n\nexport function convertStringValuesToNumbers<T>(obj: T): T {\n\tif (typeof obj === 'string' && !isNaN(Number(obj))) {\n\t\treturn Number(obj) as T;\n\t}\n\n\tif (Array.isArray(obj)) {\n\t\treturn obj.map(convertStringValuesToNumbers) as T;\n\t}\n\n\tif (obj !== null && typeof obj === 'object') {\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(obj).map(([key, value]) => [\n\t\t\t\tkey,\n\t\t\t\tconvertStringValuesToNumbers(value),\n\t\t\t])\n\t\t) as T;\n\t}\n\n\treturn obj;\n}\n\n/**\n * Returns an array of an object's string values (deep).\n */\nexport function extractStringValuesFromObject(value: object): string[] {\n\tif (typeof value === 'string') {\n\t\treturn [value];\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn value.flatMap(extractStringValuesFromObject);\n\t}\n\n\tif (value && typeof value === 'object') {\n\t\treturn Object.values(value).flatMap(extractStringValuesFromObject);\n\t}\n\n\treturn [];\n}\n"]}