@gvnrdao/dh-sdk 0.0.286 → 0.0.288

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 (76) hide show
  1. package/browser/dist/397.browser.js +2 -0
  2. package/browser/dist/397.browser.js.LICENSE.txt +1 -0
  3. package/browser/dist/833.browser.js +1 -1
  4. package/browser/dist/browser.js +1 -1
  5. package/browser/dist/browser.js.LICENSE.txt +10 -5
  6. package/dist/deployments.js +45 -21
  7. package/dist/deployments.mjs +45 -21
  8. package/dist/index.js +620 -1103
  9. package/dist/index.mjs +620 -1103
  10. package/package.json +1 -1
  11. package/dist/constants/chunks/contract-abis.d.ts +0 -20
  12. package/dist/constants/chunks/deployment-addresses.d.ts +0 -79
  13. package/dist/constants/chunks/encrypted-provider-params.d.ts +0 -21
  14. package/dist/constants/chunks/environment.browser.d.ts +0 -44
  15. package/dist/constants/chunks/environment.d.ts +0 -57
  16. package/dist/constants/chunks/network-configs.d.ts +0 -72
  17. package/dist/constants/chunks/sdk-config.d.ts +0 -33
  18. package/dist/constants/chunks/sdk-limits.d.ts +0 -66
  19. package/dist/constants/index.d.ts +0 -15
  20. package/dist/contracts/typechain-contracts/common.d.ts +0 -50
  21. package/dist/contracts/typechain-contracts/factories/src/psm/SimplePSMV2__factory.d.ts +0 -1996
  22. package/dist/contracts/typechain-contracts/src/psm/SimplePSMV2.d.ts +0 -1198
  23. package/dist/graphs/client.d.ts +0 -22
  24. package/dist/graphs/diamond-hands.d.ts +0 -259
  25. package/dist/index.d.ts +0 -56
  26. package/dist/interfaces/chunks/btc.i.d.ts +0 -36
  27. package/dist/interfaces/chunks/config.i.d.ts +0 -270
  28. package/dist/interfaces/chunks/contract-interactions.i.d.ts +0 -64
  29. package/dist/interfaces/chunks/contract-types.i.d.ts +0 -171
  30. package/dist/interfaces/chunks/lit-actions-results.i.d.ts +0 -165
  31. package/dist/interfaces/chunks/lit-actions.i.d.ts +0 -98
  32. package/dist/interfaces/chunks/loan-operations.i.d.ts +0 -331
  33. package/dist/interfaces/chunks/pkp-integration.i.d.ts +0 -87
  34. package/dist/interfaces/chunks/position-query.i.d.ts +0 -76
  35. package/dist/interfaces/chunks/requests.i.d.ts +0 -55
  36. package/dist/interfaces/chunks/ucd-minting.i.d.ts +0 -34
  37. package/dist/interfaces/chunks/utility.i.d.ts +0 -64
  38. package/dist/interfaces/index.d.ts +0 -17
  39. package/dist/modules/bitcoin/bitcoin-operations.module.d.ts +0 -254
  40. package/dist/modules/cache/cache-manager.module.d.ts +0 -259
  41. package/dist/modules/contract/contract-manager.module.d.ts +0 -152
  42. package/dist/modules/diamond-hands-sdk.d.ts +0 -969
  43. package/dist/modules/loan/loan-creator.module.d.ts +0 -132
  44. package/dist/modules/loan/loan-query.module.d.ts +0 -204
  45. package/dist/modules/mock/mock-token-manager.module.d.ts +0 -83
  46. package/dist/modules/pkp/pkp-manager.module.d.ts +0 -136
  47. package/dist/modules/withdrawal-address/withdrawal-address.module.d.ts +0 -78
  48. package/dist/protocol/protocol-pause.d.ts +0 -19
  49. package/dist/server.d.ts +0 -17
  50. package/dist/types/authorization-params.d.ts +0 -160
  51. package/dist/types/branded/domain-values.d.ts +0 -138
  52. package/dist/types/branded/ids.d.ts +0 -23
  53. package/dist/types/event-types.d.ts +0 -261
  54. package/dist/types/graph-dtos.d.ts +0 -228
  55. package/dist/types/loanStatus.d.ts +0 -10
  56. package/dist/types/protocol-event-types.d.ts +0 -99
  57. package/dist/types/result.d.ts +0 -120
  58. package/dist/utils/address-conversion.utils.d.ts +0 -51
  59. package/dist/utils/bitcoin-address-cache.utils.d.ts +0 -87
  60. package/dist/utils/bitcoin-provider.utils.d.ts +0 -84
  61. package/dist/utils/btc-withdrawal-message.d.ts +0 -60
  62. package/dist/utils/chunks/bitcoin-utils.d.ts +0 -85
  63. package/dist/utils/chunks/eip1559-broadcast.utils.d.ts +0 -33
  64. package/dist/utils/eip712-login.d.ts +0 -34
  65. package/dist/utils/error-handler.d.ts +0 -106
  66. package/dist/utils/ethers-interop.utils.d.ts +0 -146
  67. package/dist/utils/extend-authorization.utils.d.ts +0 -61
  68. package/dist/utils/lit-signature.utils.d.ts +0 -6
  69. package/dist/utils/logger.utils.d.ts +0 -142
  70. package/dist/utils/mint-authorization.utils.d.ts +0 -248
  71. package/dist/utils/position-delegate.utils.d.ts +0 -41
  72. package/dist/utils/quantum-timing.d.ts +0 -75
  73. package/dist/utils/server-session.d.ts +0 -50
  74. package/dist/utils/service-endpoint-policy.d.ts +0 -16
  75. package/dist/utils/signature-tempering.utils.d.ts +0 -34
  76. package/dist/utils/telegram-messaging.utils.d.ts +0 -188
@@ -1,969 +0,0 @@
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 { type Signer, type TransactionResponse } from "ethers";
15
- import { Result } from "../types/result";
16
- import { Satoshis } from "../types/branded/domain-values";
17
- import { SDKError } from "../utils/error-handler";
18
- import type { CreateLoanRequest, CreateLoanResult, LoanDataDetail, UCDMintRequest, UCDMintResult, PartialPaymentRequest, PartialPaymentResult, BTCWithdrawalResult, RenewPositionRequest, RenewPositionResult, LiquidationRequest, LiquidationResult, ConfirmBalanceRequest, ConfirmBalanceResult, TermsWithFeesResult } from "../interfaces/chunks/loan-operations.i";
19
- import type { DiamondHandsSDKConfig } from "../interfaces/chunks/config.i";
20
- import type { PKPData } from "../interfaces/chunks/pkp-integration.i";
21
- import { ContractManager } from "./contract/contract-manager.module";
22
- import { WithdrawalAddressModule } from "./withdrawal-address/withdrawal-address.module";
23
- import { BitcoinOperations } from "./bitcoin/bitcoin-operations.module";
24
- import type { SupportedStablecoinData } from "../graphs/diamond-hands";
25
- type PositionDetailsView = {
26
- positionId: string;
27
- pkpId: string;
28
- ucdDebt: any;
29
- debt?: any;
30
- btcVault?: any;
31
- btcVaultBalance?: any;
32
- btcPrice?: any;
33
- [key: string]: any;
34
- };
35
- /**
36
- * Diamond Hands SDK
37
- *
38
- * Main SDK class providing high-level API for the Diamond Hands lending protocol.
39
- *
40
- * @example
41
- * ```typescript
42
- * const sdkResult = await DiamondHandsSDK.create({
43
- * mode: 'service',
44
- * serviceEndpoint: 'https://lit-ops.example.com',
45
- * contractSigner: wallet,
46
- * });
47
- *
48
- * if (!sdkResult.success) {
49
- * console.error('Failed to initialize SDK:', sdkResult.error);
50
- * return;
51
- * }
52
- *
53
- * const sdk = sdkResult.value;
54
- *
55
- * // Create a loan
56
- * const result = await sdk.createLoan({ selectedTerm: 12 });
57
- * if (result.success) {
58
- * console.log('Position created:', result.value.positionId);
59
- * }
60
- *
61
- * // Clean up when done
62
- * sdk.dispose();
63
- * ```
64
- */
65
- export declare class DiamondHandsSDK {
66
- private readonly config;
67
- private readonly contractManager;
68
- private readonly cacheManager;
69
- private readonly litOps;
70
- private readonly pkpManager;
71
- private readonly loanCreator;
72
- private readonly loanQuery;
73
- private readonly bitcoinOperations;
74
- private readonly withdrawalAddressModule;
75
- private readonly mockTokenManager?;
76
- private readonly graphClient;
77
- /**
78
- * Session helper for the lit-ops-server. Set in service mode; undefined
79
- * in standalone mode (no server to authenticate against). Use
80
- * `this.getAuthHeader()` which centralizes the undefined check.
81
- */
82
- private readonly serverSession?;
83
- private isInitialized;
84
- private isDisposed;
85
- /**
86
- * Audit H-13: per-position write serialization. Tracks positions with an
87
- * in-flight state-mutating call so a concurrent mint / payment / extend /
88
- * withdraw / liquidation for the same position fast-fails locally instead
89
- * of paying a full Lit-Action round-trip + gas only to revert on-chain
90
- * via the M-4 flash-loan protection's `lastInteractionBlockByPosition`
91
- * guard. Stored as a Set — no Promise needed since callers don't await
92
- * on each other; they get an immediate refusal and can retry once their
93
- * sibling call has completed.
94
- */
95
- private readonly inFlightWrites;
96
- /**
97
- * Acquire the per-position write lock. Returns `null` on success, or a
98
- * structured failure when another write is already in flight. The caller
99
- * must `cast` the failure to the method's specific result type — every
100
- * write-method result includes a `{ success: false; error: string }`
101
- * branch so the cast is safe.
102
- */
103
- private tryAcquireWriteLock;
104
- /** Release the per-position write lock. Safe to call when not held. */
105
- private releaseWriteLock;
106
- /**
107
- * Build the `Authorization: Bearer <jwt>` header for a request to
108
- * lit-ops-server. Returns an empty object in standalone mode (no server
109
- * to authenticate to) or when the session helper has not been wired —
110
- * in which case the server's `requireSessionToken` middleware will
111
- * reject the call with 401, which is the correct outcome.
112
- */
113
- private getAuthHeader;
114
- /**
115
- * Audit H-9: invalidate the LoanQuery cache so subsequent reads return
116
- * the post-write state. We clear the entire loan-query cache (not just
117
- * the entry for this position) because the cache keys by `pkpId` and we
118
- * don't always have it in scope at the release site — a position-keyed
119
- * helper would require a pre-write lookup that defeats the cache. The
120
- * blast radius is bounded: the cache is per-process and a fresh fetch
121
- * is cheap relative to a Lit Action call.
122
- *
123
- * `includePkpCache: true` is passed by liquidation to also drop the
124
- * 24-hour PKP-data cache entry — the Lit auth-context attached to a
125
- * PKP changes when ownership transfers, so the cached `ethAddress`
126
- * (used for capacity-credit delegation) must be re-derived.
127
- */
128
- private invalidateCachesForPosition;
129
- /**
130
- * Audit H-11: pre-flight check for `PositionManager.getProtocolPauseStatus()`.
131
- *
132
- * Returns `{ ok: true }` if none of the supplied pause keys are set, or
133
- * `{ ok: false, error }` if the protocol is paused for this operation
134
- * type. Caller returns the structured failure to the user before paying
135
- * for a LIT Action round-trip + gas that the on-chain function would
136
- * later revert.
137
- *
138
- * Best-effort: if no EVM provider is available (e.g., service-mode setup
139
- * without `ethRpcUrl`) or the read itself fails, we return `{ ok: true }`
140
- * with a debug log — the on-chain call remains the final authority.
141
- */
142
- private preflightProtocolPause;
143
- /**
144
- * Private constructor - use DiamondHandsSDK.create() instead
145
- *
146
- * @param config - SDK configuration
147
- */
148
- private constructor();
149
- /**
150
- * Create and initialize a new Diamond Hands SDK instance
151
- *
152
- * This is the recommended way to create an SDK instance. It validates the
153
- * configuration, initializes all modules, and verifies connectivity before
154
- * returning the SDK instance.
155
- *
156
- * @param config - SDK configuration (discriminated union based on mode)
157
- * @returns Result containing initialized SDK or error
158
- *
159
- * @example Service Mode
160
- * ```typescript
161
- * const result = await DiamondHandsSDK.create({
162
- * mode: 'service',
163
- * serviceEndpoint: 'https://lit-ops.example.com',
164
- * contractSigner: wallet,
165
- * });
166
- * ```
167
- *
168
- * @example Standalone Mode
169
- * ```typescript
170
- * const result = await DiamondHandsSDK.create({
171
- * mode: 'standalone',
172
- * litOpsSigner: wallet,
173
- * contractSigner: wallet,
174
- * });
175
- * ```
176
- */
177
- static create(config: DiamondHandsSDKConfig): Promise<Result<DiamondHandsSDK, SDKError>>;
178
- /**
179
- * Enrich configuration with network defaults from network-configs.ts
180
- *
181
- * If contractAddresses or subgraphs are not provided, attempt to load them
182
- * from the network configuration based on the detected chainId.
183
- */
184
- private static enrichConfigWithNetworkDefaults;
185
- /**
186
- * Initialize the SDK and verify it's ready for use
187
- *
188
- * This method:
189
- * 1. Marks the SDK as initialized
190
- * 2. Verifies network connectivity
191
- * 3. Validates contract addresses
192
- *
193
- * @returns Result indicating success or failure
194
- */
195
- private initialize;
196
- /**
197
- * Verify network connectivity and contract availability
198
- */
199
- private verifyConnection;
200
- /**
201
- * Dispose of the SDK and clean up resources
202
- *
203
- * This method:
204
- * - Clears all caches
205
- * - Removes event listeners
206
- * - Marks the SDK as disposed
207
- *
208
- * After calling dispose(), the SDK instance cannot be reused.
209
- */
210
- dispose(): void;
211
- /**
212
- * Check if SDK is ready for operations
213
- */
214
- private _relayNotification;
215
- private checkInitialized;
216
- private toSDKError;
217
- /**
218
- * Get SDK initialization state
219
- */
220
- get initialized(): boolean;
221
- /**
222
- * Get SDK disposal state
223
- */
224
- get disposed(): boolean;
225
- /**
226
- * Create a new loan
227
- *
228
- * Complete flow: PKP creation → address derivation → authorization → contract call
229
- *
230
- * @param request - Loan creation request
231
- * @returns Loan creation result with position ID and audit trail
232
- * @example
233
- * ```typescript
234
- * const result = await sdk.createLoan({
235
- * collateralAmount: 25_000,
236
- * collateralRatio: 150,
237
- * selectedTerm: 3,
238
- * });
239
- * if (result.success) {
240
- * console.log(result.value.positionId);
241
- * }
242
- * ```
243
- */
244
- createLoan(request: CreateLoanRequest): Promise<Result<CreateLoanResult, SDKError>>;
245
- /**
246
- * Request UCD minting against existing collateral
247
- * Performs LIT Action validation and calls contract
248
- *
249
- * @param request - Mint request with position ID and amount
250
- * @returns Mint result with transaction details
251
- * @example
252
- * ```typescript
253
- * const mint = await sdk.requestMintUCD({ positionId, amount: 100 });
254
- * if (!mint.success) {
255
- * console.error(mint.error);
256
- * }
257
- * ```
258
- */
259
- requestMintUCD(request: UCDMintRequest): Promise<UCDMintResult>;
260
- /**
261
- * Request UCD minting using the SDK-wide `Result` contract.
262
- *
263
- * Use this in new integrations when you want a consistent error model that
264
- * avoids thrown exceptions for routine operation failures.
265
- *
266
- * @param request - Mint request with position ID and amount.
267
- * @returns `Result` containing mint transaction data or an `SDKError`.
268
- * @example
269
- * ```typescript
270
- * const result = await sdk.requestMintUCDResult({ positionId, amount: 100 });
271
- * if (!result.success) {
272
- * console.error(result.error.code, result.error.message);
273
- * return;
274
- * }
275
- * console.log(result.value.transactionHash);
276
- * ```
277
- */
278
- requestMintUCDResult(request: UCDMintRequest): Promise<Result<UCDMintResult, SDKError>>;
279
- private _requestMintUCDAttempt;
280
- /**
281
- * @notice Liquidate position using commit-reveal system with MEV protection
282
- * @dev Executes liquidation with randomized delay to prevent MEV attacks using LIQUIDATOR_ROLE.
283
- * On-chain liquidation burns the position debt in UCD from the liquidator via `UCDController`;
284
- * `UCDToken` (M-4) requires an allowance from the liquidator to UCDController. Before
285
- * `commitLiquidation`, the SDK checks UCD balance and allowance; if allowance is below debt
286
- * it submits `approve(ucdController, debt)` unless `request.skipUcdApproval` is true.
287
- * @param request - Liquidation request with position ID and options
288
- * @returns Liquidation result with transaction details
289
- * @example
290
- * ```typescript
291
- * const liq = await sdk.liquidatePosition({ positionId });
292
- * if (!liq.success) {
293
- * console.error(liq.error);
294
- * }
295
- * ```
296
- */
297
- liquidatePosition(request: LiquidationRequest): Promise<LiquidationResult>;
298
- /**
299
- * Liquidate a position using the SDK-wide `Result` contract.
300
- *
301
- * @param request - Liquidation request payload.
302
- * @returns `Result` containing liquidation details or an `SDKError`.
303
- * @example
304
- * ```typescript
305
- * const result = await sdk.liquidatePositionResult({ positionId });
306
- * if (result.success) {
307
- * console.log(result.value.transactionHash);
308
- * }
309
- * ```
310
- */
311
- liquidatePositionResult(request: LiquidationRequest): Promise<Result<LiquidationResult, SDKError>>;
312
- /**
313
- * Extend position term
314
- *
315
- * Follows main's security pattern: authorization → LIT validation → contract execution
316
- * Same pattern as makePayment: generate user auth, call lit-ops for LIT Action, then call contract.
317
- *
318
- * @param _positionId - Position identifier
319
- * @param _selectedTerm - Extension term in months
320
- * @returns Transaction receipt
321
- */
322
- private extendPosition;
323
- /**
324
- * Renew (extend) position with consistent response structure
325
- *
326
- * This method provides a consistent API for position renewal that returns
327
- * structured transaction details instead of raw TransactionReceipt.
328
- *
329
- * @param request - Renew position request with position ID and selected term
330
- * @returns Structured renewal result with transaction details
331
- * @example
332
- * ```typescript
333
- * const renewal = await sdk.renewPosition({ positionId, selectedTerm: 6 });
334
- * if (renewal.success) {
335
- * console.log(renewal.transactionHash);
336
- * }
337
- * ```
338
- */
339
- renewPosition(request: RenewPositionRequest): Promise<RenewPositionResult>;
340
- /**
341
- * Renew a position using the SDK-wide `Result` contract.
342
- *
343
- * @param request - Renewal request with position and term.
344
- * @returns `Result` containing renewal details or an `SDKError`.
345
- * @example
346
- * ```typescript
347
- * const result = await sdk.renewPositionResult({ positionId, selectedTerm: 3 });
348
- * if (!result.success) {
349
- * throw result.error;
350
- * }
351
- * ```
352
- */
353
- renewPositionResult(request: RenewPositionRequest): Promise<Result<RenewPositionResult, SDKError>>;
354
- /**
355
- * Confirm Bitcoin balance for a position
356
- *
357
- * This method:
358
- * 1. Queries BTC balance via LIT Action
359
- * 2. Gets PKP signature for the balance
360
- * 3. Calls PositionManager.updateBalance() on-chain
361
- * 4. Transitions position status to PENDING_MINT
362
- *
363
- * @param request - Confirm balance request with position ID
364
- * @returns Confirmation result with transaction details
365
- */
366
- confirmBalance(request: ConfirmBalanceRequest): Promise<ConfirmBalanceResult>;
367
- /**
368
- * Make a payment on a loan position
369
- *
370
- * Follows main's security pattern: authorization → LIT validation → contract execution
371
- *
372
- * @param request - Payment request with position ID and amount
373
- * @returns Payment result with transaction details
374
- */
375
- makePayment(request: PartialPaymentRequest): Promise<PartialPaymentResult>;
376
- /**
377
- * Access the approved-withdrawal-address allowlist module (self-service
378
- * add/remove + reads). The connected wallet manages its OWN addresses; a
379
- * newly-added address is only usable after the registry's time-lock delay.
380
- */
381
- get withdrawalAddresses(): WithdrawalAddressModule;
382
- /**
383
- * Add a Bitcoin address to the connected wallet's approved-withdrawal allowlist.
384
- * Usable only after the registry's delay (default 24h) elapses.
385
- */
386
- addApprovedWithdrawalAddress(btcAddress: string): Promise<Result<TransactionResponse, SDKError>>;
387
- /** Remove a Bitcoin address from the connected wallet's allowlist (immediate). */
388
- removeApprovedWithdrawalAddress(btcAddress: string): Promise<Result<TransactionResponse, SDKError>>;
389
- /**
390
- * Read the connected wallet's (or `user`'s) approved-address entries from the
391
- * contract (hashes + timestamps + derived approval state). For human-readable
392
- * address strings, query the subgraph `WithdrawalAddressBook`.
393
- */
394
- getApprovedWithdrawalAddresses(user?: string): Promise<Result<import("./withdrawal-address/withdrawal-address.module").WithdrawalAddressEntry[], SDKError>>;
395
- /**
396
- * Withdraw Bitcoin from a position
397
- *
398
- * @param positionId - Position identifier
399
- * @param withdrawalAddress - Bitcoin address to send BTC to
400
- * @param withdrawalAmount - Amount to withdraw in satoshis (REQUIRED)
401
- * @param networkFee - Network fee for Bitcoin transaction in satoshis (REQUIRED)
402
- * @returns Withdrawal result with transaction details
403
- */
404
- /**
405
- * Withdraw BTC from position vault
406
- *
407
- * IMPORTANT: withdrawalAmount is the TOTAL DEDUCTION from vault.
408
- * The operator will deduct the actual network fee at execution time.
409
- * User receives: withdrawalAmount - actualNetworkFee
410
- *
411
- * @param positionId - Position identifier
412
- * @param withdrawalAddress - Bitcoin address to receive withdrawn funds
413
- * @param withdrawalAmount - Total amount to deduct from vault in satoshis (includes fee)
414
- * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
415
- * @param customBitcoinRpcUrl - Optional custom Bitcoin RPC URL (for local testing)
416
- * @returns Withdrawal result with transaction details
417
- */
418
- withdrawBTC(positionId: string, withdrawalAddress: string, withdrawalAmount: number): Promise<BTCWithdrawalResult>;
419
- /**
420
- * Execute Bitcoin withdrawal (Phase 2)
421
- *
422
- * Signs and broadcasts the Bitcoin transaction for an authorized withdrawal.
423
- * User must have previously authorized the withdrawal via withdrawBTC().
424
- *
425
- * @param request - Execution request with positionId, utxoIdentifier, and networkFee
426
- * @returns Execution result with Bitcoin txid
427
- */
428
- executeBTCWithdrawal(request: {
429
- positionId: string;
430
- utxoIdentifier: string;
431
- utxoSatoshis: number;
432
- networkFee: number;
433
- destination: string;
434
- /**
435
- * User-authorized withdrawal amount in satoshis (Phase 1 `withdrawalAmount`).
436
- * Bound into the Phase-2 signature alongside `destination` so the Lit
437
- * Action can cross-check against the on-chain authorizer record.
438
- */
439
- targetAmount: number;
440
- }): Promise<{
441
- success: boolean;
442
- txid?: string;
443
- amountSent?: number;
444
- networkFee?: number;
445
- destination?: string;
446
- error?: string;
447
- }>;
448
- /**
449
- * Execute pending Bitcoin transfers
450
- *
451
- * Queries authorized spends that haven't been broadcast to Bitcoin network yet
452
- * and executes them by signing and broadcasting the transactions.
453
- *
454
- * @param positionId - Position identifier
455
- * @param networkFee - Network fee for Bitcoin transaction in satoshis
456
- * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
457
- * @returns Array of execution results for each pending transfer
458
- */
459
- executePendingBtcTransfers(positionId: string, networkFee: number): Promise<Array<{
460
- success: boolean;
461
- utxoIdentifier?: string;
462
- txid?: string;
463
- amountSent?: number;
464
- networkFee?: number;
465
- destination?: string;
466
- error?: string;
467
- }>>;
468
- /**
469
- * Get pending BTC withdrawals for a position
470
- *
471
- * Returns all authorized spends recorded in BTCSpendAuthorizer that have not yet
472
- * been broadcast to the Bitcoin network. An empty array means no pending withdrawals.
473
- *
474
- * @param positionId - Position identifier
475
- * @returns Array of pending withdrawals, each including a pre-computed utxoKey for use with cancelPendingWithdrawal
476
- */
477
- getPendingWithdrawals(positionId: string): Promise<Array<{
478
- txid: string;
479
- vout: number;
480
- satoshis: number;
481
- targetAddress: string;
482
- targetAmount: number;
483
- authorizedAt: number;
484
- utxoKey: string;
485
- }>>;
486
- /**
487
- * Cancel a pending BTC withdrawal
488
- *
489
- * Removes a stale authorized spend from BTCSpendAuthorizer, unlocking the UTXO
490
- * and allowing the borrower to retry the withdrawal from scratch.
491
- * Only the position's borrower may call this — requires a connected signer.
492
- *
493
- * @param positionId - Position identifier
494
- * @param txid - Bitcoin UTXO transaction ID (from getPendingWithdrawals)
495
- * @param vout - Output index (from getPendingWithdrawals)
496
- * @returns Transaction hash of the cancellation EVM transaction
497
- */
498
- /**
499
- * Recover (clear) a stale BTC reservation via LIT-attested proof.
500
- *
501
- * Replaces the disabled borrower-callable cleanup path (`markSpentByOwner` /
502
- * `cancelStaleSpendByOwner`, both permanently revert with
503
- * `BorrowerBTCSpendMutationDisabled` as of audit #62210). The recovery is
504
- * permissionless on-chain — any caller with a valid LIT attestation can
505
- * invoke `BTCSpendAuthorizer.cancelStaleSpendWithProof`.
506
- *
507
- * Two-step flow:
508
- * 1. Call `staleSpendRecoveryValidator` LIT Action with `invalidatorTxid`.
509
- * The action verifies on Bitcoin that the original authorized UTXO is
510
- * provably consumed at depth ≥ 6 confirmations, and signs an
511
- * EIP-712 `StaleSpendRecovery` attestation.
512
- * 2. Submit the attestation to `BTCSpendAuthorizer.cancelStaleSpendWithProof`
513
- * on-chain. The contract enforces freshness
514
- * (`MAX_ATTESTATION_AGE = 1 hour`) and replay-protects via
515
- * `authorizedAt` binding.
516
- *
517
- * `invalidatorTxid` is either:
518
- * - the borrower's own authorized broadcast (classified "consumed-as-authorized"
519
- * by the LIT validator), once it has ≥6 confirmations on the BTC
520
- * network — the natural post-withdrawal cleanup case; OR
521
- * - a vault-to-vault self-spend (PKP-signed) that consumed the original
522
- * UTXO before the authorized broadcast landed, classified "invalidated".
523
- *
524
- * @returns Transaction hash + classification on success, or error on failure.
525
- */
526
- recoverStaleSpend(params: {
527
- positionId: string;
528
- utxoTxid: string;
529
- utxoVout: number;
530
- invalidatorTxid: string;
531
- minConfirmations?: number;
532
- rpcUrl?: string;
533
- }): Promise<{
534
- success: boolean;
535
- transactionHash?: string;
536
- classification?: "invalidated" | "consumed-as-authorized";
537
- attestation?: {
538
- positionId: string;
539
- utxoKey: string;
540
- authorizedAt: string;
541
- invalidatorTxid: string;
542
- attestationTimestamp: number;
543
- };
544
- error?: string;
545
- failedStep?: "attestation" | "submit" | "config";
546
- }>;
547
- /**
548
- * Withdraw BTC and execute transfer (Complete Flow)
549
- *
550
- * Performs both Phase 1 (authorization) and Phase 2 (execution) in sequence:
551
- * 1. Authorizes withdrawal on contract (withdrawBTC)
552
- * 2. Executes pending Bitcoin transfers (signs and broadcasts)
553
- *
554
- * @param positionId - Position identifier
555
- * @param withdrawalAddress - Bitcoin address to receive withdrawn funds
556
- * @param withdrawalAmount - Total amount to deduct from vault in satoshis
557
- * @param networkFee - Network fee for Bitcoin transaction in satoshis
558
- * @param rpcUrl - Optional RPC URL override for LIT Action (for local testing)
559
- * @param customBitcoinRpcUrl - Optional custom Bitcoin RPC URL (for local testing)
560
- * @returns Complete withdrawal result with both authorization and execution details
561
- */
562
- withdrawBTCAndExecute(positionId: string, withdrawalAddress: string, withdrawalAmount: number, networkFee: number): Promise<{
563
- success: boolean;
564
- authorization?: BTCWithdrawalResult;
565
- transfers?: Array<{
566
- success: boolean;
567
- utxoIdentifier?: string;
568
- txid?: string;
569
- amountSent?: number;
570
- networkFee?: number;
571
- destination?: string;
572
- error?: string;
573
- }>;
574
- error?: string;
575
- }>;
576
- /**
577
- * Get loan data by position ID
578
- *
579
- * @param positionId - Position ID
580
- * @param enrichBalance - Whether to enrich with current Bitcoin balance
581
- * @returns Detailed loan data
582
- */
583
- getLoanById(positionId: string, enrichBalance?: boolean): Promise<Result<LoanDataDetail | null, SDKError>>;
584
- /**
585
- * Get loan data by PKP ID
586
- *
587
- * @param pkpId - PKP token ID
588
- * @param enrichBalance - Whether to enrich with current Bitcoin balance
589
- * @returns Loan data
590
- */
591
- getLoanByPkpId(pkpId: string, enrichBalance?: boolean): Promise<Result<LoanDataDetail | null, SDKError>>;
592
- /**
593
- * Get loans for a borrower
594
- *
595
- * @param borrower - Borrower address
596
- * @param pagination - Optional pagination parameters (page, pageSize)
597
- * @returns Paginated loans response with loans array, page info, and total count
598
- */
599
- getLoansByBorrower(borrower: string, pagination?: {
600
- page: number;
601
- pageSize: number;
602
- }, orderBy?: "createdAt" | "lastUpdatedAt" | "ucdDebt", orderDirection?: "asc" | "desc"): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
603
- /**
604
- * Get all active loans
605
- *
606
- * @param pagination - Optional pagination parameters (page, pageSize)
607
- * @returns Paginated loans response with loans array, page info, and total count
608
- */
609
- getActiveLoans(pagination?: {
610
- page: number;
611
- pageSize: number;
612
- }): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
613
- /**
614
- * Get loans by state/status
615
- *
616
- * @param state - Loan state (PENDING_DEPOSIT, ACTIVE, EXPIRED, REPAID, LIQUIDATED, EXTENDED, CLOSED)
617
- * @param pagination - Optional pagination parameters (page, pageSize)
618
- * @returns Paginated loans response with loans array, page info, and total count
619
- */
620
- getLoansByState(state: string, pagination?: {
621
- page: number;
622
- pageSize: number;
623
- }): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
624
- /**
625
- * Get all loans with pagination
626
- *
627
- * @param pagination - Pagination parameters (page, maxRows, orderBy, orderDirection)
628
- * @param enrichBalance - Whether to enrich loans with Bitcoin balance (not used currently)
629
- * @param source - Data source: "subgraph" (default) or "contract"
630
- * @returns Paginated loans response with loans array, page info, and total count
631
- */
632
- getLoansAll(pagination?: {
633
- page?: number;
634
- maxRows?: number;
635
- orderBy?: "createdAt" | "lastUpdatedAt" | "ucdDebt";
636
- orderDirection?: "asc" | "desc";
637
- }, source?: "subgraph" | "contract"): Promise<Result<import("../interfaces/chunks/loan-operations.i").PaginatedLoansResponse, SDKError>>;
638
- /**
639
- * Get all events for a loan position from the subgraph
640
- */
641
- getLoanEvents(positionId: string, filter?: import("../types/event-types").LoanEventsFilter): Promise<Result<import("../types/event-types").LoanEvents, SDKError>>;
642
- /**
643
- * Get protocol-wide events across all indexed entity types.
644
- * Returns a merged, sorted discriminated-union timeline.
645
- * Narrow to a position with filter.positionId, or restrict event kinds with filter.kinds.
646
- */
647
- getAllEvents(filter?: import("../types/protocol-event-types").ProtocolEventsFilter): Promise<import("../types/protocol-event-types").ProtocolEventsResult>;
648
- /**
649
- * Return PSM-supported stablecoins from the subgraph, including indexed reserves,
650
- * fees, exchange rate, and volume stats.
651
- *
652
- * @param onlySupported - When true (default) filters to currently-supported coins only.
653
- */
654
- getPSMStablecoins(onlySupported?: boolean): Promise<SupportedStablecoinData[]>;
655
- /**
656
- * Return the live on-chain swap and redeem limits for a single stablecoin in the PSM.
657
- * All amounts are returned as bigint in the token's native decimals (stablecoin decimals
658
- * for swap limits, 18 decimals for redeem limits which are denominated in UCD).
659
- *
660
- * @param stablecoinAddress - EVM address of the stablecoin to query.
661
- */
662
- getPSMLimits(stablecoinAddress: string): Promise<{
663
- minSwapAmount: bigint;
664
- maxSwapAmount: bigint;
665
- minRedeemAmount: bigint;
666
- maxRedeemAmount: bigint;
667
- }>;
668
- /**
669
- * Return the live on-chain available reserve balance for a single stablecoin in the PSM.
670
- * Prefer this over the subgraph `reserves` field when freshness matters (e.g. pre-swap validation).
671
- *
672
- * @param stablecoinAddress - EVM address of the stablecoin to query.
673
- */
674
- getPSMAvailableReserves(stablecoinAddress: string): Promise<bigint>;
675
- /**
676
- * Execute a PSM stablecoin → UCD swap.
677
- * Handles stablecoin approval to the PSM contract if the current allowance is insufficient.
678
- *
679
- * @param params.stablecoinAddress - ERC-20 address of the stablecoin to swap in
680
- * @param params.amountWei - Stablecoin amount in native decimals (bigint)
681
- * @param params.minUcdOutWei - Minimum UCD to receive; reverts if below this (1% slippage guard)
682
- * @param params.signer - Connected signer for the approval and swap transactions
683
- */
684
- psmSwap(params: {
685
- stablecoinAddress: string;
686
- amountWei: bigint;
687
- minUcdOutWei: bigint;
688
- signer: Signer;
689
- }): Promise<{
690
- hash: string;
691
- blockNumber: number;
692
- }>;
693
- /**
694
- * Execute a PSM UCD → stablecoin redeem.
695
- * Handles UCD approval to UCDController (not PSM) to satisfy the M-4 burn allowance guard:
696
- * UCDToken.burn(from, amount) calls _spendAllowance(from, msg.sender=ucdController, amount).
697
- *
698
- * @param params.stablecoinAddress - ERC-20 address of the stablecoin to receive
699
- * @param params.ucdAmountWei - UCD amount to redeem (18 decimals, bigint)
700
- * @param params.minStablecoinOutWei - Minimum stablecoin to receive (slippage guard)
701
- * @param params.signer - Connected signer
702
- */
703
- psmRedeem(params: {
704
- stablecoinAddress: string;
705
- ucdAmountWei: bigint;
706
- minStablecoinOutWei: bigint;
707
- signer: Signer;
708
- }): Promise<{
709
- hash: string;
710
- blockNumber: number;
711
- }>;
712
- /**
713
- * Wait for the subgraph to index up to (and including) the given block number.
714
- * Call after on-chain actions (createLoan, mintUCD, etc.) before querying the subgraph.
715
- *
716
- * @param targetBlock - Block number the subgraph must have indexed
717
- * @param options - Override timeout/interval for this call
718
- * @throws if timeout is reached before subgraph catches up
719
- */
720
- /**
721
- * Get Bitcoin balance for an address
722
- *
723
- * @param address - Bitcoin address
724
- * @returns Balance in satoshis
725
- */
726
- getBitcoinBalance(address: string): Promise<Result<import("./bitcoin/bitcoin-operations.module").EnrichedBitcoinBalance, SDKError>>;
727
- /**
728
- * Get the current Bitcoin price
729
- *
730
- * @returns the current Bitcoin price in USD
731
- */
732
- getBitcoinPrice(): Promise<{
733
- price: number;
734
- priceE8: string;
735
- timestamp: number;
736
- source: string;
737
- signature?: undefined;
738
- signer?: undefined;
739
- } | {
740
- price: number;
741
- priceE8: string;
742
- timestamp: number;
743
- source: string;
744
- signature: string | undefined;
745
- signer: string | undefined;
746
- }>;
747
- /**
748
- * Derive Bitcoin addresses from PKP public key
749
- *
750
- * @param publicKey - PKP public key
751
- * @returns Bitcoin addresses for all networks
752
- */
753
- deriveBitcoinAddresses(publicKey: string): Promise<Result<import("../interfaces/chunks/loan-operations.i").BitcoinAddresses, SDKError>>;
754
- /**
755
- * Get PKP data by token ID
756
- *
757
- * @param tokenId - PKP token ID
758
- * @returns PKP data
759
- */
760
- getPKPData(tokenId: string): Promise<Result<PKPData | null, SDKError>>;
761
- /**
762
- * Get PKP public key by token ID
763
- *
764
- * @param tokenId - PKP token ID
765
- * @returns PKP public key
766
- */
767
- getPKPPublicKey(tokenId: string): Promise<Result<string, SDKError>>;
768
- /**
769
- * Get all available loan terms with their fees
770
- *
771
- * Retrieves all valid loan terms from the TermManager contract along with
772
- * their origination fees and extension/renewal fees.
773
- *
774
- * @returns Result containing array of terms with fees
775
- *
776
- * @example
777
- * ```typescript
778
- * const result = await sdk.getTermsWithFees();
779
- * if (result.success) {
780
- * result.value.terms.forEach(term => {
781
- * console.log(`${term.termMonths} months: ${term.originationFeeBps}bps origination, ${term.extensionFeeBps}bps renewal`);
782
- * });
783
- * }
784
- * ```
785
- */
786
- getTermsWithFees(): Promise<Result<TermsWithFeesResult, SDKError>>;
787
- getProtocolConfig(): Promise<Result<{
788
- liquidationThreshold: string;
789
- minimumLoanValueUcd: string;
790
- minimumLoanValueWei: string;
791
- maxSingleLoanValueUcd: string;
792
- maxSingleLoanValueWei: string;
793
- }, SDKError>>;
794
- getGasBalance(address: string): Promise<Result<{
795
- balanceWei: string;
796
- balanceEth: string;
797
- }, SDKError>>;
798
- getVaultBalance(positionId: string): Promise<Result<{
799
- vaultAddress: string;
800
- balanceSats: string;
801
- balanceBtc: string;
802
- btcPrice: string;
803
- }, SDKError>>;
804
- /**
805
- * Get a PKP-signed TOTAL confirmed Bitcoin balance for a raw vault ADDRESS
806
- * (no positionId) via the `btc-address-balance` LIT Action.
807
- *
808
- * Exercises the balance-query path (BitcoinProviderRegistry decrypt →
809
- * cross-provider consensus → PKP signature) using only an address. This is
810
- * NOT a protocol trusted/available balance: authorized spends are not
811
- * subtracted, and the returned signature is an `AddressBalanceAttestation`
812
- * (NOT a `BalanceConfirmation` — it is not consumable by
813
- * `PositionManager.updateBalance`).
814
- */
815
- getAddressBalance(vaultAddress: string): Promise<Result<{
816
- vaultAddress: string;
817
- totalBalanceSats: string;
818
- totalBalanceBtc: string;
819
- providerCount: number;
820
- signature: string;
821
- validatorPkp: string;
822
- }, SDKError>>;
823
- /**
824
- * Mint mock BTC tokens (test networks only)
825
- *
826
- * @param amount - Amount in satoshis
827
- * @param recipient - Recipient address
828
- * @returns Transaction result
829
- */
830
- mintMockBTC(amount: Satoshis, recipient: string): Promise<Result<import("./mock/mock-token-manager.module").MockTokenTransactionResult, SDKError>>;
831
- /**
832
- * Approve mock BTC spending (test networks only)
833
- *
834
- * @param spender - Spender address
835
- * @param amount - Amount in satoshis
836
- * @returns Transaction result
837
- */
838
- approveMockBTC(spender: string, amount: Satoshis): Promise<Result<import("./mock/mock-token-manager.module").MockTokenTransactionResult, SDKError>>;
839
- /**
840
- * Get SDK configuration
841
- */
842
- getConfig(): DiamondHandsSDKConfig;
843
- /**
844
- * Clear all caches
845
- */
846
- clearAllCaches(): void;
847
- /**
848
- * Get cache statistics
849
- */
850
- getCacheStats(): Record<string, import("./cache/cache-manager.module").CacheStats>;
851
- /**
852
- * Get contract manager (for advanced usage)
853
- */
854
- getContractManager(): ContractManager;
855
- /**
856
- * Get Bitcoin operations module (for advanced usage)
857
- */
858
- getBitcoinOperations(): BitcoinOperations;
859
- /**
860
- * Check if running on production network
861
- */
862
- private isProductionNetwork;
863
- /**
864
- * Get Bitcoin network based on chain.
865
- *
866
- * Priority order:
867
- * 1. explicit `bitcoinNetwork` config override
868
- * 2. first configured bitcoinProvider's `network` field — keeps provider
869
- * config as the single source of truth (e.g. Sepolia EVM + regtest faucet)
870
- * 3. chain-name inference (mainnet/sepolia/other)
871
- */
872
- private getBitcoinNetwork;
873
- /**
874
- * Extract error message from LIT Action response
875
- * Checks both `error` and `reason` fields and parses nested error structures
876
- *
877
- * @private
878
- * @remarks Production-ready error parser for LIT Protocol responses
879
- * Will be integrated into core methods in Round 2
880
- */
881
- private extractLitActionError;
882
- /**
883
- * Build the Chipotle service-mode fallback config for getPKPPublicKeyFromTokenId.
884
- * Returns undefined in standalone mode so the helper falls back to throwing.
885
- */
886
- private getChipotlePublicKeyFallback;
887
- /**
888
- * Get provider or throw error
889
- */
890
- private getProviderOrThrow;
891
- /**
892
- * Get signer or throw error
893
- */
894
- private getSignerOrThrow;
895
- /**
896
- * Get contract addresses or throw error
897
- */
898
- private getContractAddressesOrThrow;
899
- /**
900
- * Ensure SDK is initialized
901
- */
902
- private ensureInitialized;
903
- /**
904
- * Convert decimal position ID to bytes32 format
905
- */
906
- private toBytes32;
907
- /**
908
- * Check if an error indicates a technical failure vs business logic rejection
909
- */
910
- /**
911
- * Get position details view from contract
912
- * Queries PositionManagerCoreModule directly for reliability (subgraph listens to core module)
913
- */
914
- getPositionDetailsView(positionId: string): Promise<PositionDetailsView>;
915
- /**
916
- * Get position by ID (internal helper)
917
- * Uses getPositionDetailsView which queries core module directly
918
- */
919
- private getPosition;
920
- /**
921
- * Verify position exists in core contract (PositionManagerCoreModule)
922
- * This is critical because mint operations check the core contract, not PositionManager
923
- *
924
- * @param positionId - Position ID to verify
925
- * @param retries - Number of retries with exponential backoff (default: 3)
926
- * @param retryDelayMs - Initial retry delay in milliseconds (default: 1000)
927
- * @returns Promise<boolean> - true if position exists, false otherwise
928
- */
929
- verifyPositionExistsInCore(positionId: string, retries?: number, retryDelayMs?: number): Promise<boolean>;
930
- /**
931
- * Get loan operations accessor
932
- * Returns a helper object for interacting with loan operations contract
933
- */
934
- loanOps(): {
935
- getProtocolConfig(): Promise<{
936
- liquidationThreshold: any;
937
- minimumLoanValueUcd: string;
938
- minimumLoanValueWei: any;
939
- maxSingleLoanValueUcd: string;
940
- maxSingleLoanValueWei: string;
941
- }>;
942
- };
943
- /**
944
- * Calculate reveal delay for MEV protection in commit-reveal liquidation
945
- * @param positionId Position identifier (for entropy)
946
- * @param quantumTimestamp LIT quantum timestamp (for additional entropy)
947
- * @returns Delay in seconds before reveal phase can execute
948
- */
949
- private calculateRevealDelay;
950
- /**
951
- * Call the liquidation validator server endpoint to obtain a signed authorization
952
- * (signature + quantumTimestamp + btcPrice + btcAmountSats) for the current market state.
953
- * Invoked once at commit time and again at reveal time (H-7: reveal requires a fresh
954
- * signature so it cannot execute against a stale commit-time BTC vault snapshot).
955
- */
956
- private requestLiquidationAuthorization;
957
- /**
958
- * Calculate the exact reveal delay by replicating LiquidationManager._calculateRandomizedDelay.
959
- * Reads vrfSeeds[positionId] from the contract and applies the same two-step keccak256 formula.
960
- * Falls back to the local estimate if the contract read fails.
961
- */
962
- private calculateRevealDelayFromContract;
963
- /**
964
- * Wait for the specified delay period (MEV protection)
965
- * @param delaySeconds Number of seconds to wait
966
- */
967
- private waitForRevealDelay;
968
- }
969
- export {};