@gvnrdao/dh-sdk 0.0.172 → 0.0.206

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