GMX 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 13쪽

ish` | `string \| Numeric` | A value convertible to `bigint` — accepts a string, number, or bigint. | | `NonZero<T>` | `T & { readonly [__nonZero]: true }` | A branded type asserting a `number` or `bigint` is not zero. Use with `isNonZero()` to narrow the type and `safeDivide()` to perform safe division. | ```typescript // Numeric accepts number or bigint const a: Numeric = 42; const b: Numeric = 42n; // BigNumberish also accepts strings — useful for user input or serialized values const c: BigNumberish = "1000000000000000000"; const d: BigNumberish = 100n; // NonZero<T> expresses divide-by-zero safety at the type level function computeShare(amount: bigint, total: bigint): bigint { if (!isNonZero(total)) { throw new Error("Total must be non-zero"); } return safeDivide(amount, total); // total is NonZero<bigint> } ``` :::note Most functions that accept `BigNumberish` call `BigInt(value)` internally. Passing a decimal string like `"1.5"` to a function that expects an integer will throw a runtime error. Convert floats to `bigint` first using [`numberToBigint`](#numbertobigint) or [`expandDecimals`](#expanddecimals). ::: ## Constants The `numbers` module exports constants for precision, basis points, and display thresholds used throughout the SDK and GMX smart contracts. ### Precision and decimals | Constant | Value | Description | | ---------------------------- | ------------ | ------------------------------------------------------------------------------------------- | | `USD_DECIMALS` | `30` | Decimal precision for USD values. All USD amounts are stored as `bigint` scaled by `10^30`. | | `PRECISION_DECIMALS` | `30` | The number of decimal places in the `PRECISION` scaling factor. | | `PRECISION` | `10n ** 30n` | Scaling factor used in multiplications before division to preserve decimal precision. | | `PERCENT_PRECISION_DECIMALS` | `28` | Decimal precision for percentage values (`PRECISION_DECIMALS - 2`). | ### Float precision | Constant | Value | Description | | ------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------- | | `FLOAT_PRECISION_SQRT_DECIMALS` | `15` | Decimal precision for square-root-scaled float values. | | `FLOAT_PRECISION_SQRT` | `10n ** 15n` | Square root of `PRECISION`, used in intermediate calculations that require reduced-precision float arithmetic. | ### Basis points | Constant | Value | Description | | ----------------------------- | -------- | ---------------------------------------------------------------------- | | `BASIS_POINTS_DIVISOR` | `10000` | Divisor for basis point calculations as a `number`. | | `BASIS_POINTS_DIVISOR_BIGINT` | `10000n` | Same divisor as a `bigint`, for use in `bigint` arithmetic. | | `BASIS_POINTS_DECIMALS` | `4` | Number of decimal places represented by basis points (1 bps = 0.0001). | ### BigInt sentinel values | Constant | Value | Description | | ----------------- | ----------------- | -------------------------------------------- | | `BN_ZERO` | `0n` | Reusable `bigint` zero. | | `BN_ONE` | `1n` | Reusable `bigint` one. | | `BN_NEGATIVE_ONE` | `-1n` | Reusable `bigint` negative one. | | `MaxUint256` | `2n ** 256n - 1n` | Maximum value of a 256-bit unsigned integer. | | `MaxInt256` | `2n ** 255n - 1n` | Maximum value of a 256-bit signed integer. | ### Display threshold prefixes | Constant | Value | Description | | ---------------------- | ----- | --------------------------------------------------------------------- | | `TRIGGER_PREFIX_ABOVE` | `">"` | Prefix displayed when a value exceeds the maximum display threshold. | | `TRIGGER_PREFIX_BELOW` | `"<"` | Prefix displayed when a value is below the minimum display threshold. | ```typescript USD_DECIMALS, PRECISION, BASIS_POINTS_DIVISOR_BIGINT, BN_ZERO, expandDecimals, } from "@gmx-io/sdk/utils/numbers"; // Represent $1,000 as a bigint with 30 decimal places const oneThousandUsd = expandDecimals(1000, USD_DECIMALS); // oneThousandUsd === 1000n * 10n ** 30n // Apply a 0.5% fee (50 basis points) using precision-safe arithmetic const feeRate = (50n * PRECISION) / BASIS_POINTS_DIVISOR_BIGINT; const fee = (oneThousandUsd * feeRate) / PRECISION; // fee === 5n * 10n ** 30n ($5.00) // Guard against an uninitialized value const balance = BN_ZERO; ``` ## Methods The `numbers` module exports methods in four categories: arithmetic and conversion, string-to-bigint parsing, display formatting, and object serialization. Each method operates on `bigint` values scaled by the appropriate decimal precision. ### Arithmetic and conversion #### expandDecimals ```typescript expandDecimals(n: BigNumberish, decimals: number): bigint ``` Multiplies `n` by `10^decimals`, converting a human-readable value into its fixed-point `bigint` representation. This is the standard way to create a scaled value for use with SDK calculations. ```typescript const oneEth = expandDecimals(1, 18); // 1000000000000000000n const oneUsd = expandDecimals(1, USD_DECIMALS); // 1000000000000000000000000000000n ``` #### basisPointsToFloat ```typescript basisPointsToFloat(basisPoints: bigint): bigint ``` Converts a basis point value into a `PRECISION`-scaled `bigint` float. The result is `(basisPoints * PRECISION) / 10000`. Use this when you need to represent a percentage as a precision-scaled factor. ```typescript // 250 bps = 2.5% const factor = basisPointsToFloat(250n); // (250n * PRECISION) / 10000n ``` #### getBasisPoints ```typescript getBasisPoints(numerator: bigint, denominator: bigint, shouldRoundUp?: boolean): bigint ``` Computes `(numerator * 10000) / denominator` as basis points. When `shouldRoundUp` is `true`, the result rounds away from zero if there is any remainder. ```typescript // Fee of 25 out of 1000 = 2.5% = 250 bps const fee = getBasisPoints(25n, 1000n); // 250n const feeRoundedUp = getBasisPoints(7n, 3n, true); // 23334n (rounds up) ``` #### roundUpMagnitudeDivision ```typescript roundUpMagnitudeDivision(a: bigint, b: bigint): bigint ``` Divides `a` by `b`, rounding the result away from zero regardless of sign. Positive results round up; negative results round toward negative infinity. ```typescript roundUpMagnitudeDivision(100n, 3n); // 34n (positive: rounds up) roundUpMagnitudeDivision(-100n, 3n); // -34n (negative: rounds toward -∞) ``` :::note The original docs stated that `roundUpMagnitudeDivision(-100n, 3n)` returns `-33n`. The source code at line 64–70 of `utils.ts` computes `(a - b + 1n) / b` for negative `a`, which gives `(-100 - 3 + 1) / 3 = -102 / 3 = -34`. This is rounding away from zero (increasing magnitude), not toward zero. ::: #### applyFactor ```typescript applyFactor(value: bigint, factor: bigint): bigint ``` Multiplies `value` by `factor` and divides by `PRECISION` (`10^30`). Use this to apply a precision-scaled multiplier — for example, a fee rate returned by `basisPointsToFloat`. ```typescript const positionSize = expandDecimals(10000, USD_DECIMALS); // $10,000 const feeRate = basisPointsToFloat(50n); // 0.5% as PRECISION-scaled factor const fee = applyFactor(positionSize, feeRate); // $50 (as USD bigint) ``` #### numberToBigint ```typescript numberToBigint(value: number, decimals: number): bigint ``` Converts a JavaScript `number` (including floats) to a `bigint` with the specified decimal places. This avoids floating-point rounding by performing the conversion digit by digit. ```typescript numberToBigint(123.456, 18); // 123456000000000000000n numberToBigint(-50.25, 6); // -50250000n ``` #### bigintToNumber ```typescript bigintToNumber(value: bigint, decimals: number): number ``` Converts a scaled `bigint` back to a JavaScript `number`. The result may lose precision for very large values due to JavaScript's floating-point representation. ```typescript const scaled = expandDecimals(123456, 18); bigintToNumber(scaled, 18); // 123456.0 (as number) const fractional = expandDecimals(1, 18) / 2n; // 5 * 10^17n bigintToNumber(fractional, 18); // 0.5 ``` #### adjustForDecimals ```typescript adjustForDecimals(amount: bigint, divDecimals: number, mulDecimals: number): bigint ``` Converts `amount` from `divDecimals` precision to `mulDecimals` precision. Useful when bridging between token decimals and USD decimals. ```typescript // Convert a USDC amount (6 decimals) to USD precision (30 decimals) const usdcAmount = expandDecimals(100, 6); // 100 USDC const asUsd = adjustForDecimals(usdcAmount, 6, 30); ``` #### roundUpDivision ```typescript roundUpDivision(a: bigint, b: bigint): bigint ``` Performs `ceiling(a / b)` for positive values using `(a + b - 1) / b`. Use this when you need to ensure you never underestimate a result (for example, fee calculations). ```typescript roundUpDivision(100n, 3n); // 34n (ceiling of 33.33...) roundUpDivision(99n, 3n); // 33n (exact) ``` #### roundToTwoDecimals ```typescript roundToTwoDecimals(n: number): number ``` Rounds a JavaScript `number` to two decimal places using `Math.round(n * 100) / 100`. ```typescript roundToTwoDecimals(123.456789); // 123.46 roundToTwoDecimals(1.005); // 1.01 ``` #### roundToOrder ```typescript roundToOrder(n: bigint, significantDigits?: number): bigint ``` Rounds a `bigint` to the specified number of significant digits (default: 1). Useful for estimating large numbers with reduced precision. ```typescript roundToOrder(123456789n, 3); // 123000000n roundToOrder(987654321n, 1); // 900000000n ``` #### roundBigIntToDecimals ```typescript roundBigIntToDecimals(value: bigint, tokenDecimals: number, roundToDecimals: number): bigint ``` Rounds a scaled `bigint` to a coarser decimal precision while preserving the original scaling. For example, round an 18-decimal value to 6 significant decimal places. ```typescript // Round an 18-decimal value to 6 decimal places const precise = expandDecimals(123456789, 12); // 123456789000000000000n const rounded = roundBigIntToDecimals(precise, 18, 6); ``` #### roundWithDecimals ```typescript roundWithDecimals(value: BigNumberish, opts: { displayDecimals: number; decimals: number }): bigint ``` Rounds `value` (with `decimals` precision) to `displayDecimals` decimal places. This is the internal rounding function used by `formatAmount`. ```typescript // Round 8-decimal value to 4 display decimals roundWithDecimals(123456789n, { displayDecimals: 4, decimals: 8 }); // 123460000n ``` #### clamp ```typescript clamp(value: number, min: number, max: number): number ``` Constrains a `number` to the `[min, max]` range, returning `min` if below or `max` if above. ```typescript clamp(150, 0, 100); // 100 clamp(-5, 0, 100); // 0 clamp(50, 0, 100); // 50 ``` #### minBigNumber ```typescript minBigNumber(...args: bigint[]): bigint | undefined ``` Returns the smallest value from a list of `bigint` arguments. Returns `undefined` if called with no arguments. ```typescript minBigNumber(100n, 50n, 200n); // 50n minBigNumber(); // undefined ``` #### maxbigint ```typescript maxbigint(...args: bigint[]): bigint | undefined ``` Returns the largest value from a list of `bigint` arguments. Returns `undefined` if called with no arguments. ```typescript maxbigint(100n, 50n, 200n); // 200n ``` #### absDiffBps ```typescript absDiffBps(value: bigint, base: bigint): bigint ``` Calculates the absolute difference between `value` and `base` expressed in basis points: `|value - base| * 10000 / base`. ```typescript absDiffBps(1050n, 1000n); // 500n (5% difference) absDiffBps(900n, 1000n); // 1000n (10% difference) ``` :::note Edge cases: if `value` is zero and `base` is non-zero (or vice versa), `absDiffBps` returns `10000n` (100%). If both are zero, it returns `0n`. ::: ### String parsing and conversion #### parseUint256DecimalString ```typescript parseUint256DecimalString(value: unknown): bigint | undefined ``` Parses a canonical unsigned base-10 integer string from `"0"` through `MaxUint256`. It rejects signs, decimals, whitespace, leading zeros, non-string values, and overflow. ```typescript parseUint256DecimalString("42"); // 42n parseUint256DecimalString("0"); // 0n parseUint256DecimalString("01"); // undefined parseUint256DecimalString("-1"); // undefined ``` #### isUint256 ```typescript isUint256(value: unknown): value is bigint ``` Returns `true` only for a `bigint` between `0n` and `MaxUint256`, inclusive. ```typescript isUint256(42n); // true isUint256(-1n); // false isUint256("42"); // false ``` #### parseValue ```typescript parseValue(value: string, tokenDecimals: number): bigint | undefined ``` Parses a user-input string (for example, `"1.5"`) into a scaled `bigint` with `tokenDecimals` precision. Returns `undefined` if the string is not a valid number or if the parsed value exceeds an internal safety cap of `10^62`. ```typescript parseValue("1.5", 18); // 1500000000000000000n parseValue("0.001", 6); // 1000n parseValue("invalid", 18); // undefined parseValue("", 18); // undefined ``` :::note `parseValue` caps the result at `10^62` to prevent downstream `bigint` overflow. Values above this threshold return `undefined`. ::: #### toBigNumberWithDecimals :::warning This function is scheduled for removal. Use `parseValue` or `numberToBigint` instead. ::: ```typescript toBigNumberWithDecimals(value: string, decimals: number): bigint ``` Converts a decimal string to a `bigint` with the specified number of decimal places. Unlike `parseValue`, it does not validate input or apply a safety cap, and it returns `0n` for empty strings instead of `undefined`. ```typescript toBigNumberWithDecimals("123.456", 18); // 123456000000000000000n toBigNumberWithDecimals("", 18); // 0n ``` #### bigNumberify :::warning `bigNumberify` is deprecated. Use native `BigInt()` directly. The function logs a console error and returns `undefined` on invalid input rather than throwing. ::: ```typescript bigNumberify(n?: BigNumberish | null | undefined): bigint | undefined ``` Wraps `BigInt()` in a try/catch, returning `undefined` instead of throwing on invalid input. ```typescript bigNumberify("123"); // 123n bigNumberify("invalid"); // undefined (logs console.error) bigNumberify(null); // undefined ``` #### trimZeroDecimals ```typescript trimZeroDecimals(amount: string): string ``` Removes trailing zeros and unnecessary decimal points from a numeric string. ```typescript trimZeroDecimals("123.000"); // "123" trimZeroDecimals("123.456"); // "123.456" trimZeroDecimals("0.00"); // "0" ``` #### limitDecimals ```typescript limitDecimals(amount: BigNumberish, maxDecimals?: number): string ``` Truncates a numeric string to at most `maxDecimals` decimal places. Does not round — it truncates. If `maxDecimals` is omitted, returns the string as-is. ```typescript limitDecimals("123.456789", 4); // "123.4567" (truncated, not rounded) limitDecimals("123.456789"); // "123.456789" limitDecimals("123.456789", 0); // "123" ``` #### padDecimals ```typescript padDecimals(amount: BigNumberish, minDecimals: number): string ``` Pads a numeric string with trailing zeros to ensure at least `minDecimals` decimal places. ```typescript padDecimals("123.4", 4); // "123.4000" padDecimals("123", 2); // "123.00" padDecimals("1.50", 2); // "1.50" (already has enough decimals) ``` #### removeTrailingZeros ```typescript removeTrailingZeros(amount: string | number): string | number ``` For decimal string inputs, removes trailing fractional zeros without converting the value to a JavaScript `number`, preserving precision. Numbers, integer strings, comma-formatted strings, and zero-only decimal strings are returned unchanged. ```typescript removeTrailingZeros("123.000"); // "123" removeTrailingZeros("0.500"); // "0.5" removeTrailingZeros("123"); // "123" (unchanged) removeTrailingZeros("0.000"); // "0.000" (unchanged) removeTrailingZeros(0); // 0 (unchanged) ``` ### Display formatting #### formatAmount ```typescript formatAmount( amount: BigNumberish | undefined, tokenDecimals: number, displayDecimals?: number, useCommas?: boolean, defaultValue?: string, visualMultiplier?: number ): string ``` Core formatting function. Divides `amount` by `10^tokenDecimals`, rounds to `displayDecimals` (default: 4), and optionally adds comma separators. Returns `defaultValue` (default: `"..."`) when `amount` is `undefined`, `null`, or empty. ```typescript const amount = expandDecimals(1234567, 18); formatAmount(amount, 18, 4, true); // "1.2346" formatAmount(amount, 18, 2, true); // "1.23" formatAmount(undefined, 18, 2); // "..." formatAmount(undefined, 18, 2, false, "-"); // "-" ``` #### formatAmountFree ```typescript formatAmountFree(amount: BigNumberish, tokenDecimals: number, displayDecimals?: number): string ``` Formats an amount without padding zeros after the decimal point. Unlike `formatAmount`, it calls `trimZeroDecimals` on the result. ```typescript formatAmountFree(expandDecimals(123, 18), 18, 6); // "0.000123" formatAmountFree(expandDecimals(1, 18), 18, 4); // "1" (not "1.0000") ``` #### formatKeyAmount ```typescript formatKeyAmount<T>(map: T | undefined, key: keyof T, tokenDecimals: number, displayDecimals: number, useCommas?: boolean): string ``` Formats a `bigint` value read from a property of an object. Returns `"..."` if the map or key is missing. ```typescript const market = { longOpenInterest: 1234567890000000000n }; formatKeyAmount(market, "longOpenInterest", 18, 4); // "1.2346" formatKeyAmount(undefined, "longOpenInterest", 18, 4); // "..." ``` #### formatArrayAmount ```typescript formatArrayAmount(arr: any[], index: number, tokenDecimals: number, displayDecimals?: number, useCommas?: boolean): string ``` Formats a `bigint` value at a specific index in an array. Returns `"..."` if the array or index is missing. ```typescript const amounts = [expandDecimals(1, 18), expandDecimals(2, 18)]; formatArrayAmount(amounts, 0, 18, 4); // "1.0000" ``` #### getLimitedDisplay ```typescript getLimitedDisplay( amount: bigint, tokenDecimals: number, opts?: { maxThreshold?: BigNumberish | null; minThreshold?: BigNumberish } ): { symbol: string; value: bigint } ``` Returns a display object with a threshold symbol (`">"` or `"<"`) and a clamped value when `amount` falls outside the display range. The default thresholds are a maximum of `1,000,000,000` and a minimum of `0.01`. Pass `maxThreshold: null` to disable the upper cap. ```typescript // Amount below minimum threshold const tiny = expandDecimals(1, 15); // 0.001 ETH getLimitedDisplay(tiny, 18); // { symbol: "<", value: <min threshold value> } // Amount above maximum threshold const huge = expandDecimals(2_000_000_000, 18); getLimitedDisplay(huge, 18); // { symbol: ">", value: <max threshold value> } // Amount in range const normal = expandDecimals(100, 18); getLimitedDisplay(normal, 18); // { symbol: "", value: 100000000000000000000n } ``` #### formatUsd ```typescript formatUsd( usd?: bigint, opts?: { fallbackToZero?: boolean; displayDecimals?: number; maxThreshold?: string | null; minThreshold?: string; displayPlus?: boolean; visualMultiplier?: number; } ): string | undefined ``` Formats a `bigint` USD amount (30-decimal precision) into a display string. Returns `undefined` if `usd` is not a `bigint` and `fallbackToZero` is not set. Default `displayDecimals` is `2`. ```typescript const amount = expandDecimals(1234, USD_DECIMALS); formatUsd(amount); // "$1,234.00" formatUsd(amount, { displayPlus: true }); // "+$1,234.00" formatUsd(-amount); // "-$1,234.00" formatUsd(undefined); // undefined formatUsd(undefined, { fallbackToZero: true }); // "$0.00" ``` #### formatBigUsd ```typescript formatBigUsd(amount: bigint, opts?: { displayDecimals?: number }): string ``` Formats a USD `bigint` using a very high upper threshold (`9999999999999999999999999`) so that the `>` prefix is effectively suppressed for all practical values. Defaults to zero decimal places, making it suitable for di
프로젝트로 돌아가기