@morpho-org/morpho-sdk 2.0.0 → 3.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 (202) hide show
  1. package/lib/cjs/abis.d.ts +2816 -0
  2. package/lib/cjs/abis.js +1951 -0
  3. package/lib/cjs/actions/index.d.ts +3 -0
  4. package/lib/cjs/actions/marketV1/borrow.js +7 -10
  5. package/lib/cjs/actions/marketV1/buildReallocationActions.d.ts +2 -3
  6. package/lib/cjs/actions/marketV1/buildReallocationActions.js +1 -2
  7. package/lib/cjs/actions/marketV1/repay.d.ts +2 -0
  8. package/lib/cjs/actions/marketV1/repay.js +7 -8
  9. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  10. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.js +9 -10
  11. package/lib/cjs/actions/marketV1/supplyCollateral.d.ts +2 -0
  12. package/lib/cjs/actions/marketV1/supplyCollateral.js +11 -12
  13. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.d.ts +2 -0
  14. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.js +13 -14
  15. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +2 -2
  16. package/lib/cjs/actions/requirements/getRequirementsAction.d.ts +28 -4
  17. package/lib/cjs/actions/requirements/getRequirementsAction.js +28 -4
  18. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -2
  19. package/lib/cjs/actions/requirements/index.d.ts +1 -0
  20. package/lib/cjs/actions/requirements/index.js +1 -0
  21. package/lib/cjs/actions/vaultV1/deposit.d.ts +2 -0
  22. package/lib/cjs/actions/vaultV1/deposit.js +13 -14
  23. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +2 -0
  24. package/lib/cjs/actions/vaultV1/migrateToV2.js +11 -9
  25. package/lib/cjs/actions/vaultV2/deposit.d.ts +2 -0
  26. package/lib/cjs/actions/vaultV2/deposit.js +13 -14
  27. package/lib/cjs/addresses.d.ts +2 -0
  28. package/lib/cjs/addresses.js +18 -0
  29. package/lib/cjs/augment/AccrualPosition.d.ts +9 -0
  30. package/lib/cjs/augment/AccrualPosition.js +8 -0
  31. package/lib/cjs/augment/AccrualVault.d.ts +8 -0
  32. package/lib/cjs/augment/AccrualVault.js +7 -0
  33. package/lib/cjs/augment/Holding.d.ts +8 -0
  34. package/lib/cjs/augment/Holding.js +7 -0
  35. package/lib/cjs/augment/Market.d.ts +8 -0
  36. package/lib/cjs/augment/Market.js +7 -0
  37. package/lib/cjs/augment/MarketParams.d.ts +8 -0
  38. package/lib/cjs/augment/MarketParams.js +7 -0
  39. package/lib/cjs/augment/Position.d.ts +8 -0
  40. package/lib/cjs/augment/Position.js +7 -0
  41. package/lib/cjs/augment/Token.d.ts +8 -0
  42. package/lib/cjs/augment/Token.js +7 -0
  43. package/lib/cjs/augment/User.d.ts +8 -0
  44. package/lib/cjs/augment/User.js +7 -0
  45. package/lib/cjs/augment/Vault.d.ts +8 -0
  46. package/lib/cjs/augment/Vault.js +7 -0
  47. package/lib/cjs/augment/VaultConfig.d.ts +8 -0
  48. package/lib/cjs/augment/VaultConfig.js +7 -0
  49. package/lib/cjs/augment/VaultMarketAllocation.d.ts +8 -0
  50. package/lib/cjs/augment/VaultMarketAllocation.js +7 -0
  51. package/lib/cjs/augment/VaultMarketConfig.d.ts +8 -0
  52. package/lib/cjs/augment/VaultMarketConfig.js +7 -0
  53. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  54. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.js +8 -0
  55. package/lib/cjs/augment/VaultUser.d.ts +8 -0
  56. package/lib/cjs/augment/VaultUser.js +7 -0
  57. package/lib/cjs/augment.d.ts +14 -0
  58. package/lib/cjs/augment.js +16 -0
  59. package/lib/cjs/bundler/actions.d.ts +555 -0
  60. package/lib/cjs/bundler/actions.js +953 -0
  61. package/lib/cjs/bundler/index.d.ts +2 -0
  62. package/lib/cjs/bundler/index.js +18 -0
  63. package/lib/cjs/bundler/types.d.ts +181 -0
  64. package/lib/cjs/bundler/types.js +2 -0
  65. package/lib/cjs/constants.d.ts +3 -0
  66. package/lib/cjs/constants.js +32 -0
  67. package/lib/cjs/entities/index.d.ts +6 -3
  68. package/lib/cjs/entities/index.js +41 -17
  69. package/lib/cjs/entities/marketV1/marketV1.d.ts +45 -11
  70. package/lib/cjs/entities/marketV1/marketV1.js +45 -23
  71. package/lib/cjs/entities/reallocationData.d.ts +193 -0
  72. package/lib/cjs/entities/reallocationData.js +406 -0
  73. package/lib/cjs/entities/vaultV1/vaultV1.js +6 -2
  74. package/lib/cjs/entities/vaultV2/vaultV2.js +6 -1
  75. package/lib/cjs/errors.d.ts +2 -0
  76. package/lib/cjs/errors.js +18 -0
  77. package/lib/cjs/fetch.d.ts +1 -0
  78. package/lib/cjs/fetch.js +30 -0
  79. package/lib/cjs/format.d.ts +2 -0
  80. package/lib/cjs/format.js +22 -0
  81. package/lib/cjs/helpers/computeReallocations.d.ts +48 -8
  82. package/lib/cjs/helpers/computeReallocations.js +120 -32
  83. package/lib/cjs/helpers/constant.d.ts +17 -0
  84. package/lib/cjs/helpers/constant.js +30 -1
  85. package/lib/cjs/helpers/index.d.ts +1 -0
  86. package/lib/cjs/helpers/index.js +9 -1
  87. package/lib/cjs/helpers/metadata.d.ts +10 -0
  88. package/lib/cjs/helpers/metadata.js +20 -1
  89. package/lib/cjs/helpers/validate.d.ts +2 -0
  90. package/lib/cjs/helpers/validate.js +14 -2
  91. package/lib/cjs/index.d.ts +0 -1
  92. package/lib/cjs/index.js +0 -1
  93. package/lib/cjs/types/client.d.ts +1 -1
  94. package/lib/cjs/types/error.d.ts +91 -1
  95. package/lib/cjs/types/error.js +126 -1
  96. package/lib/cjs/types/sharedLiquidity.d.ts +43 -3
  97. package/lib/cjs/types.d.ts +3 -0
  98. package/lib/cjs/types.js +17 -0
  99. package/lib/cjs/utils.d.ts +9 -0
  100. package/lib/cjs/utils.js +65 -0
  101. package/lib/esm/abis.d.ts +2816 -0
  102. package/lib/esm/abis.js +1922 -0
  103. package/lib/esm/actions/index.d.ts +3 -0
  104. package/lib/esm/actions/marketV1/borrow.js +2 -5
  105. package/lib/esm/actions/marketV1/buildReallocationActions.d.ts +2 -3
  106. package/lib/esm/actions/marketV1/buildReallocationActions.js +1 -2
  107. package/lib/esm/actions/marketV1/repay.d.ts +2 -0
  108. package/lib/esm/actions/marketV1/repay.js +4 -5
  109. package/lib/esm/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  110. package/lib/esm/actions/marketV1/repayWithdrawCollateral.js +4 -5
  111. package/lib/esm/actions/marketV1/supplyCollateral.d.ts +2 -0
  112. package/lib/esm/actions/marketV1/supplyCollateral.js +4 -5
  113. package/lib/esm/actions/marketV1/supplyCollateralBorrow.d.ts +2 -0
  114. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +4 -5
  115. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +1 -1
  116. package/lib/esm/actions/requirements/getRequirementsAction.d.ts +28 -4
  117. package/lib/esm/actions/requirements/getRequirementsAction.js +29 -5
  118. package/lib/esm/actions/requirements/getRequirementsApproval.js +1 -1
  119. package/lib/esm/actions/requirements/index.d.ts +1 -0
  120. package/lib/esm/actions/requirements/index.js +1 -0
  121. package/lib/esm/actions/vaultV1/deposit.d.ts +2 -0
  122. package/lib/esm/actions/vaultV1/deposit.js +3 -4
  123. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +2 -0
  124. package/lib/esm/actions/vaultV1/migrateToV2.js +3 -1
  125. package/lib/esm/actions/vaultV2/deposit.d.ts +2 -0
  126. package/lib/esm/actions/vaultV2/deposit.js +3 -4
  127. package/lib/esm/addresses.d.ts +2 -0
  128. package/lib/esm/addresses.js +1 -0
  129. package/lib/esm/augment/AccrualPosition.d.ts +9 -0
  130. package/lib/esm/augment/AccrualPosition.js +5 -0
  131. package/lib/esm/augment/AccrualVault.d.ts +8 -0
  132. package/lib/esm/augment/AccrualVault.js +4 -0
  133. package/lib/esm/augment/Holding.d.ts +8 -0
  134. package/lib/esm/augment/Holding.js +4 -0
  135. package/lib/esm/augment/Market.d.ts +8 -0
  136. package/lib/esm/augment/Market.js +4 -0
  137. package/lib/esm/augment/MarketParams.d.ts +8 -0
  138. package/lib/esm/augment/MarketParams.js +4 -0
  139. package/lib/esm/augment/Position.d.ts +8 -0
  140. package/lib/esm/augment/Position.js +4 -0
  141. package/lib/esm/augment/Token.d.ts +8 -0
  142. package/lib/esm/augment/Token.js +4 -0
  143. package/lib/esm/augment/User.d.ts +8 -0
  144. package/lib/esm/augment/User.js +4 -0
  145. package/lib/esm/augment/Vault.d.ts +8 -0
  146. package/lib/esm/augment/Vault.js +4 -0
  147. package/lib/esm/augment/VaultConfig.d.ts +8 -0
  148. package/lib/esm/augment/VaultConfig.js +4 -0
  149. package/lib/esm/augment/VaultMarketAllocation.d.ts +8 -0
  150. package/lib/esm/augment/VaultMarketAllocation.js +4 -0
  151. package/lib/esm/augment/VaultMarketConfig.d.ts +8 -0
  152. package/lib/esm/augment/VaultMarketConfig.js +4 -0
  153. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  154. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +5 -0
  155. package/lib/esm/augment/VaultUser.d.ts +8 -0
  156. package/lib/esm/augment/VaultUser.js +4 -0
  157. package/lib/esm/augment.d.ts +14 -0
  158. package/lib/esm/augment.js +14 -0
  159. package/lib/esm/bundler/actions.d.ts +555 -0
  160. package/lib/esm/bundler/actions.js +950 -0
  161. package/lib/esm/bundler/index.d.ts +2 -0
  162. package/lib/esm/bundler/index.js +2 -0
  163. package/lib/esm/bundler/types.d.ts +181 -0
  164. package/lib/esm/bundler/types.js +1 -0
  165. package/lib/esm/constants.d.ts +3 -0
  166. package/lib/esm/constants.js +3 -0
  167. package/lib/esm/entities/index.d.ts +6 -3
  168. package/lib/esm/entities/index.js +5 -3
  169. package/lib/esm/entities/marketV1/marketV1.d.ts +45 -11
  170. package/lib/esm/entities/marketV1/marketV1.js +46 -24
  171. package/lib/esm/entities/reallocationData.d.ts +193 -0
  172. package/lib/esm/entities/reallocationData.js +402 -0
  173. package/lib/esm/entities/vaultV1/vaultV1.js +6 -2
  174. package/lib/esm/entities/vaultV2/vaultV2.js +6 -1
  175. package/lib/esm/errors.d.ts +2 -0
  176. package/lib/esm/errors.js +1 -0
  177. package/lib/esm/fetch.d.ts +1 -0
  178. package/lib/esm/fetch.js +1 -0
  179. package/lib/esm/format.d.ts +2 -0
  180. package/lib/esm/format.js +1 -0
  181. package/lib/esm/helpers/computeReallocations.d.ts +48 -8
  182. package/lib/esm/helpers/computeReallocations.js +119 -31
  183. package/lib/esm/helpers/constant.d.ts +17 -0
  184. package/lib/esm/helpers/constant.js +30 -1
  185. package/lib/esm/helpers/index.d.ts +1 -0
  186. package/lib/esm/helpers/index.js +1 -0
  187. package/lib/esm/helpers/metadata.d.ts +10 -0
  188. package/lib/esm/helpers/metadata.js +20 -1
  189. package/lib/esm/helpers/validate.d.ts +2 -0
  190. package/lib/esm/helpers/validate.js +12 -1
  191. package/lib/esm/index.d.ts +0 -1
  192. package/lib/esm/index.js +0 -1
  193. package/lib/esm/types/client.d.ts +1 -1
  194. package/lib/esm/types/error.d.ts +91 -1
  195. package/lib/esm/types/error.js +118 -0
  196. package/lib/esm/types/sharedLiquidity.d.ts +43 -3
  197. package/lib/esm/types.d.ts +3 -0
  198. package/lib/esm/types.js +1 -0
  199. package/lib/esm/utils.d.ts +9 -0
  200. package/lib/esm/utils.js +7 -0
  201. package/package.json +121 -14
  202. package/src/index.ts +0 -1
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchVaultV2MorphoVaultV1Adapter = exports.fetchVaultV2MorphoMarketV1AdapterV2 = exports.fetchVaultV2MorphoMarketV1Adapter = exports.fetchVaultV2Adapter = exports.fetchVaultV2 = exports.fetchVaultUser = exports.fetchVaultMarketPublicAllocatorConfig = exports.fetchVaultMarketConfig = exports.fetchVaultMarketAllocation = exports.fetchVaultConfig = exports.fetchVault = exports.fetchUser = exports.fetchToken = exports.fetchPreLiquidationPosition = exports.fetchPreLiquidationParams = exports.fetchPosition = exports.fetchMarketParams = exports.fetchMarket = exports.fetchHolding = exports.fetchAccrualVaultV2MorphoVaultV1Adapter = exports.fetchAccrualVaultV2MorphoMarketV1AdapterV2 = exports.fetchAccrualVaultV2MorphoMarketV1Adapter = exports.fetchAccrualVaultV2Adapter = exports.fetchAccrualVaultV2 = exports.fetchAccrualVault = exports.fetchAccrualPosition = void 0;
4
+ var blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
5
+ Object.defineProperty(exports, "fetchAccrualPosition", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchAccrualPosition; } });
6
+ Object.defineProperty(exports, "fetchAccrualVault", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchAccrualVault; } });
7
+ Object.defineProperty(exports, "fetchAccrualVaultV2", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchAccrualVaultV2; } });
8
+ Object.defineProperty(exports, "fetchAccrualVaultV2Adapter", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchAccrualVaultV2Adapter; } });
9
+ Object.defineProperty(exports, "fetchAccrualVaultV2MorphoMarketV1Adapter", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchAccrualVaultV2MorphoMarketV1Adapter; } });
10
+ Object.defineProperty(exports, "fetchAccrualVaultV2MorphoMarketV1AdapterV2", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchAccrualVaultV2MorphoMarketV1AdapterV2; } });
11
+ Object.defineProperty(exports, "fetchAccrualVaultV2MorphoVaultV1Adapter", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchAccrualVaultV2MorphoVaultV1Adapter; } });
12
+ Object.defineProperty(exports, "fetchHolding", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchHolding; } });
13
+ Object.defineProperty(exports, "fetchMarket", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchMarket; } });
14
+ Object.defineProperty(exports, "fetchMarketParams", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchMarketParams; } });
15
+ Object.defineProperty(exports, "fetchPosition", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchPosition; } });
16
+ Object.defineProperty(exports, "fetchPreLiquidationParams", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchPreLiquidationParams; } });
17
+ Object.defineProperty(exports, "fetchPreLiquidationPosition", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchPreLiquidationPosition; } });
18
+ Object.defineProperty(exports, "fetchToken", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchToken; } });
19
+ Object.defineProperty(exports, "fetchUser", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchUser; } });
20
+ Object.defineProperty(exports, "fetchVault", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVault; } });
21
+ Object.defineProperty(exports, "fetchVaultConfig", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultConfig; } });
22
+ Object.defineProperty(exports, "fetchVaultMarketAllocation", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultMarketAllocation; } });
23
+ Object.defineProperty(exports, "fetchVaultMarketConfig", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultMarketConfig; } });
24
+ Object.defineProperty(exports, "fetchVaultMarketPublicAllocatorConfig", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultMarketPublicAllocatorConfig; } });
25
+ Object.defineProperty(exports, "fetchVaultUser", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultUser; } });
26
+ Object.defineProperty(exports, "fetchVaultV2", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultV2; } });
27
+ Object.defineProperty(exports, "fetchVaultV2Adapter", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultV2Adapter; } });
28
+ Object.defineProperty(exports, "fetchVaultV2MorphoMarketV1Adapter", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultV2MorphoMarketV1Adapter; } });
29
+ Object.defineProperty(exports, "fetchVaultV2MorphoMarketV1AdapterV2", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultV2MorphoMarketV1AdapterV2; } });
30
+ Object.defineProperty(exports, "fetchVaultV2MorphoVaultV1Adapter", { enumerable: true, get: function () { return blue_sdk_viem_1.fetchVaultV2MorphoVaultV1Adapter; } });
@@ -0,0 +1,2 @@
1
+ export type { LocaleParts } from "@morpho-org/morpho-ts";
2
+ export { BaseFormatter, CommasFormatter, CommonFormatter, convertNumStrFromEffectiveTo, convertNumStrToLocal, createFormat, Format, format, formatEnumeration, formatLongString, formatUnion, getEffectiveLocale, getEnUSNumberToLocalParts, getLocaleSymbols, HexFormatter, NumberFormatter, PercentFormatter, ShortFormatter, } from "@morpho-org/morpho-ts";
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ShortFormatter = exports.PercentFormatter = exports.NumberFormatter = exports.HexFormatter = exports.getLocaleSymbols = exports.getEnUSNumberToLocalParts = exports.getEffectiveLocale = exports.formatUnion = exports.formatLongString = exports.formatEnumeration = exports.format = exports.Format = exports.createFormat = exports.convertNumStrToLocal = exports.convertNumStrFromEffectiveTo = exports.CommonFormatter = exports.CommasFormatter = exports.BaseFormatter = void 0;
4
+ var morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ Object.defineProperty(exports, "BaseFormatter", { enumerable: true, get: function () { return morpho_ts_1.BaseFormatter; } });
6
+ Object.defineProperty(exports, "CommasFormatter", { enumerable: true, get: function () { return morpho_ts_1.CommasFormatter; } });
7
+ Object.defineProperty(exports, "CommonFormatter", { enumerable: true, get: function () { return morpho_ts_1.CommonFormatter; } });
8
+ Object.defineProperty(exports, "convertNumStrFromEffectiveTo", { enumerable: true, get: function () { return morpho_ts_1.convertNumStrFromEffectiveTo; } });
9
+ Object.defineProperty(exports, "convertNumStrToLocal", { enumerable: true, get: function () { return morpho_ts_1.convertNumStrToLocal; } });
10
+ Object.defineProperty(exports, "createFormat", { enumerable: true, get: function () { return morpho_ts_1.createFormat; } });
11
+ Object.defineProperty(exports, "Format", { enumerable: true, get: function () { return morpho_ts_1.Format; } });
12
+ Object.defineProperty(exports, "format", { enumerable: true, get: function () { return morpho_ts_1.format; } });
13
+ Object.defineProperty(exports, "formatEnumeration", { enumerable: true, get: function () { return morpho_ts_1.formatEnumeration; } });
14
+ Object.defineProperty(exports, "formatLongString", { enumerable: true, get: function () { return morpho_ts_1.formatLongString; } });
15
+ Object.defineProperty(exports, "formatUnion", { enumerable: true, get: function () { return morpho_ts_1.formatUnion; } });
16
+ Object.defineProperty(exports, "getEffectiveLocale", { enumerable: true, get: function () { return morpho_ts_1.getEffectiveLocale; } });
17
+ Object.defineProperty(exports, "getEnUSNumberToLocalParts", { enumerable: true, get: function () { return morpho_ts_1.getEnUSNumberToLocalParts; } });
18
+ Object.defineProperty(exports, "getLocaleSymbols", { enumerable: true, get: function () { return morpho_ts_1.getLocaleSymbols; } });
19
+ Object.defineProperty(exports, "HexFormatter", { enumerable: true, get: function () { return morpho_ts_1.HexFormatter; } });
20
+ Object.defineProperty(exports, "NumberFormatter", { enumerable: true, get: function () { return morpho_ts_1.NumberFormatter; } });
21
+ Object.defineProperty(exports, "PercentFormatter", { enumerable: true, get: function () { return morpho_ts_1.PercentFormatter; } });
22
+ Object.defineProperty(exports, "ShortFormatter", { enumerable: true, get: function () { return morpho_ts_1.ShortFormatter; } });
@@ -1,23 +1,63 @@
1
1
  import { type MarketId } from "@morpho-org/blue-sdk";
2
- import type { SimulationState } from "@morpho-org/simulation-sdk";
2
+ import type { ReallocationData } from "../entities/reallocationData.js";
3
3
  import { type ReallocationComputeOptions, type VaultReallocation } from "../types/index.js";
4
4
  /**
5
5
  * Computes vault reallocations for a borrow operation on a target market.
6
6
  *
7
- * Replicates the shared liquidity algorithm from `populateSubBundle` in
8
- * `@morpho-org/bundler-sdk-viem`. First attempts "friendly" reallocations
9
- * respecting withdrawal utilization targets, then falls back to aggressive
10
- * reallocations (100% withdrawal utilization) if liquidity is still insufficient.
7
+ * First attempts "friendly" reallocations respecting withdrawal utilization
8
+ * targets, then falls back to aggressive reallocations (100% withdrawal
9
+ * utilization) if liquidity is still insufficient.
11
10
  *
12
- * @param params.reallocationData - The simulation state containing market, vault, and position data.
11
+ * @remarks Pass `options.timestamp` from the same block used to fetch `reallocationData`; when omitted, market accrual falls back to the target market's `lastUpdate`, which can diverge from the source rows' fetch block. Per-market `maxWithdrawalUtilization` overrides apply only to phase 1; phase 2 forces 100% utilization on every source market.
12
+ * @param params.reallocationData - The local state containing market, vault, and position data.
13
13
  * @param params.marketId - The target market to reallocate liquidity into.
14
14
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
15
15
  * @param params.options - Optional reallocation computation options.
16
16
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
17
- * @throws {InsufficientSharedLiquidityError} If shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
17
+ * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
18
+ * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
19
+ * @example
20
+ * ```ts
21
+ * import { createPublicClient, http, parseUnits } from "viem";
22
+ * import { mainnet } from "viem/chains";
23
+ * import { markets, vaults } from "@morpho-org/morpho-test";
24
+ * import {
25
+ * computeReallocations,
26
+ * morphoViemExtension,
27
+ * } from "@morpho-org/morpho-sdk";
28
+ *
29
+ * const client = createPublicClient({
30
+ * chain: mainnet,
31
+ * transport: http(),
32
+ * }).extend(morphoViemExtension());
33
+ *
34
+ * const userAddress = "0x000000000000000000000000000000000000dEaD";
35
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
36
+ * const market = client.morpho.marketV1(marketParams, mainnet.id);
37
+ * const block = await client.getBlock();
38
+ * const reallocationData = await market.getReallocationData({
39
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
40
+ * block: { number: block.number, timestamp: block.timestamp },
41
+ * });
42
+ * const borrowAmount = parseUnits("1000", 6);
43
+ * const reallocations = computeReallocations({
44
+ * reallocationData,
45
+ * marketId: marketParams.id,
46
+ * borrowAmount,
47
+ * options: { timestamp: block.timestamp },
48
+ * });
49
+ * const positionData = await market.getPositionData(userAddress);
50
+ * const borrow = market.borrow({
51
+ * userAddress,
52
+ * amount: borrowAmount,
53
+ * positionData,
54
+ * reallocations,
55
+ * });
56
+ * // borrow.buildTx() includes any required PublicAllocator reallocations.
57
+ * ```
18
58
  */
19
59
  export declare const computeReallocations: ({ reallocationData: data, marketId, borrowAmount, options, }: {
20
- readonly reallocationData: SimulationState;
60
+ readonly reallocationData: ReallocationData;
21
61
  readonly marketId: MarketId;
22
62
  readonly borrowAmount: bigint;
23
63
  readonly options?: ReallocationComputeOptions;
@@ -2,32 +2,126 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.computeReallocations = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
- const bundler_sdk_viem_1 = require("@morpho-org/bundler-sdk-viem");
6
5
  const index_js_1 = require("../types/index.js");
6
+ const constant_js_1 = require("./constant.js");
7
+ const validate_js_1 = require("./validate.js");
8
+ const groupWithdrawalsByVault = (withdrawals) => {
9
+ const groups = [];
10
+ const groupsByVault = new Map();
11
+ for (const [index, { vault, id, assets }] of withdrawals.entries()) {
12
+ if (assets <= 0n)
13
+ continue;
14
+ let group = groupsByVault.get(vault);
15
+ if (group == null) {
16
+ group = {
17
+ vault,
18
+ firstIndex: index,
19
+ totalAssets: 0n,
20
+ withdrawals: [],
21
+ };
22
+ groupsByVault.set(vault, group);
23
+ groups.push(group);
24
+ }
25
+ group.totalAssets += assets;
26
+ group.withdrawals.push({ id, assets });
27
+ }
28
+ return groups.sort((a, b) => {
29
+ if (a.totalAssets > b.totalAssets)
30
+ return -1;
31
+ if (a.totalAssets < b.totalAssets)
32
+ return 1;
33
+ return a.firstIndex - b.firstIndex;
34
+ });
35
+ };
36
+ const capVaultWithdrawals = (withdrawals, assets) => {
37
+ const cappedWithdrawals = [];
38
+ let remainingAssets = assets;
39
+ for (const withdrawal of withdrawals) {
40
+ const cappedAssets = blue_sdk_1.MathLib.min(withdrawal.assets, remainingAssets);
41
+ if (cappedAssets <= 0n)
42
+ continue;
43
+ const existing = cappedWithdrawals.find((item) => item.id === withdrawal.id);
44
+ if (existing != null) {
45
+ existing.assets += cappedAssets;
46
+ }
47
+ else {
48
+ cappedWithdrawals.push({
49
+ id: withdrawal.id,
50
+ assets: cappedAssets,
51
+ });
52
+ }
53
+ remainingAssets -= cappedAssets;
54
+ if (remainingAssets === 0n)
55
+ break;
56
+ }
57
+ return cappedWithdrawals;
58
+ };
7
59
  /**
8
60
  * Computes vault reallocations for a borrow operation on a target market.
9
61
  *
10
- * Replicates the shared liquidity algorithm from `populateSubBundle` in
11
- * `@morpho-org/bundler-sdk-viem`. First attempts "friendly" reallocations
12
- * respecting withdrawal utilization targets, then falls back to aggressive
13
- * reallocations (100% withdrawal utilization) if liquidity is still insufficient.
62
+ * First attempts "friendly" reallocations respecting withdrawal utilization
63
+ * targets, then falls back to aggressive reallocations (100% withdrawal
64
+ * utilization) if liquidity is still insufficient.
14
65
  *
15
- * @param params.reallocationData - The simulation state containing market, vault, and position data.
66
+ * @remarks Pass `options.timestamp` from the same block used to fetch `reallocationData`; when omitted, market accrual falls back to the target market's `lastUpdate`, which can diverge from the source rows' fetch block. Per-market `maxWithdrawalUtilization` overrides apply only to phase 1; phase 2 forces 100% utilization on every source market.
67
+ * @param params.reallocationData - The local state containing market, vault, and position data.
16
68
  * @param params.marketId - The target market to reallocate liquidity into.
17
69
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
18
70
  * @param params.options - Optional reallocation computation options.
19
71
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
20
- * @throws {InsufficientSharedLiquidityError} If shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
72
+ * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
73
+ * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
74
+ * @example
75
+ * ```ts
76
+ * import { createPublicClient, http, parseUnits } from "viem";
77
+ * import { mainnet } from "viem/chains";
78
+ * import { markets, vaults } from "@morpho-org/morpho-test";
79
+ * import {
80
+ * computeReallocations,
81
+ * morphoViemExtension,
82
+ * } from "@morpho-org/morpho-sdk";
83
+ *
84
+ * const client = createPublicClient({
85
+ * chain: mainnet,
86
+ * transport: http(),
87
+ * }).extend(morphoViemExtension());
88
+ *
89
+ * const userAddress = "0x000000000000000000000000000000000000dEaD";
90
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
91
+ * const market = client.morpho.marketV1(marketParams, mainnet.id);
92
+ * const block = await client.getBlock();
93
+ * const reallocationData = await market.getReallocationData({
94
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
95
+ * block: { number: block.number, timestamp: block.timestamp },
96
+ * });
97
+ * const borrowAmount = parseUnits("1000", 6);
98
+ * const reallocations = computeReallocations({
99
+ * reallocationData,
100
+ * marketId: marketParams.id,
101
+ * borrowAmount,
102
+ * options: { timestamp: block.timestamp },
103
+ * });
104
+ * const positionData = await market.getPositionData(userAddress);
105
+ * const borrow = market.borrow({
106
+ * userAddress,
107
+ * amount: borrowAmount,
108
+ * positionData,
109
+ * reallocations,
110
+ * });
111
+ * // borrow.buildTx() includes any required PublicAllocator reallocations.
112
+ * ```
21
113
  */
22
114
  const computeReallocations = ({ reallocationData: data, marketId, borrowAmount, options, }) => {
23
115
  if (options?.enabled === false)
24
116
  return [];
25
- const market = data.getMarket(marketId).accrueInterest(data.block.timestamp);
117
+ // ReallocationData does not retain the fetch block; pass that block timestamp
118
+ // to compute against the same accrued state, otherwise Market defaults to lastUpdate.
119
+ const market = data.getMarket(marketId).accrueInterest(options?.timestamp);
26
120
  const newTotalBorrowAssets = market.totalBorrowAssets + borrowAmount;
27
121
  const newTotalSupplyAssets = market.totalSupplyAssets;
28
122
  const supplyTargetUtilization = options?.supplyTargetUtilization?.[market.params.id] ??
29
123
  options?.defaultSupplyTargetUtilization ??
30
- bundler_sdk_viem_1.DEFAULT_SUPPLY_TARGET_UTILIZATION;
124
+ constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION;
31
125
  if (blue_sdk_1.MarketUtils.getUtilization({
32
126
  totalSupplyAssets: newTotalSupplyAssets,
33
127
  totalBorrowAssets: newTotalBorrowAssets,
@@ -58,27 +152,20 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
58
152
  const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
59
153
  ? newTotalBorrowAssets - newTotalSupplyAssets
60
154
  : 0n;
61
- // Group withdrawals by vault, capping total at requiredAssets.
62
- const reallocationsMap = {};
155
+ const reallocations = [];
63
156
  let totalReallocated = 0n;
64
- for (const { vault, ...withdrawal } of withdrawals) {
65
- const vaultReallocations = (reallocationsMap[vault] ??= []);
66
- const existing = vaultReallocations.find((item) => item.id === withdrawal.id);
67
- const reallocatedAssets = blue_sdk_1.MathLib.min(withdrawal.assets, requiredAssets);
157
+ let remainingRequiredAssets = requiredAssets;
158
+ for (const group of groupWithdrawalsByVault(withdrawals)) {
159
+ const reallocatedAssets = blue_sdk_1.MathLib.min(group.totalAssets, remainingRequiredAssets);
68
160
  if (reallocatedAssets <= 0n)
69
161
  continue;
70
- if (existing != null) {
71
- existing.assets += reallocatedAssets;
72
- }
73
- else {
74
- vaultReallocations.push({
75
- ...withdrawal,
76
- assets: reallocatedAssets,
77
- });
78
- }
79
- requiredAssets -= reallocatedAssets;
162
+ reallocations.push({
163
+ vault: group.vault,
164
+ withdrawals: capVaultWithdrawals(group.withdrawals, reallocatedAssets),
165
+ });
166
+ remainingRequiredAssets -= reallocatedAssets;
80
167
  totalReallocated += reallocatedAssets;
81
- if (requiredAssets === 0n)
168
+ if (remainingRequiredAssets === 0n)
82
169
  break;
83
170
  }
84
171
  // Refuse fee-bearing partial plans for an unreachable borrow.
@@ -90,10 +177,10 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
90
177
  });
91
178
  }
92
179
  // Transform into VaultReallocation[] format.
93
- return Object.entries(reallocationsMap)
94
- .filter(([, vaultWithdrawals]) => vaultWithdrawals.length > 0)
95
- .map(([vault, vaultWithdrawals]) => ({
96
- vault: vault,
180
+ return reallocations
181
+ .filter(({ withdrawals: vaultWithdrawals }) => vaultWithdrawals.length > 0)
182
+ .map(({ vault, withdrawals: vaultWithdrawals }) => ({
183
+ vault,
97
184
  fee: (() => {
98
185
  const config = data.getVault(vault).publicAllocatorConfig;
99
186
  if (config == null) {
@@ -102,8 +189,9 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
102
189
  return config.fee;
103
190
  })(),
104
191
  withdrawals: vaultWithdrawals
105
- // Reallocation withdrawals must be sorted by market id in ascending order.
106
- .sort(({ id: idA }, { id: idB }) => idA > idB ? 1 : idA < idB ? -1 : 0)
192
+ // Reallocation withdrawals must be sorted by market id in ascending
193
+ // order. Normalize first because `MarketId` can be mixed-case hex.
194
+ .sort(({ id: idA }, { id: idB }) => (0, validate_js_1.compareMarketIds)(idA, idB))
107
195
  .map(({ id, assets }) => ({
108
196
  marketParams: data.getMarket(id).params,
109
197
  amount: assets,
@@ -1,6 +1,23 @@
1
+ import { type Address } from "viem";
1
2
  /** Maximum slippage tolerance: 10% */
2
3
  export declare const MAX_SLIPPAGE_TOLERANCE: bigint;
3
4
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
4
5
  export declare const DEFAULT_LLTV_BUFFER: bigint;
5
6
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
6
7
  export declare const MAX_ABSOLUTE_SHARE_PRICE: bigint;
8
+ /**
9
+ * The default maximum utilization allowed to reach when withdrawing shared liquidity.
10
+ */
11
+ export declare const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
12
+ /**
13
+ * The default target utilization above which shared liquidity reallocations are triggered.
14
+ */
15
+ export declare const DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
16
+ /**
17
+ * Tokens that require setting allowance from zero before changing approval.
18
+ */
19
+ export declare const APPROVE_ONLY_ONCE_TOKENS: Partial<Record<number, Address[]>>;
20
+ /**
21
+ * Token-specific maximum approval amounts for tokens that cannot use uint256 max.
22
+ */
23
+ export declare const MAX_TOKEN_APPROVALS: Partial<Record<number, Record<Address, bigint>>>;
@@ -1,10 +1,39 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_LLTV_BUFFER = exports.MAX_SLIPPAGE_TOLERANCE = void 0;
3
+ exports.MAX_TOKEN_APPROVALS = exports.APPROVE_ONLY_ONCE_TOKENS = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_LLTV_BUFFER = exports.MAX_SLIPPAGE_TOLERANCE = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const viem_1 = require("viem");
5
6
  /** Maximum slippage tolerance: 10% */
6
7
  exports.MAX_SLIPPAGE_TOLERANCE = blue_sdk_1.MathLib.WAD / 10n;
7
8
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
8
9
  exports.DEFAULT_LLTV_BUFFER = blue_sdk_1.MathLib.WAD / 200n;
9
10
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
10
11
  exports.MAX_ABSOLUTE_SHARE_PRICE = 100n * blue_sdk_1.MathLib.RAY;
12
+ /**
13
+ * The default maximum utilization allowed to reach when withdrawing shared liquidity.
14
+ */
15
+ exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
16
+ /**
17
+ * The default target utilization above which shared liquidity reallocations are triggered.
18
+ */
19
+ exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
20
+ /**
21
+ * Tokens that require setting allowance from zero before changing approval.
22
+ */
23
+ exports.APPROVE_ONLY_ONCE_TOKENS = {
24
+ [blue_sdk_1.ChainId.EthMainnet]: [
25
+ "0xdAC17F958D2ee523a2206206994597C13D831ec7", // USDT
26
+ "0xD533a949740bb3306d119CC777fa900bA034cd52", // CRV
27
+ ],
28
+ };
29
+ /**
30
+ * Token-specific maximum approval amounts for tokens that cannot use uint256 max.
31
+ */
32
+ exports.MAX_TOKEN_APPROVALS = {
33
+ [blue_sdk_1.ChainId.EthMainnet]: {
34
+ "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984": viem_1.maxUint96, // UNI
35
+ "0xfAbA6f8e4a5E8Ab82F62fe7C39859FA577269BE3": viem_1.maxUint96, // ONDO
36
+ "0xc00e94Cb662C3520282E6f5717214004A7f26888": viem_1.maxUint96, // COMP
37
+ "0x6f40d4A6237C257fff2dB00FA0510DeEECd303eb": viem_1.maxUint96, // FLUID
38
+ },
39
+ };
@@ -1,4 +1,5 @@
1
1
  export { computeReallocations } from "./computeReallocations.js";
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";
2
3
  export { addTransactionMetadata } from "./metadata.js";
3
4
  export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./slippage.js";
4
5
  export { validateAccrualPosition, validateChainId, validateNativeCollateral, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./validate.js";
@@ -1,8 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayParams = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeCollateral = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinBorrowSharePrice = exports.computeMaxRepaySharePrice = exports.addTransactionMetadata = exports.computeReallocations = void 0;
3
+ exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayParams = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeCollateral = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinBorrowSharePrice = exports.computeMaxRepaySharePrice = exports.addTransactionMetadata = exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_LLTV_BUFFER = exports.APPROVE_ONLY_ONCE_TOKENS = exports.computeReallocations = void 0;
4
4
  var computeReallocations_js_1 = require("./computeReallocations.js");
5
5
  Object.defineProperty(exports, "computeReallocations", { enumerable: true, get: function () { return computeReallocations_js_1.computeReallocations; } });
6
+ var constant_js_1 = require("./constant.js");
7
+ Object.defineProperty(exports, "APPROVE_ONLY_ONCE_TOKENS", { enumerable: true, get: function () { return constant_js_1.APPROVE_ONLY_ONCE_TOKENS; } });
8
+ Object.defineProperty(exports, "DEFAULT_LLTV_BUFFER", { enumerable: true, get: function () { return constant_js_1.DEFAULT_LLTV_BUFFER; } });
9
+ Object.defineProperty(exports, "DEFAULT_SUPPLY_TARGET_UTILIZATION", { enumerable: true, get: function () { return constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION; } });
10
+ Object.defineProperty(exports, "DEFAULT_WITHDRAWAL_TARGET_UTILIZATION", { enumerable: true, get: function () { return constant_js_1.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION; } });
11
+ Object.defineProperty(exports, "MAX_ABSOLUTE_SHARE_PRICE", { enumerable: true, get: function () { return constant_js_1.MAX_ABSOLUTE_SHARE_PRICE; } });
12
+ Object.defineProperty(exports, "MAX_SLIPPAGE_TOLERANCE", { enumerable: true, get: function () { return constant_js_1.MAX_SLIPPAGE_TOLERANCE; } });
13
+ Object.defineProperty(exports, "MAX_TOKEN_APPROVALS", { enumerable: true, get: function () { return constant_js_1.MAX_TOKEN_APPROVALS; } });
6
14
  var metadata_js_1 = require("./metadata.js");
7
15
  Object.defineProperty(exports, "addTransactionMetadata", { enumerable: true, get: function () { return metadata_js_1.addTransactionMetadata; } });
8
16
  var slippage_js_1 = require("./slippage.js");
@@ -9,6 +9,16 @@ import type { Metadata } from "../types/index.js";
9
9
  * The function ensures that the transaction data is correctly formatted
10
10
  * and includes optional metadata elements if provided.
11
11
  *
12
+ * `metadata.origin` accepts either a raw hex string (`"cafe"`) or a
13
+ * 0x-prefixed hex string (`"0xcafe"` / `"0Xcafe"`); both produce the same
14
+ * appended 4-byte origin tag. The 0x/0X prefix is stripped case-insensitively
15
+ * before length-validation, so an origin of `"0xdeadbeef"` (10 chars
16
+ * including prefix, 8 raw hex chars) is accepted while `"0xdeadbeef00"`
17
+ * (10 raw hex chars) is rejected and a warning is logged. Odd-length raw
18
+ * fragments (e.g. `"abc"`, `"0xabc"`) are also rejected — concatenating
19
+ * a non-byte-aligned fragment would corrupt the trailing analytics byte
20
+ * once viem's `concatHex` pads it to a whole byte at broadcast time.
21
+ *
12
22
  * @param {Object} tx - The original transaction object.
13
23
  * @param {Hex} tx.data - The existing hex-encoded data for the transaction.
14
24
  * @param {bigint} tx.value - The value to be sent with the transaction.
@@ -12,6 +12,16 @@ const viem_1 = require("viem");
12
12
  * The function ensures that the transaction data is correctly formatted
13
13
  * and includes optional metadata elements if provided.
14
14
  *
15
+ * `metadata.origin` accepts either a raw hex string (`"cafe"`) or a
16
+ * 0x-prefixed hex string (`"0xcafe"` / `"0Xcafe"`); both produce the same
17
+ * appended 4-byte origin tag. The 0x/0X prefix is stripped case-insensitively
18
+ * before length-validation, so an origin of `"0xdeadbeef"` (10 chars
19
+ * including prefix, 8 raw hex chars) is accepted while `"0xdeadbeef00"`
20
+ * (10 raw hex chars) is rejected and a warning is logged. Odd-length raw
21
+ * fragments (e.g. `"abc"`, `"0xabc"`) are also rejected — concatenating
22
+ * a non-byte-aligned fragment would corrupt the trailing analytics byte
23
+ * once viem's `concatHex` pads it to a whole byte at broadcast time.
24
+ *
15
25
  * @param {Object} tx - The original transaction object.
16
26
  * @param {Hex} tx.data - The existing hex-encoded data for the transaction.
17
27
  * @param {bigint} tx.value - The value to be sent with the transaction.
@@ -34,11 +44,20 @@ function addTransactionMetadata(tx, metadata) {
34
44
  concatItems.push((0, viem_1.numberToHex)(morpho_ts_1.Time.timestamp(), { size: 4 }));
35
45
  }
36
46
  try {
37
- const origin = metadata.origin.replace(/^(?!0x)/, "");
47
+ // Strip a leading "0x" / "0X" case-insensitively so callers can pass
48
+ // "cafe", "0xcafe", or "0Xcafe" — all produce the same 4-byte appended
49
+ // origin. The case-insensitive form prevents "0Xcafe" from falling
50
+ // through to `isHex("0x0Xcafe")` and being silently dropped.
51
+ const origin = metadata.origin.replace(/^0x/i, "");
38
52
  if (!(0, viem_1.isHex)(`0x${origin}`))
39
53
  throw Error("Calldata origin must consists of only hex characters");
40
54
  if (origin.length > 8)
41
55
  throw Error("Calldata origin must be at most 8 characters long");
56
+ // Reject odd-length raw fragments. viem's `concatHex` would pad the
57
+ // stray nibble to a whole byte at broadcast, corrupting the trailing
58
+ // analytics byte on-chain.
59
+ if (origin.length % 2 !== 0)
60
+ throw Error("Calldata origin must have an even number of hex characters");
42
61
  concatItems.push(`0x${origin}`);
43
62
  }
44
63
  catch (error) {
@@ -1,6 +1,8 @@
1
1
  import { type AccrualPosition, type MarketId } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
3
  import { type VaultReallocation } from "../types/index.js";
4
+ /** @internal */
5
+ export declare const compareMarketIds: (idA: MarketId, idB: MarketId) => 0 | 1 | -1;
4
6
  /**
5
7
  * Asserts that the client has a connected account AND that it matches
6
8
  * the provided user address.
@@ -1,12 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateSlippageTolerance = exports.validateReallocations = exports.validateRepayParams = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeCollateral = exports.validateChainId = exports.validatePositionHealth = exports.validateAccrualPosition = void 0;
3
+ exports.validateSlippageTolerance = exports.validateReallocations = exports.validateRepayParams = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeCollateral = exports.validateChainId = exports.validatePositionHealth = exports.validateAccrualPosition = exports.compareMarketIds = void 0;
4
4
  exports.validateUserAddress = validateUserAddress;
5
5
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
7
  const viem_1 = require("viem");
8
8
  const index_js_1 = require("../types/index.js");
9
9
  const constant_js_1 = require("./constant.js");
10
+ /** @internal */
11
+ const compareMarketIds = (idA, idB) => {
12
+ const normalizedIdA = idA.toLowerCase();
13
+ const normalizedIdB = idB.toLowerCase();
14
+ if (normalizedIdA > normalizedIdB)
15
+ return 1;
16
+ if (normalizedIdA < normalizedIdB)
17
+ return -1;
18
+ return 0;
19
+ };
20
+ exports.compareMarketIds = compareMarketIds;
10
21
  /**
11
22
  * Asserts that the client has a connected account AND that it matches
12
23
  * the provided user address.
@@ -264,7 +275,8 @@ const validateReallocations = (reallocations, targetMarketId) => {
264
275
  if (w.marketParams.id === targetMarketId) {
265
276
  throw new index_js_1.ReallocationWithdrawalOnTargetMarketError(r.vault, w.marketParams.id);
266
277
  }
267
- if (prevId !== undefined && w.marketParams.id <= prevId) {
278
+ if (prevId !== undefined &&
279
+ (0, exports.compareMarketIds)(w.marketParams.id, prevId) <= 0) {
268
280
  throw new index_js_1.UnsortedReallocationWithdrawalsError(r.vault, w.marketParams.id);
269
281
  }
270
282
  prevId = w.marketParams.id;
@@ -1,5 +1,4 @@
1
1
  export * from "./actions/index.js";
2
2
  export * from "./client/index.js";
3
- export * from "./entities/index.js";
4
3
  export * from "./helpers/index.js";
5
4
  export * from "./types/index.js";
package/lib/cjs/index.js CHANGED
@@ -16,6 +16,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./actions/index.js"), exports);
18
18
  __exportStar(require("./client/index.js"), exports);
19
- __exportStar(require("./entities/index.js"), exports);
20
19
  __exportStar(require("./helpers/index.js"), exports);
21
20
  __exportStar(require("./types/index.js"), exports);
@@ -1,6 +1,6 @@
1
1
  import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Address, Client } from "viem";
3
- import type { MarketV1Actions, VaultV1Actions, VaultV2Actions } from "../entities/index.js";
3
+ import type { MarketV1Actions, VaultV1Actions, VaultV2Actions } from "../actions/index.js";
4
4
  import type { Metadata } from "./index.js";
5
5
  /**
6
6
  * Structural contract every concrete `MorphoClient` implementation satisfies. Carries the viem