@gearbox-protocol/sdk 16.4.0-next.1 → 16.4.0-next.11

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 (116) hide show
  1. package/dist/cjs/dev/index.js +3 -2
  2. package/dist/cjs/dev/kycUtils.js +18 -35
  3. package/dist/cjs/dev/midasUtils.js +80 -16
  4. package/dist/cjs/dev/securitizeUtils.js +14 -10
  5. package/dist/cjs/dev/withdrawalUtils.js +3 -6
  6. package/dist/cjs/model/errors/index.js +1 -0
  7. package/dist/cjs/model/errors/operation-errors.js +9 -0
  8. package/dist/cjs/model/index.js +1 -0
  9. package/dist/cjs/onchain/accounts/intents/borrow.js +139 -0
  10. package/dist/cjs/onchain/accounts/intents/{collateral-money.js → collateral-valuation.js} +7 -7
  11. package/dist/cjs/onchain/accounts/intents/index.js +86 -2
  12. package/dist/cjs/onchain/accounts/intents/leverage-band.js +2 -12
  13. package/dist/cjs/onchain/accounts/intents/maxBorrow.js +89 -0
  14. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +14 -14
  15. package/dist/cjs/onchain/accounts/intents/open-strategy.js +6 -45
  16. package/dist/cjs/onchain/accounts/intents/realize.js +44 -0
  17. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  18. package/dist/cjs/onchain/accounts/intents/utils/common.js +19 -0
  19. package/dist/cjs/onchain/accounts/intents/utils/credit-account-slice.js +21 -0
  20. package/dist/cjs/onchain/accounts/intents/utils/index.js +2 -0
  21. package/dist/cjs/onchain/accounts/intents/utils/price-impact.js +3 -3
  22. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +8 -8
  23. package/dist/cjs/onchain/accounts/utils/midasUtils.js +7 -1
  24. package/dist/cjs/onchain/core/createAddressProvider.js +2 -5
  25. package/dist/cjs/onchain/index.js +4 -0
  26. package/dist/cjs/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +11 -3
  27. package/dist/cjs/onchain/positions/calcHealthFactor.js +3 -3
  28. package/dist/cjs/onchain/preview/index.js +2 -0
  29. package/dist/cjs/onchain/preview/preview/index.js +2 -0
  30. package/dist/cjs/onchain/preview/preview/midasGreenlistsAccount.js +17 -0
  31. package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +5 -2
  32. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +2 -1
  33. package/dist/cjs/onchain/validation/bundles/checkMidasAccountGreenlist.js +44 -0
  34. package/dist/cjs/onchain/validation/bundles/checkRWAOpening.js +15 -5
  35. package/dist/cjs/onchain/validation/bundles/index.js +2 -0
  36. package/dist/cjs/onchain/validation/index.js +2 -0
  37. package/dist/cjs/sdk/execute/ExecuteApi.js +65 -5
  38. package/dist/cjs/sdk/prepare/PrepareApi.js +86 -12
  39. package/dist/esm/dev/index.js +3 -3
  40. package/dist/esm/dev/kycUtils.js +17 -33
  41. package/dist/esm/dev/midasUtils.js +80 -18
  42. package/dist/esm/dev/securitizeUtils.js +15 -11
  43. package/dist/esm/dev/withdrawalUtils.js +3 -6
  44. package/dist/esm/model/errors/index.js +2 -2
  45. package/dist/esm/model/errors/operation-errors.js +9 -1
  46. package/dist/esm/model/index.js +2 -2
  47. package/dist/esm/onchain/accounts/intents/borrow.js +137 -0
  48. package/dist/esm/onchain/accounts/intents/{collateral-money.js → collateral-valuation.js} +7 -7
  49. package/dist/esm/onchain/accounts/intents/index.js +86 -2
  50. package/dist/esm/onchain/accounts/intents/leverage-band.js +2 -12
  51. package/dist/esm/onchain/accounts/intents/maxBorrow.js +87 -0
  52. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +14 -14
  53. package/dist/esm/onchain/accounts/intents/open-strategy.js +6 -45
  54. package/dist/esm/onchain/accounts/intents/realize.js +44 -0
  55. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  56. package/dist/esm/onchain/accounts/intents/utils/common.js +19 -1
  57. package/dist/esm/onchain/accounts/intents/utils/credit-account-slice.js +21 -1
  58. package/dist/esm/onchain/accounts/intents/utils/index.js +3 -3
  59. package/dist/esm/onchain/accounts/intents/utils/price-impact.js +3 -3
  60. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +8 -8
  61. package/dist/esm/onchain/accounts/utils/midasUtils.js +8 -2
  62. package/dist/esm/onchain/core/createAddressProvider.js +2 -5
  63. package/dist/esm/onchain/index.js +3 -1
  64. package/dist/esm/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +11 -3
  65. package/dist/esm/onchain/positions/calcHealthFactor.js +3 -3
  66. package/dist/esm/onchain/preview/index.js +2 -1
  67. package/dist/esm/onchain/preview/preview/index.js +2 -1
  68. package/dist/esm/onchain/preview/preview/midasGreenlistsAccount.js +16 -0
  69. package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +5 -2
  70. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +2 -1
  71. package/dist/esm/onchain/validation/bundles/checkMidasAccountGreenlist.js +43 -0
  72. package/dist/esm/onchain/validation/bundles/checkRWAOpening.js +15 -5
  73. package/dist/esm/onchain/validation/bundles/index.js +2 -1
  74. package/dist/esm/onchain/validation/index.js +2 -1
  75. package/dist/esm/sdk/execute/ExecuteApi.js +65 -5
  76. package/dist/esm/sdk/prepare/PrepareApi.js +86 -12
  77. package/dist/types/dev/index.d.ts +3 -3
  78. package/dist/types/dev/kycUtils.d.ts +1 -5
  79. package/dist/types/dev/midasUtils.d.ts +15 -4
  80. package/dist/types/model/errors/index.d.ts +2 -2
  81. package/dist/types/model/errors/operation-errors.d.ts +14 -1
  82. package/dist/types/model/index.d.ts +2 -2
  83. package/dist/types/model/previews.d.ts +17 -2
  84. package/dist/types/onchain/accounts/index.d.ts +4 -3
  85. package/dist/types/onchain/accounts/intents/borrow.d.ts +141 -0
  86. package/dist/types/onchain/accounts/intents/{collateral-money.d.ts → collateral-valuation.d.ts} +8 -8
  87. package/dist/types/onchain/accounts/intents/index.d.ts +81 -2
  88. package/dist/types/onchain/accounts/intents/maxBorrow.d.ts +54 -0
  89. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +3 -3
  90. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +3 -17
  91. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +2 -0
  92. package/dist/types/onchain/accounts/intents/tests/open-strategy.fixtures.d.ts +2 -2
  93. package/dist/types/onchain/accounts/intents/types.d.ts +15 -1
  94. package/dist/types/onchain/accounts/intents/utils/common.d.ts +15 -1
  95. package/dist/types/onchain/accounts/intents/utils/credit-account-slice.d.ts +14 -1
  96. package/dist/types/onchain/accounts/intents/utils/index.d.ts +3 -3
  97. package/dist/types/onchain/accounts/intents/withdraw-limits.d.ts +1 -1
  98. package/dist/types/onchain/accounts/utils/midasUtils.d.ts +2 -1
  99. package/dist/types/onchain/index.d.ts +7 -4
  100. package/dist/types/onchain/market/adapters/contracts/MidasGatewayAdapterContract.d.ts +8 -2
  101. package/dist/types/onchain/preview/index.d.ts +2 -1
  102. package/dist/types/onchain/preview/preview/index.d.ts +2 -1
  103. package/dist/types/onchain/preview/preview/midasGreenlistsAccount.d.ts +13 -0
  104. package/dist/types/onchain/validation/bundles/checkCreditOperation.d.ts +2 -2
  105. package/dist/types/onchain/validation/bundles/checkMidasAccountGreenlist.d.ts +22 -0
  106. package/dist/types/onchain/validation/bundles/checkRWAOpening.d.ts +6 -4
  107. package/dist/types/onchain/validation/bundles/index.d.ts +3 -2
  108. package/dist/types/onchain/validation/checks/checkDebtLimits.d.ts +2 -2
  109. package/dist/types/onchain/validation/index.d.ts +3 -2
  110. package/dist/types/sdk/execute/index.d.ts +2 -2
  111. package/dist/types/sdk/execute/types.d.ts +48 -6
  112. package/dist/types/sdk/index.d.ts +5 -4
  113. package/dist/types/sdk/prepare/PrepareApi.d.ts +15 -3
  114. package/dist/types/sdk/prepare/index.d.ts +4 -3
  115. package/dist/types/sdk/prepare/types.d.ts +176 -49
  116. package/package.json +1 -1
@@ -14,10 +14,10 @@ const require_dev_detectChain = require("./detectChain.js");
14
14
  const require_dev_isOutOfSyncError = require("./isOutOfSyncError.js");
15
15
  const require_dev_isRateLimitError = require("./isRateLimitError.js");
16
16
  const require_dev_isTransientError = require("./isTransientError.js");
17
+ const require_dev_midasUtils = require("./midasUtils.js");
17
18
  const require_dev_kycUtils = require("./kycUtils.js");
18
19
  const require_dev_logSplitterTransport = require("./logSplitterTransport.js");
19
20
  const require_dev_ltUtils = require("./ltUtils.js");
20
- const require_dev_midasUtils = require("./midasUtils.js");
21
21
  const require_dev_migrateFaucet = require("./migrateFaucet.js");
22
22
  const require_dev_providers = require("./providers.js");
23
23
  const require_dev_replaceStorage = require("./replaceStorage.js");
@@ -42,6 +42,8 @@ exports.calcLiquidatableLTs = require_dev_calcLiquidatableLTs.calcLiquidatableLT
42
42
  exports.claimDSToken = require_dev_securitizeUtils.claimDSToken;
43
43
  exports.claimDSTokens = require_dev_securitizeUtils.claimDSTokens;
44
44
  exports.claimFromFaucet = require_dev_claimFromFaucet.claimFromFaucet;
45
+ exports.collectMidasGateways = require_dev_midasUtils.collectMidasGateways;
46
+ exports.collectMidasMTokens = require_dev_midasUtils.collectMidasMTokens;
45
47
  exports.createAnvilClient = require_dev_createAnvilClient.createAnvilClient;
46
48
  exports.createMinter = require_dev_mint_factory.createMinter;
47
49
  exports.deployUsingPublicCreate2 = require_dev_create2.deployUsingPublicCreate2;
@@ -86,4 +88,3 @@ exports.setLTZero = require_dev_ltUtils.setLTZero;
86
88
  exports.setLTs = require_dev_ltUtils.setLTs;
87
89
  exports.unpauseMidasIssuanceVault = require_dev_midasUtils.unpauseMidasIssuanceVault;
88
90
  exports.verifyTestnet = require_dev_verifyTestnet.verifyTestnet;
89
- exports.writeAndWait = require_dev_kycUtils.writeAndWait;
@@ -5,23 +5,12 @@ const require_onchain_OnchainSDK = require("../onchain/OnchainSDK.js");
5
5
  require("../onchain/index.js");
6
6
  const require_abi_rwa_iDSRegistryService = require("../abi/rwa/iDSRegistryService.js");
7
7
  const require_abi_rwa_iDSToken = require("../abi/rwa/iDSToken.js");
8
+ const require_dev_midasUtils = require("./midasUtils.js");
8
9
  const require_dev_withdrawalAbi = require("./withdrawalAbi.js");
9
10
  let viem = require("viem");
10
11
  let viem_accounts = require("viem/accounts");
11
12
  //#region src/dev/kycUtils.ts
12
13
  /**
13
- * Writes to a contract, mines a block and waits for the receipt
14
- */
15
- async function writeAndWait(anvil, params) {
16
- const hash = await anvil.writeContract(params);
17
- await anvil.mine({ blocks: 1 });
18
- await anvil.waitForTransactionReceipt({
19
- hash,
20
- pollingInterval: 100
21
- });
22
- return hash;
23
- }
24
- /**
25
14
  * Resolves the account that performs the DS registry writes: either the admin
26
15
  * private key, or the admin address impersonated on the fork
27
16
  */
@@ -99,36 +88,39 @@ async function registerSecuritizeInvestor(props) {
99
88
  const { account, release } = await useSecuritizeAdmin(props);
100
89
  try {
101
90
  if (!investorExists) {
102
- await writeAndWait(anvil, {
91
+ await anvil.writeContractSync({
103
92
  account,
104
93
  chain: anvil.chain,
105
94
  address: registryService,
106
95
  abi: require_abi_rwa_iDSRegistryService.iDSRegistryServiceAbi,
107
96
  functionName: "registerInvestor",
108
- args: [investorId, investorId]
97
+ args: [investorId, investorId],
98
+ throwOnReceiptRevert: true
109
99
  });
110
100
  logger?.debug(`Registered investor "${investorId}"`);
111
101
  }
112
- await writeAndWait(anvil, {
102
+ await anvil.writeContractSync({
113
103
  account,
114
104
  chain: anvil.chain,
115
105
  address: registryService,
116
106
  abi: require_abi_rwa_iDSRegistryService.iDSRegistryServiceAbi,
117
107
  functionName: "addWallet",
118
- args: [investor, investorId]
108
+ args: [investor, investorId],
109
+ throwOnReceiptRevert: true
119
110
  });
120
111
  logger?.debug(`Added wallet ${investor} for investor "${investorId}"`);
121
112
  try {
122
- await writeAndWait(anvil, {
113
+ await anvil.writeContractSync({
123
114
  account,
124
115
  chain: anvil.chain,
125
116
  address: registryService,
126
117
  abi: require_abi_rwa_iDSRegistryService.iDSRegistryServiceAbi,
127
118
  functionName: "setCountry",
128
- args: [investorId, "US"]
119
+ args: [investorId, "US"],
120
+ throwOnReceiptRevert: true
129
121
  });
130
122
  logger?.debug(`Set country for investor "${investorId}" to "US"`);
131
- await writeAndWait(anvil, {
123
+ await anvil.writeContractSync({
132
124
  account,
133
125
  chain: anvil.chain,
134
126
  address: registryService,
@@ -140,7 +132,8 @@ async function registerSecuritizeInvestor(props) {
140
132
  BigInt(APPROVED),
141
133
  require_onchain_constants_math.MAX_UINT256,
142
134
  "fake proof"
143
- ]
135
+ ],
136
+ throwOnReceiptRevert: true
144
137
  });
145
138
  logger?.debug(`Set attributes for investor "${investorId}"`);
146
139
  } catch (e) {
@@ -242,13 +235,14 @@ async function greenlistMidasGateway(props) {
242
235
  logger?.debug(`midas: ${account} already has role ${role}`);
243
236
  continue;
244
237
  }
245
- await writeAndWait(anvil, {
238
+ await anvil.writeContractSync({
246
239
  account: admin,
247
240
  chain: anvil.chain,
248
241
  address: accessControl,
249
242
  abi: iMidasAccessControlAbi,
250
243
  functionName: "grantRole",
251
- args: [role, account]
244
+ args: [role, account],
245
+ throwOnReceiptRevert: true
252
246
  });
253
247
  logger?.debug(`midas: granted role ${role} to ${account}`);
254
248
  }
@@ -280,7 +274,7 @@ async function findMidasGateway(props) {
280
274
  });
281
275
  await sdk.attach({ marketConfigurators });
282
276
  }
283
- const candidates = collectMidasGateways(sdk);
277
+ const candidates = require_dev_midasUtils.collectMidasGateways(sdk);
284
278
  if (candidates.length === 0) throw new Error("no midas gateway adapters found in loaded markets");
285
279
  const index = (await anvil.multicall({
286
280
  allowFailure: false,
@@ -295,16 +289,6 @@ async function findMidasGateway(props) {
295
289
  return candidates[index];
296
290
  }
297
291
  /**
298
- * Collects the target contracts of all Midas gateway adapters of the loaded
299
- * credit managers, same as the foundry tests do with
300
- * `ICreditConfiguratorV3.allowedAdapters`
301
- */
302
- function collectMidasGateways(sdk) {
303
- const gateways = new require_onchain_utils_AddressSet.AddressSet();
304
- for (const cm of sdk.marketRegister.creditManagers) for (const adapter of cm.creditManager.adapters.values()) if (adapter.contractType === "ADAPTER::MIDAS_GATEWAY") gateways.add(adapter.targetContract);
305
- return gateways.asArray();
306
- }
307
- /**
308
292
  * Registers a wallet as an investor (fake KYC) in every Securitize DSToken and
309
293
  * every Midas gateway of the markets loaded by `sdk`.
310
294
  *
@@ -336,7 +320,7 @@ async function registerRWAInvestor(props) {
336
320
  });
337
321
  }
338
322
  else if (dsTokens.size > 0) logger?.warn(`securitize: no registry admin, skipping ${dsTokens.size} DSToken(s)`);
339
- const gateways = collectMidasGateways(sdk);
323
+ const gateways = require_dev_midasUtils.collectMidasGateways(sdk);
340
324
  for (const gateway of gateways) try {
341
325
  await greenlistMidasGateway({
342
326
  anvil,
@@ -366,4 +350,3 @@ exports.greenlistMidasGateway = greenlistMidasGateway;
366
350
  exports.registerMidasInvestor = registerMidasInvestor;
367
351
  exports.registerRWAInvestor = registerRWAInvestor;
368
352
  exports.registerSecuritizeInvestor = registerSecuritizeInvestor;
369
- exports.writeAndWait = writeAndWait;
@@ -1,5 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_dev_kycUtils = require("./kycUtils.js");
2
+ const require_onchain_utils_AddressSet = require("../onchain/utils/AddressSet.js");
3
+ const require_onchain_market_adapters_contracts_MidasGatewayAdapterContract = require("../onchain/market/adapters/contracts/MidasGatewayAdapterContract.js");
4
+ require("../onchain/index.js");
3
5
  let viem = require("viem");
4
6
  //#region src/dev/midasUtils.ts
5
7
  /**
@@ -10,14 +12,24 @@ const iMidasPausableVaultAbi = (0, viem.parseAbi)([
10
12
  "function paused() external view returns (bool)",
11
13
  "function pause() external",
12
14
  "function unpause() external",
15
+ "function fnPaused(bytes4 fn) external view returns (bool)",
16
+ "function pauseFn(bytes4 fn) external",
17
+ "function unpauseFn(bytes4 fn) external",
13
18
  "function pauseAdminRole() external view returns (bytes32)",
14
19
  "function accessControl() external view returns (address)"
15
20
  ]);
16
21
  const iMidasAccessControlAbi = (0, viem.parseAbi)(["function hasRole(bytes32 role, address account) external view returns (bool)", "function grantRole(bytes32 role, address account) external"]);
17
22
  /**
18
- * Unpauses a globally paused Midas issuance vault on an anvil fork, so that
19
- * `depositInstant` stops reverting with `Pausable: paused`, and returns a
20
- * callback that restores the original pause state.
23
+ * Selector for `DepositVault.depositInstant(address,uint256,uint256,bytes32)`,
24
+ * the 4-arg mint Gearbox adapters encode. Distinct from the custom-recipient
25
+ * overload.
26
+ */
27
+ const DEPOSIT_INSTANT_SELECTOR = (0, viem.toFunctionSelector)("depositInstant(address,uint256,uint256,bytes32)");
28
+ /**
29
+ * Unpauses a Midas issuance vault on an anvil fork so that `depositInstant`
30
+ * stops reverting with `Pausable: paused` (global) or `Pausable: fn paused`
31
+ * (per-selector), and returns a callback that restores the original pause
32
+ * state of each layer that was cleared.
21
33
  *
22
34
  * Impersonates `admin` and grants it `pauseAdminRole()` when missing, same as
23
35
  * `greenlistMidasGateway` does with the greenlist roles. The grant is not
@@ -25,11 +37,20 @@ const iMidasAccessControlAbi = (0, viem.parseAbi)(["function hasRole(bytes32 rol
25
37
  */
26
38
  async function unpauseMidasIssuanceVault(props) {
27
39
  const { anvil, vault, admin, logger } = props;
28
- if (!await anvil.readContract({
29
- address: vault,
30
- abi: iMidasPausableVaultAbi,
31
- functionName: "paused"
32
- })) {
40
+ const [paused, depositInstantPaused] = await anvil.multicall({
41
+ allowFailure: false,
42
+ contracts: [{
43
+ address: vault,
44
+ abi: iMidasPausableVaultAbi,
45
+ functionName: "paused"
46
+ }, {
47
+ address: vault,
48
+ abi: iMidasPausableVaultAbi,
49
+ functionName: "fnPaused",
50
+ args: [DEPOSIT_INSTANT_SELECTOR]
51
+ }]
52
+ });
53
+ if (!paused && !depositInstantPaused) {
33
54
  logger?.debug(`midas: issuance vault ${vault} is not paused`);
34
55
  return async () => {};
35
56
  }
@@ -51,7 +72,7 @@ async function unpauseMidasIssuanceVault(props) {
51
72
  functionName: "hasRole",
52
73
  args: [pauseAdminRole, admin]
53
74
  });
54
- logger?.debug(`midas: unpausing issuance vault ${vault} as ${admin}, access control ${accessControl}, pause admin role ${pauseAdminRole}`);
75
+ logger?.debug(`midas: unpausing issuance vault ${vault} as ${admin}, access control ${accessControl}, pause admin role ${pauseAdminRole}` + (paused ? ", global" : "") + (depositInstantPaused ? ", depositInstant" : ""));
55
76
  await anvil.impersonateAccount({ address: admin });
56
77
  try {
57
78
  await anvil.setBalance({
@@ -59,22 +80,33 @@ async function unpauseMidasIssuanceVault(props) {
59
80
  value: (0, viem.parseEther)("100")
60
81
  });
61
82
  if (!isPauseAdmin) {
62
- await require_dev_kycUtils.writeAndWait(anvil, {
83
+ await anvil.writeContractSync({
63
84
  account: admin,
64
85
  chain: anvil.chain,
65
86
  address: accessControl,
66
87
  abi: iMidasAccessControlAbi,
67
88
  functionName: "grantRole",
68
- args: [pauseAdminRole, admin]
89
+ args: [pauseAdminRole, admin],
90
+ throwOnReceiptRevert: true
69
91
  });
70
92
  logger?.debug(`midas: granted pause admin role to ${admin}`);
71
93
  }
72
- await require_dev_kycUtils.writeAndWait(anvil, {
94
+ if (paused) await anvil.writeContractSync({
95
+ account: admin,
96
+ chain: anvil.chain,
97
+ address: vault,
98
+ abi: iMidasPausableVaultAbi,
99
+ functionName: "unpause",
100
+ throwOnReceiptRevert: true
101
+ });
102
+ if (depositInstantPaused) await anvil.writeContractSync({
73
103
  account: admin,
74
104
  chain: anvil.chain,
75
105
  address: vault,
76
106
  abi: iMidasPausableVaultAbi,
77
- functionName: "unpause"
107
+ functionName: "unpauseFn",
108
+ args: [DEPOSIT_INSTANT_SELECTOR],
109
+ throwOnReceiptRevert: true
78
110
  });
79
111
  } finally {
80
112
  await anvil.stopImpersonatingAccount({ address: admin });
@@ -90,12 +122,22 @@ async function unpauseMidasIssuanceVault(props) {
90
122
  address: admin,
91
123
  value: (0, viem.parseEther)("100")
92
124
  });
93
- await require_dev_kycUtils.writeAndWait(anvil, {
125
+ if (paused) await anvil.writeContractSync({
126
+ account: admin,
127
+ chain: anvil.chain,
128
+ address: vault,
129
+ abi: iMidasPausableVaultAbi,
130
+ functionName: "pause",
131
+ throwOnReceiptRevert: true
132
+ });
133
+ if (depositInstantPaused) await anvil.writeContractSync({
94
134
  account: admin,
95
135
  chain: anvil.chain,
96
136
  address: vault,
97
137
  abi: iMidasPausableVaultAbi,
98
- functionName: "pause"
138
+ functionName: "pauseFn",
139
+ args: [DEPOSIT_INSTANT_SELECTOR],
140
+ throwOnReceiptRevert: true
99
141
  });
100
142
  } catch (e) {
101
143
  logger?.warn(`midas: failed to pause issuance vault ${vault} back: ${e}`);
@@ -104,5 +146,27 @@ async function unpauseMidasIssuanceVault(props) {
104
146
  }
105
147
  };
106
148
  }
149
+ function* midasGatewayAdapters(sdk) {
150
+ for (const cm of sdk.marketRegister.creditManagers) for (const adapter of cm.creditManager.adapters.values()) if (adapter instanceof require_onchain_market_adapters_contracts_MidasGatewayAdapterContract.MidasGatewayAdapterContract) yield adapter;
151
+ }
152
+ /**
153
+ * Target contracts of all Midas gateway adapters of the loaded credit managers,
154
+ * same as the foundry tests do with `ICreditConfiguratorV3.allowedAdapters`
155
+ */
156
+ function collectMidasGateways(sdk) {
157
+ const gateways = new require_onchain_utils_AddressSet.AddressSet();
158
+ for (const adapter of midasGatewayAdapters(sdk)) gateways.add(adapter.targetContract);
159
+ return gateways.asArray();
160
+ }
161
+ /**
162
+ * mTokens of all Midas gateway adapters of the loaded credit managers
163
+ */
164
+ function collectMidasMTokens(sdk) {
165
+ const mTokens = new require_onchain_utils_AddressSet.AddressSet();
166
+ for (const adapter of midasGatewayAdapters(sdk)) mTokens.add(adapter.mToken);
167
+ return mTokens.asArray();
168
+ }
107
169
  //#endregion
170
+ exports.collectMidasGateways = collectMidasGateways;
171
+ exports.collectMidasMTokens = collectMidasMTokens;
108
172
  exports.unpauseMidasIssuanceVault = unpauseMidasIssuanceVault;
@@ -65,7 +65,7 @@ async function issueDSTokens(props) {
65
65
  const { timestamp } = await anvil.getBlock();
66
66
  const issuanceTime = timestamp - lockPeriod - 1n;
67
67
  try {
68
- const hash = await require_dev_kycUtils.writeAndWait(anvil, {
68
+ const receipt = await anvil.writeContractSync({
69
69
  account,
70
70
  chain: anvil.chain,
71
71
  address: token,
@@ -78,14 +78,15 @@ async function issueDSTokens(props) {
78
78
  0n,
79
79
  "",
80
80
  0n
81
- ]
81
+ ],
82
+ throwOnReceiptRevert: true
82
83
  });
83
84
  logger?.debug({
84
85
  issuanceTime,
85
86
  investor,
86
87
  amount
87
88
  }, "issueTokensCustom successful");
88
- return hash;
89
+ return receipt.transactionHash;
89
90
  } catch (e) {
90
91
  logger?.debug(`issueTokensCustom failed: ${e}`);
91
92
  }
@@ -94,14 +95,15 @@ async function issueDSTokens(props) {
94
95
  investor,
95
96
  amount
96
97
  }, "Falling back to issueTokens");
97
- return require_dev_kycUtils.writeAndWait(anvil, {
98
+ return (await anvil.writeContractSync({
98
99
  account,
99
100
  chain: anvil.chain,
100
101
  address: token,
101
102
  abi: require_abi_rwa_iDSToken.iDSTokenAbi,
102
103
  functionName: "issueTokens",
103
- args: [investor, amount]
104
- });
104
+ args: [investor, amount],
105
+ throwOnReceiptRevert: true
106
+ })).transactionHash;
105
107
  }
106
108
  /**
107
109
  * Resolves unique compliance configuration services of `tokens`: several
@@ -161,13 +163,14 @@ async function enableDSTokenBackDating(props) {
161
163
  continue;
162
164
  }
163
165
  logger?.info(`Allowing back-dating on ${service}`);
164
- await require_dev_kycUtils.writeAndWait(anvil, {
166
+ await anvil.writeContractSync({
165
167
  account,
166
168
  chain: anvil.chain,
167
169
  address: service,
168
170
  abi: iDSComplianceConfigurationServiceAbi,
169
171
  functionName: "setDisallowBackDating",
170
- args: [false]
172
+ args: [false],
173
+ throwOnReceiptRevert: true
171
174
  });
172
175
  toRestore.push(service);
173
176
  }
@@ -177,13 +180,14 @@ async function enableDSTokenBackDating(props) {
177
180
  for (const service of services) {
178
181
  logger?.info(`Disallowing back-dating on ${service}`);
179
182
  try {
180
- await require_dev_kycUtils.writeAndWait(anvil, {
183
+ await anvil.writeContractSync({
181
184
  account,
182
185
  chain: anvil.chain,
183
186
  address: service,
184
187
  abi: iDSComplianceConfigurationServiceAbi,
185
188
  functionName: "setDisallowBackDating",
186
- args: [true]
189
+ args: [true],
190
+ throwOnReceiptRevert: true
187
191
  });
188
192
  } catch (e) {
189
193
  logger?.warn(`Failed to restore disallowBackDating on ${service}: ${e}`);
@@ -205,18 +205,15 @@ async function fulfillMidasRedeemer(anvil, redeemer, logger) {
205
205
  address: MIDAS_VAULT_ADMIN,
206
206
  value: (0, viem.parseEther)("100")
207
207
  });
208
- const hash = await anvil.writeContract({
208
+ await anvil.writeContractSync({
209
209
  chain: anvil.chain,
210
210
  address: midasRedemptionVault,
211
211
  account: MIDAS_VAULT_ADMIN,
212
212
  abi: iMidasRedemptionVaultExtAbi,
213
213
  functionName: "safeApproveRequest",
214
- args: [requestId, mTokenRate]
214
+ args: [requestId, mTokenRate],
215
+ throwOnReceiptRevert: true
215
216
  });
216
- if ((await anvil.waitForTransactionReceipt({
217
- hash,
218
- pollingInterval: 100
219
- })).status !== "success") throw new Error(`midas: safeApproveRequest tx ${hash} reverted`);
220
217
  await anvil.stopImpersonatingAccount({ address: MIDAS_VAULT_ADMIN });
221
218
  }
222
219
  /**
@@ -5,6 +5,7 @@ const require_model_errors_operation_errors = require("./operation-errors.js");
5
5
  const require_model_errors_oracle_errors = require("./oracle-errors.js");
6
6
  const require_model_errors_prepare_errors = require("./prepare-errors.js");
7
7
  const require_model_errors_preview_errors = require("./preview-errors.js");
8
+ exports.accountNotMidasGreenlisted = require_model_errors_operation_errors.accountNotMidasGreenlisted;
8
9
  exports.creditAccountFrozen = require_model_errors_liquidation_errors.creditAccountFrozen;
9
10
  exports.creditAccountNotEmpty = require_model_errors_prepare_errors.creditAccountNotEmpty;
10
11
  exports.creditAccountNotFound = require_model_errors_prepare_errors.creditAccountNotFound;
@@ -126,7 +126,16 @@ function rwaOpenRequirementsNotMet(args) {
126
126
  ...args
127
127
  };
128
128
  }
129
+ /** {@inheritDoc AccountNotMidasGreenlistedError} */
130
+ function accountNotMidasGreenlisted(args) {
131
+ return {
132
+ code: "accountNotMidasGreenlisted",
133
+ message: `The credit account is not Midas-greenlisted for ${args.token.symbol}.`,
134
+ ...args
135
+ };
136
+ }
129
137
  //#endregion
138
+ exports.accountNotMidasGreenlisted = accountNotMidasGreenlisted;
130
139
  exports.creditManagerPaused = creditManagerPaused;
131
140
  exports.debtOutOfRange = debtOutOfRange;
132
141
  exports.forbiddenToken = forbiddenToken;
@@ -50,6 +50,7 @@ exports.SECURITIZE_REGISTER_VAULT_TYPES = require_model_rwa.SECURITIZE_REGISTER_
50
50
  exports.STRATEGY_OPPORTUNITY_CHART_METRICS = require_model_charts.STRATEGY_OPPORTUNITY_CHART_METRICS;
51
51
  exports.STRATEGY_POSITION_CHART_METRICS = require_model_charts.STRATEGY_POSITION_CHART_METRICS;
52
52
  exports.STRATEGY_POSITION_COLLATERAL_ERROR = require_model_positions.STRATEGY_POSITION_COLLATERAL_ERROR;
53
+ exports.accountNotMidasGreenlisted = require_model_errors_operation_errors.accountNotMidasGreenlisted;
53
54
  exports.amountSchema = require_model_primitives_schema.amountSchema;
54
55
  exports.analyticsChartQueryOptionsSchema = require_model_analytics_schema.analyticsChartQueryOptionsSchema;
55
56
  exports.analyticsChartQueryParamsSchema = require_model_analytics_schema.analyticsChartQueryParamsSchema;
@@ -0,0 +1,139 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_model_errors_operation_errors = require("../../../model/errors/operation-errors.js");
3
+ const require_model_errors_prepare_errors = require("../../../model/errors/prepare-errors.js");
4
+ require("../../../model/index.js");
5
+ const require_onchain_validation_helpers_token = require("../../validation/helpers/token.js");
6
+ const require_onchain_validation_raise = require("../../validation/raise.js");
7
+ require("../../validation/index.js");
8
+ const require_onchain_accounts_intents_utils_common = require("./utils/common.js");
9
+ const require_onchain_accounts_intents_guards = require("./guards.js");
10
+ const require_onchain_accounts_intents_math = require("./math.js");
11
+ const require_onchain_accounts_intents_utils_credit_account_slice = require("./utils/credit-account-slice.js");
12
+ const require_onchain_accounts_intents_utils_price_impact = require("./utils/price-impact.js");
13
+ const require_onchain_accounts_intents_utils_quotas_for_update = require("./utils/quotas-for-update.js");
14
+ const require_onchain_accounts_intents_utils_router_path = require("./utils/router-path.js");
15
+ require("./utils/index.js");
16
+ //#region src/onchain/accounts/intents/borrow.ts
17
+ /**
18
+ * Builds the state a borrow would leave behind.
19
+ *
20
+ * The debt is named rather than derived: a borrow asks for an amount, where an
21
+ * opening asks for a leverage and lets the collateral decide. Everything the
22
+ * loan pays out leaves the account, so the collateral alone backs it — which
23
+ * is what makes the health factor here a straight function of the two amounts.
24
+ *
25
+ * Produces no operation list, as opening never does: the caller hands the
26
+ * numbers and the calls to `sdk.accounts.openCA`, with `withdrawToken` set to
27
+ * the payout.
28
+ */
29
+ async function buildBorrowState(props) {
30
+ const { sdk, creditManager, collateralAmount, borrowAmount, slippage = 0, quotaReserve, creditAccount: existing } = props;
31
+ const suite = sdk.marketRegister.findCreditManager(creditManager);
32
+ const market = sdk.marketRegister.findByCreditManager(creditManager);
33
+ require_onchain_accounts_intents_guards.assertMarketOperable(suite);
34
+ const underlying = market.pool.underlying.toLowerCase();
35
+ const collateralToken = props.collateralToken.toLowerCase();
36
+ const borrowToken = props.borrowToken.toLowerCase();
37
+ const convert = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value;
38
+ if (require_onchain_accounts_intents_utils_common.eq(collateralToken, borrowToken)) throw new require_onchain_validation_raise.IntentPreviewError(require_model_errors_prepare_errors.unsupportedCollateralToken(require_onchain_validation_helpers_token.toToken(sdk, collateralToken)), "borrow: the payout token cannot also be the collateral");
39
+ const rwaAsset = sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset?.toLowerCase();
40
+ const unwrapsPayout = !!rwaAsset && require_onchain_accounts_intents_utils_common.eq(borrowToken, rwaAsset);
41
+ if (rwaAsset && require_onchain_accounts_intents_utils_common.eq(borrowToken, underlying)) throw new require_onchain_validation_raise.IntentPreviewError(require_model_errors_prepare_errors.unsupportedCollateralToken(require_onchain_validation_helpers_token.toToken(sdk, borrowToken)), `borrow: ${underlying} cannot leave the account, ask for the payout in ${rwaAsset}`);
42
+ if (collateralAmount <= 0n) throw new require_onchain_validation_raise.IntentPreviewError(require_model_errors_operation_errors.insufficientBalance(), "borrow: no collateral supplied");
43
+ if (borrowAmount <= 0n) throw new require_onchain_validation_raise.IntentPreviewError(require_model_errors_operation_errors.insufficientBalance(), "borrow: nothing to borrow");
44
+ const margin = convert(collateralToken, underlying, collateralAmount);
45
+ if (margin <= 0n) throw new require_onchain_validation_raise.IntentPreviewError(require_model_errors_operation_errors.insufficientBalance(), "borrow: collateral is worth nothing in underlying");
46
+ const debt = require_onchain_accounts_intents_utils_common.eq(borrowToken, underlying) ? borrowAmount : unwrapsPayout ? require_onchain_accounts_intents_utils_common.toTargetDecimals(borrowAmount, borrowToken, underlying, sdk) : convert(borrowToken, underlying, borrowAmount);
47
+ require_onchain_accounts_intents_math.assertDebtLimits(sdk, debt, suite.creditFacade, underlying);
48
+ require_onchain_accounts_intents_guards.assertCanBorrow(sdk, suite, debt);
49
+ const account = existing ?? require_onchain_accounts_intents_utils_credit_account_slice.unopenedAccountSlice({
50
+ creditManager,
51
+ creditFacade: suite.creditFacade.address,
52
+ underlying
53
+ });
54
+ const leg = require_onchain_accounts_intents_utils_common.eq(borrowToken, underlying) || unwrapsPayout ? void 0 : await require_onchain_accounts_intents_utils_router_path.createRouterPaths({
55
+ sdk,
56
+ creditAccount: account,
57
+ slippage
58
+ }).swap({
59
+ tokenIn: underlying,
60
+ tokenOut: borrowToken,
61
+ amount: debt,
62
+ keep: require_onchain_accounts_intents_utils_common.eq(collateralToken, underlying) ? collateralAmount : 0n
63
+ });
64
+ const unwrap = unwrapsPayout ? await sdk.accounts.assembleRWAUnwrapCalls(debt, creditManager) : void 0;
65
+ if (unwrapsPayout && !unwrap) throw new Error(`borrow: no unwrap calls found for ${borrowToken}`);
66
+ const assets = [{
67
+ token: collateralToken,
68
+ balance: collateralAmount
69
+ }];
70
+ const quotaIncrease = borrowCollateralQuota({
71
+ sdk,
72
+ creditManager,
73
+ assets,
74
+ quotaReserve
75
+ });
76
+ require_onchain_accounts_intents_guards.assertGrowthAllowed({
77
+ sdk,
78
+ suite,
79
+ market,
80
+ before: [],
81
+ after: assets
82
+ });
83
+ require_onchain_accounts_intents_guards.assertQuotaAvailable(sdk, market, quotaIncrease);
84
+ const snapshot = {
85
+ creditManager,
86
+ assets,
87
+ quotas: quotaIncrease,
88
+ totalDebt: debt,
89
+ totalValue: margin
90
+ };
91
+ const projection = sdk.positions.projection(snapshot, { availableLiquidityChange: -debt });
92
+ require_onchain_accounts_intents_guards.assertCollateralised(projection.safeHealthFactor, true);
93
+ const priced = (token, balance) => market.priceOracle.toTokenAmount(token, balance);
94
+ const payout = unwrapsPayout ? require_onchain_accounts_intents_utils_common.toTargetDecimals(debt, underlying, borrowToken, sdk) : leg ? leg.amount : debt;
95
+ return {
96
+ ...projection,
97
+ currentPrice: sdk.positions.currentPrice(snapshot),
98
+ executionCost: void 0,
99
+ priceImpact: await require_onchain_accounts_intents_utils_price_impact.collectPriceImpact(leg?.probe ? [leg.probe] : [], {
100
+ totalValue: margin,
101
+ netValue: margin - debt,
102
+ toUnderlying: (from, amount) => convert(from, underlying, amount)
103
+ }),
104
+ collateral: priced(collateralToken, collateralAmount),
105
+ borrowed: priced(borrowToken, payout),
106
+ minBorrowed: priced(borrowToken, leg ? leg.minAmount : payout),
107
+ slippage,
108
+ quotaIncrease,
109
+ calls: leg ? [...leg.calls] : unwrap ?? [],
110
+ creditAccount: existing?.creditAccount
111
+ };
112
+ }
113
+ /**
114
+ * Quota a borrow buys for its collateral on an account that holds none yet.
115
+ *
116
+ * Shared with `maxBorrow`, because a quota short of the collateral's weighted
117
+ * value is what caps the loan: the two have to read the same number or the
118
+ * ceiling one offers is one the other refuses.
119
+ *
120
+ * @param props - {@link BorrowCollateralQuotaProps}
121
+ **/
122
+ function borrowCollateralQuota({ sdk, creditManager, assets, quotaReserve }) {
123
+ const suite = sdk.marketRegister.findCreditManager(creditManager);
124
+ const market = sdk.marketRegister.findByCreditManager(creditManager);
125
+ return require_onchain_accounts_intents_utils_quotas_for_update.getQuotasForUpdate({
126
+ assetsBefore: [],
127
+ assetsAfter: assets,
128
+ initialQuotas: [],
129
+ quotaReserve,
130
+ underlyingToken: market.pool.underlying,
131
+ liquidationThresholds: suite.creditManager.liquidationThresholds,
132
+ quotas: market.pool.pqk.quotas,
133
+ maxDebt: suite.creditFacade.maxDebt,
134
+ convert: (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value
135
+ }).quotaIncrease;
136
+ }
137
+ //#endregion
138
+ exports.borrowCollateralQuota = borrowCollateralQuota;
139
+ exports.buildBorrowState = buildBorrowState;
@@ -3,9 +3,9 @@ const require_onchain_utils_bigint_math = require("../../utils/bigint-math.js");
3
3
  const require_onchain_constants_math = require("../../constants/math.js");
4
4
  require("../../utils/index.js");
5
5
  const require_onchain_accounts_intents_utils_common = require("./utils/common.js");
6
- //#region src/onchain/accounts/intents/collateral-money.ts
7
- /** {@inheritDoc CollateralMoney} */
8
- function collateralMoney(creditAccount, sdk) {
6
+ //#region src/onchain/accounts/intents/collateral-valuation.ts
7
+ /** {@inheritDoc CollateralValuation} */
8
+ function collateralValuation(creditAccount, sdk) {
9
9
  const { market, creditManager } = sdk.marketRegister.findCreditManager(creditAccount.creditManager);
10
10
  const { priceOracle } = market;
11
11
  const { pqk } = market.pool;
@@ -21,21 +21,21 @@ function collateralMoney(creditAccount, sdk) {
21
21
  const lt = (token) => BigInt(creditManager.liquidationThresholds.get(token) ?? 0);
22
22
  const checkedUsd = (holding) => require_onchain_accounts_intents_utils_common.eq(holding.token, underlying) ? mainUsd(holding.token, holding.balance) ?? 0n : priceOracle.safeConvertMinUSD(holding.token, holding.balance).value;
23
23
  /** A quota is underlying-denominated, and a closed market backs nothing. */
24
- const quotaMoney = (holding) => pqk.hasActiveQuota(holding.token) ? (mainUsd(underlying, holding.quota) ?? 0n) * require_onchain_constants_math.PERCENTAGE_FACTOR : 0n;
24
+ const quotaValue = (holding) => pqk.hasActiveQuota(holding.token) ? (mainUsd(underlying, holding.quota) ?? 0n) * require_onchain_constants_math.PERCENTAGE_FACTOR : 0n;
25
25
  const weigh = (holding) => {
26
26
  const weighted = checkedUsd(holding) * lt(holding.token);
27
27
  if (holding.quota === 0n) return weighted;
28
- return require_onchain_utils_bigint_math.BigIntMath.min(quotaMoney(holding), weighted);
28
+ return require_onchain_utils_bigint_math.BigIntMath.min(quotaValue(holding), weighted);
29
29
  };
30
30
  return {
31
31
  underlying,
32
32
  counts: (holding) => holding.balance > 10n && (!masked || (holding.mask & creditAccount.enabledTokensMask) !== 0n),
33
33
  weigh,
34
- quotaMoney,
34
+ quotaValue,
35
35
  mainUsd,
36
36
  checkedUsd,
37
37
  lt
38
38
  };
39
39
  }
40
40
  //#endregion
41
- exports.collateralMoney = collateralMoney;
41
+ exports.collateralValuation = collateralValuation;