@lifi/perps-sdk 36.0.0 → 36.1.0

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.
Files changed (68) hide show
  1. package/dist/cjs/client/PerpsClient.d.ts.map +1 -1
  2. package/dist/cjs/client/PerpsClient.js +4 -4
  3. package/dist/cjs/client/PerpsClient.js.map +1 -1
  4. package/dist/cjs/decimal/compare.d.ts +2 -0
  5. package/dist/cjs/decimal/compare.d.ts.map +1 -1
  6. package/dist/cjs/decimal/compare.js +6 -1
  7. package/dist/cjs/decimal/compare.js.map +1 -1
  8. package/dist/cjs/index.d.ts +3 -1
  9. package/dist/cjs/index.d.ts.map +1 -1
  10. package/dist/cjs/index.js +11 -5
  11. package/dist/cjs/index.js.map +1 -1
  12. package/dist/cjs/math/leverage.d.ts +10 -0
  13. package/dist/cjs/math/leverage.d.ts.map +1 -0
  14. package/dist/cjs/math/leverage.js +32 -0
  15. package/dist/cjs/math/leverage.js.map +1 -0
  16. package/dist/cjs/types/provider.d.ts +3 -3
  17. package/dist/cjs/types/provider.d.ts.map +1 -1
  18. package/dist/cjs/version.d.ts +1 -1
  19. package/dist/cjs/version.js +1 -1
  20. package/dist/cjs/wire/orderAmounts.d.ts +8 -2
  21. package/dist/cjs/wire/orderAmounts.d.ts.map +1 -1
  22. package/dist/cjs/wire/orderAmounts.js +26 -6
  23. package/dist/cjs/wire/orderAmounts.js.map +1 -1
  24. package/dist/esm/client/PerpsClient.d.ts +4 -3
  25. package/dist/esm/client/PerpsClient.d.ts.map +1 -1
  26. package/dist/esm/client/PerpsClient.js +8 -7
  27. package/dist/esm/client/PerpsClient.js.map +1 -1
  28. package/dist/esm/decimal/compare.d.ts +14 -0
  29. package/dist/esm/decimal/compare.d.ts.map +1 -1
  30. package/dist/esm/decimal/compare.js +16 -0
  31. package/dist/esm/decimal/compare.js.map +1 -1
  32. package/dist/esm/index.d.ts +3 -1
  33. package/dist/esm/index.d.ts.map +1 -1
  34. package/dist/esm/index.js +2 -1
  35. package/dist/esm/index.js.map +1 -1
  36. package/dist/esm/math/leverage.d.ts +40 -0
  37. package/dist/esm/math/leverage.d.ts.map +1 -0
  38. package/dist/esm/math/leverage.js +50 -0
  39. package/dist/esm/math/leverage.js.map +1 -0
  40. package/dist/esm/types/provider.d.ts +15 -8
  41. package/dist/esm/types/provider.d.ts.map +1 -1
  42. package/dist/esm/version.d.ts +1 -1
  43. package/dist/esm/version.js +1 -1
  44. package/dist/esm/wire/orderAmounts.d.ts +29 -9
  45. package/dist/esm/wire/orderAmounts.d.ts.map +1 -1
  46. package/dist/esm/wire/orderAmounts.js +39 -11
  47. package/dist/esm/wire/orderAmounts.js.map +1 -1
  48. package/dist/types/client/PerpsClient.d.ts +4 -3
  49. package/dist/types/client/PerpsClient.d.ts.map +1 -1
  50. package/dist/types/decimal/compare.d.ts +14 -0
  51. package/dist/types/decimal/compare.d.ts.map +1 -1
  52. package/dist/types/index.d.ts +3 -1
  53. package/dist/types/index.d.ts.map +1 -1
  54. package/dist/types/math/leverage.d.ts +40 -0
  55. package/dist/types/math/leverage.d.ts.map +1 -0
  56. package/dist/types/types/provider.d.ts +15 -8
  57. package/dist/types/types/provider.d.ts.map +1 -1
  58. package/dist/types/version.d.ts +1 -1
  59. package/dist/types/wire/orderAmounts.d.ts +29 -9
  60. package/dist/types/wire/orderAmounts.d.ts.map +1 -1
  61. package/package.json +2 -2
  62. package/src/client/PerpsClient.ts +16 -7
  63. package/src/decimal/compare.ts +21 -0
  64. package/src/index.ts +8 -0
  65. package/src/math/leverage.ts +83 -0
  66. package/src/types/provider.ts +20 -7
  67. package/src/version.ts +1 -1
  68. package/src/wire/orderAmounts.ts +72 -18
@@ -1,21 +1,39 @@
1
1
  import { type DecimalString, type Market } from '@lifi/perps-types';
2
2
  import type { PerpsSDKClient } from '../types/provider.js';
3
3
  /** @public */
4
- export interface OrderAmountsInput {
4
+ export interface OrderAmountsInputBase {
5
5
  sdk: PerpsSDKClient;
6
6
  market: Market;
7
7
  /** The field the user typed; the other two are calculated from it. */
8
8
  held: 'margin' | 'size' | 'notional';
9
9
  amount: DecimalString;
10
- leverage: number;
10
+ /** The leverage multiple. Not read when `initialMarginFractionBps` is present. */
11
+ leverage?: number;
12
+ /**
13
+ * The venue's native integer IMF in basis points (`'700'` is 7.00%), the
14
+ * exact margin rate of a venue that stores one. Pass the reported
15
+ * `MarketSettings.initialMarginFractionBps`; `leverage` then stays unread.
16
+ */
17
+ initialMarginFractionBps?: DecimalString;
11
18
  price: DecimalString;
12
19
  }
20
+ /**
21
+ * The order-entry input with at least one margin-rate source: the leverage
22
+ * multiple, the native IMF, or both.
23
+ *
24
+ * @public
25
+ */
26
+ export type OrderAmountsInput = OrderAmountsInputBase & ({
27
+ leverage: number;
28
+ } | {
29
+ initialMarginFractionBps: DecimalString;
30
+ });
13
31
  /** @public */
14
32
  export interface OrderAmounts {
15
33
  /**
16
34
  * The held `amount`, byte-identical, when the user holds the margin;
17
- * otherwise `notional ÷ leverage`, a display and comparison value that
18
- * never reaches a venue.
35
+ * otherwise `notional ÷ leverage` or `notional × IMF ÷ 10000`, a display
36
+ * and comparison value that never reaches a venue.
19
37
  */
20
38
  margin: DecimalString;
21
39
  /** Snapped onto the venue lot grid; the one amount an order sends. */
@@ -28,13 +46,15 @@ export interface OrderAmounts {
28
46
  * Only `size` snaps, onto the market's venue lot grid, because an order sends
29
47
  * size alone; no quote amount has a grid. A held margin returns byte-identical,
30
48
  * `notional` is the snapped size × price, and a derived margin is
31
- * `notional ÷ leverage` in `DivBig` (40 places, half-up).
49
+ * `notional ÷ leverage`, or `notional × initialMarginFractionBps ÷ 10000`
50
+ * from a native IMF, in `DivBig` (40 places, half-up).
32
51
  *
33
52
  * @throws {PerpsError} `ValidationError` that names `amount` or `price` when
34
- * it is not a positive decimal, or `leverage` when it is not a finite number
35
- * above zero. `ValidationError` with the lot size when the snapped size is
36
- * zero (below one lot). `SDKError` when `market.providerId` names no
37
- * registered provider plugin.
53
+ * it is not a positive decimal, `initialMarginFractionBps` when it is
54
+ * present and not a positive integer, or `leverage` when no IMF is present
55
+ * and it is not a finite number above zero. `ValidationError` with the lot
56
+ * size when the snapped size is zero (below one lot). `SDKError` when
57
+ * `market.providerId` names no registered provider plugin.
38
58
  * @public
39
59
  */
40
60
  export declare function calculateOrderAmounts(input: OrderAmountsInput): OrderAmounts;
@@ -1 +1 @@
1
- {"version":3,"file":"orderAmounts.d.ts","sourceRoot":"","sources":["../../../src/wire/orderAmounts.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,MAAM,EAEZ,MAAM,mBAAmB,CAAA;AAO1B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAI1D,cAAc;AACd,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,EAAE,MAAM,CAAA;IACd,sEAAsE;IACtE,IAAI,EAAE,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAA;IACpC,MAAM,EAAE,aAAa,CAAA;IACrB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,aAAa,CAAA;CACrB;AAED,cAAc;AACd,MAAM,WAAW,YAAY;IAC3B;;;;OAIG;IACH,MAAM,EAAE,aAAa,CAAA;IACrB,sEAAsE;IACtE,IAAI,EAAE,aAAa,CAAA;IACnB,qDAAqD;IACrD,QAAQ,EAAE,aAAa,CAAA;CACxB;AAgBD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,iBAAiB,GAAG,YAAY,CAkC5E;AAED,cAAc;AACd,eAAO,MAAM,yBAAyB,wDAGrC,CAAA"}
1
+ {"version":3,"file":"orderAmounts.d.ts","sourceRoot":"","sources":["../../../src/wire/orderAmounts.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,MAAM,EAEZ,MAAM,mBAAmB,CAAA;AAW1B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAI1D,cAAc;AACd,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,EAAE,MAAM,CAAA;IACd,sEAAsE;IACtE,IAAI,EAAE,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAA;IACpC,MAAM,EAAE,aAAa,CAAA;IACrB,kFAAkF;IAClF,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;OAIG;IACH,wBAAwB,CAAC,EAAE,aAAa,CAAA;IACxC,KAAK,EAAE,aAAa,CAAA;CACrB;AAED;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,qBAAqB,GACnD,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,wBAAwB,EAAE,aAAa,CAAA;CAAE,CAAC,CAAA;AAEtE,cAAc;AACd,MAAM,WAAW,YAAY;IAC3B;;;;OAIG;IACH,MAAM,EAAE,aAAa,CAAA;IACrB,sEAAsE;IACtE,IAAI,EAAE,aAAa,CAAA;IACnB,qDAAqD;IACrD,QAAQ,EAAE,aAAa,CAAA;CACxB;AA+CD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,iBAAiB,GAAG,YAAY,CAmC5E;AAED,cAAc;AACd,eAAO,MAAM,yBAAyB,wDAGrC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifi/perps-sdk",
3
- "version": "36.0.0",
3
+ "version": "36.1.0",
4
4
  "description": "LI.FI Perps SDK for perpetuals trading",
5
5
  "homepage": "https://github.com/lifinance/perps-sdk",
6
6
  "bugs": {
@@ -45,7 +45,7 @@
45
45
  "@lifi/types": "^18.3.0",
46
46
  "big.js": "^7.0.1",
47
47
  "partysocket": "^1.1.19",
48
- "@lifi/perps-types": "^30.1.0"
48
+ "@lifi/perps-types": "^30.2.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "viem": ">=2.57.11 <2.57.12"
@@ -415,14 +415,16 @@ export class PerpsClient {
415
415
  * Ask the provider plugin for the signer-bearing wire fields of `action` —
416
416
  * the on-wire `signerAddress` and any signer-derived params (e.g.
417
417
  * Hyperliquid's `agentAddress` for `APPROVE_AGENT`). Forwards the descriptor's
418
- * `signer` so the plugin can branch on signer role. Returns empty when the
419
- * plugin signs as the user or with a non-EVM credential. Core constructs no
420
- * `signerAddress` itself; signer identity is plugin-owned.
418
+ * `signer` so the plugin can branch on signer role, and the caller's `params`
419
+ * so the plugin can contribute a venue encoding of a caller value. Returns
420
+ * empty when the plugin signs as the user or with a non-EVM credential. Core
421
+ * constructs no `signerAddress` itself; signer identity is plugin-owned.
421
422
  */
422
423
  private async resolveActionRequest(
423
424
  provider: string,
424
425
  descriptor: ProviderAction,
425
- address: Address
426
+ address: Address,
427
+ params?: ActionParamsMap[ActionType]
426
428
  ): Promise<ActionSignerContribution> {
427
429
  const plugin = this.requireProvider(provider)
428
430
  if (typeof plugin.resolveActionRequest !== 'function') {
@@ -431,7 +433,8 @@ export class PerpsClient {
431
433
  return plugin.resolveActionRequest(
432
434
  descriptor.type,
433
435
  address,
434
- descriptor.signer
436
+ descriptor.signer,
437
+ params
435
438
  )
436
439
  }
437
440
 
@@ -723,7 +726,8 @@ export class PerpsClient {
723
726
  await this.resolveActionRequest(
724
727
  params.provider,
725
728
  descriptor,
726
- params.address
729
+ params.address,
730
+ params.params
727
731
  )
728
732
  return createAction(this.sdkClient, {
729
733
  provider: params.provider,
@@ -1673,7 +1677,12 @@ export class PerpsClient {
1673
1677
  const descriptor = findActionDescriptor(metadata, action)
1674
1678
 
1675
1679
  const { signerAddress, params: signerParams } =
1676
- await this.resolveActionRequest(provider, descriptor, address)
1680
+ await this.resolveActionRequest(
1681
+ provider,
1682
+ descriptor,
1683
+ address,
1684
+ params.params
1685
+ )
1677
1686
 
1678
1687
  const { actions } = await createAction(this.sdkClient, {
1679
1688
  provider,
@@ -45,6 +45,27 @@ export const safeIsDecimalStringZero = createSafeFunction(
45
45
  isDecimalStringZero
46
46
  )
47
47
 
48
+ /**
49
+ * Exact `value` has no fractional part, so `'700.0'` is an integer and
50
+ * `'700.5'` is not.
51
+ *
52
+ * @throws {PerpsError} `ValidationError` when `value` does not match the decimal pattern.
53
+ * @public
54
+ */
55
+ export function isDecimalStringInteger(value: string): boolean {
56
+ return decimalStringToBig(value).mod(1).eq(0)
57
+ }
58
+
59
+ /**
60
+ * {@link isDecimalStringInteger}, or `undefined` with a warning when it throws.
61
+ *
62
+ * @public
63
+ */
64
+ export const safeIsDecimalStringInteger = createSafeFunction(
65
+ 'isDecimalStringInteger',
66
+ isDecimalStringInteger
67
+ )
68
+
48
69
  /**
49
70
  * Exact three-way compare for a sort: `-1` when `a < b`, `0` when equal, `1`
50
71
  * when `a > b`.
package/src/index.ts CHANGED
@@ -36,9 +36,11 @@ export {
36
36
  export {
37
37
  compareDecimalStrings,
38
38
  isDecimalStringGreaterThan,
39
+ isDecimalStringInteger,
39
40
  isDecimalStringZero,
40
41
  safeCompareDecimalStrings,
41
42
  safeIsDecimalStringGreaterThan,
43
+ safeIsDecimalStringInteger,
42
44
  safeIsDecimalStringZero,
43
45
  } from './decimal/compare.js'
44
46
  export type { DecimalRounding } from './decimal/convert.js'
@@ -89,6 +91,12 @@ export {
89
91
  annualizeFundingRate,
90
92
  safeAnnualizeFundingRate,
91
93
  } from './math/funding.js'
94
+ export type { LeverageSource } from './math/leverage.js'
95
+ export {
96
+ resolveExactLeverage,
97
+ safeResolveExactLeverage,
98
+ validateInitialMarginFractionBps,
99
+ } from './math/leverage.js'
92
100
  export type { ExpectedPnl } from './math/order.js'
93
101
  export {
94
102
  buildQuote,
@@ -0,0 +1,83 @@
1
+ import type { DecimalString } from '@lifi/perps-types'
2
+ import { divideDecimalString } from '../decimal/arithmetic.js'
3
+ import {
4
+ isDecimalStringGreaterThan,
5
+ isDecimalStringInteger,
6
+ } from '../decimal/compare.js'
7
+ import { roundDecimalString } from '../decimal/convert.js'
8
+ import { isDecimalString } from '../decimal/parse.js'
9
+ import { invalidInput } from '../errors/invalidInput.js'
10
+ import { createSafeFunction } from '../utils/createSafeFunction.js'
11
+
12
+ /** Basis points in one whole unit: an IMF of `'700'` is `700 ÷ 10000`. */
13
+ export const BASIS_POINTS_PER_UNIT = '10000'
14
+
15
+ /**
16
+ * The leverage fields of a `MarketSettings` or a `Position`: the venue's
17
+ * native integer IMF in basis points when it stores one, and the leverage
18
+ * multiple.
19
+ *
20
+ * @public
21
+ */
22
+ export interface LeverageSource {
23
+ leverage?: DecimalString
24
+ initialMarginFractionBps?: DecimalString
25
+ }
26
+
27
+ /**
28
+ * The native IMF as a canonical integer string (`'700.0'` gives `'700'`), so
29
+ * a formula reads it as an exact margin rate and a venue request carries
30
+ * plain digits. `parameter` names the input in the error.
31
+ *
32
+ * @throws {PerpsError} `ValidationError` when `value` is not a positive
33
+ * integer decimal string.
34
+ * @public
35
+ */
36
+ export function validateInitialMarginFractionBps(
37
+ value: DecimalString,
38
+ parameter = 'initialMarginFractionBps'
39
+ ): DecimalString {
40
+ if (
41
+ !isDecimalString(value) ||
42
+ !isDecimalStringGreaterThan(value, '0') ||
43
+ !isDecimalStringInteger(value)
44
+ ) {
45
+ throw invalidInput(parameter, `must be a positive integer, got '${value}'`)
46
+ }
47
+ return roundDecimalString(value, 0, 'truncate')
48
+ }
49
+
50
+ /**
51
+ * The exact leverage multiple of a venue setting, for the TP/SL and
52
+ * liquidation formulas: `10000 ÷ initialMarginFractionBps` (40 places,
53
+ * half-up) when the native IMF is present, else `leverage` unchanged. A
54
+ * display leverage never feeds a formula. `calculateOrderAmounts` takes the
55
+ * IMF itself, so a derived margin stays exact.
56
+ *
57
+ * @throws {PerpsError} `ValidationError` when `initialMarginFractionBps` is
58
+ * present but not a positive integer, or when it is absent and `leverage`
59
+ * is absent or not a positive decimal.
60
+ * @public
61
+ */
62
+ export function resolveExactLeverage(source: LeverageSource): DecimalString {
63
+ const { initialMarginFractionBps, leverage } = source
64
+ if (initialMarginFractionBps !== undefined) {
65
+ return divideDecimalString(
66
+ BASIS_POINTS_PER_UNIT,
67
+ validateInitialMarginFractionBps(initialMarginFractionBps)
68
+ )
69
+ }
70
+ if (leverage === undefined || !isDecimalStringGreaterThan(leverage, '0')) {
71
+ throw invalidInput(
72
+ 'leverage',
73
+ `must be a positive decimal, got '${String(leverage)}'`
74
+ )
75
+ }
76
+ return leverage
77
+ }
78
+
79
+ /** @public */
80
+ export const safeResolveExactLeverage = createSafeFunction(
81
+ 'resolveExactLeverage',
82
+ resolveExactLeverage
83
+ )
@@ -3,6 +3,7 @@ import type {
3
3
  AccountConfigSetting,
4
4
  AccountResponse,
5
5
  AccountSummary,
6
+ ActionParamsMap,
6
7
  ActionResult,
7
8
  ActionStep,
8
9
  ActionType,
@@ -153,9 +154,10 @@ export interface ActionSignerContribution {
153
154
  */
154
155
  signerAddress?: Address
155
156
  /**
156
- * Extra action params the plugin injects from its own signer state — e.g.
157
- * Hyperliquid's `agentAddress` for `APPROVE_AGENT`. Merged over the caller's
158
- * params.
157
+ * Extra action params the plugin injects from its own signer state (e.g.
158
+ * Hyperliquid's `agentAddress` for `APPROVE_AGENT`) or from the caller's
159
+ * params (Lighter's `initialMarginFractionBps` for a leverage action).
160
+ * Merged over the caller's params.
159
161
  */
160
162
  params?: Record<string, unknown>
161
163
  }
@@ -526,8 +528,15 @@ export interface PerpsProviderPlugin {
526
528
  ): Promise<MarketSettings>
527
529
 
528
530
  /** Compare a requested leverage with the venue setting, without I/O.
531
+ * `requestedInitialMarginFractionBps` is the exact native source that the
532
+ * request carried, when the caller sent one; a venue that stores an IMF
533
+ * compares it instead of encoding `requested`.
529
534
  * Throw `ValidationError` for unusable or unsupported values or missing required source data. */
530
- isLeverageEqual(requested: DecimalString, reported: MarketSettings): boolean
535
+ isLeverageEqual(
536
+ requested: DecimalString,
537
+ reported: MarketSettings,
538
+ requestedInitialMarginFractionBps?: DecimalString
539
+ ): boolean
531
540
 
532
541
  /**
533
542
  * The amounts the account can still buy and sell on one market, in that
@@ -729,15 +738,19 @@ export interface PerpsProviderPlugin {
729
738
  * `agentAddress` param. The agent address must be known pre-build so the
730
739
  * backend builds the right typed data, so core calls this before
731
740
  * `createAction` and threads the same result into `executeAction`.
741
+ * The caller's `params` are forwarded so a plugin can contribute a venue
742
+ * encoding of a caller value (Lighter's `initialMarginFractionBps`). A setup
743
+ * step runs with the backend-staged params and forwards none.
732
744
  *
733
745
  * Optional: providers that sign as the user or with a non-EVM session
734
- * credential (Lighter's API key) omit it — core then sends no `signerAddress`
735
- * and no injected params.
746
+ * credential and contribute no params omit it — core then sends no
747
+ * `signerAddress` and no injected params.
736
748
  */
737
749
  resolveActionRequest?(
738
750
  action: ActionType,
739
751
  address: Address,
740
- signer: PerpsSigner
752
+ signer: PerpsSigner,
753
+ params?: ActionParamsMap[ActionType]
741
754
  ): Promise<ActionSignerContribution>
742
755
 
743
756
  /**
package/src/version.ts CHANGED
@@ -10,4 +10,4 @@ export const name = '@lifi/perps-sdk'
10
10
  *
11
11
  * @public
12
12
  */
13
- export const version = '36.0.0'
13
+ export const version = '36.1.0'
@@ -9,27 +9,47 @@ import { isDecimalStringZero } from '../decimal/compare.js'
9
9
  import { isDecimalString } from '../decimal/parse.js'
10
10
  import { invalidInput } from '../errors/invalidInput.js'
11
11
  import { PerpsError } from '../errors/PerpsError.js'
12
+ import {
13
+ BASIS_POINTS_PER_UNIT,
14
+ validateInitialMarginFractionBps,
15
+ } from '../math/leverage.js'
12
16
  import type { PerpsSDKClient } from '../types/provider.js'
13
17
  import { createSafeFunction } from '../utils/createSafeFunction.js'
14
18
  import { snapOrderSize } from './snap.js'
15
19
 
16
20
  /** @public */
17
- export interface OrderAmountsInput {
21
+ export interface OrderAmountsInputBase {
18
22
  sdk: PerpsSDKClient
19
23
  market: Market
20
24
  /** The field the user typed; the other two are calculated from it. */
21
25
  held: 'margin' | 'size' | 'notional'
22
26
  amount: DecimalString
23
- leverage: number
27
+ /** The leverage multiple. Not read when `initialMarginFractionBps` is present. */
28
+ leverage?: number
29
+ /**
30
+ * The venue's native integer IMF in basis points (`'700'` is 7.00%), the
31
+ * exact margin rate of a venue that stores one. Pass the reported
32
+ * `MarketSettings.initialMarginFractionBps`; `leverage` then stays unread.
33
+ */
34
+ initialMarginFractionBps?: DecimalString
24
35
  price: DecimalString
25
36
  }
26
37
 
38
+ /**
39
+ * The order-entry input with at least one margin-rate source: the leverage
40
+ * multiple, the native IMF, or both.
41
+ *
42
+ * @public
43
+ */
44
+ export type OrderAmountsInput = OrderAmountsInputBase &
45
+ ({ leverage: number } | { initialMarginFractionBps: DecimalString })
46
+
27
47
  /** @public */
28
48
  export interface OrderAmounts {
29
49
  /**
30
50
  * The held `amount`, byte-identical, when the user holds the margin;
31
- * otherwise `notional ÷ leverage`, a display and comparison value that
32
- * never reaches a venue.
51
+ * otherwise `notional ÷ leverage` or `notional × IMF ÷ 10000`, a display
52
+ * and comparison value that never reaches a venue.
33
53
  */
34
54
  margin: DecimalString
35
55
  /** Snapped onto the venue lot grid; the one amount an order sends. */
@@ -52,37 +72,68 @@ function requirePositiveDecimal(value: DecimalString, parameter: string): Big {
52
72
  const lotSize = (market: Market): DecimalString =>
53
73
  market.sizeIncrement ?? new TruncBig(`1e-${market.szDecimals}`).toFixed()
54
74
 
75
+ /**
76
+ * The margin rate as `[numerator, denominator]`, so each amount divides one
77
+ * time: the native IMF over its scale, else one over the leverage.
78
+ *
79
+ * @throws {PerpsError} `ValidationError` as {@link calculateOrderAmounts}.
80
+ */
81
+ function resolveMarginRate(
82
+ input: OrderAmountsInput
83
+ ): [Big | number, Big | number] {
84
+ if (input.initialMarginFractionBps !== undefined) {
85
+ return [
86
+ new TruncBig(
87
+ validateInitialMarginFractionBps(input.initialMarginFractionBps)
88
+ ),
89
+ new TruncBig(BASIS_POINTS_PER_UNIT),
90
+ ]
91
+ }
92
+ const { leverage } = input
93
+ if (
94
+ typeof leverage !== 'number' ||
95
+ !Number.isFinite(leverage) ||
96
+ leverage <= 0
97
+ ) {
98
+ throw invalidInput(
99
+ 'leverage',
100
+ `must be a finite number above zero, got ${leverage}`
101
+ )
102
+ }
103
+ return [1, leverage]
104
+ }
105
+
55
106
  /**
56
107
  * The three order-entry amounts, derived from whichever one the user typed.
57
108
  * Only `size` snaps, onto the market's venue lot grid, because an order sends
58
109
  * size alone; no quote amount has a grid. A held margin returns byte-identical,
59
110
  * `notional` is the snapped size × price, and a derived margin is
60
- * `notional ÷ leverage` in `DivBig` (40 places, half-up).
111
+ * `notional ÷ leverage`, or `notional × initialMarginFractionBps ÷ 10000`
112
+ * from a native IMF, in `DivBig` (40 places, half-up).
61
113
  *
62
114
  * @throws {PerpsError} `ValidationError` that names `amount` or `price` when
63
- * it is not a positive decimal, or `leverage` when it is not a finite number
64
- * above zero. `ValidationError` with the lot size when the snapped size is
65
- * zero (below one lot). `SDKError` when `market.providerId` names no
66
- * registered provider plugin.
115
+ * it is not a positive decimal, `initialMarginFractionBps` when it is
116
+ * present and not a positive integer, or `leverage` when no IMF is present
117
+ * and it is not a finite number above zero. `ValidationError` with the lot
118
+ * size when the snapped size is zero (below one lot). `SDKError` when
119
+ * `market.providerId` names no registered provider plugin.
67
120
  * @public
68
121
  */
69
122
  export function calculateOrderAmounts(input: OrderAmountsInput): OrderAmounts {
70
- const { sdk, market, held, leverage } = input
123
+ const { sdk, market, held } = input
71
124
  const amount = requirePositiveDecimal(input.amount, 'amount')
72
125
  const price = requirePositiveDecimal(input.price, 'price')
73
- if (!Number.isFinite(leverage) || leverage <= 0) {
74
- throw invalidInput(
75
- 'leverage',
76
- `must be a finite number above zero, got ${leverage}`
77
- )
78
- }
126
+ const [rateNumerator, rateDenominator] = resolveMarginRate(input)
79
127
 
80
128
  const requested =
81
129
  held === 'size'
82
130
  ? input.amount
83
131
  : held === 'notional'
84
132
  ? amount.div(price).toFixed()
85
- : amount.times(leverage).div(price).toFixed()
133
+ : amount
134
+ .times(rateDenominator)
135
+ .div(price.times(rateNumerator))
136
+ .toFixed()
86
137
  const size = snapOrderSize(sdk, market, requested)
87
138
  if (isDecimalStringZero(size)) {
88
139
  throw new PerpsError(
@@ -96,7 +147,10 @@ export function calculateOrderAmounts(input: OrderAmountsInput): OrderAmounts {
96
147
  margin:
97
148
  held === 'margin'
98
149
  ? input.amount
99
- : new DivBig(notional).div(leverage).toFixed(),
150
+ : new DivBig(notional)
151
+ .times(rateNumerator)
152
+ .div(rateDenominator)
153
+ .toFixed(),
100
154
  size,
101
155
  notional: notional.toFixed(),
102
156
  }