@morpho-org/morpho-sdk 5.0.0 → 5.1.2

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 (51) hide show
  1. package/README.md +4 -4
  2. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +47 -0
  3. package/lib/cjs/actions/blue/buildAssetFundingActions.js +63 -0
  4. package/lib/cjs/actions/blue/repay.d.ts +39 -39
  5. package/lib/cjs/actions/blue/repay.js +65 -46
  6. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +37 -37
  7. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +64 -41
  8. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +69 -0
  9. package/lib/cjs/actions/blue/resolveRepayFunding.js +82 -0
  10. package/lib/cjs/actions/blue/supply.d.ts +1 -1
  11. package/lib/cjs/actions/blue/supply.js +8 -22
  12. package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -1
  13. package/lib/cjs/actions/blue/supplyCollateral.js +8 -22
  14. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +1 -1
  15. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +8 -21
  16. package/lib/cjs/entities/blue/blue.js +161 -87
  17. package/lib/cjs/helpers/index.d.ts +1 -1
  18. package/lib/cjs/helpers/index.js +1 -2
  19. package/lib/cjs/helpers/validate.d.ts +0 -18
  20. package/lib/cjs/helpers/validate.js +1 -38
  21. package/lib/cjs/types/action.d.ts +51 -3
  22. package/lib/cjs/types/error.d.ts +24 -2
  23. package/lib/cjs/types/error.js +26 -5
  24. package/lib/cjs/utils.d.ts +1 -1
  25. package/lib/cjs/utils.js +2 -3
  26. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +47 -0
  27. package/lib/esm/actions/blue/buildAssetFundingActions.js +59 -0
  28. package/lib/esm/actions/blue/repay.d.ts +39 -39
  29. package/lib/esm/actions/blue/repay.js +66 -47
  30. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +37 -37
  31. package/lib/esm/actions/blue/repayWithdrawCollateral.js +65 -42
  32. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +69 -0
  33. package/lib/esm/actions/blue/resolveRepayFunding.js +78 -0
  34. package/lib/esm/actions/blue/supply.d.ts +1 -1
  35. package/lib/esm/actions/blue/supply.js +9 -23
  36. package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -1
  37. package/lib/esm/actions/blue/supplyCollateral.js +9 -23
  38. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +1 -1
  39. package/lib/esm/actions/blue/supplyCollateralBorrow.js +9 -22
  40. package/lib/esm/entities/blue/blue.js +162 -88
  41. package/lib/esm/helpers/index.d.ts +1 -1
  42. package/lib/esm/helpers/index.js +1 -1
  43. package/lib/esm/helpers/validate.d.ts +0 -18
  44. package/lib/esm/helpers/validate.js +1 -37
  45. package/lib/esm/types/action.d.ts +51 -3
  46. package/lib/esm/types/error.d.ts +24 -2
  47. package/lib/esm/types/error.js +23 -3
  48. package/lib/esm/utils.d.ts +1 -1
  49. package/lib/esm/utils.js +1 -1
  50. package/package.json +20 -19
  51. package/src/index.ts +0 -4
@@ -4,7 +4,7 @@ import { Time } from "@morpho-org/morpho-ts";
4
4
  import { isAddressEqual } from "viem";
5
5
  import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawCollateral, getBlueAuthorizationRequirement, getGeneralAdapterRequirements, } from "../../actions/index.js";
6
6
  import { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, computeReallocations, validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
7
- import { BorrowAmountAndSharesExclusiveError, MarketIdMismatchError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeBorrowSharesError, NegativeNativeAmountError, NegativeSupplyAmountError, NonPositiveAssetAmountError, NonPositiveBorrowAmountError, NonPositiveRepayAmountError, NonPositiveWithdrawAmountError, NonPositiveWithdrawCollateralAmountError, RefinanceExceedsBorrowAssetsError, RefinanceExceedsBorrowSharesError, RefinanceExceedsCollateralError, RefinanceSameMarketError, RefinanceTokenMismatchError, selectRequirementSignatures, WithdrawExceedsCollateralError, ZeroCollateralAmountError, ZeroSupplyAmountError, } from "../../types/index.js";
7
+ import { BorrowAmountAndSharesExclusiveError, MarketIdMismatchError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NativeAmountExceedsTransferAmountError, NegativeBorrowSharesError, NegativeNativeAmountError, NegativeSupplyAmountError, NonPositiveAssetAmountError, NonPositiveBorrowAmountError, NonPositiveRepayAmountError, NonPositiveWithdrawAmountError, NonPositiveWithdrawCollateralAmountError, RefinanceExceedsBorrowAssetsError, RefinanceExceedsBorrowSharesError, RefinanceExceedsCollateralError, RefinanceSameMarketError, RefinanceTokenMismatchError, selectRequirementSignatures, WithdrawExceedsCollateralError, ZeroCollateralAmountError, ZeroSupplyAmountError, } from "../../types/index.js";
8
8
  import { ReallocationData } from "../reallocationData.js";
9
9
  export class MorphoBlue {
10
10
  client;
@@ -262,19 +262,12 @@ export class MorphoBlue {
262
262
  repay(params) {
263
263
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
264
264
  const { userAddress, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, } = params;
265
- if ("assets" in params && "shares" in params) {
265
+ if ("amount" in params && "shares" in params) {
266
266
  throw new MutuallyExclusiveRepayAmountsError(this.marketParams.id);
267
267
  }
268
- const isSharesMode = "shares" in params;
269
- if (isSharesMode) {
270
- if (params.shares <= 0n) {
271
- throw new NonPositiveRepayAmountError(this.marketParams.id);
272
- }
273
- }
274
- else {
275
- if (params.assets <= 0n) {
276
- throw new NonPositiveRepayAmountError(this.marketParams.id);
277
- }
268
+ const nativeAmount = params.nativeAmount ?? 0n;
269
+ if (nativeAmount < 0n) {
270
+ throw new NegativeNativeAmountError(nativeAmount);
278
271
  }
279
272
  validateSlippageTolerance(slippageTolerance);
280
273
  if (!positionData) {
@@ -285,51 +278,83 @@ export class MorphoBlue {
285
278
  expectedMarketId: this.marketParams.id,
286
279
  expectedUser: userAddress,
287
280
  });
288
- let assets;
289
- let shares;
290
- let transferAmount;
281
+ if (nativeAmount > 0n) {
282
+ validateNativeAsset(this.chainId, this.marketParams.loanToken);
283
+ }
284
+ let repayAssets;
285
+ let repayShares;
286
+ let erc20Amount;
291
287
  let marketForRepay;
292
- if (isSharesMode) {
288
+ if ("shares" in params) {
289
+ const shares = params.shares;
290
+ if (shares <= 0n) {
291
+ throw new NonPositiveRepayAmountError(this.marketParams.id);
292
+ }
293
293
  validateRepayShares({
294
294
  positionData,
295
- repayShares: params.shares,
295
+ repayShares: shares,
296
296
  marketId: this.marketParams.id,
297
297
  });
298
- assets = 0n;
299
- shares = params.shares;
298
+ repayAssets = 0n;
299
+ repayShares = shares;
300
300
  // 2h forward accrual upper-bounds the on-chain repay price; bundle
301
301
  // skims residual back to the receiver.
302
302
  const accrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
303
303
  Time.s.from.h(2n);
304
304
  marketForRepay = positionData.market.accrueInterest(accrualTimestamp);
305
- transferAmount = marketForRepay.toBorrowAssets(shares, "Up");
305
+ const borrowAssets = marketForRepay.toBorrowAssets(shares, "Up");
306
+ // Native funds part of the transfer; the ERC-20 pulled is the remainder.
307
+ if (nativeAmount > borrowAssets) {
308
+ throw new NativeAmountExceedsTransferAmountError({
309
+ nativeAmount,
310
+ transferAmount: borrowAssets,
311
+ market: this.marketParams.id,
312
+ });
313
+ }
314
+ erc20Amount = borrowAssets - nativeAmount;
306
315
  }
307
316
  else {
317
+ // Assets mode is additive, like supply: repaid = amount + nativeAmount.
318
+ const amount = params.amount ?? 0n;
319
+ // Reject a negative ERC-20 amount before it can be masked by nativeAmount
320
+ // in the sum below (a negative amount would otherwise yield a negative
321
+ // erc20Amount and a negative approval in getRequirements).
322
+ if (amount < 0n) {
323
+ throw new NonPositiveRepayAmountError(this.marketParams.id);
324
+ }
325
+ repayAssets = amount + nativeAmount;
326
+ if (repayAssets <= 0n) {
327
+ throw new NonPositiveRepayAmountError(this.marketParams.id);
328
+ }
308
329
  validateRepayAmount({
309
330
  positionData,
310
- repayAssets: params.assets,
331
+ repayAssets,
311
332
  marketId: this.marketParams.id,
312
333
  });
313
- assets = params.assets;
314
- shares = 0n;
315
- transferAmount = params.assets;
334
+ repayShares = 0n;
335
+ erc20Amount = amount;
316
336
  marketForRepay = positionData.market;
317
337
  }
318
338
  const maxSharePrice = computeMaxRepaySharePrice({
319
- repayAssets: assets,
320
- repayShares: shares,
339
+ repayAssets,
340
+ repayShares,
321
341
  market: marketForRepay,
322
342
  slippageTolerance,
323
343
  });
324
344
  return {
325
- getRequirements: (reqParams) => getGeneralAdapterRequirements(this.client.viemClient, {
326
- address: this.marketParams.loanToken,
327
- chainId: this.chainId,
328
- supportSignature: this.client.options.supportSignature,
329
- supportDeployless: this.client.options.supportDeployless,
330
- useSimplePermit: reqParams?.useSimplePermit,
331
- args: { amount: transferAmount, from: userAddress },
332
- }),
345
+ getRequirements: (reqParams) => {
346
+ // Fully native repay pulls no ERC-20, so it needs no approval/permit.
347
+ if (erc20Amount === 0n)
348
+ return Promise.resolve([]);
349
+ return getGeneralAdapterRequirements(this.client.viemClient, {
350
+ address: this.marketParams.loanToken,
351
+ chainId: this.chainId,
352
+ supportSignature: this.client.options.supportSignature,
353
+ supportDeployless: this.client.options.supportDeployless,
354
+ useSimplePermit: reqParams?.useSimplePermit,
355
+ args: { amount: erc20Amount, from: userAddress },
356
+ });
357
+ },
333
358
  buildTx: (signatures) => {
334
359
  const { permit } = selectRequirementSignatures(signatures, {
335
360
  permit: true,
@@ -339,15 +364,27 @@ export class MorphoBlue {
339
364
  chainId: this.chainId,
340
365
  marketParams: this.marketParams,
341
366
  },
342
- args: {
343
- assets,
344
- shares,
345
- transferAmount,
346
- onBehalf: userAddress,
347
- receiver: userAddress,
348
- maxSharePrice,
349
- requirementSignature: permit,
350
- },
367
+ // Shares mode: repay `shares`, ERC-20 to pull = `erc20Amount`.
368
+ // Assets mode: repay `repayAssets` (= amount + native), pull `erc20Amount`.
369
+ args: repayShares > 0n
370
+ ? {
371
+ shares: repayShares,
372
+ transferAmount: erc20Amount,
373
+ nativeAmount,
374
+ onBehalf: userAddress,
375
+ receiver: userAddress,
376
+ maxSharePrice,
377
+ requirementSignature: permit,
378
+ }
379
+ : {
380
+ amount: erc20Amount,
381
+ transferAmount: repayAssets,
382
+ nativeAmount,
383
+ onBehalf: userAddress,
384
+ receiver: userAddress,
385
+ maxSharePrice,
386
+ requirementSignature: permit,
387
+ },
351
388
  metadata: this.client.options.metadata,
352
389
  });
353
390
  },
@@ -397,19 +434,12 @@ export class MorphoBlue {
397
434
  repayWithdrawCollateral(params) {
398
435
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
399
436
  const { userAddress, withdrawAmount, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, } = params;
400
- if ("assets" in params && "shares" in params) {
437
+ if ("amount" in params && "shares" in params) {
401
438
  throw new MutuallyExclusiveRepayAmountsError(this.marketParams.id);
402
439
  }
403
- const isSharesMode = "shares" in params;
404
- if (isSharesMode) {
405
- if (params.shares <= 0n) {
406
- throw new NonPositiveRepayAmountError(this.marketParams.id);
407
- }
408
- }
409
- else {
410
- if (params.assets <= 0n) {
411
- throw new NonPositiveRepayAmountError(this.marketParams.id);
412
- }
440
+ const nativeAmount = params.nativeAmount ?? 0n;
441
+ if (nativeAmount < 0n) {
442
+ throw new NegativeNativeAmountError(nativeAmount);
413
443
  }
414
444
  if (withdrawAmount <= 0n) {
415
445
  throw new NonPositiveWithdrawCollateralAmountError(this.marketParams.id);
@@ -423,34 +453,61 @@ export class MorphoBlue {
423
453
  expectedMarketId: this.marketParams.id,
424
454
  expectedUser: userAddress,
425
455
  });
426
- let assets;
427
- let shares;
428
- let transferAmount;
456
+ if (nativeAmount > 0n) {
457
+ validateNativeAsset(this.chainId, this.marketParams.loanToken);
458
+ }
459
+ let repayAssets;
460
+ let repayShares;
461
+ let erc20Amount;
429
462
  let marketForRepay;
430
463
  // 2h forward accrual upper-bounds the on-chain repay price (shares
431
464
  // mode) and the post-repay health check; bundle skims residual back.
432
465
  const accrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
433
466
  Time.s.from.h(2n);
434
- if (isSharesMode) {
467
+ if ("shares" in params) {
468
+ const shares = params.shares;
469
+ if (shares <= 0n) {
470
+ throw new NonPositiveRepayAmountError(this.marketParams.id);
471
+ }
435
472
  validateRepayShares({
436
473
  positionData,
437
- repayShares: params.shares,
474
+ repayShares: shares,
438
475
  marketId: this.marketParams.id,
439
476
  });
440
- assets = 0n;
441
- shares = params.shares;
477
+ repayAssets = 0n;
478
+ repayShares = shares;
442
479
  marketForRepay = positionData.market.accrueInterest(accrualTimestamp);
443
- transferAmount = marketForRepay.toBorrowAssets(shares, "Up");
480
+ const borrowAssets = marketForRepay.toBorrowAssets(shares, "Up");
481
+ // Native funds part of the transfer; the ERC-20 pulled is the remainder.
482
+ if (nativeAmount > borrowAssets) {
483
+ throw new NativeAmountExceedsTransferAmountError({
484
+ nativeAmount,
485
+ transferAmount: borrowAssets,
486
+ market: this.marketParams.id,
487
+ });
488
+ }
489
+ erc20Amount = borrowAssets - nativeAmount;
444
490
  }
445
491
  else {
492
+ // Assets mode is additive, like supply: repaid = amount + nativeAmount.
493
+ const amount = params.amount ?? 0n;
494
+ // Reject a negative ERC-20 amount before it can be masked by nativeAmount
495
+ // in the sum below (a negative amount would otherwise yield a negative
496
+ // erc20Amount and a negative approval in getRequirements).
497
+ if (amount < 0n) {
498
+ throw new NonPositiveRepayAmountError(this.marketParams.id);
499
+ }
500
+ repayAssets = amount + nativeAmount;
501
+ if (repayAssets <= 0n) {
502
+ throw new NonPositiveRepayAmountError(this.marketParams.id);
503
+ }
446
504
  validateRepayAmount({
447
505
  positionData,
448
- repayAssets: params.assets,
506
+ repayAssets,
449
507
  marketId: this.marketParams.id,
450
508
  });
451
- assets = params.assets;
452
- shares = 0n;
453
- transferAmount = params.assets;
509
+ repayShares = 0n;
510
+ erc20Amount = amount;
454
511
  marketForRepay = positionData.market;
455
512
  }
456
513
  if (withdrawAmount > positionData.collateral) {
@@ -460,7 +517,7 @@ export class MorphoBlue {
460
517
  market: positionData.marketId,
461
518
  });
462
519
  }
463
- const { position: positionAfterRepay } = positionData.repay(assets, shares, accrualTimestamp);
520
+ const { position: positionAfterRepay } = positionData.repay(repayAssets, repayShares, accrualTimestamp);
464
521
  validatePositionHealthAfterWithdraw({
465
522
  positionData: positionAfterRepay,
466
523
  withdrawAmount,
@@ -468,22 +525,25 @@ export class MorphoBlue {
468
525
  marketId: this.marketParams.id,
469
526
  });
470
527
  const maxSharePrice = computeMaxRepaySharePrice({
471
- repayAssets: assets,
472
- repayShares: shares,
528
+ repayAssets,
529
+ repayShares,
473
530
  market: marketForRepay,
474
531
  slippageTolerance,
475
532
  });
476
533
  return {
477
534
  getRequirements: async (reqParams) => {
478
535
  const [erc20Requirements, authTx] = await Promise.all([
479
- getGeneralAdapterRequirements(this.client.viemClient, {
480
- address: this.marketParams.loanToken,
481
- chainId: this.chainId,
482
- supportSignature: this.client.options.supportSignature,
483
- supportDeployless: this.client.options.supportDeployless,
484
- useSimplePermit: reqParams?.useSimplePermit,
485
- args: { amount: transferAmount, from: userAddress },
486
- }),
536
+ // Fully native repay pulls no ERC-20, so it needs no approval/permit.
537
+ erc20Amount === 0n
538
+ ? Promise.resolve([])
539
+ : getGeneralAdapterRequirements(this.client.viemClient, {
540
+ address: this.marketParams.loanToken,
541
+ chainId: this.chainId,
542
+ supportSignature: this.client.options.supportSignature,
543
+ supportDeployless: this.client.options.supportDeployless,
544
+ useSimplePermit: reqParams?.useSimplePermit,
545
+ args: { amount: erc20Amount, from: userAddress },
546
+ }),
487
547
  getBlueAuthorizationRequirement({
488
548
  viemClient: this.client.viemClient,
489
549
  chainId: this.chainId,
@@ -500,17 +560,31 @@ export class MorphoBlue {
500
560
  chainId: this.chainId,
501
561
  marketParams: this.marketParams,
502
562
  },
503
- args: {
504
- assets,
505
- shares,
506
- transferAmount,
507
- withdrawAmount,
508
- onBehalf: userAddress,
509
- receiver: userAddress,
510
- maxSharePrice,
511
- requirementSignature: permit,
512
- authorizationSignature: authorization,
513
- },
563
+ // Shares mode: repay `shares`, ERC-20 to pull = `erc20Amount`.
564
+ // Assets mode: repay `repayAssets` (= amount + native), pull `erc20Amount`.
565
+ args: repayShares > 0n
566
+ ? {
567
+ shares: repayShares,
568
+ transferAmount: erc20Amount,
569
+ nativeAmount,
570
+ withdrawAmount,
571
+ onBehalf: userAddress,
572
+ receiver: userAddress,
573
+ maxSharePrice,
574
+ requirementSignature: permit,
575
+ authorizationSignature: authorization,
576
+ }
577
+ : {
578
+ amount: erc20Amount,
579
+ transferAmount: repayAssets,
580
+ nativeAmount,
581
+ withdrawAmount,
582
+ onBehalf: userAddress,
583
+ receiver: userAddress,
584
+ maxSharePrice,
585
+ requirementSignature: permit,
586
+ authorizationSignature: authorization,
587
+ },
514
588
  metadata: this.client.options.metadata,
515
589
  });
516
590
  },
@@ -2,4 +2,4 @@ export { computeReallocations } from "./computeReallocations.js";
2
2
  export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
3
3
  export { addTransactionMetadata } from "./metadata.js";
4
4
  export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, } from "./slippage.js";
5
- export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
5
+ export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
@@ -2,4 +2,4 @@ export { computeReallocations } from "./computeReallocations.js";
2
2
  export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
3
3
  export { addTransactionMetadata } from "./metadata.js";
4
4
  export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, } from "./slippage.js";
5
- export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
5
+ export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
@@ -121,24 +121,6 @@ export declare const validateRepayShares: (params: {
121
121
  repayShares: bigint;
122
122
  marketId: MarketId;
123
123
  }) => void;
124
- /**
125
- * Validates the common repay input parameters shared by `blueRepay`
126
- * and `blueRepayWithdrawCollateral`.
127
- *
128
- * @param params - Validation parameters.
129
- * @param params.assets - Repay assets amount (0n when repaying by shares).
130
- * @param params.shares - Repay shares amount (0n when repaying by assets).
131
- * @param params.transferAmount - ERC20 amount to transfer to GeneralAdapter1.
132
- * @param params.maxSharePrice - Maximum repay share price (in ray). Must be positive.
133
- * @param params.marketId - The market identifier (for error messages).
134
- */
135
- export declare const validateRepayParams: (params: {
136
- assets: bigint;
137
- shares: bigint;
138
- transferAmount: bigint;
139
- maxSharePrice: bigint;
140
- marketId: MarketId;
141
- }) => void;
142
124
  /**
143
125
  * Validates that vault reallocations are well-formed.
144
126
  *
@@ -1,7 +1,7 @@
1
1
  import { getChainAddresses, MathLib, ORACLE_PRICE_SCALE, } from "@morpho-org/blue-sdk";
2
2
  import { isDefined } from "@morpho-org/morpho-ts";
3
3
  import { isAddressEqual } from "viem";
4
- import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, EmptyReallocationWithdrawalsError, ExcessiveSlippageToleranceError, MarketIdMismatchError, MissingClientPropertyError, MissingMarketPriceError, MutuallyExclusiveRepayAmountsError, NativeAmountOnNonWNativeAssetError, NegativeReallocationFeeError, NegativeSlippageToleranceError, NonPositiveReallocationAmountError, NonPositiveRepayAmountError, NonPositiveRepayMaxSharePriceError, NonPositiveTransferAmountError, ReallocationWithdrawalOnTargetMarketError, RepayExceedsDebtError, RepaySharesExceedDebtError, TransferAmountNotEqualToAssetsError, UnsortedReallocationWithdrawalsError, WithdrawExceedsCollateralError, WithdrawExceedsSupplyError, WithdrawMakesPositionUnhealthyError, WithdrawSharesExceedSupplyError, } from "../types/index.js";
4
+ import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, EmptyReallocationWithdrawalsError, ExcessiveSlippageToleranceError, MarketIdMismatchError, MissingClientPropertyError, MissingMarketPriceError, NativeAmountOnNonWNativeAssetError, NegativeReallocationFeeError, NegativeSlippageToleranceError, NonPositiveReallocationAmountError, ReallocationWithdrawalOnTargetMarketError, RepayExceedsDebtError, RepaySharesExceedDebtError, UnsortedReallocationWithdrawalsError, WithdrawExceedsCollateralError, WithdrawExceedsSupplyError, WithdrawMakesPositionUnhealthyError, WithdrawSharesExceedSupplyError, } from "../types/index.js";
5
5
  import { DEFAULT_LLTV_BUFFER, MAX_SLIPPAGE_TOLERANCE } from "./constant.js";
6
6
  /** @internal */
7
7
  export const compareMarketIds = (idA, idB) => {
@@ -199,42 +199,6 @@ export const validateRepayShares = (params) => {
199
199
  });
200
200
  }
201
201
  };
202
- /**
203
- * Validates the common repay input parameters shared by `blueRepay`
204
- * and `blueRepayWithdrawCollateral`.
205
- *
206
- * @param params - Validation parameters.
207
- * @param params.assets - Repay assets amount (0n when repaying by shares).
208
- * @param params.shares - Repay shares amount (0n when repaying by assets).
209
- * @param params.transferAmount - ERC20 amount to transfer to GeneralAdapter1.
210
- * @param params.maxSharePrice - Maximum repay share price (in ray). Must be positive.
211
- * @param params.marketId - The market identifier (for error messages).
212
- */
213
- export const validateRepayParams = (params) => {
214
- const { assets, shares, transferAmount, maxSharePrice, marketId } = params;
215
- if (maxSharePrice <= 0n) {
216
- throw new NonPositiveRepayMaxSharePriceError(marketId);
217
- }
218
- if (assets < 0n || shares < 0n) {
219
- throw new NonPositiveRepayAmountError(marketId);
220
- }
221
- if (assets > 0n && shares > 0n) {
222
- throw new MutuallyExclusiveRepayAmountsError(marketId);
223
- }
224
- if (assets === 0n && shares === 0n) {
225
- throw new NonPositiveRepayAmountError(marketId);
226
- }
227
- if (transferAmount <= 0n) {
228
- throw new NonPositiveTransferAmountError(marketId);
229
- }
230
- if (assets > 0n && transferAmount !== assets) {
231
- throw new TransferAmountNotEqualToAssetsError({
232
- transferAmount,
233
- assets,
234
- market: marketId,
235
- });
236
- }
237
- };
238
202
  /**
239
203
  * Validates that vault reallocations are well-formed.
240
204
  *
@@ -132,6 +132,8 @@ export interface BlueRepayAction extends BaseAction<"blueRepay", {
132
132
  onBehalf: Address;
133
133
  receiver: Address;
134
134
  maxSharePrice: bigint;
135
+ /** Native token wrapped into wNative to fund the repay. Present when `> 0n`. */
136
+ nativeAmount?: bigint;
135
137
  }> {
136
138
  }
137
139
  export interface BlueWithdrawCollateralAction extends BaseAction<"blueWithdrawCollateral", {
@@ -150,6 +152,8 @@ export interface BlueRepayWithdrawCollateralAction extends BaseAction<"blueRepay
150
152
  maxSharePrice: bigint;
151
153
  onBehalf: Address;
152
154
  receiver: Address;
155
+ /** Native token wrapped into wNative to fund the repay. Present when `> 0n`. */
156
+ nativeAmount?: bigint;
153
157
  }> {
154
158
  }
155
159
  export interface BlueRefinanceAction extends BaseAction<"blueRefinance", {
@@ -171,15 +175,59 @@ export interface BlueRefinanceAction extends BaseAction<"blueRefinance", {
171
175
  * - `shares`: operate on an exact share count (typical for full position closes,
172
176
  * immune to interest accrual between tx construction and execution).
173
177
  *
174
- * Used by repay (asserts on borrow side) and withdraw (asserts on supply side).
178
+ * Used by withdraw (asserts on supply side). Repay uses {@link RepayAmountArgs},
179
+ * which additionally supports native wrapping.
175
180
  */
176
181
  export type AssetsOrSharesArgs = {
177
182
  assets: bigint;
178
183
  } | {
179
184
  shares: bigint;
180
185
  };
181
- /** @deprecated Use {@link AssetsOrSharesArgs}. Kept as an alias for back-compat. */
182
- export type RepayAmountArgs = AssetsOrSharesArgs;
186
+ /**
187
+ * Repay funding sources for the **entity layer** (`MorphoBlue.repay` /
188
+ * `MorphoBlue.repayWithdrawCollateral`), which computes the loan-token
189
+ * `transferAmount` itself from live market state.
190
+ *
191
+ * - **assets mode** ({@link DepositAmountArgs}): repay an exact asset total of
192
+ * `amount` (ERC-20) + `nativeAmount` (wrapped native). Additive — mirrors `blueSupply`.
193
+ * - **shares mode** (`{ shares }`): repay an exact borrow-share count (full close,
194
+ * immune to interest accrual). `nativeAmount` funds part of the transfer.
195
+ *
196
+ * `nativeAmount` requires the market's loan token to be the chain's wNative.
197
+ */
198
+ export type RepayAmountArgs = DepositAmountArgs | {
199
+ shares: bigint;
200
+ nativeAmount?: bigint;
201
+ };
202
+ /**
203
+ * Repay funding sources for the **action layer** (`blueRepay` /
204
+ * `blueRepayWithdrawCollateral`) — a flat, pre-resolved shape. The entity layer
205
+ * ({@link RepayAmountArgs}) derives these from live market state; the action does no
206
+ * amount arithmetic. The mode is discriminated on `shares`:
207
+ *
208
+ * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets
209
+ * (`= amount + nativeAmount`, additive like `blueSupply`), pulling `amount` ERC-20
210
+ * and wrapping `nativeAmount`. No residual.
211
+ * - **shares mode** (`shares > 0n`): repays an exact borrow-share count (full close),
212
+ * pulling `transferAmount` ERC-20 (already net of native) and wrapping `nativeAmount`;
213
+ * the residual loan token is skimmed back to `receiver`.
214
+ *
215
+ * `nativeAmount` requires the market's loan token to be the chain's wNative.
216
+ */
217
+ export interface RepayActionAmountArgs {
218
+ /** Assets-mode ERC-20 loan tokens pulled from the payer. Omit (or `0n`) in shares mode. */
219
+ amount?: bigint;
220
+ /** Shares-mode borrow shares to repay (full close). Omit (or `0n`) in assets mode. */
221
+ shares?: bigint;
222
+ /** Native ETH wrapped into wNative to help fund the repay. Loan token must be wNative. */
223
+ nativeAmount?: bigint;
224
+ /**
225
+ * Loan tokens routed into `GeneralAdapter1`. Assets mode: the total repaid
226
+ * (`amount + nativeAmount`). Shares mode: the ERC-20 pulled
227
+ * (`toBorrowAssets(shares) − nativeAmount`).
228
+ */
229
+ transferAmount: bigint;
230
+ }
183
231
  /** Metadata for a Blue authorization prerequisite transaction. */
184
232
  export interface BlueAuthorizationAction extends BaseAction<"blueAuthorization", {
185
233
  authorized: Address;
@@ -244,11 +244,22 @@ export declare class ReallocationWithdrawalOnTargetMarketError extends Error {
244
244
  export declare class UnsortedReallocationWithdrawalsError extends Error {
245
245
  constructor(vault: string, marketId: string);
246
246
  }
247
- /** Thrown when a market repay's `transferAmount` is zero or negative. */
247
+ /**
248
+ * Thrown when a market repay's `transferAmount` is zero or negative.
249
+ *
250
+ * @deprecated No longer thrown. The repay action layer no longer validates `transferAmount`
251
+ * directly (assets mode uses {@link NonPositiveRepayAmountError}; shares mode allows a zero
252
+ * ERC-20 transfer for fully-native repays). Retained as exported API for back-compat; slated
253
+ * for removal in a future major.
254
+ */
248
255
  export declare class NonPositiveTransferAmountError extends Error {
249
256
  constructor(market: string);
250
257
  }
251
- /** Thrown when a market repay in assets mode has `transferAmount !== assets` (asset-mode requires exact transfer). */
258
+ /**
259
+ * Thrown when a market repay in assets mode has `transferAmount !== amount + nativeAmount` — the
260
+ * pre-resolved ERC-20 pull plus the wrapped native must equal the assets repaid, so the bundle
261
+ * neither strands over-pulled loan tokens on `GeneralAdapter1` nor under-funds the repay.
262
+ */
252
263
  export declare class TransferAmountNotEqualToAssetsError extends Error {
253
264
  constructor(params: {
254
265
  transferAmount: bigint;
@@ -256,6 +267,17 @@ export declare class TransferAmountNotEqualToAssetsError extends Error {
256
267
  market: string;
257
268
  });
258
269
  }
270
+ /**
271
+ * Thrown when a shares-mode repay's `nativeAmount` exceeds `transferAmount`, which
272
+ * would make the ERC-20 amount to pull (`transferAmount − nativeAmount`) negative.
273
+ */
274
+ export declare class NativeAmountExceedsTransferAmountError extends Error {
275
+ constructor(params: {
276
+ nativeAmount: bigint;
277
+ transferAmount: bigint;
278
+ market: string;
279
+ });
280
+ }
259
281
  /** Thrown when a market repay specifies both `assets` and `shares` as non-zero (modes are mutually exclusive). */
260
282
  export declare class MutuallyExclusiveRepayAmountsError extends Error {
261
283
  constructor(market: string);
@@ -320,16 +320,36 @@ export class UnsortedReallocationWithdrawalsError extends Error {
320
320
  super(`Reallocation withdrawals must be strictly sorted by market ID for vault ${vault}. Market ${marketId} is out of order.`);
321
321
  }
322
322
  }
323
- /** Thrown when a market repay's `transferAmount` is zero or negative. */
323
+ /**
324
+ * Thrown when a market repay's `transferAmount` is zero or negative.
325
+ *
326
+ * @deprecated No longer thrown. The repay action layer no longer validates `transferAmount`
327
+ * directly (assets mode uses {@link NonPositiveRepayAmountError}; shares mode allows a zero
328
+ * ERC-20 transfer for fully-native repays). Retained as exported API for back-compat; slated
329
+ * for removal in a future major.
330
+ */
324
331
  export class NonPositiveTransferAmountError extends Error {
325
332
  constructor(market) {
326
333
  super(`Transfer amount must be positive for market: ${market}`);
327
334
  }
328
335
  }
329
- /** Thrown when a market repay in assets mode has `transferAmount !== assets` (asset-mode requires exact transfer). */
336
+ /**
337
+ * Thrown when a market repay in assets mode has `transferAmount !== amount + nativeAmount` — the
338
+ * pre-resolved ERC-20 pull plus the wrapped native must equal the assets repaid, so the bundle
339
+ * neither strands over-pulled loan tokens on `GeneralAdapter1` nor under-funds the repay.
340
+ */
330
341
  export class TransferAmountNotEqualToAssetsError extends Error {
331
342
  constructor(params) {
332
- super(`Transfer amount ${params.transferAmount} is not equal to repay assets ${params.assets} for market: ${params.market}`);
343
+ super(`Transfer amount ${params.transferAmount} is not equal to repay assets ${params.assets} for market: ${params.market}. In assets mode, transferAmount must equal amount + nativeAmount.`);
344
+ }
345
+ }
346
+ /**
347
+ * Thrown when a shares-mode repay's `nativeAmount` exceeds `transferAmount`, which
348
+ * would make the ERC-20 amount to pull (`transferAmount − nativeAmount`) negative.
349
+ */
350
+ export class NativeAmountExceedsTransferAmountError extends Error {
351
+ constructor(params) {
352
+ super(`Native amount ${params.nativeAmount} exceeds transfer amount ${params.transferAmount} for market: ${params.market}. Reduce nativeAmount to at most transferAmount.`);
333
353
  }
334
354
  }
335
355
  /** Thrown when a market repay specifies both `assets` and `shares` as non-zero (modes are mutually exclusive). */
@@ -6,4 +6,4 @@ export { bigIntComparator, createGetValue, createHasValue, deepFreeze, entries,
6
6
  export { computeReallocations } from "./helpers/computeReallocations.js";
7
7
  export { addTransactionMetadata } from "./helpers/metadata.js";
8
8
  export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./helpers/slippage.js";
9
- export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./helpers/validate.js";
9
+ export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./helpers/validate.js";
package/lib/esm/utils.js CHANGED
@@ -4,4 +4,4 @@ export { bigIntComparator, createGetValue, createHasValue, deepFreeze, entries,
4
4
  export { computeReallocations } from "./helpers/computeReallocations.js";
5
5
  export { addTransactionMetadata } from "./helpers/metadata.js";
6
6
  export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./helpers/slippage.js";
7
- export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./helpers/validate.js";
7
+ export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./helpers/validate.js";