@gvnrdao/dh-sdk 0.0.166 → 0.0.205

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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -5
  3. package/browser/dist/397.browser.js +1 -1
  4. package/browser/dist/833.browser.js +1 -1
  5. package/browser/dist/browser.js +1 -13
  6. package/browser/dist/browser.js.LICENSE.txt +1 -70
  7. package/browser/dist/index.d.ts +3 -4
  8. package/browser/dist/index.d.ts.map +1 -1
  9. package/browser/dist/index.js +4 -3
  10. package/dist/constants/chunks/contract-abis.d.ts +7 -0
  11. package/dist/constants/chunks/deployment-addresses.d.ts +68 -0
  12. package/dist/constants/chunks/encrypted-provider-params.d.ts +21 -0
  13. package/dist/constants/chunks/environment.browser.d.ts +45 -0
  14. package/dist/constants/chunks/environment.d.ts +57 -0
  15. package/dist/constants/chunks/network-configs.d.ts +65 -0
  16. package/dist/constants/chunks/sdk-config.d.ts +33 -0
  17. package/dist/constants/chunks/sdk-limits.d.ts +66 -0
  18. package/dist/constants/index.d.ts +15 -0
  19. package/dist/graphs/client.d.ts +19 -0
  20. package/dist/graphs/diamond-hands.d.ts +248 -0
  21. package/dist/index.d.ts +47 -7391
  22. package/dist/index.js +4525 -16860
  23. package/dist/index.mjs +4489 -16801
  24. package/dist/interfaces/chunks/btc.i.d.ts +36 -0
  25. package/dist/interfaces/chunks/config.i.d.ts +250 -0
  26. package/dist/interfaces/chunks/contract-interactions.i.d.ts +64 -0
  27. package/dist/interfaces/chunks/contract-types.i.d.ts +165 -0
  28. package/dist/interfaces/chunks/lit-actions-results.i.d.ts +165 -0
  29. package/dist/interfaces/chunks/lit-actions.i.d.ts +98 -0
  30. package/dist/interfaces/chunks/loan-operations.i.d.ts +332 -0
  31. package/dist/interfaces/chunks/pkp-integration.i.d.ts +87 -0
  32. package/dist/interfaces/chunks/position-query.i.d.ts +76 -0
  33. package/dist/interfaces/chunks/requests.i.d.ts +55 -0
  34. package/dist/interfaces/chunks/ucd-minting.i.d.ts +34 -0
  35. package/dist/interfaces/chunks/utility.i.d.ts +64 -0
  36. package/dist/interfaces/index.d.ts +17 -0
  37. package/dist/modules/bitcoin/bitcoin-operations.module.d.ts +223 -0
  38. package/dist/modules/cache/cache-manager.module.d.ts +92 -0
  39. package/dist/modules/contract/contract-manager.module.d.ts +136 -0
  40. package/dist/modules/diamond-hands-sdk.d.ts +669 -0
  41. package/dist/modules/loan/loan-creator.module.d.ts +143 -0
  42. package/dist/modules/loan/loan-query.module.d.ts +206 -0
  43. package/dist/modules/mock/mock-token-manager.module.d.ts +83 -0
  44. package/dist/modules/pkp/pkp-manager.module.d.ts +136 -0
  45. package/dist/protocol/protocol-pause.d.ts +19 -0
  46. package/dist/server.d.ts +17 -0
  47. package/dist/server.js +285 -0
  48. package/dist/server.mjs +242 -0
  49. package/dist/types/authorization-params.d.ts +160 -0
  50. package/dist/types/branded/domain-values.d.ts +138 -0
  51. package/dist/types/branded/ids.d.ts +23 -0
  52. package/dist/types/event-types.d.ts +235 -0
  53. package/dist/types/graph-dtos.d.ts +228 -0
  54. package/dist/types/loanStatus.d.ts +10 -0
  55. package/dist/types/result.d.ts +120 -0
  56. package/dist/utils/bitcoin-address-cache.utils.d.ts +87 -0
  57. package/dist/utils/bitcoin-provider.utils.d.ts +48 -0
  58. package/dist/utils/bitcoin-signature.d.ts +20 -0
  59. package/dist/utils/chunks/bitcoin-utils.d.ts +75 -0
  60. package/dist/utils/chunks/eip1559-broadcast.utils.d.ts +24 -0
  61. package/dist/utils/error-handler.d.ts +106 -0
  62. package/dist/utils/ethers-interop.utils.d.ts +146 -0
  63. package/dist/utils/extend-authorization.utils.d.ts +61 -0
  64. package/dist/utils/lit-signature.utils.d.ts +6 -0
  65. package/dist/utils/logger.utils.d.ts +142 -0
  66. package/dist/utils/mint-authorization.utils.d.ts +224 -0
  67. package/dist/utils/quantum-timing.d.ts +75 -0
  68. package/dist/utils/signature-tempering.utils.d.ts +31 -0
  69. package/dist/utils/telegram-messaging.utils.d.ts +188 -0
  70. package/package.json +43 -22
  71. package/dist/index.d.mts +0 -7392
@@ -0,0 +1,669 @@
1
+ /**
2
+ * Diamond Hands SDK - Main Entry Point
3
+ *
4
+ * This is the primary SDK class that orchestrates all modules.
5
+ * It provides a clean, high-level API for interacting with the Diamond Hands protocol.
6
+ *
7
+ * Architecture:
8
+ * - Thin orchestrator (< 500 lines)
9
+ * - Delegates to specialized modules
10
+ * - No business logic (all in modules)
11
+ * - Dependency injection pattern
12
+ * - Result-based error handling
13
+ */
14
+ import { Result } from "../types/result";
15
+ import { Satoshis } from "../types/branded/domain-values";
16
+ import { SDKError } from "../utils/error-handler";
17
+ import type { CreateLoanRequest, CreateLoanResult, LoanData, LoanDataDetail, UCDMintRequest, UCDMintResult, PartialPaymentRequest, PartialPaymentResult, BTCWithdrawalResult, RenewPositionRequest, RenewPositionResult, LiquidationRequest, LiquidationResult, ConfirmBalanceRequest, ConfirmBalanceResult, TermsWithFeesResult } from "../interfaces/chunks/loan-operations.i";
18
+ import type { DiamondHandsSDKConfig } from "../interfaces/chunks/config.i";
19
+ import type { PKPData } from "../interfaces/chunks/pkp-integration.i";
20
+ import { ContractManager } from "./contract/contract-manager.module";
21
+ import { BitcoinOperations } from "./bitcoin/bitcoin-operations.module";
22
+ type PositionDetailsView = {
23
+ positionId: string;
24
+ pkpId: string;
25
+ ucdDebt: any;
26
+ debt?: any;
27
+ btcVault?: any;
28
+ btcVaultBalance?: any;
29
+ btcPrice?: any;
30
+ [key: string]: any;
31
+ };
32
+ /**
33
+ * Diamond Hands SDK
34
+ *
35
+ * Main SDK class providing high-level API for the Diamond Hands lending protocol.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const sdkResult = await DiamondHandsSDK.create({
40
+ * mode: 'service',
41
+ * serviceEndpoint: 'https://lit-ops.example.com',
42
+ * contractSigner: wallet,
43
+ * });
44
+ *
45
+ * if (!sdkResult.success) {
46
+ * console.error('Failed to initialize SDK:', sdkResult.error);
47
+ * return;
48
+ * }
49
+ *
50
+ * const sdk = sdkResult.value;
51
+ *
52
+ * // Create a loan
53
+ * const result = await sdk.createLoan({ selectedTerm: 12 });
54
+ * if (result.success) {
55
+ * console.log('Position created:', result.value.positionId);
56
+ * }
57
+ *
58
+ * // Clean up when done
59
+ * sdk.dispose();
60
+ * ```
61
+ */
62
+ export declare class DiamondHandsSDK {
63
+ private readonly config;
64
+ private readonly contractManager;
65
+ private readonly cacheManager;
66
+ private readonly litOps;
67
+ private readonly pkpManager;
68
+ private readonly loanCreator;
69
+ private readonly loanQuery;
70
+ private readonly bitcoinOperations;
71
+ private readonly mockTokenManager?;
72
+ private readonly graphClient;
73
+ private isInitialized;
74
+ private isDisposed;
75
+ /**
76
+ * Private constructor - use DiamondHandsSDK.create() instead
77
+ *
78
+ * @param config - SDK configuration
79
+ */
80
+ private constructor();
81
+ /**
82
+ * Create and initialize a new Diamond Hands SDK instance
83
+ *
84
+ * This is the recommended way to create an SDK instance. It validates the
85
+ * configuration, initializes all modules, and verifies connectivity before
86
+ * returning the SDK instance.
87
+ *
88
+ * @param config - SDK configuration (discriminated union based on mode)
89
+ * @returns Result containing initialized SDK or error
90
+ *
91
+ * @example Service Mode
92
+ * ```typescript
93
+ * const result = await DiamondHandsSDK.create({
94
+ * mode: 'service',
95
+ * serviceEndpoint: 'https://lit-ops.example.com',
96
+ * contractSigner: wallet,
97
+ * });
98
+ * ```
99
+ *
100
+ * @example Standalone Mode
101
+ * ```typescript
102
+ * const result = await DiamondHandsSDK.create({
103
+ * mode: 'standalone',
104
+ * litOpsSigner: wallet,
105
+ * contractSigner: wallet,
106
+ * });
107
+ * ```
108
+ */
109
+ static create(config: DiamondHandsSDKConfig): Promise<Result<DiamondHandsSDK, SDKError>>;
110
+ /**
111
+ * Enrich configuration with network defaults from network-configs.ts
112
+ *
113
+ * If contractAddresses or subgraphs are not provided, attempt to load them
114
+ * from the network configuration based on the detected chainId.
115
+ */
116
+ private static enrichConfigWithNetworkDefaults;
117
+ /**
118
+ * Initialize the SDK and verify it's ready for use
119
+ *
120
+ * This method:
121
+ * 1. Marks the SDK as initialized
122
+ * 2. Verifies network connectivity
123
+ * 3. Validates contract addresses
124
+ *
125
+ * @returns Result indicating success or failure
126
+ */
127
+ private initialize;
128
+ /**
129
+ * Verify network connectivity and contract availability
130
+ */
131
+ private verifyConnection;
132
+ /**
133
+ * Dispose of the SDK and clean up resources
134
+ *
135
+ * This method:
136
+ * - Clears all caches
137
+ * - Removes event listeners
138
+ * - Marks the SDK as disposed
139
+ *
140
+ * After calling dispose(), the SDK instance cannot be reused.
141
+ */
142
+ dispose(): void;
143
+ /**
144
+ * Check if SDK is ready for operations
145
+ */
146
+ private checkInitialized;
147
+ private toSDKError;
148
+ /**
149
+ * Get SDK initialization state
150
+ */
151
+ get initialized(): boolean;
152
+ /**
153
+ * Get SDK disposal state
154
+ */
155
+ get disposed(): boolean;
156
+ /**
157
+ * Create a new loan
158
+ *
159
+ * Complete flow: PKP creation → address derivation → authorization → contract call
160
+ *
161
+ * @param request - Loan creation request
162
+ * @returns Loan creation result with position ID and audit trail
163
+ * @example
164
+ * ```typescript
165
+ * const result = await sdk.createLoan({
166
+ * collateralAmount: 25_000,
167
+ * collateralRatio: 150,
168
+ * selectedTerm: 3,
169
+ * });
170
+ * if (result.success) {
171
+ * console.log(result.value.positionId);
172
+ * }
173
+ * ```
174
+ */
175
+ createLoan(request: CreateLoanRequest): Promise<Result<CreateLoanResult, SDKError>>;
176
+ /**
177
+ * Request UCD minting against existing collateral
178
+ * Performs LIT Action validation and calls contract
179
+ *
180
+ * @param request - Mint request with position ID and amount
181
+ * @returns Mint result with transaction details
182
+ * @example
183
+ * ```typescript
184
+ * const mint = await sdk.requestMintUCD({ positionId, amount: 100 });
185
+ * if (!mint.success) {
186
+ * console.error(mint.error);
187
+ * }
188
+ * ```
189
+ */
190
+ requestMintUCD(request: UCDMintRequest): Promise<UCDMintResult>;
191
+ /**
192
+ * Request UCD minting using the SDK-wide `Result` contract.
193
+ *
194
+ * Use this in new integrations when you want a consistent error model that
195
+ * avoids thrown exceptions for routine operation failures.
196
+ *
197
+ * @param request - Mint request with position ID and amount.
198
+ * @returns `Result` containing mint transaction data or an `SDKError`.
199
+ * @example
200
+ * ```typescript
201
+ * const result = await sdk.requestMintUCDResult({ positionId, amount: 100 });
202
+ * if (!result.success) {
203
+ * console.error(result.error.code, result.error.message);
204
+ * return;
205
+ * }
206
+ * console.log(result.value.transactionHash);
207
+ * ```
208
+ */
209
+ requestMintUCDResult(request: UCDMintRequest): Promise<Result<UCDMintResult, SDKError>>;
210
+ private _requestMintUCDAttempt;
211
+ /**
212
+ * @notice Liquidate position using commit-reveal system with MEV protection
213
+ * @dev Executes liquidation with randomized delay to prevent MEV attacks using LIQUIDATOR_ROLE.
214
+ * On-chain liquidation burns the position debt in UCD from the liquidator via `UCDController`;
215
+ * `UCDToken` (M-4) requires an allowance from the liquidator to UCDController. Before
216
+ * `commitLiquidation`, the SDK checks UCD balance and allowance; if allowance is below debt
217
+ * it submits `approve(ucdController, debt)` unless `request.skipUcdApproval` is true.
218
+ * @param request - Liquidation request with position ID and options
219
+ * @returns Liquidation result with transaction details
220
+ * @example
221
+ * ```typescript
222
+ * const liq = await sdk.liquidatePosition({ positionId });
223
+ * if (!liq.success) {
224
+ * console.error(liq.error);
225
+ * }
226
+ * ```
227
+ */
228
+ liquidatePosition(request: LiquidationRequest): Promise<LiquidationResult>;
229
+ /**
230
+ * Liquidate a position using the SDK-wide `Result` contract.
231
+ *
232
+ * @param request - Liquidation request payload.
233
+ * @returns `Result` containing liquidation details or an `SDKError`.
234
+ * @example
235
+ * ```typescript
236
+ * const result = await sdk.liquidatePositionResult({ positionId });
237
+ * if (result.success) {
238
+ * console.log(result.value.transactionHash);
239
+ * }
240
+ * ```
241
+ */
242
+ liquidatePositionResult(request: LiquidationRequest): Promise<Result<LiquidationResult, SDKError>>;
243
+ /**
244
+ * Extend position term
245
+ *
246
+ * Follows main's security pattern: authorization → LIT validation → contract execution
247
+ * Same pattern as makePayment: generate user auth, call lit-ops for LIT Action, then call contract.
248
+ *
249
+ * @param _positionId - Position identifier
250
+ * @param _selectedTerm - Extension term in months
251
+ * @returns Transaction receipt
252
+ */
253
+ private extendPosition;
254
+ /**
255
+ * Renew (extend) position with consistent response structure
256
+ *
257
+ * This method provides a consistent API for position renewal that returns
258
+ * structured transaction details instead of raw TransactionReceipt.
259
+ *
260
+ * @param request - Renew position request with position ID and selected term
261
+ * @returns Structured renewal result with transaction details
262
+ * @example
263
+ * ```typescript
264
+ * const renewal = await sdk.renewPosition({ positionId, selectedTerm: 6 });
265
+ * if (renewal.success) {
266
+ * console.log(renewal.transactionHash);
267
+ * }
268
+ * ```
269
+ */
270
+ renewPosition(request: RenewPositionRequest): Promise<RenewPositionResult>;
271
+ /**
272
+ * Renew a position using the SDK-wide `Result` contract.
273
+ *
274
+ * @param request - Renewal request with position and term.
275
+ * @returns `Result` containing renewal details or an `SDKError`.
276
+ * @example
277
+ * ```typescript
278
+ * const result = await sdk.renewPositionResult({ positionId, selectedTerm: 3 });
279
+ * if (!result.success) {
280
+ * throw result.error;
281
+ * }
282
+ * ```
283
+ */
284
+ renewPositionResult(request: RenewPositionRequest): Promise<Result<RenewPositionResult, SDKError>>;
285
+ /**
286
+ * Confirm Bitcoin balance for a position
287
+ *
288
+ * This method:
289
+ * 1. Queries BTC balance via LIT Action
290
+ * 2. Gets PKP signature for the balance
291
+ * 3. Calls PositionManager.updateBalance() on-chain
292
+ * 4. Transitions position status to PENDING_MINT
293
+ *
294
+ * @param request - Confirm balance request with position ID
295
+ * @returns Confirmation result with transaction details
296
+ */
297
+ confirmBalance(request: ConfirmBalanceRequest): Promise<ConfirmBalanceResult>;
298
+ /**
299
+ * Make a payment on a loan position
300
+ *
301
+ * Follows main's security pattern: authorization → LIT validation → contract execution
302
+ *
303
+ * @param request - Payment request with position ID and amount
304
+ * @returns Payment result with transaction details
305
+ */
306
+ makePayment(request: PartialPaymentRequest): Promise<PartialPaymentResult>;
307
+ /**
308
+ * Withdraw Bitcoin from a position
309
+ *
310
+ * @param positionId - Position identifier
311
+ * @param withdrawalAddress - Bitcoin address to send BTC to
312
+ * @param withdrawalAmount - Amount to withdraw in satoshis (REQUIRED)
313
+ * @param networkFee - Network fee for Bitcoin transaction in satoshis (REQUIRED)
314
+ * @returns Withdrawal result with transaction details
315
+ */
316
+ /**
317
+ * Withdraw BTC from position vault
318
+ *
319
+ * IMPORTANT: withdrawalAmount is the TOTAL DEDUCTION from vault.
320
+ * The operator will deduct the actual network fee at execution time.
321
+ * User receives: withdrawalAmount - actualNetworkFee
322
+ *
323
+ * @param positionId - Position identifier
324
+ * @param withdrawalAddress - Bitcoin address to receive withdrawn funds
325
+ * @param withdrawalAmount - Total amount to deduct from vault in satoshis (includes fee)
326
+ * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
327
+ * @param customBitcoinRpcUrl - Optional custom Bitcoin RPC URL (for local testing)
328
+ * @returns Withdrawal result with transaction details
329
+ */
330
+ withdrawBTC(positionId: string, withdrawalAddress: string, withdrawalAmount: number, rpcUrl?: string, customBitcoinRpcUrl?: string): Promise<BTCWithdrawalResult>;
331
+ /**
332
+ * Execute Bitcoin withdrawal (Phase 2)
333
+ *
334
+ * Signs and broadcasts the Bitcoin transaction for an authorized withdrawal.
335
+ * User must have previously authorized the withdrawal via withdrawBTC().
336
+ *
337
+ * @param request - Execution request with positionId, utxoIdentifier, and networkFee
338
+ * @returns Execution result with Bitcoin txid
339
+ */
340
+ executeBTCWithdrawal(request: {
341
+ positionId: string;
342
+ utxoIdentifier: string;
343
+ networkFee: number;
344
+ destination: string;
345
+ rpcUrl?: string;
346
+ customBitcoinRpcUrl?: string;
347
+ }): Promise<{
348
+ success: boolean;
349
+ txid?: string;
350
+ amountSent?: number;
351
+ networkFee?: number;
352
+ destination?: string;
353
+ error?: string;
354
+ }>;
355
+ /**
356
+ * Execute pending Bitcoin transfers
357
+ *
358
+ * Queries authorized spends that haven't been broadcast to Bitcoin network yet
359
+ * and executes them by signing and broadcasting the transactions.
360
+ *
361
+ * @param positionId - Position identifier
362
+ * @param networkFee - Network fee for Bitcoin transaction in satoshis
363
+ * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
364
+ * @returns Array of execution results for each pending transfer
365
+ */
366
+ executePendingBtcTransfers(positionId: string, networkFee: number, rpcUrl?: string): Promise<Array<{
367
+ success: boolean;
368
+ utxoIdentifier?: string;
369
+ txid?: string;
370
+ amountSent?: number;
371
+ networkFee?: number;
372
+ destination?: string;
373
+ error?: string;
374
+ }>>;
375
+ /**
376
+ * Withdraw BTC and execute transfer (Complete Flow)
377
+ *
378
+ * Performs both Phase 1 (authorization) and Phase 2 (execution) in sequence:
379
+ * 1. Authorizes withdrawal on contract (withdrawBTC)
380
+ * 2. Executes pending Bitcoin transfers (signs and broadcasts)
381
+ *
382
+ * @param positionId - Position identifier
383
+ * @param withdrawalAddress - Bitcoin address to receive withdrawn funds
384
+ * @param withdrawalAmount - Total amount to deduct from vault in satoshis
385
+ * @param networkFee - Network fee for Bitcoin transaction in satoshis
386
+ * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
387
+ * @param customBitcoinRpcUrl - Optional custom Bitcoin RPC URL (for local testing)
388
+ * @returns Complete withdrawal result with both authorization and execution details
389
+ */
390
+ withdrawBTCAndExecute(positionId: string, withdrawalAddress: string, withdrawalAmount: number, networkFee: number, rpcUrl?: string, customBitcoinRpcUrl?: string): Promise<{
391
+ success: boolean;
392
+ authorization?: BTCWithdrawalResult;
393
+ transfers?: Array<{
394
+ success: boolean;
395
+ utxoIdentifier?: string;
396
+ txid?: string;
397
+ amountSent?: number;
398
+ networkFee?: number;
399
+ destination?: string;
400
+ error?: string;
401
+ }>;
402
+ error?: string;
403
+ }>;
404
+ /**
405
+ * Get loan data by position ID
406
+ *
407
+ * @param positionId - Position ID
408
+ * @param enrichBalance - Whether to enrich with current Bitcoin balance
409
+ * @returns Detailed loan data
410
+ */
411
+ getLoanById(positionId: string, enrichBalance?: boolean): Promise<Result<LoanDataDetail | null, SDKError>>;
412
+ /**
413
+ * Get loan data by PKP ID
414
+ *
415
+ * @param pkpId - PKP token ID
416
+ * @param enrichBalance - Whether to enrich with current Bitcoin balance
417
+ * @returns Loan data
418
+ */
419
+ getLoanByPkpId(pkpId: string, enrichBalance?: boolean): Promise<Result<LoanData | null, SDKError>>;
420
+ /**
421
+ * Get loans for a borrower
422
+ *
423
+ * @param borrower - Borrower address
424
+ * @param pagination - Optional pagination parameters (page, pageSize)
425
+ * @returns Paginated loans response with loans array, page info, and total count
426
+ */
427
+ getLoansByBorrower(borrower: string, pagination?: {
428
+ page: number;
429
+ pageSize: number;
430
+ }): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
431
+ /**
432
+ * Get all active loans
433
+ *
434
+ * @param pagination - Optional pagination parameters (page, pageSize)
435
+ * @returns Paginated loans response with loans array, page info, and total count
436
+ */
437
+ getActiveLoans(pagination?: {
438
+ page: number;
439
+ pageSize: number;
440
+ }): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
441
+ /**
442
+ * Get loans by state/status
443
+ *
444
+ * @param state - Loan state (PENDING_DEPOSIT, ACTIVE, EXPIRED, REPAID, LIQUIDATED, EXTENDED, CLOSED)
445
+ * @param pagination - Optional pagination parameters (page, pageSize)
446
+ * @returns Paginated loans response with loans array, page info, and total count
447
+ */
448
+ getLoansByState(state: string, pagination?: {
449
+ page: number;
450
+ pageSize: number;
451
+ }): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
452
+ /**
453
+ * Get all loans with pagination
454
+ *
455
+ * @param pagination - Pagination parameters (page, maxRows, orderBy, orderDirection)
456
+ * @param enrichBalance - Whether to enrich loans with Bitcoin balance (not used currently)
457
+ * @param source - Data source: "subgraph" (default) or "contract"
458
+ * @returns Paginated loans response with loans array, page info, and total count
459
+ */
460
+ getLoansAll(pagination?: {
461
+ page?: number;
462
+ maxRows?: number;
463
+ orderBy?: "createdAt" | "lastUpdatedAt" | "ucdDebt";
464
+ orderDirection?: "asc" | "desc";
465
+ }, source?: "subgraph" | "contract"): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
466
+ /**
467
+ * Get all events for a loan position from the subgraph
468
+ */
469
+ getLoanEvents(positionId: string, filter?: import("../types/event-types").LoanEventsFilter): Promise<Result<import("../types/event-types").LoanEvents, SDKError>>;
470
+ /**
471
+ * Wait for the subgraph to index up to (and including) the given block number.
472
+ * Call after on-chain actions (createLoan, mintUCD, etc.) before querying the subgraph.
473
+ *
474
+ * @param targetBlock - Block number the subgraph must have indexed
475
+ * @param options - Override timeout/interval for this call
476
+ * @throws if timeout is reached before subgraph catches up
477
+ */
478
+ /**
479
+ * Get Bitcoin balance for an address
480
+ *
481
+ * @param address - Bitcoin address
482
+ * @returns Balance in satoshis
483
+ */
484
+ getBitcoinBalance(address: string): Promise<Result<import("./bitcoin/bitcoin-operations.module").EnrichedBitcoinBalance, SDKError>>;
485
+ /**
486
+ * Get the current Bitcoin price
487
+ *
488
+ * @returns the current Bitcoin price in USD
489
+ */
490
+ getBitcoinPrice(): Promise<{
491
+ price: number;
492
+ priceE8: string;
493
+ timestamp: number;
494
+ source: string;
495
+ signature: string | undefined;
496
+ signer: string | undefined;
497
+ }>;
498
+ /**
499
+ * Derive Bitcoin addresses from PKP public key
500
+ *
501
+ * @param publicKey - PKP public key
502
+ * @returns Bitcoin addresses for all networks
503
+ */
504
+ deriveBitcoinAddresses(publicKey: string): Promise<Result<import("../interfaces/chunks/loan-operations.i").BitcoinAddresses, SDKError>>;
505
+ /**
506
+ * Get PKP data by token ID
507
+ *
508
+ * @param tokenId - PKP token ID
509
+ * @returns PKP data
510
+ */
511
+ getPKPData(tokenId: string): Promise<Result<PKPData | null, SDKError>>;
512
+ /**
513
+ * Get PKP public key by token ID
514
+ *
515
+ * @param tokenId - PKP token ID
516
+ * @returns PKP public key
517
+ */
518
+ getPKPPublicKey(tokenId: string): Promise<Result<string, SDKError>>;
519
+ /**
520
+ * Get all available loan terms with their fees
521
+ *
522
+ * Retrieves all valid loan terms from the TermManager contract along with
523
+ * their origination fees and extension/renewal fees.
524
+ *
525
+ * @returns Result containing array of terms with fees
526
+ *
527
+ * @example
528
+ * ```typescript
529
+ * const result = await sdk.getTermsWithFees();
530
+ * if (result.success) {
531
+ * result.value.terms.forEach(term => {
532
+ * console.log(`${term.termMonths} months: ${term.originationFeeBps}bps origination, ${term.extensionFeeBps}bps renewal`);
533
+ * });
534
+ * }
535
+ * ```
536
+ */
537
+ getTermsWithFees(): Promise<Result<TermsWithFeesResult, SDKError>>;
538
+ /**
539
+ * Mint mock BTC tokens (test networks only)
540
+ *
541
+ * @param amount - Amount in satoshis
542
+ * @param recipient - Recipient address
543
+ * @returns Transaction result
544
+ */
545
+ mintMockBTC(amount: Satoshis, recipient: string): Promise<Result<import("./mock/mock-token-manager.module").MockTokenTransactionResult, SDKError>>;
546
+ /**
547
+ * Approve mock BTC spending (test networks only)
548
+ *
549
+ * @param spender - Spender address
550
+ * @param amount - Amount in satoshis
551
+ * @returns Transaction result
552
+ */
553
+ approveMockBTC(spender: string, amount: Satoshis): Promise<Result<import("./mock/mock-token-manager.module").MockTokenTransactionResult, SDKError>>;
554
+ /**
555
+ * Get SDK configuration
556
+ */
557
+ getConfig(): DiamondHandsSDKConfig;
558
+ /**
559
+ * Clear all caches
560
+ */
561
+ clearAllCaches(): void;
562
+ /**
563
+ * Get cache statistics
564
+ */
565
+ getCacheStats(): Record<string, {
566
+ size: number;
567
+ maxSize: number;
568
+ ttlMs: number;
569
+ }>;
570
+ /**
571
+ * Get contract manager (for advanced usage)
572
+ */
573
+ getContractManager(): ContractManager;
574
+ /**
575
+ * Get Bitcoin operations module (for advanced usage)
576
+ */
577
+ getBitcoinOperations(): BitcoinOperations;
578
+ /**
579
+ * Check if running on production network
580
+ */
581
+ private isProductionNetwork;
582
+ /**
583
+ * Get Bitcoin network based on chain
584
+ */
585
+ private getBitcoinNetwork;
586
+ /**
587
+ * Extract error message from LIT Action response
588
+ * Checks both `error` and `reason` fields and parses nested error structures
589
+ *
590
+ * @private
591
+ * @remarks Production-ready error parser for LIT Protocol responses
592
+ * Will be integrated into core methods in Round 2
593
+ */
594
+ private extractLitActionError;
595
+ /**
596
+ * Get provider or throw error
597
+ */
598
+ private getProviderOrThrow;
599
+ /**
600
+ * Get signer or throw error
601
+ */
602
+ private getSignerOrThrow;
603
+ /**
604
+ * Get contract addresses or throw error
605
+ */
606
+ private getContractAddressesOrThrow;
607
+ /**
608
+ * Ensure SDK is initialized
609
+ */
610
+ private ensureInitialized;
611
+ /**
612
+ * Convert decimal position ID to bytes32 format
613
+ */
614
+ private toBytes32;
615
+ /**
616
+ * Check if an error indicates a technical failure vs business logic rejection
617
+ */
618
+ /**
619
+ * Get position details view from contract
620
+ * Queries PositionManagerCoreModule directly for reliability (subgraph listens to core module)
621
+ */
622
+ getPositionDetailsView(positionId: string): Promise<PositionDetailsView>;
623
+ /**
624
+ * Get position by ID (internal helper)
625
+ * Uses getPositionDetailsView which queries core module directly
626
+ */
627
+ private getPosition;
628
+ /**
629
+ * Verify position exists in core contract (PositionManagerCoreModule)
630
+ * This is critical because mint operations check the core contract, not PositionManager
631
+ *
632
+ * @param positionId - Position ID to verify
633
+ * @param retries - Number of retries with exponential backoff (default: 3)
634
+ * @param retryDelayMs - Initial retry delay in milliseconds (default: 1000)
635
+ * @returns Promise<boolean> - true if position exists, false otherwise
636
+ */
637
+ verifyPositionExistsInCore(positionId: string, retries?: number, retryDelayMs?: number): Promise<boolean>;
638
+ /**
639
+ * Get loan operations accessor
640
+ * Returns a helper object for interacting with loan operations contract
641
+ */
642
+ loanOps(): {
643
+ getProtocolConfig(): Promise<{
644
+ liquidationThreshold: any;
645
+ minimumLoanValueUcd: any;
646
+ minimumLoanValueWei: any;
647
+ maxSingleLoanValueUcd: any;
648
+ }>;
649
+ };
650
+ /**
651
+ * Calculate reveal delay for MEV protection in commit-reveal liquidation
652
+ * @param positionId Position identifier (for entropy)
653
+ * @param quantumTimestamp LIT quantum timestamp (for additional entropy)
654
+ * @returns Delay in seconds before reveal phase can execute
655
+ */
656
+ private calculateRevealDelay;
657
+ /**
658
+ * Calculate the exact reveal delay by replicating LiquidationManager._calculateRandomizedDelay.
659
+ * Reads vrfSeeds[positionId] from the contract and applies the same two-step keccak256 formula.
660
+ * Falls back to the local estimate if the contract read fails.
661
+ */
662
+ private calculateRevealDelayFromContract;
663
+ /**
664
+ * Wait for the specified delay period (MEV protection)
665
+ * @param delaySeconds Number of seconds to wait
666
+ */
667
+ private waitForRevealDelay;
668
+ }
669
+ export {};