@mento-protocol/mento-sdk 3.2.0 → 3.2.1

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.
@@ -11,16 +11,18 @@ const borrowTransactionService_1 = require("./internal/borrowTransactionService"
11
11
  * handle interest rates and batch managers, and query position data.
12
12
  *
13
13
  * All `build*` methods return `CallParams` ({ to, data, value }) that can be
14
- * executed with any wallet client. The `debtTokenSymbol` parameter (e.g., 'USDm')
14
+ * executed with any wallet client. The `debtTokenSymbol` parameter (e.g., 'GBPm')
15
15
  * identifies which borrowing deployment to interact with.
16
16
  *
17
17
  * @example
18
18
  * ```typescript
19
19
  * const mento = await Mento.create(ChainId.CELO)
20
20
  *
21
+ * const ownerIndex = await mento.borrow.findNextAvailableOwnerIndex('GBPm', '0x...', '0x...')
22
+ *
21
23
  * // Open a trove
22
- * const tx = await mento.borrow.buildOpenTroveTransaction('USDm', {
23
- * owner: '0x...', ownerIndex: 0,
24
+ * const tx = await mento.borrow.buildOpenTroveTransaction('GBPm', {
25
+ * owner: '0x...', ownerIndex,
24
26
  * collAmount: parseUnits('10', 18),
25
27
  * boldAmount: parseUnits('1000', 18),
26
28
  * annualInterestRate: parseUnits('0.05', 18),
@@ -40,7 +42,7 @@ class BorrowService {
40
42
  * Builds a transaction to open a new trove (borrowing position).
41
43
  * Requires prior collateral approval via `buildCollateralApprovalParams`.
42
44
  *
43
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
45
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
44
46
  * @param params - Trove opening parameters including collateral, debt amount, and interest rate
45
47
  * @returns Transaction parameters ready to send
46
48
  */
@@ -50,7 +52,7 @@ class BorrowService {
50
52
  /**
51
53
  * Builds a transaction to adjust an existing trove's collateral and/or debt.
52
54
  *
53
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
55
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
54
56
  * @param params - Adjustment parameters specifying collateral/debt changes
55
57
  * @returns Transaction parameters ready to send
56
58
  */
@@ -58,10 +60,13 @@ class BorrowService {
58
60
  return this.withContext(debtTokenSymbol, (ctx) => this.txService.buildAdjustTroveTransaction(ctx, params));
59
61
  }
60
62
  /**
61
- * Builds a transaction to adjust a zombie trove (a trove that fell below minimum debt
62
- * after a liquidation). Same parameters as `buildAdjustTroveTransaction`.
63
+ * Builds a transaction to adjust a zombie trove. Zombie troves are still-open troves whose
64
+ * debt fell below the branch minimum debt, typically after a redemption.
65
+ *
66
+ * Use this when `getTroveData()` or `getUserTroves()` returns `status === 'zombie'`.
67
+ * Same parameters as `buildAdjustTroveTransaction`.
63
68
  *
64
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
69
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
65
70
  * @param params - Adjustment parameters specifying collateral/debt changes
66
71
  * @returns Transaction parameters ready to send
67
72
  */
@@ -71,7 +76,7 @@ class BorrowService {
71
76
  /**
72
77
  * Builds a transaction to close a trove, repaying all debt and reclaiming collateral.
73
78
  *
74
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
79
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
75
80
  * @param troveId - The NFT token ID identifying the trove
76
81
  * @returns Transaction parameters ready to send
77
82
  */
@@ -82,7 +87,7 @@ class BorrowService {
82
87
  * Builds a transaction to add collateral to an existing trove.
83
88
  * Requires prior collateral approval via `buildCollateralApprovalParams`.
84
89
  *
85
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
90
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
86
91
  * @param troveId - The NFT token ID identifying the trove
87
92
  * @param amount - Amount of collateral to add (in wei)
88
93
  * @returns Transaction parameters ready to send
@@ -93,7 +98,7 @@ class BorrowService {
93
98
  /**
94
99
  * Builds a transaction to withdraw collateral from an existing trove.
95
100
  *
96
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
101
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
97
102
  * @param troveId - The NFT token ID identifying the trove
98
103
  * @param amount - Amount of collateral to withdraw (in wei)
99
104
  * @returns Transaction parameters ready to send
@@ -104,7 +109,7 @@ class BorrowService {
104
109
  /**
105
110
  * Builds a transaction to borrow additional debt against an existing trove.
106
111
  *
107
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
112
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
108
113
  * @param troveId - The NFT token ID identifying the trove
109
114
  * @param amount - Additional debt amount to borrow (in wei)
110
115
  * @param maxFee - Maximum upfront fee the borrower is willing to pay (in wei)
@@ -116,7 +121,7 @@ class BorrowService {
116
121
  /**
117
122
  * Builds a transaction to repay debt on an existing trove.
118
123
  *
119
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
124
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
120
125
  * @param troveId - The NFT token ID identifying the trove
121
126
  * @param amount - Amount of debt to repay (in wei)
122
127
  * @returns Transaction parameters ready to send
@@ -127,7 +132,7 @@ class BorrowService {
127
132
  /**
128
133
  * Builds a transaction to change the annual interest rate on a trove.
129
134
  *
130
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
135
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
131
136
  * @param troveId - The NFT token ID identifying the trove
132
137
  * @param newRate - New annual interest rate (18-decimal fixed-point, e.g., parseUnits('0.05', 18) for 5%)
133
138
  * @param maxFee - Maximum upfront fee the borrower is willing to pay (in wei)
@@ -138,8 +143,10 @@ class BorrowService {
138
143
  }
139
144
  /**
140
145
  * Builds a transaction to claim collateral surplus after a liquidation.
146
+ * This is for collateral held in the surplus pool after `closedByLiquidation`.
147
+ * Zombie troves with remaining collateral should usually be closed or adjusted instead.
141
148
  *
142
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
149
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
143
150
  * @returns Transaction parameters ready to send
144
151
  */
145
152
  buildClaimCollateralTransaction(debtTokenSymbol) {
@@ -148,7 +155,7 @@ class BorrowService {
148
155
  /**
149
156
  * Builds a transaction to delegate interest rate management to a batch manager.
150
157
  *
151
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
158
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
152
159
  * @param troveId - The NFT token ID identifying the trove
153
160
  * @param manager - Address of the batch manager contract
154
161
  * @param maxFee - Maximum upfront fee the borrower is willing to pay (in wei)
@@ -160,7 +167,7 @@ class BorrowService {
160
167
  /**
161
168
  * Builds a transaction to remove a trove from a batch manager, setting a new individual rate.
162
169
  *
163
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
170
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
164
171
  * @param troveId - The NFT token ID identifying the trove
165
172
  * @param newRate - New individual annual interest rate (18-decimal fixed-point)
166
173
  * @param maxFee - Maximum upfront fee the borrower is willing to pay (in wei)
@@ -172,7 +179,7 @@ class BorrowService {
172
179
  /**
173
180
  * Builds a transaction to switch a trove to a different batch manager.
174
181
  *
175
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
182
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
176
183
  * @param troveId - The NFT token ID identifying the trove
177
184
  * @param newManager - Address of the new batch manager contract
178
185
  * @param maxFee - Maximum upfront fee the borrower is willing to pay (in wei)
@@ -185,7 +192,7 @@ class BorrowService {
185
192
  * Builds a transaction to delegate interest rate management to another address
186
193
  * with bounded rate constraints.
187
194
  *
188
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
195
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
189
196
  * @param troveId - The NFT token ID identifying the trove
190
197
  * @param delegate - Address to delegate interest rate management to
191
198
  * @param minRate - Minimum allowed annual interest rate (18-decimal fixed-point)
@@ -201,7 +208,7 @@ class BorrowService {
201
208
  /**
202
209
  * Builds a transaction to remove the interest rate delegate from a trove.
203
210
  *
204
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
211
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
205
212
  * @param troveId - The NFT token ID identifying the trove
206
213
  * @returns Transaction parameters ready to send
207
214
  */
@@ -212,7 +219,7 @@ class BorrowService {
212
219
  * Builds approval params to allow BorrowerOperations to spend collateral tokens.
213
220
  * Must be executed before `buildOpenTroveTransaction` or `buildAddCollTransaction`.
214
221
  *
215
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
222
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
216
223
  * @param amount - Amount of collateral to approve (in wei)
217
224
  * @returns Transaction parameters for the ERC-20 approve call
218
225
  */
@@ -222,7 +229,7 @@ class BorrowService {
222
229
  /**
223
230
  * Builds approval params for the debt token (e.g., for repayment or closing).
224
231
  *
225
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
232
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
226
233
  * @param spender - Address to approve as spender
227
234
  * @param amount - Amount of debt tokens to approve (in wei)
228
235
  * @returns Transaction parameters for the ERC-20 approve call
@@ -233,7 +240,7 @@ class BorrowService {
233
240
  /**
234
241
  * Builds approval params for the gas compensation token (required when opening a trove).
235
242
  *
236
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
243
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
237
244
  * @param amount - Amount to approve (in wei). If omitted, approves the gas compensation amount.
238
245
  * @returns Transaction parameters for the ERC-20 approve call
239
246
  */
@@ -243,7 +250,7 @@ class BorrowService {
243
250
  /**
244
251
  * Gets the current collateral token allowance for BorrowerOperations.
245
252
  *
246
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
253
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
247
254
  * @param owner - Address to check allowance for
248
255
  * @returns Current allowance in wei
249
256
  */
@@ -253,7 +260,7 @@ class BorrowService {
253
260
  /**
254
261
  * Gets the current debt token allowance for a specific spender.
255
262
  *
256
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
263
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
257
264
  * @param owner - Address to check allowance for
258
265
  * @param spender - Address of the approved spender
259
266
  * @returns Current allowance in wei
@@ -264,7 +271,7 @@ class BorrowService {
264
271
  /**
265
272
  * Gets the current gas compensation token allowance.
266
273
  *
267
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
274
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
268
275
  * @param owner - Address to check allowance for
269
276
  * @returns Current allowance in wei
270
277
  */
@@ -273,8 +280,10 @@ class BorrowService {
273
280
  }
274
281
  /**
275
282
  * Fetches on-chain data for a specific trove.
283
+ * The returned position reflects the trove's current lifecycle status, including
284
+ * zombie troves that may still hold collateral even when their debt is zero.
276
285
  *
277
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
286
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
278
287
  * @param troveId - The NFT token ID identifying the trove
279
288
  * @returns Trove position data including collateral, debt, interest rate, and status
280
289
  */
@@ -282,11 +291,14 @@ class BorrowService {
282
291
  return this.withContext(debtTokenSymbol, (ctx) => this.readService.getTroveData(ctx, troveId));
283
292
  }
284
293
  /**
285
- * Fetches all troves owned by an address.
294
+ * Fetches troves currently owned by an address via the Trove NFT.
295
+ * This includes zombie troves that have been removed from `SortedTroves` but are still owned
296
+ * by the address. Closed or liquidated troves are not returned once their Trove NFT is burned
297
+ * or transferred away.
286
298
  *
287
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
299
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
288
300
  * @param owner - Address to query troves for
289
- * @returns Array of trove positions owned by the address
301
+ * @returns Array of trove positions currently owned by the address
290
302
  */
291
303
  getUserTroves(debtTokenSymbol, owner) {
292
304
  return this.withContext(debtTokenSymbol, (ctx) => this.readService.getUserTroves(ctx, owner));
@@ -294,7 +306,7 @@ class BorrowService {
294
306
  /**
295
307
  * Gets the current collateral token price from the price feed.
296
308
  *
297
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
309
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
298
310
  * @returns Collateral price in 18-decimal fixed-point format
299
311
  */
300
312
  getCollateralPrice(debtTokenSymbol) {
@@ -304,7 +316,7 @@ class BorrowService {
304
316
  * Gets the system parameters for a borrowing deployment.
305
317
  * Returns MCR, CCR, SCR, BCR, minimum debt, gas compensation, and minimum interest rate.
306
318
  *
307
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
319
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
308
320
  * @returns System parameters (all values in 18-decimal fixed-point)
309
321
  */
310
322
  getSystemParams(debtTokenSymbol) {
@@ -313,7 +325,7 @@ class BorrowService {
313
325
  /**
314
326
  * Checks whether the borrowing system has been shut down (e.g., during a crisis).
315
327
  *
316
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
328
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
317
329
  * @returns true if the system is shut down, false otherwise
318
330
  */
319
331
  isSystemShutDown(debtTokenSymbol) {
@@ -322,7 +334,7 @@ class BorrowService {
322
334
  /**
323
335
  * Gets aggregate collateral and debt statistics for the borrowing branch.
324
336
  *
325
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
337
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
326
338
  * @returns Total collateral and total debt across all troves (in wei)
327
339
  */
328
340
  getBranchStats(debtTokenSymbol) {
@@ -331,7 +343,7 @@ class BorrowService {
331
343
  /**
332
344
  * Gets the distribution of debt across interest rate brackets.
333
345
  *
334
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
346
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
335
347
  * @returns Array of brackets, each with a rate and total debt at that rate
336
348
  */
337
349
  getInterestRateBrackets(debtTokenSymbol) {
@@ -340,7 +352,7 @@ class BorrowService {
340
352
  /**
341
353
  * Gets the weighted average interest rate across all active troves.
342
354
  *
343
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
355
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
344
356
  * @returns Average annual interest rate in 18-decimal fixed-point
345
357
  */
346
358
  getAverageInterestRate(debtTokenSymbol) {
@@ -349,7 +361,7 @@ class BorrowService {
349
361
  /**
350
362
  * Gets information about a batch manager's configuration.
351
363
  *
352
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
364
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
353
365
  * @param address - Address of the batch manager
354
366
  * @returns Batch manager config (min/max rate, min change period), or null if not a valid manager
355
367
  */
@@ -359,7 +371,7 @@ class BorrowService {
359
371
  /**
360
372
  * Estimates the upfront fee for opening a new trove.
361
373
  *
362
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
374
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
363
375
  * @param amount - Debt amount to borrow (in wei)
364
376
  * @param rate - Annual interest rate (18-decimal fixed-point)
365
377
  * @returns Estimated upfront fee in wei
@@ -370,7 +382,7 @@ class BorrowService {
370
382
  /**
371
383
  * Estimates the upfront fee for increasing debt on an existing trove.
372
384
  *
373
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
385
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
374
386
  * @param troveId - The NFT token ID identifying the trove
375
387
  * @param debtIncrease - Amount of additional debt (in wei)
376
388
  * @returns Estimated upfront fee in wei
@@ -381,7 +393,7 @@ class BorrowService {
381
393
  /**
382
394
  * Estimates the upfront fee for changing a trove's interest rate.
383
395
  *
384
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
396
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
385
397
  * @param troveId - The NFT token ID identifying the trove
386
398
  * @param newRate - New annual interest rate (18-decimal fixed-point)
387
399
  * @returns Estimated upfront fee in wei
@@ -392,7 +404,7 @@ class BorrowService {
392
404
  /**
393
405
  * Estimates the upfront fee for joining a batch manager.
394
406
  *
395
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
407
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
396
408
  * @param troveId - The NFT token ID identifying the trove
397
409
  * @param batchAddress - Address of the batch manager to join
398
410
  * @returns Estimated upfront fee in wei
@@ -401,15 +413,40 @@ class BorrowService {
401
413
  return this.withContext(debtTokenSymbol, (ctx) => this.readService.predictJoinBatchUpfrontFee(ctx, troveId, batchAddress));
402
414
  }
403
415
  /**
404
- * Gets the next available owner index for opening a new trove.
405
- * Each owner can have multiple troves, indexed starting from 0.
416
+ * Gets the current number of troves owned by an address via the Trove NFT.
417
+ *
418
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
419
+ * @param owner - Address of the trove owner
420
+ * @returns The number of troves currently owned by the address
421
+ */
422
+ getOwnedTroveCount(debtTokenSymbol, owner) {
423
+ return this.withContext(debtTokenSymbol, (ctx) => this.readService.getOwnedTroveCount(ctx, owner));
424
+ }
425
+ /**
426
+ * Finds the first safe owner index for opening a trove with the given transaction sender.
427
+ *
428
+ * The `opener` must be the address that will call BorrowerOperations on-chain.
429
+ * For smart accounts, pass the smart account address rather than the controlling EOA.
430
+ *
431
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
432
+ * @param owner - Address that will own the trove NFT
433
+ * @param opener - Address that will submit the open-trove transaction on-chain
434
+ * @returns The first owner index that does not already map to an existing trove
435
+ */
436
+ findNextAvailableOwnerIndex(debtTokenSymbol, owner, opener) {
437
+ return this.withContext(debtTokenSymbol, (ctx) => this.readService.findNextAvailableOwnerIndex(ctx, owner, opener));
438
+ }
439
+ /**
440
+ * Gets the current number of troves owned by an address via the Trove NFT.
441
+ *
442
+ * @deprecated Use `findNextAvailableOwnerIndex` when preparing an open-trove transaction.
406
443
  *
407
- * @param debtTokenSymbol - The debt token symbol (e.g., 'USDm')
444
+ * @param debtTokenSymbol - The debt token symbol (e.g., 'GBPm')
408
445
  * @param owner - Address of the trove owner
409
- * @returns The next available index (pass to OpenTroveParams.ownerIndex)
446
+ * @returns The number of troves currently owned by the address
410
447
  */
411
448
  getNextOwnerIndex(debtTokenSymbol, owner) {
412
- return this.withContext(debtTokenSymbol, (ctx) => this.readService.getNextOwnerIndex(ctx, owner));
449
+ return this.withContext(debtTokenSymbol, (ctx) => this.readService.getOwnedTroveCount(ctx, owner));
413
450
  }
414
451
  async withContext(debtTokenSymbol, callback) {
415
452
  const ctx = await this.ensureInitialized(debtTokenSymbol);
@@ -9,5 +9,13 @@ export declare function calculateDebtSuggestions(maxDebt: bigint, minDebt: bigin
9
9
  ltv: bigint;
10
10
  risk: RiskLevel;
11
11
  }[];
12
+ /**
13
+ * Computes collateralization metrics from the supplied collateral, debt, price, and MCR.
14
+ *
15
+ * This helper is lifecycle-agnostic: it does not inspect trove status. For example, a zombie
16
+ * trove with `debt === 0` may still hold collateral on-chain, but this function only reports
17
+ * the math implied by the inputs. Combine its output with `BorrowPosition.status` when building
18
+ * UI for open, zombie, closed, or liquidated troves.
19
+ */
12
20
  export declare function getLoanDetails(collateral: bigint | null, debt: bigint | null, interestRate: bigint | null, collPrice: bigint | null, mcr: bigint): LoanDetails;
13
21
  //# sourceMappingURL=borrowMath.d.ts.map
@@ -80,6 +80,14 @@ function calculateDebtSuggestions(maxDebt, minDebt) {
80
80
  }
81
81
  return suggestions;
82
82
  }
83
+ /**
84
+ * Computes collateralization metrics from the supplied collateral, debt, price, and MCR.
85
+ *
86
+ * This helper is lifecycle-agnostic: it does not inspect trove status. For example, a zombie
87
+ * trove with `debt === 0` may still hold collateral on-chain, but this function only reports
88
+ * the math implied by the inputs. Combine its output with `BorrowPosition.status` when building
89
+ * UI for open, zombie, closed, or liquidated troves.
90
+ */
83
91
  function getLoanDetails(collateral, debt, interestRate, collPrice, mcr) {
84
92
  // maxLtv = 1 / MCR (MCR is e.g. 1.1e18 meaning 110%)
85
93
  const maxLtv = (DECIMAL_PRECISION * DECIMAL_PRECISION) / mcr;
@@ -23,6 +23,8 @@ export declare class BorrowReadService {
23
23
  predictAdjustUpfrontFee(ctx: DeploymentContext, troveId: string, debtIncrease: bigint): Promise<bigint>;
24
24
  predictAdjustInterestRateUpfrontFee(ctx: DeploymentContext, troveId: string, newRate: bigint): Promise<bigint>;
25
25
  predictJoinBatchUpfrontFee(ctx: DeploymentContext, troveId: string, batchAddress: string): Promise<bigint>;
26
+ getOwnedTroveCount(ctx: DeploymentContext, owner: string): Promise<number>;
27
+ findNextAvailableOwnerIndex(ctx: DeploymentContext, owner: string, opener: string): Promise<number>;
26
28
  getNextOwnerIndex(ctx: DeploymentContext, owner: string): Promise<number>;
27
29
  private readContractsInChunks;
28
30
  }
@@ -9,6 +9,7 @@ const borrowValidation_1 = require("./borrowValidation");
9
9
  const TROVE_ID_BATCH_SIZE = 64;
10
10
  const TROVE_OWNER_BATCH_SIZE = 64;
11
11
  const TROVE_DETAIL_BATCH_SIZE = 64;
12
+ const OWNER_INDEX_PROBE_BATCH_SIZE = 64;
12
13
  class BorrowReadService {
13
14
  constructor(publicClient) {
14
15
  this.publicClient = publicClient;
@@ -33,6 +34,10 @@ class BorrowReadService {
33
34
  }
34
35
  async getUserTroves(ctx, owner) {
35
36
  const ownerAddress = (0, borrowValidation_1.requireAddress)(owner, 'owner');
37
+ const ownedTroveCount = await this.getOwnedTroveCount(ctx, ownerAddress);
38
+ if (ownedTroveCount === 0) {
39
+ return [];
40
+ }
36
41
  const troveCount = (await this.publicClient.readContract({
37
42
  address: ctx.addresses.troveManager,
38
43
  abi: abis_1.TROVE_MANAGER_ABI,
@@ -212,7 +217,7 @@ class BorrowReadService {
212
217
  args: [constants_1.COLL_INDEX, parsedTroveId, managerAddress],
213
218
  }));
214
219
  }
215
- async getNextOwnerIndex(ctx, owner) {
220
+ async getOwnedTroveCount(ctx, owner) {
216
221
  const ownerAddress = (0, borrowValidation_1.requireAddress)(owner, 'owner');
217
222
  const ownerTroveCount = (await this.publicClient.readContract({
218
223
  address: ctx.addresses.troveNFT,
@@ -225,6 +230,30 @@ class BorrowReadService {
225
230
  }
226
231
  return Number(ownerTroveCount);
227
232
  }
233
+ async findNextAvailableOwnerIndex(ctx, owner, opener) {
234
+ const ownerAddress = (0, borrowValidation_1.requireAddress)(owner, 'owner');
235
+ const openerAddress = (0, borrowValidation_1.requireAddress)(opener, 'opener');
236
+ let candidateIndex = await this.getOwnedTroveCount(ctx, ownerAddress);
237
+ while (candidateIndex <= Number.MAX_SAFE_INTEGER) {
238
+ const batchIndices = Array.from({ length: Math.min(OWNER_INDEX_PROBE_BATCH_SIZE, Number.MAX_SAFE_INTEGER - candidateIndex + 1) }, (_, offset) => candidateIndex + offset);
239
+ const statusContracts = batchIndices.map((ownerIndex) => ({
240
+ address: ctx.addresses.troveManager,
241
+ abi: abis_1.TROVE_MANAGER_ABI,
242
+ functionName: 'getTroveStatus',
243
+ args: [(0, borrowValidation_1.deriveTroveId)(openerAddress, ownerAddress, ownerIndex)],
244
+ }));
245
+ const statuses = await this.readContractsInChunks(statusContracts, OWNER_INDEX_PROBE_BATCH_SIZE);
246
+ const availableOffset = statuses.findIndex((status) => status === 0 || status === 0n);
247
+ if (availableOffset !== -1) {
248
+ return batchIndices[availableOffset];
249
+ }
250
+ candidateIndex += batchIndices.length;
251
+ }
252
+ throw new Error('Next available owner index exceeds Number.MAX_SAFE_INTEGER');
253
+ }
254
+ async getNextOwnerIndex(ctx, owner) {
255
+ return this.getOwnedTroveCount(ctx, owner);
256
+ }
228
257
  async readContractsInChunks(contracts, chunkSize) {
229
258
  if (contracts.length === 0) {
230
259
  return [];
@@ -5,6 +5,7 @@ export declare function requireAddress(address: string, fieldName: string): Addr
5
5
  export declare function optionalAddressOrZero(value: string | undefined, fieldName: string): Address;
6
6
  export declare function parseTroveId(troveId: string): bigint;
7
7
  export declare function formatTroveId(troveId: bigint): string;
8
+ export declare function deriveTroveId(opener: string, owner: string, ownerIndex: number): bigint;
8
9
  export declare function requireNonNegativeInteger(value: number, fieldName: string): number;
9
10
  export declare function requireNonNegativeBigInt(value: bigint, fieldName: string): bigint;
10
11
  export declare function requirePositiveBigInt(value: bigint, fieldName: string): bigint;
@@ -6,6 +6,7 @@ exports.requireAddress = requireAddress;
6
6
  exports.optionalAddressOrZero = optionalAddressOrZero;
7
7
  exports.parseTroveId = parseTroveId;
8
8
  exports.formatTroveId = formatTroveId;
9
+ exports.deriveTroveId = deriveTroveId;
9
10
  exports.requireNonNegativeInteger = requireNonNegativeInteger;
10
11
  exports.requireNonNegativeBigInt = requireNonNegativeBigInt;
11
12
  exports.requirePositiveBigInt = requirePositiveBigInt;
@@ -15,6 +16,7 @@ const viem_1 = require("viem");
15
16
  const validation_1 = require("../../../utils/validation");
16
17
  const UINT128_MAX = (1n << 128n) - 1n;
17
18
  exports.MAX_SAFE_INTEGER_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
19
+ const TROVE_ID_PARAMETERS = (0, viem_1.parseAbiParameters)('address opener, address owner, uint256 ownerIndex');
18
20
  function requireDebtTokenSymbol(symbol) {
19
21
  if (typeof symbol !== 'string' || symbol.trim().length === 0) {
20
22
  throw new Error('debtTokenSymbol must be a non-empty string');
@@ -49,6 +51,12 @@ function parseTroveId(troveId) {
49
51
  function formatTroveId(troveId) {
50
52
  return `0x${troveId.toString(16)}`;
51
53
  }
54
+ function deriveTroveId(opener, owner, ownerIndex) {
55
+ const openerAddress = (0, viem_1.getAddress)(requireAddress(opener, 'opener'));
56
+ const ownerAddress = (0, viem_1.getAddress)(requireAddress(owner, 'owner'));
57
+ const validatedOwnerIndex = requireNonNegativeInteger(ownerIndex, 'ownerIndex');
58
+ return BigInt((0, viem_1.keccak256)((0, viem_1.encodeAbiParameters)(TROVE_ID_PARAMETERS, [openerAddress, ownerAddress, BigInt(validatedOwnerIndex)])));
59
+ }
52
60
  function requireNonNegativeInteger(value, fieldName) {
53
61
  if (!Number.isSafeInteger(value) || value < 0) {
54
62
  throw new Error(`${fieldName} must be a non-negative safe integer`);
@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
36
  exports.RouteService = void 0;
27
37
  const abis_1 = require("../../core/abis");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mento-protocol/mento-sdk",
3
3
  "description": "Official SDK for interacting with the Mento Protocol",
4
- "version": "3.2.0",
4
+ "version": "3.2.1",
5
5
  "license": "MIT",
6
6
  "author": "Mento Labs",
7
7
  "keywords": [