@morpho-org/morpho-sdk 8.3.0 → 9.0.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 (155) hide show
  1. package/MIGRATION-v8-to-v9.md +54 -0
  2. package/README.md +13 -7
  3. package/lib/cjs/actions/bundles/common.d.ts +4 -7
  4. package/lib/cjs/actions/bundles/common.js +8 -14
  5. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +1 -8
  7. package/lib/cjs/actions/midnight/authorization.d.ts +3 -1
  8. package/lib/cjs/actions/midnight/authorization.js +11 -1
  9. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -0
  10. package/lib/cjs/actions/midnight/cancelAndMake.js +10 -2
  11. package/lib/cjs/actions/midnight/redeem.d.ts +3 -1
  12. package/lib/cjs/actions/midnight/redeem.js +9 -3
  13. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  14. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +7 -3
  15. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +4 -1
  16. package/lib/cjs/actions/midnight/supplyCollateral.js +10 -3
  17. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  18. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +9 -3
  19. package/lib/cjs/actions/midnight/takeBorrow.d.ts +3 -1
  20. package/lib/cjs/actions/midnight/takeBorrow.js +9 -3
  21. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  22. package/lib/cjs/actions/midnight/takeLend.js +7 -2
  23. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  24. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +8 -2
  25. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +3 -1
  26. package/lib/cjs/actions/midnight/takeWithdraw.js +10 -3
  27. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  28. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +5 -7
  29. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +7 -11
  30. package/lib/cjs/actions/requirements/getRequirementsApproval.js +8 -15
  31. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  32. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +11 -8
  33. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  34. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  35. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +1 -1
  36. package/lib/cjs/actions/vaultV1/inKindRedeem.js +1 -1
  37. package/lib/cjs/actions/vaultV1/withdraw.d.ts +4 -4
  38. package/lib/cjs/actions/vaultV1/withdraw.js +4 -4
  39. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +1 -1
  40. package/lib/cjs/actions/vaultV2/forceWithdraw.js +1 -1
  41. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +1 -1
  42. package/lib/cjs/actions/vaultV2/inKindRedeem.js +1 -1
  43. package/lib/cjs/actions/vaultV2/withdraw.d.ts +4 -4
  44. package/lib/cjs/actions/vaultV2/withdraw.js +4 -4
  45. package/lib/cjs/entities/blue/blue.d.ts +2 -12
  46. package/lib/cjs/entities/blue/blue.js +0 -4
  47. package/lib/cjs/entities/midnight/midnight.d.ts +56 -17
  48. package/lib/cjs/entities/midnight/midnight.js +131 -52
  49. package/lib/cjs/entities/midnight/types.d.ts +2 -9
  50. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  51. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +0 -7
  52. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  53. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -20
  54. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +40 -37
  55. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -34
  56. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +36 -34
  57. package/lib/cjs/entities/vaultV2/vaultV2.js +8 -34
  58. package/lib/cjs/helpers/encodeMidnightCalldata.d.ts +48 -0
  59. package/lib/cjs/helpers/encodeMidnightCalldata.js +74 -0
  60. package/lib/cjs/helpers/slippage.d.ts +9 -25
  61. package/lib/cjs/helpers/slippage.js +10 -27
  62. package/lib/cjs/helpers/validate.d.ts +1 -0
  63. package/lib/cjs/helpers/validate.js +5 -0
  64. package/lib/cjs/helpers/validateMidnightAccount.d.ts +34 -0
  65. package/lib/cjs/helpers/validateMidnightAccount.js +47 -0
  66. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  67. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +4 -0
  68. package/lib/cjs/helpers/validateMidnightMarket.d.ts +2 -0
  69. package/lib/cjs/helpers/validateMidnightMarket.js +5 -0
  70. package/lib/cjs/helpers/validateMidnightPublication.d.ts +11 -0
  71. package/lib/cjs/helpers/validateMidnightPublication.js +12 -1
  72. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +1 -0
  73. package/lib/cjs/helpers/validateMidnightReceiver.js +8 -0
  74. package/lib/cjs/helpers/validateTakeableOffers.d.ts +2 -1
  75. package/lib/cjs/helpers/validateTakeableOffers.js +4 -3
  76. package/lib/cjs/types/action.d.ts +3 -1
  77. package/lib/cjs/types/error.d.ts +56 -5
  78. package/lib/cjs/types/error.js +139 -10
  79. package/lib/esm/actions/bundles/common.d.ts +4 -7
  80. package/lib/esm/actions/bundles/common.js +8 -14
  81. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  82. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -9
  83. package/lib/esm/actions/midnight/authorization.d.ts +3 -1
  84. package/lib/esm/actions/midnight/authorization.js +12 -2
  85. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -0
  86. package/lib/esm/actions/midnight/cancelAndMake.js +11 -3
  87. package/lib/esm/actions/midnight/redeem.d.ts +3 -1
  88. package/lib/esm/actions/midnight/redeem.js +10 -4
  89. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  90. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +8 -4
  91. package/lib/esm/actions/midnight/supplyCollateral.d.ts +4 -1
  92. package/lib/esm/actions/midnight/supplyCollateral.js +11 -4
  93. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  94. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +10 -4
  95. package/lib/esm/actions/midnight/takeBorrow.d.ts +3 -1
  96. package/lib/esm/actions/midnight/takeBorrow.js +10 -4
  97. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  98. package/lib/esm/actions/midnight/takeLend.js +8 -3
  99. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  100. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +9 -3
  101. package/lib/esm/actions/midnight/takeWithdraw.d.ts +3 -1
  102. package/lib/esm/actions/midnight/takeWithdraw.js +11 -4
  103. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  104. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +6 -8
  105. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +7 -11
  106. package/lib/esm/actions/requirements/getRequirementsApproval.js +9 -16
  107. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  108. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +12 -9
  109. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  110. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  111. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +1 -1
  112. package/lib/esm/actions/vaultV1/inKindRedeem.js +1 -1
  113. package/lib/esm/actions/vaultV1/withdraw.d.ts +4 -4
  114. package/lib/esm/actions/vaultV1/withdraw.js +4 -4
  115. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +1 -1
  116. package/lib/esm/actions/vaultV2/forceWithdraw.js +1 -1
  117. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +1 -1
  118. package/lib/esm/actions/vaultV2/inKindRedeem.js +1 -1
  119. package/lib/esm/actions/vaultV2/withdraw.d.ts +4 -4
  120. package/lib/esm/actions/vaultV2/withdraw.js +4 -4
  121. package/lib/esm/entities/blue/blue.d.ts +2 -12
  122. package/lib/esm/entities/blue/blue.js +0 -4
  123. package/lib/esm/entities/midnight/midnight.d.ts +56 -17
  124. package/lib/esm/entities/midnight/midnight.js +132 -53
  125. package/lib/esm/entities/midnight/types.d.ts +2 -9
  126. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  127. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +1 -8
  128. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  129. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +9 -21
  130. package/lib/esm/entities/vaultV1/vaultV1.d.ts +40 -37
  131. package/lib/esm/entities/vaultV1/vaultV1.js +6 -35
  132. package/lib/esm/entities/vaultV2/vaultV2.d.ts +36 -34
  133. package/lib/esm/entities/vaultV2/vaultV2.js +8 -34
  134. package/lib/esm/helpers/encodeMidnightCalldata.d.ts +48 -0
  135. package/lib/esm/helpers/encodeMidnightCalldata.js +69 -0
  136. package/lib/esm/helpers/slippage.d.ts +9 -25
  137. package/lib/esm/helpers/slippage.js +9 -25
  138. package/lib/esm/helpers/validate.d.ts +1 -0
  139. package/lib/esm/helpers/validate.js +5 -0
  140. package/lib/esm/helpers/validateMidnightAccount.d.ts +34 -0
  141. package/lib/esm/helpers/validateMidnightAccount.js +43 -0
  142. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  143. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +4 -0
  144. package/lib/esm/helpers/validateMidnightMarket.d.ts +2 -0
  145. package/lib/esm/helpers/validateMidnightMarket.js +5 -0
  146. package/lib/esm/helpers/validateMidnightPublication.d.ts +11 -0
  147. package/lib/esm/helpers/validateMidnightPublication.js +10 -0
  148. package/lib/esm/helpers/validateMidnightReceiver.d.ts +1 -0
  149. package/lib/esm/helpers/validateMidnightReceiver.js +8 -0
  150. package/lib/esm/helpers/validateTakeableOffers.d.ts +2 -1
  151. package/lib/esm/helpers/validateTakeableOffers.js +4 -3
  152. package/lib/esm/types/action.d.ts +3 -1
  153. package/lib/esm/types/error.d.ts +56 -5
  154. package/lib/esm/types/error.js +134 -6
  155. package/package.json +4 -3
@@ -17,7 +17,7 @@ export interface BundlesTokenPermit {
17
17
  }
18
18
  /** ABI-ready ERC-2612 share permit consumed by vault bundles. */
19
19
  export interface BundleSharesPermit {
20
- /** Exact vault-share allowance authorized by the permit. */
20
+ /** Vault-share allowance authorized by the permit. */
21
21
  readonly value: bigint;
22
22
  /** Vault permit nonce signed by the owner. */
23
23
  readonly nonce: bigint;
@@ -149,7 +149,7 @@ export declare const normalizeBundlesSignature: (serializedSignature: Hex, onInv
149
149
  * @param params.deadline - Unix timestamp in seconds used by the empty-permit sentinel.
150
150
  * @param params.owner - Optional expected signature owner.
151
151
  * @param params.spender - Optional expected fixed bundles contract authorized to pull shares.
152
- * @param params.amount - Optional exact share allowance in the vault share token's smallest unit.
152
+ * @param params.amount - Optional minimum share allowance in the vault share token's smallest unit.
153
153
  * @param params.requirementSignature - Optional signed ERC-2612 share requirement; omit for the empty-permit sentinel.
154
154
  * @returns The signed share permit or the contract's empty-permit sentinel.
155
155
  * @throws {NonPositiveInputError} when a bundle or permit deadline is not positive.
@@ -203,22 +203,19 @@ export declare const selectBundlesTokenRequirementSignature: (signatures: readon
203
203
  * @internal
204
204
  *
205
205
  * @param signatures - Signatures passed to the operation's `buildTx` function.
206
- * @param expected - Immutable spender, amount bounds, and deadline required by the operation.
206
+ * @param expected - Immutable spender, minimum amount, and deadline required by the operation.
207
207
  * @param expected.spender - Fixed bundles contract the permit must authorize.
208
208
  * @param expected.amount - Minimum share allowance the permit must cover.
209
- * @param expected.maxAmount - Optional inclusive share allowance ceiling; defaults to
210
- * `expected.amount`, which accepts only an exact match.
211
209
  * @param expected.deadline - Deadline the permit must carry.
212
210
  * @returns The matching ERC-2612 signature, or `undefined` when no signature is supplied.
213
211
  * @throws {BundlesPermitMismatchError} when the signature is not ERC-2612, its spender or
214
212
  * deadline differ from the operation's, its signed amount differs from its action's amount, or
215
- * its amount is outside `[expected.amount, expected.maxAmount ?? expected.amount]`.
213
+ * its amount is below `expected.amount`.
216
214
  * The nonce is not checked here: it is onchain state the vault's `permit` verifies at execution.
217
215
  */
218
216
  export declare const selectBundlesSharesPermitSignature: (signatures: readonly RequirementSignature[] | undefined, expected: {
219
217
  readonly spender: Address;
220
218
  readonly amount: bigint;
221
- readonly maxAmount?: bigint;
222
219
  readonly deadline: bigint;
223
220
  }) => Erc2612RequirementSignature | undefined;
224
221
  /** @internal Returns the exact referral fee deducted from a fixed gross asset amount. */
@@ -223,7 +223,7 @@ export const normalizeBundlesSignature = (serializedSignature, onInvalid = (deta
223
223
  * @param params.deadline - Unix timestamp in seconds used by the empty-permit sentinel.
224
224
  * @param params.owner - Optional expected signature owner.
225
225
  * @param params.spender - Optional expected fixed bundles contract authorized to pull shares.
226
- * @param params.amount - Optional exact share allowance in the vault share token's smallest unit.
226
+ * @param params.amount - Optional minimum share allowance in the vault share token's smallest unit.
227
227
  * @param params.requirementSignature - Optional signed ERC-2612 share requirement; omit for the empty-permit sentinel.
228
228
  * @returns The signed share permit or the contract's empty-permit sentinel.
229
229
  * @throws {NonPositiveInputError} when a bundle or permit deadline is not positive.
@@ -291,11 +291,11 @@ export const getBundlesSharesPermit = (params) => {
291
291
  });
292
292
  }
293
293
  if (params.amount != null &&
294
- (requirementSignature.args.amount !== params.amount ||
295
- requirementSignature.action.args.amount !== params.amount)) {
294
+ (requirementSignature.args.amount < params.amount ||
295
+ requirementSignature.action.args.amount < params.amount)) {
296
296
  throw new BundlesPermitMismatchError({
297
297
  field: "amount",
298
- expected: String(params.amount),
298
+ expected: `at least ${params.amount}`,
299
299
  actual: String(requirementSignature.args.amount),
300
300
  });
301
301
  }
@@ -408,16 +408,14 @@ export const selectBundlesTokenRequirementSignature = (signatures, expected) =>
408
408
  * @internal
409
409
  *
410
410
  * @param signatures - Signatures passed to the operation's `buildTx` function.
411
- * @param expected - Immutable spender, amount bounds, and deadline required by the operation.
411
+ * @param expected - Immutable spender, minimum amount, and deadline required by the operation.
412
412
  * @param expected.spender - Fixed bundles contract the permit must authorize.
413
413
  * @param expected.amount - Minimum share allowance the permit must cover.
414
- * @param expected.maxAmount - Optional inclusive share allowance ceiling; defaults to
415
- * `expected.amount`, which accepts only an exact match.
416
414
  * @param expected.deadline - Deadline the permit must carry.
417
415
  * @returns The matching ERC-2612 signature, or `undefined` when no signature is supplied.
418
416
  * @throws {BundlesPermitMismatchError} when the signature is not ERC-2612, its spender or
419
417
  * deadline differ from the operation's, its signed amount differs from its action's amount, or
420
- * its amount is outside `[expected.amount, expected.maxAmount ?? expected.amount]`.
418
+ * its amount is below `expected.amount`.
421
419
  * The nonce is not checked here: it is onchain state the vault's `permit` verifies at execution.
422
420
  */
423
421
  export const selectBundlesSharesPermitSignature = (signatures, expected) => {
@@ -439,10 +437,6 @@ export const selectBundlesSharesPermitSignature = (signatures, expected) => {
439
437
  actual: action.args.spender,
440
438
  });
441
439
  }
442
- const maxAmount = expected.maxAmount ?? expected.amount;
443
- const expectedAmount = expected.maxAmount == null || expected.maxAmount === expected.amount
444
- ? String(expected.amount)
445
- : `[${expected.amount}, ${expected.maxAmount}]`;
446
440
  if (permit.args.amount !== action.args.amount) {
447
441
  throw new BundlesPermitMismatchError({
448
442
  field: "amount",
@@ -450,10 +444,10 @@ export const selectBundlesSharesPermitSignature = (signatures, expected) => {
450
444
  actual: String(permit.args.amount),
451
445
  });
452
446
  }
453
- if (permit.args.amount < expected.amount || permit.args.amount > maxAmount) {
447
+ if (permit.args.amount < expected.amount) {
454
448
  throw new BundlesPermitMismatchError({
455
449
  field: "amount",
456
- expected: expectedAmount,
450
+ expected: `at least ${expected.amount}`,
457
451
  actual: String(permit.args.amount),
458
452
  });
459
453
  }
@@ -5,8 +5,6 @@ export type BundlesTokenRequirementsState = {
5
5
  readonly type: "approval";
6
6
  /** Current allowance of the funding token for `spender`. */
7
7
  readonly allowance: bigint;
8
- /** Allowance to set when the current allowance cannot cover `amount`. */
9
- readonly approvalAmount: bigint;
10
8
  } | {
11
9
  readonly type: "permit2SignatureTransfer";
12
10
  readonly permit2Allowance: bigint;
@@ -36,7 +34,6 @@ export type BundlesTokenRequirementsState = {
36
34
  * @param params.state - Prefetched state for either classic approval or Permit2 SignatureTransfer.
37
35
  * @param params.state.type - `approval` for a direct allowance or `permit2SignatureTransfer` for a signed pull.
38
36
  * @param params.state.allowance - In the approval branch, current token allowance from `owner` to `spender`.
39
- * @param params.state.approvalAmount - In the approval branch, allowance to set if needed; must cover `amount`.
40
37
  * @param params.state.permit2Allowance - In the SignatureTransfer branch, current token allowance from `owner` to canonical Permit2.
41
38
  * @param params.state.permit2Nonce - In the SignatureTransfer branch, caller-selected unused uint256 unordered nonce.
42
39
  * @param params.state.nonceBitmap - In the SignatureTransfer branch, owner's Permit2 bitmap word at `permit2Nonce >> 8n`.
@@ -48,7 +45,6 @@ export type BundlesTokenRequirementsState = {
48
45
  * @throws {InputExceedsMaxError} when `amount`, the Permit2 nonce, or the SignatureTransfer
49
46
  * `deadline` exceeds uint256.
50
47
  * @throws {Permit2SignatureTransferNonceAlreadyUsedError} when the selected nonce bit is set.
51
- * @throws {ApprovalAmountLessThanSpendAmountError} when a classic approval cannot cover the pull.
52
48
  * @throws {UnknownAddressError} when the SignatureTransfer branch runs on a chain without canonical Permit2.
53
49
  * @throws {NonPositiveInputError} when the SignatureTransfer `deadline` is not positive.
54
50
  * @throws {ExpiredDeadlineError} when the SignatureTransfer `deadline` is positive but not in the future.
@@ -65,7 +61,7 @@ export type BundlesTokenRequirementsState = {
65
61
  * chainId: 1,
66
62
  * amount: 1_000_000n,
67
63
  * deadline: 1_900_000_000n,
68
- * state: { type: "approval", allowance: 1_000_000n, approvalAmount: 1_000_000n },
64
+ * state: { type: "approval", allowance: 1_000_000n },
69
65
  * });
70
66
  * // requirements is empty because the allowance already covers the amount.
71
67
  * ```
@@ -2,7 +2,7 @@ import { getChainAddress } from "@morpho-org/morpho-ts";
2
2
  import { maxUint256 } from "viem";
3
3
  import { validateUint256Field } from "../../helpers/validate.js";
4
4
  import { validateRequirementSpender } from "../../helpers/validateRequirementSpender.js";
5
- import { ApprovalAmountLessThanSpendAmountError, InputExceedsMaxError, NegativeInputError, Permit2SignatureTransferNonceAlreadyUsedError, } from "../../types/index.js";
5
+ import { InputExceedsMaxError, NegativeInputError, Permit2SignatureTransferNonceAlreadyUsedError, } from "../../types/index.js";
6
6
  import { encodeErc20Permit2SignatureTransfer } from "../requirements/encode/index.js";
7
7
  import { getRequirementsApproval } from "../requirements/getRequirementsApproval.js";
8
8
  /**
@@ -28,7 +28,6 @@ import { getRequirementsApproval } from "../requirements/getRequirementsApproval
28
28
  * @param params.state - Prefetched state for either classic approval or Permit2 SignatureTransfer.
29
29
  * @param params.state.type - `approval` for a direct allowance or `permit2SignatureTransfer` for a signed pull.
30
30
  * @param params.state.allowance - In the approval branch, current token allowance from `owner` to `spender`.
31
- * @param params.state.approvalAmount - In the approval branch, allowance to set if needed; must cover `amount`.
32
31
  * @param params.state.permit2Allowance - In the SignatureTransfer branch, current token allowance from `owner` to canonical Permit2.
33
32
  * @param params.state.permit2Nonce - In the SignatureTransfer branch, caller-selected unused uint256 unordered nonce.
34
33
  * @param params.state.nonceBitmap - In the SignatureTransfer branch, owner's Permit2 bitmap word at `permit2Nonce >> 8n`.
@@ -40,7 +39,6 @@ import { getRequirementsApproval } from "../requirements/getRequirementsApproval
40
39
  * @throws {InputExceedsMaxError} when `amount`, the Permit2 nonce, or the SignatureTransfer
41
40
  * `deadline` exceeds uint256.
42
41
  * @throws {Permit2SignatureTransferNonceAlreadyUsedError} when the selected nonce bit is set.
43
- * @throws {ApprovalAmountLessThanSpendAmountError} when a classic approval cannot cover the pull.
44
42
  * @throws {UnknownAddressError} when the SignatureTransfer branch runs on a chain without canonical Permit2.
45
43
  * @throws {NonPositiveInputError} when the SignatureTransfer `deadline` is not positive.
46
44
  * @throws {ExpiredDeadlineError} when the SignatureTransfer `deadline` is positive but not in the future.
@@ -57,7 +55,7 @@ import { getRequirementsApproval } from "../requirements/getRequirementsApproval
57
55
  * chainId: 1,
58
56
  * amount: 1_000_000n,
59
57
  * deadline: 1_900_000_000n,
60
- * state: { type: "approval", allowance: 1_000_000n, approvalAmount: 1_000_000n },
58
+ * state: { type: "approval", allowance: 1_000_000n },
61
59
  * });
62
60
  * // requirements is empty because the allowance already covers the amount.
63
61
  * ```
@@ -73,9 +71,6 @@ export const resolveBundlesTokenRequirements = (params) => {
73
71
  if (params.amount === 0n)
74
72
  return [];
75
73
  if (params.state.type === "approval") {
76
- if (params.state.approvalAmount < params.amount) {
77
- throw new ApprovalAmountLessThanSpendAmountError();
78
- }
79
74
  return getRequirementsApproval({
80
75
  address: params.token,
81
76
  chainId: params.chainId,
@@ -83,7 +78,6 @@ export const resolveBundlesTokenRequirements = (params) => {
83
78
  // Compare against the bounded pull to avoid redundant approvals and USDT zero-resets.
84
79
  spender: params.spender,
85
80
  spendAmount: params.amount,
86
- approvalAmount: params.state.approvalAmount,
87
81
  },
88
82
  allowances: params.state.allowance,
89
83
  });
@@ -110,7 +104,6 @@ export const resolveBundlesTokenRequirements = (params) => {
110
104
  args: {
111
105
  spender: permit2,
112
106
  spendAmount: params.amount,
113
- approvalAmount: maxUint256,
114
107
  },
115
108
  allowances: params.state.permit2Allowance,
116
109
  }),
@@ -1,5 +1,5 @@
1
1
  import { type Address } from "viem";
2
- import type { Metadata, MidnightAuthorizationAction, Transaction } from "../../types/index.js";
2
+ import { type Metadata, type MidnightAuthorizationAction, type Transaction } from "../../types/index.js";
3
3
  /** Parameters for encoding a direct Midnight `setIsAuthorized` call. */
4
4
  export interface MidnightSetIsAuthorizedParams {
5
5
  readonly chainId: number;
@@ -23,7 +23,9 @@ export interface MidnightSetIsAuthorizedParams {
23
23
  * @param params.isAuthorized - Optional target state; defaults to `true`.
24
24
  * @param params.metadata - Optional analytics metadata appended to calldata.
25
25
  * @returns A deep-frozen `Transaction<MidnightAuthorizationAction>` targeting `Midnight`.
26
+ * @throws {MidnightZeroOnBehalfError} when `onBehalf` is the zero address.
26
27
  * @throws {UnsupportedMidnightAuthorizationTargetError} when granting authorization to an unsupported operator.
28
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
27
29
  * @example
28
30
  * ```ts
29
31
  * import { midnightSetIsAuthorized } from "@morpho-org/morpho-sdk";
@@ -1,8 +1,11 @@
1
1
  import { midnightAbi } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { encodeFunctionData } from "viem";
3
+ import { isAddressEqual, zeroAddress } from "viem";
4
+ import { encodeMidnightCalldata } from "../../helpers/encodeMidnightCalldata.js";
4
5
  import { addTransactionMetadata } from "../../helpers/index.js";
6
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
5
7
  import { validateMidnightAuthorizationTarget } from "../../helpers/validateMidnightAuthorizationTarget.js";
8
+ import { MidnightZeroOnBehalfError, } from "../../types/index.js";
6
9
  /**
7
10
  * Encodes `Midnight.setIsAuthorized`. Grants target MidnightBundlesV2;
8
11
  * revocations accept any operator.
@@ -18,7 +21,9 @@ import { validateMidnightAuthorizationTarget } from "../../helpers/validateMidni
18
21
  * @param params.isAuthorized - Optional target state; defaults to `true`.
19
22
  * @param params.metadata - Optional analytics metadata appended to calldata.
20
23
  * @returns A deep-frozen `Transaction<MidnightAuthorizationAction>` targeting `Midnight`.
24
+ * @throws {MidnightZeroOnBehalfError} when `onBehalf` is the zero address.
21
25
  * @throws {UnsupportedMidnightAuthorizationTargetError} when granting authorization to an unsupported operator.
26
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
22
27
  * @example
23
28
  * ```ts
24
29
  * import { midnightSetIsAuthorized } from "@morpho-org/morpho-sdk";
@@ -31,6 +36,11 @@ import { validateMidnightAuthorizationTarget } from "../../helpers/validateMidni
31
36
  * ```
32
37
  */
33
38
  export const midnightSetIsAuthorized = (params) => {
39
+ // Reject a malformed account before comparing it with the zero address.
40
+ validateMidnightAddress("onBehalf", params.onBehalf);
41
+ if (isAddressEqual(params.onBehalf, zeroAddress)) {
42
+ throw new MidnightZeroOnBehalfError("onBehalf");
43
+ }
34
44
  const isAuthorized = params.isAuthorized ?? true;
35
45
  if (isAuthorized) {
36
46
  // Restrict grants to known protocol operators; revocations remain permissionless by target.
@@ -43,7 +53,7 @@ export const midnightSetIsAuthorized = (params) => {
43
53
  let tx = {
44
54
  to: midnight,
45
55
  value: 0n,
46
- data: encodeFunctionData({
56
+ data: encodeMidnightCalldata({
47
57
  abi: midnightAbi,
48
58
  functionName: "setIsAuthorized",
49
59
  args: [params.authorized, isAuthorized, params.onBehalf],
@@ -72,6 +72,8 @@ export type { MidnightCancelAndMakeParams, MidnightMakeBorrowCollateral, Midnigh
72
72
  * @throws {UnknownCollateralIndexError} when a collateral index is not configured on the market.
73
73
  * @throws {NonPositiveInputError} when a collateral supply amount is non-positive.
74
74
  * @throws {NonPositiveInputError} when `blueSupply.assets` is non-positive.
75
+ * @throws {MidnightCalldataEncodingError} when another input cannot be ABI-encoded, such as an
76
+ * out-of-range integer or malformed address.
75
77
  * @example
76
78
  * ```ts
77
79
  * import { getChainAddress } from "@morpho-org/morpho-ts";
@@ -1,8 +1,10 @@
1
1
  import { InvalidTreeError, MarketUtils, midnightBundlesV2Abi, } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress, getChainAddresses, } from "@morpho-org/morpho-ts";
3
- import { encodeFunctionData, isAddressEqual, maxUint128, zeroAddress, zeroHash, } from "viem";
3
+ import { isAddressEqual, maxUint128, zeroAddress, zeroHash, } from "viem";
4
+ import { encodeMidnightCalldata, encodeMidnightMarketId, } from "../../helpers/encodeMidnightCalldata.js";
4
5
  import { addTransactionMetadata } from "../../helpers/index.js";
5
6
  import { validateDeadline, validateMidnightNativeAmount, } from "../../helpers/validate.js";
7
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
6
8
  import { validateMidnightCollateralSupplySums, validateMidnightUint128Field, } from "../../helpers/validateMidnightBounds.js";
7
9
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
8
10
  import { snapshotMidnightCancelAndMakeParams, validateMidnightPublication, } from "../../helpers/validateMidnightPublication.js";
@@ -97,6 +99,8 @@ const emptyMidnightMarket = {
97
99
  * @throws {UnknownCollateralIndexError} when a collateral index is not configured on the market.
98
100
  * @throws {NonPositiveInputError} when a collateral supply amount is non-positive.
99
101
  * @throws {NonPositiveInputError} when `blueSupply.assets` is non-positive.
102
+ * @throws {MidnightCalldataEncodingError} when another input cannot be ABI-encoded, such as an
103
+ * out-of-range integer or malformed address.
100
104
  * @example
101
105
  * ```ts
102
106
  * import { getChainAddress } from "@morpho-org/morpho-ts";
@@ -162,6 +166,7 @@ export const midnightCancelAndMake = (params) => {
162
166
  }
163
167
  const { priceRatifierV1, rateRatifierV1 } = getChainAddresses(snapshot.chainId);
164
168
  const supportedTargets = [priceRatifierV1, rateRatifierV1].filter((target) => target != null);
169
+ validateMidnightAddress("publication.ratifier", publication.ratifier);
165
170
  if (!supportedTargets.some((target) => isAddressEqual(publication.ratifier, target))) {
166
171
  throw new UnsupportedMidnightAuthorizationTargetError({
167
172
  authorized: publication.ratifier,
@@ -250,7 +255,7 @@ export const midnightCancelAndMake = (params) => {
250
255
  let tx = {
251
256
  to: getChainAddress(snapshot.chainId, "midnightBundlesV2"),
252
257
  value: nativeFunding.value,
253
- data: encodeFunctionData({
258
+ data: encodeMidnightCalldata({
254
259
  abi: midnightBundlesV2Abi,
255
260
  functionName: "midnightBundlesV2CancelAndMake",
256
261
  args: [
@@ -286,13 +291,16 @@ export const midnightCancelAndMake = (params) => {
286
291
  args: {
287
292
  market: publication?.collateral == null
288
293
  ? zeroHash
289
- : MarketUtils.toId(publication.collateral.market),
294
+ : encodeMidnightMarketId(publication.collateral.market),
290
295
  ratifier: publication?.ratifier ?? zeroAddress,
291
296
  root: publication?.root ?? zeroHash,
292
297
  groups: [...(publication?.groups ?? [])],
293
298
  cancellations,
294
299
  collateralSupplies: supplies,
295
300
  ...(blueSupply && { blueSupply }),
301
+ ...(nativeFunding.value > 0n
302
+ ? { nativeAmount: nativeFunding.value }
303
+ : {}),
296
304
  deadline: snapshot.deadline,
297
305
  },
298
306
  },
@@ -23,7 +23,8 @@ export interface MidnightRedeemParams {
23
23
  * @param params.chainId - Chain id used to resolve `Midnight`.
24
24
  * @param params.market - Midnight market whose credit is redeemed.
25
25
  * @param params.units - Credit units to withdraw.
26
- * @param params.onBehalf - Account whose credit balance is reduced.
26
+ * @param params.onBehalf - Account whose credit balance is reduced. `onBehalf`, or an operator
27
+ * it authorized, must send the transaction; otherwise Midnight reverts `Unauthorized()`.
27
28
  * @param params.receiver - Optional receiver for withdrawn loan assets; defaults to `onBehalf`.
28
29
  * Midnight protocol and market token contracts are rejected.
29
30
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -33,6 +34,7 @@ export interface MidnightRedeemParams {
33
34
  * @throws {MidnightZeroOnBehalfError} when `onBehalf` is the zero address.
34
35
  * @throws {ChainIdMismatchError} when the market targets another chain.
35
36
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
37
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
36
38
  * @throws {MidnightZeroReceiverError} when `receiver` resolves to the zero address.
37
39
  * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
38
40
  * market token contract.
@@ -1,7 +1,9 @@
1
1
  import { MarketUtils, midnightAbi, } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { encodeFunctionData, isAddressEqual, zeroAddress, } from "viem";
3
+ import { isAddressEqual, zeroAddress } from "viem";
4
+ import { encodeMidnightCalldata, encodeMidnightMarketId, } from "../../helpers/encodeMidnightCalldata.js";
4
5
  import { addTransactionMetadata } from "../../helpers/index.js";
6
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
5
7
  import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
6
8
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
7
9
  import { validateMidnightReceiver } from "../../helpers/validateMidnightReceiver.js";
@@ -19,7 +21,8 @@ import { MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/i
19
21
  * @param params.chainId - Chain id used to resolve `Midnight`.
20
22
  * @param params.market - Midnight market whose credit is redeemed.
21
23
  * @param params.units - Credit units to withdraw.
22
- * @param params.onBehalf - Account whose credit balance is reduced.
24
+ * @param params.onBehalf - Account whose credit balance is reduced. `onBehalf`, or an operator
25
+ * it authorized, must send the transaction; otherwise Midnight reverts `Unauthorized()`.
23
26
  * @param params.receiver - Optional receiver for withdrawn loan assets; defaults to `onBehalf`.
24
27
  * Midnight protocol and market token contracts are rejected.
25
28
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -29,6 +32,7 @@ import { MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/i
29
32
  * @throws {MidnightZeroOnBehalfError} when `onBehalf` is the zero address.
30
33
  * @throws {ChainIdMismatchError} when the market targets another chain.
31
34
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
35
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
32
36
  * @throws {MidnightZeroReceiverError} when `receiver` resolves to the zero address.
33
37
  * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
34
38
  * market token contract.
@@ -45,6 +49,8 @@ import { MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/i
45
49
  * ```
46
50
  */
47
51
  export const midnightRedeem = (params) => {
52
+ // Reject a malformed account before comparing it with the zero address.
53
+ validateMidnightAddress("onBehalf", params.onBehalf);
48
54
  if (params.units <= 0n) {
49
55
  throw new NonPositiveInputError("units", params.units);
50
56
  }
@@ -54,7 +60,7 @@ export const midnightRedeem = (params) => {
54
60
  }
55
61
  // Reject markets from another chain deployment before encoding the call.
56
62
  validateMidnightMarket({ market: params.market, chainId: params.chainId });
57
- const marketId = MarketUtils.toId(params.market);
63
+ const marketId = encodeMidnightMarketId(params.market);
58
64
  const midnight = getChainAddress(params.chainId, "midnight");
59
65
  const receiver = params.receiver ?? params.onBehalf;
60
66
  // Rejects receivers that would strand the redeemed assets in a contract.
@@ -67,7 +73,7 @@ export const midnightRedeem = (params) => {
67
73
  let tx = {
68
74
  to: midnight,
69
75
  value: 0n,
70
- data: encodeFunctionData({
76
+ data: encodeMidnightCalldata({
71
77
  abi: midnightAbi,
72
78
  functionName: "withdraw",
73
79
  args: [
@@ -65,6 +65,7 @@ export interface MidnightRepayWithdrawCollateralParams {
65
65
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
66
66
  * @throws {UnknownCollateralIndexError} when a withdrawal targets an unconfigured collateral index.
67
67
  * @throws {MidnightZeroReceiverError} when collateral is withdrawn to the zero address.
68
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
68
69
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
69
70
  * contract or a market token contract.
70
71
  * @example
@@ -1,8 +1,10 @@
1
1
  import { MarketUtils, midnightBundlesV2Abi, } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { encodeFunctionData, maxUint256, zeroAddress, } from "viem";
3
+ import { maxUint256, zeroAddress } from "viem";
4
+ import { encodeMidnightCalldata, encodeMidnightMarketId, } from "../../helpers/encodeMidnightCalldata.js";
4
5
  import { addTransactionMetadata } from "../../helpers/index.js";
5
6
  import { validateDeadline, validateMidnightNativeAmount, validateUint256Field, } from "../../helpers/validate.js";
7
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
6
8
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
7
9
  import { validateMidnightReceiver } from "../../helpers/validateMidnightReceiver.js";
8
10
  import { InputExceedsMaxError, NonPositiveInputError, } from "../../types/index.js";
@@ -47,6 +49,7 @@ import { InputExceedsMaxError, NonPositiveInputError, } from "../../types/index.
47
49
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
48
50
  * @throws {UnknownCollateralIndexError} when a withdrawal targets an unconfigured collateral index.
49
51
  * @throws {MidnightZeroReceiverError} when collateral is withdrawn to the zero address.
52
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
50
53
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
51
54
  * contract or a market token contract.
52
55
  * @example
@@ -93,6 +96,7 @@ export const midnightRepayWithdrawCollateral = (params) => {
93
96
  // Throws UnknownCollateralIndexError when the index is not configured on the market.
94
97
  MarketUtils.getCollateralByIndex(params.market, collateralIndex);
95
98
  }
99
+ validateMidnightAddress("collateralReceiver", params.collateralReceiver);
96
100
  if (params.collateralWithdrawals.length > 0) {
97
101
  // Rejects receivers that would strand the withdrawn collateral in a contract.
98
102
  validateMidnightReceiver({
@@ -145,12 +149,12 @@ export const midnightRepayWithdrawCollateral = (params) => {
145
149
  to: getChainAddress(params.chainId, "midnightBundlesV2"),
146
150
  value: nativeFunding.value,
147
151
  data: repay.type === "assets"
148
- ? encodeFunctionData({
152
+ ? encodeMidnightCalldata({
149
153
  abi: midnightBundlesV2Abi,
150
154
  functionName: "midnightBundlesV2BuyWithAssetsTargetAndWithdrawCollateral",
151
155
  args: [market, repay.assets, repay.assets, ...args],
152
156
  })
153
- : encodeFunctionData({
157
+ : encodeMidnightCalldata({
154
158
  abi: midnightBundlesV2Abi,
155
159
  functionName: "midnightBundlesV2BuyWithUnitsTargetAndWithdrawCollateral",
156
160
  args: [market, maxUint256, repay.maxBuyerAssets, ...args],
@@ -164,7 +168,7 @@ export const midnightRepayWithdrawCollateral = (params) => {
164
168
  action: {
165
169
  type: "midnightRepayWithdrawCollateral",
166
170
  args: {
167
- market: MarketUtils.toId(params.market),
171
+ market: encodeMidnightMarketId(params.market),
168
172
  repay: { ...repay },
169
173
  collateralWithdrawals: params.collateralWithdrawals.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
170
174
  collateralReceiver: params.collateralReceiver,
@@ -22,7 +22,9 @@ export interface MidnightSupplyCollateralParams {
22
22
  * @param params.market - Midnight market receiving collateral.
23
23
  * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
24
24
  * @param params.assets - Collateral assets to supply.
25
- * @param params.onBehalf - Account whose collateral balance increases.
25
+ * @param params.onBehalf - Account whose collateral balance increases. `onBehalf`, or an
26
+ * operator it authorized, must send the transaction; otherwise Midnight reverts
27
+ * `Unauthorized()`. The collateral is pulled from the sender.
26
28
  * @param params.metadata - Optional analytics metadata appended to calldata.
27
29
  * @returns A deep-frozen `Transaction<MidnightSupplyCollateralAction>` targeting `Midnight`.
28
30
  * @throws {NonPositiveInputError} when `assets <= 0n`.
@@ -31,6 +33,7 @@ export interface MidnightSupplyCollateralParams {
31
33
  * @throws {ChainIdMismatchError} when the market targets another chain.
32
34
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
33
35
  * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
36
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
34
37
  * @example
35
38
  * ```ts
36
39
  * import { midnightSupplyCollateral } from "@morpho-org/morpho-sdk";
@@ -1,7 +1,9 @@
1
1
  import { MarketUtils, midnightAbi, } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { encodeFunctionData, isAddressEqual, zeroAddress, } from "viem";
3
+ import { isAddressEqual, zeroAddress } from "viem";
4
+ import { encodeMidnightCalldata, encodeMidnightMarketId, } from "../../helpers/encodeMidnightCalldata.js";
4
5
  import { addTransactionMetadata } from "../../helpers/index.js";
6
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
5
7
  import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
6
8
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
7
9
  import { MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/index.js";
@@ -17,7 +19,9 @@ import { MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/i
17
19
  * @param params.market - Midnight market receiving collateral.
18
20
  * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
19
21
  * @param params.assets - Collateral assets to supply.
20
- * @param params.onBehalf - Account whose collateral balance increases.
22
+ * @param params.onBehalf - Account whose collateral balance increases. `onBehalf`, or an
23
+ * operator it authorized, must send the transaction; otherwise Midnight reverts
24
+ * `Unauthorized()`. The collateral is pulled from the sender.
21
25
  * @param params.metadata - Optional analytics metadata appended to calldata.
22
26
  * @returns A deep-frozen `Transaction<MidnightSupplyCollateralAction>` targeting `Midnight`.
23
27
  * @throws {NonPositiveInputError} when `assets <= 0n`.
@@ -26,6 +30,7 @@ import { MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/i
26
30
  * @throws {ChainIdMismatchError} when the market targets another chain.
27
31
  * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
28
32
  * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
33
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
29
34
  * @example
30
35
  * ```ts
31
36
  * import { midnightSupplyCollateral } from "@morpho-org/morpho-sdk";
@@ -40,6 +45,8 @@ import { MidnightZeroOnBehalfError, NonPositiveInputError, } from "../../types/i
40
45
  * ```
41
46
  */
42
47
  export const midnightSupplyCollateral = (params) => {
48
+ // Reject a malformed account before comparing it with the zero address.
49
+ validateMidnightAddress("onBehalf", params.onBehalf);
43
50
  if (params.assets <= 0n) {
44
51
  throw new NonPositiveInputError("assets", params.assets);
45
52
  }
@@ -49,7 +56,7 @@ export const midnightSupplyCollateral = (params) => {
49
56
  }
50
57
  // Reject markets from another chain deployment before encoding the call.
51
58
  validateMidnightMarket({ market: params.market, chainId: params.chainId });
52
- const marketId = MarketUtils.toId(params.market);
59
+ const marketId = encodeMidnightMarketId(params.market);
53
60
  const midnight = getChainAddress(params.chainId, "midnight");
54
61
  const collateralIndex = params.collateralIndex ?? 0n;
55
62
  // Validate that the supplied collateral index is configured before encoding.
@@ -57,7 +64,7 @@ export const midnightSupplyCollateral = (params) => {
57
64
  let tx = {
58
65
  to: midnight,
59
66
  value: 0n,
60
- data: encodeFunctionData({
67
+ data: encodeMidnightCalldata({
61
68
  abi: midnightAbi,
62
69
  functionName: "supplyCollateral",
63
70
  args: [
@@ -38,7 +38,8 @@ export interface MidnightSupplyCollateralTakeBorrowParams extends MidnightTakeBo
38
38
  * for the full pulled amount.
39
39
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
40
40
  * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
41
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
41
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
42
+ * proceeds; on an assets target it is added on top of `target.assets`.
42
43
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
43
44
  * @param params.metadata - Optional analytics metadata appended to calldata.
44
45
  * @returns A deep-frozen `Transaction<MidnightSupplyCollateralTakeBorrowAction>` targeting `MidnightBundlesV2`.
@@ -69,6 +70,7 @@ export interface MidnightSupplyCollateralTakeBorrowParams extends MidnightTakeBo
69
70
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
70
71
  * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
71
72
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
73
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
72
74
  * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
73
75
  * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
74
76
  * a unit sells for at most one asset.
@@ -1,8 +1,10 @@
1
1
  import { MarketUtils, midnightBundlesV2Abi } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { encodeFunctionData, maxUint256 } from "viem";
3
+ import { maxUint256 } from "viem";
4
+ import { encodeMidnightCalldata } from "../../helpers/encodeMidnightCalldata.js";
4
5
  import { addTransactionMetadata } from "../../helpers/index.js";
5
6
  import { validateDeadline, validateMidnightNativeAmount, validateReferralFee, } from "../../helpers/validate.js";
7
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
6
8
  import { validateMidnightCollateralSupplySums, validateMidnightReferralFeeCap, validateMidnightTakeableOfferBounds, validateMidnightUint128Field, } from "../../helpers/validateMidnightBounds.js";
7
9
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
8
10
  import { validateMidnightReceiver } from "../../helpers/validateMidnightReceiver.js";
@@ -35,7 +37,8 @@ import { EmptyMidnightCollateralSuppliesError, NonPositiveInputError, UnboundedM
35
37
  * for the full pulled amount.
36
38
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
37
39
  * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
38
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
40
+ * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
41
+ * proceeds; on an assets target it is added on top of `target.assets`.
39
42
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
40
43
  * @param params.metadata - Optional analytics metadata appended to calldata.
41
44
  * @returns A deep-frozen `Transaction<MidnightSupplyCollateralTakeBorrowAction>` targeting `MidnightBundlesV2`.
@@ -66,6 +69,7 @@ import { EmptyMidnightCollateralSuppliesError, NonPositiveInputError, UnboundedM
66
69
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
67
70
  * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
68
71
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
72
+ * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32`, an out-of-range integer or a malformed address.
69
73
  * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
70
74
  * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
71
75
  * a unit sells for at most one asset.
@@ -144,6 +148,8 @@ export const midnightSupplyCollateralTakeBorrow = (params) => {
144
148
  throw new UnboundedMidnightTakeInputError("deadline");
145
149
  }
146
150
  validateDeadline(params.deadline);
151
+ if (params.referralFeeRecipient !== undefined)
152
+ validateMidnightAddress("referralFeeRecipient", params.referralFeeRecipient);
147
153
  const { referralFeePct, referralFeeRecipient } = validateReferralFee(params);
148
154
  validateMidnightReferralFeeCap(referralFeePct);
149
155
  validateMidnightSellTargetBounds({ target, referralFeePct });
@@ -183,12 +189,12 @@ export const midnightSupplyCollateralTakeBorrow = (params) => {
183
189
  to: getChainAddress(params.chainId, "midnightBundlesV2"),
184
190
  value: nativeFunding.value,
185
191
  data: target.type === "assets"
186
- ? encodeFunctionData({
192
+ ? encodeMidnightCalldata({
187
193
  abi: midnightBundlesV2Abi,
188
194
  functionName: "midnightBundlesV2SupplyCollateralAndSellWithAssetsTarget",
189
195
  args: [market, target.assets, target.maxUnits, ...args],
190
196
  })
191
- : encodeFunctionData({
197
+ : encodeMidnightCalldata({
192
198
  abi: midnightBundlesV2Abi,
193
199
  functionName: "midnightBundlesV2SupplyCollateralAndSellWithUnitsTarget",
194
200
  args: [market, target.units, target.minSellerAssets, ...args],