@gvnrdao/dh-sdk 0.0.288 → 0.0.289

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/833.browser.js +1 -1
  2. package/browser/dist/browser.js +1 -1
  3. package/browser/dist/browser.js.LICENSE.txt +5 -10
  4. package/dist/constants/chunks/contract-abis.d.ts +20 -0
  5. package/dist/constants/chunks/deployment-addresses.d.ts +79 -0
  6. package/dist/constants/chunks/encrypted-provider-params.d.ts +21 -0
  7. package/dist/constants/chunks/environment.browser.d.ts +44 -0
  8. package/dist/constants/chunks/environment.d.ts +57 -0
  9. package/dist/constants/chunks/network-configs.d.ts +72 -0
  10. package/dist/constants/chunks/sdk-config.d.ts +33 -0
  11. package/dist/constants/chunks/sdk-limits.d.ts +66 -0
  12. package/dist/constants/index.d.ts +15 -0
  13. package/dist/contracts/typechain-contracts/common.d.ts +50 -0
  14. package/dist/contracts/typechain-contracts/factories/src/psm/SimplePSMV2__factory.d.ts +1996 -0
  15. package/dist/contracts/typechain-contracts/src/psm/SimplePSMV2.d.ts +1198 -0
  16. package/dist/deployments.js +21 -45
  17. package/dist/deployments.mjs +21 -45
  18. package/dist/graphs/client.d.ts +22 -0
  19. package/dist/graphs/diamond-hands.d.ts +259 -0
  20. package/dist/index.d.ts +56 -0
  21. package/dist/index.js +1123 -628
  22. package/dist/index.mjs +1123 -628
  23. package/dist/interfaces/chunks/btc.i.d.ts +36 -0
  24. package/dist/interfaces/chunks/config.i.d.ts +270 -0
  25. package/dist/interfaces/chunks/contract-interactions.i.d.ts +64 -0
  26. package/dist/interfaces/chunks/contract-types.i.d.ts +171 -0
  27. package/dist/interfaces/chunks/lit-actions-results.i.d.ts +165 -0
  28. package/dist/interfaces/chunks/lit-actions.i.d.ts +98 -0
  29. package/dist/interfaces/chunks/loan-operations.i.d.ts +331 -0
  30. package/dist/interfaces/chunks/pkp-integration.i.d.ts +87 -0
  31. package/dist/interfaces/chunks/position-query.i.d.ts +76 -0
  32. package/dist/interfaces/chunks/requests.i.d.ts +55 -0
  33. package/dist/interfaces/chunks/ucd-minting.i.d.ts +34 -0
  34. package/dist/interfaces/chunks/utility.i.d.ts +64 -0
  35. package/dist/interfaces/index.d.ts +17 -0
  36. package/dist/modules/bitcoin/bitcoin-operations.module.d.ts +254 -0
  37. package/dist/modules/cache/cache-manager.module.d.ts +259 -0
  38. package/dist/modules/contract/contract-manager.module.d.ts +152 -0
  39. package/dist/modules/diamond-hands-sdk.d.ts +969 -0
  40. package/dist/modules/loan/loan-creator.module.d.ts +132 -0
  41. package/dist/modules/loan/loan-query.module.d.ts +204 -0
  42. package/dist/modules/mock/mock-token-manager.module.d.ts +83 -0
  43. package/dist/modules/pkp/pkp-manager.module.d.ts +136 -0
  44. package/dist/modules/withdrawal-address/withdrawal-address.module.d.ts +78 -0
  45. package/dist/protocol/protocol-pause.d.ts +19 -0
  46. package/dist/server.d.ts +17 -0
  47. package/dist/types/authorization-params.d.ts +160 -0
  48. package/dist/types/branded/domain-values.d.ts +138 -0
  49. package/dist/types/branded/ids.d.ts +23 -0
  50. package/dist/types/event-types.d.ts +261 -0
  51. package/dist/types/graph-dtos.d.ts +228 -0
  52. package/dist/types/loanStatus.d.ts +10 -0
  53. package/dist/types/protocol-event-types.d.ts +99 -0
  54. package/dist/types/result.d.ts +120 -0
  55. package/dist/utils/address-conversion.utils.d.ts +51 -0
  56. package/dist/utils/bitcoin-address-cache.utils.d.ts +87 -0
  57. package/dist/utils/bitcoin-provider.utils.d.ts +84 -0
  58. package/dist/utils/btc-withdrawal-message.d.ts +60 -0
  59. package/dist/utils/chunks/bitcoin-utils.d.ts +85 -0
  60. package/dist/utils/chunks/eip1559-broadcast.utils.d.ts +33 -0
  61. package/dist/utils/eip712-login.d.ts +34 -0
  62. package/dist/utils/error-handler.d.ts +106 -0
  63. package/dist/utils/ethers-interop.utils.d.ts +146 -0
  64. package/dist/utils/extend-authorization.utils.d.ts +61 -0
  65. package/dist/utils/lit-signature.utils.d.ts +6 -0
  66. package/dist/utils/logger.utils.d.ts +142 -0
  67. package/dist/utils/mint-authorization.utils.d.ts +248 -0
  68. package/dist/utils/position-delegate.utils.d.ts +41 -0
  69. package/dist/utils/quantum-timing.d.ts +75 -0
  70. package/dist/utils/server-session.d.ts +50 -0
  71. package/dist/utils/service-endpoint-policy.d.ts +16 -0
  72. package/dist/utils/signature-tempering.utils.d.ts +34 -0
  73. package/dist/utils/telegram-messaging.utils.d.ts +188 -0
  74. package/package.json +1 -1
  75. package/browser/dist/397.browser.js +0 -2
  76. package/browser/dist/397.browser.js.LICENSE.txt +0 -1
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Loan Creator Module
3
+ *
4
+ * Responsible for:
5
+ * - Orchestrating the multi-step loan creation flow
6
+ * - Creating PKP for custody
7
+ * - Authorizing loan creation
8
+ * - Submitting loan creation transaction
9
+ * - Building comprehensive audit trail
10
+ *
11
+ * Flow: PKP Creation → Authorization → Contract Call → Verification
12
+ */
13
+ import { type Wallet } from "ethers";
14
+ import { Result } from "../../types/result";
15
+ import { SDKError } from "../../utils/error-handler";
16
+ import type { PKPManager } from "../pkp/pkp-manager.module";
17
+ import type { ContractManager } from "../contract/contract-manager.module";
18
+ import type { BitcoinOperations } from "../bitcoin/bitcoin-operations.module";
19
+ import type { CreateLoanRequest, CreateLoanResult } from "../../interfaces/chunks/loan-operations.i";
20
+ import type { LitOps } from "@gvnrdao/dh-lit-ops";
21
+ /**
22
+ * Loan Creator configuration
23
+ */
24
+ export interface LoanCreatorConfig {
25
+ /** LitOps instance for PKP operations */
26
+ litOps: LitOps;
27
+ /** PKP Manager for PKP operations */
28
+ pkpManager: PKPManager;
29
+ /** Contract Manager for contract interactions */
30
+ contractManager: ContractManager;
31
+ /** Bitcoin Operations for address derivation */
32
+ bitcoinOperations: BitcoinOperations;
33
+ /** Wallet for contract transactions (Ethereum mainnet/Sepolia) */
34
+ wallet: Wallet;
35
+ /** Wallet for LIT Protocol operations (Yellowstone signer, capacity credits owner) - standalone mode only */
36
+ litOpsSigner?: Wallet;
37
+ /** SDK mode: 'service' or 'standalone' */
38
+ mode?: "service" | "standalone";
39
+ /** LIT Action CID for loan creation */
40
+ litActionCid: string;
41
+ /** User ID (typically wallet address) */
42
+ userId: string;
43
+ /** Lit Protocol network (e.g. 'chipotle') */
44
+ litNetwork?: string;
45
+ /** Enable debug logging */
46
+ debug?: boolean;
47
+ /** Transaction timeout (ms) */
48
+ transactionTimeoutMs?: number;
49
+ /** Validator version for loan creation (createPosition) - REQUIRED */
50
+ loanCreationValidatorVersion: number;
51
+ /** EVM JSON-RPC URL for service-mode PKP flow (forwards to lit-ops-server) */
52
+ ethRpcUrl?: string;
53
+ /** Security testing: Temper signatures to test contract validation */
54
+ temperSignaturesTest?: boolean;
55
+ }
56
+ /**
57
+ * Loan creation audit trail
58
+ */
59
+ export interface LoanCreationAudit {
60
+ /** PKP creation details */
61
+ pkpCreation: {
62
+ tokenId: string;
63
+ publicKey: string;
64
+ ethAddress: string;
65
+ timestamp: number;
66
+ };
67
+ /** Bitcoin addresses derived */
68
+ bitcoinAddresses: {
69
+ mainnet: string;
70
+ testnet: string;
71
+ regtest: string;
72
+ };
73
+ /** Authorization details */
74
+ authorization: {
75
+ signature: string;
76
+ timestamp: number;
77
+ };
78
+ /** Contract call details */
79
+ contractCall: {
80
+ transactionHash: string;
81
+ blockNumber: number;
82
+ gasUsed: string;
83
+ timestamp: number;
84
+ };
85
+ }
86
+ /**
87
+ * Loan Creator Module
88
+ *
89
+ * Orchestrates the complete loan creation flow with comprehensive error handling
90
+ */
91
+ export declare class LoanCreator {
92
+ private readonly config;
93
+ private readonly transactionTimeoutMs;
94
+ private pkpValidationRegistryAddressCache;
95
+ constructor(config: LoanCreatorConfig);
96
+ /**
97
+ * Create a new loan
98
+ *
99
+ * Complete flow:
100
+ * 1. Create PKP for Bitcoin custody
101
+ * 2. Derive Bitcoin addresses
102
+ * 3. Build authorization signature
103
+ * 4. Authorize loan creation (LIT Action)
104
+ * 5. Submit loan creation transaction
105
+ * 6. Wait for confirmation
106
+ * 7. Build audit trail
107
+ *
108
+ * @param request - Loan creation request
109
+ * @returns Loan creation result with audit trail
110
+ */
111
+ createLoan(request: CreateLoanRequest): Promise<Result<CreateLoanResult, SDKError>>;
112
+ /**
113
+ * Step 2: Derive Bitcoin addresses from PKP public key
114
+ */
115
+ private deriveBitcoinAddresses;
116
+ /**
117
+ * Step 3: Submit loan creation transaction
118
+ */
119
+ private submitLoanCreation;
120
+ /**
121
+ * Extract position ID from transaction receipt
122
+ */
123
+ private extractPositionId;
124
+ /**
125
+ * Get vault address for current network
126
+ */
127
+ private getVaultAddressForNetwork;
128
+ }
129
+ /**
130
+ * Factory function to create a LoanCreator instance
131
+ */
132
+ export declare function createLoanCreator(config: LoanCreatorConfig): Result<LoanCreator, SDKError>;
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Loan Query Module
3
+ *
4
+ * Responsible for:
5
+ * - Querying loan data from subgraph
6
+ * - Enriching loans with Bitcoin balance data
7
+ * - Caching query results for performance
8
+ * - Supporting pagination for large result sets
9
+ *
10
+ * Uses the existing DiamondHandsGraphClient for subgraph queries
11
+ */
12
+ import { Result } from "../../types/result";
13
+ import { SDKError } from "../../utils/error-handler";
14
+ import type { BitcoinOperations } from "../bitcoin/bitcoin-operations.module";
15
+ import type { Cache } from "../cache/cache-manager.module";
16
+ import type { LoanData, LoanDataDetail, PaginatedLoansResponse } from "../../interfaces/chunks/loan-operations.i";
17
+ import type { LoanEvents, LoanEventsFilter } from "../../types/event-types";
18
+ import { DiamondHandsGraphClient } from "@graphs/diamond-hands";
19
+ import { type Provider } from "ethers";
20
+ /**
21
+ * Loan query filters
22
+ */
23
+ export interface LoanQueryFilters {
24
+ /** Filter by borrower address */
25
+ borrower?: string;
26
+ /** Filter by status */
27
+ status?: number;
28
+ /** Filter by minimum collateral ratio (BPS) */
29
+ minCollateralRatio?: number;
30
+ /** Filter by maximum collateral ratio (BPS) */
31
+ maxCollateralRatio?: number;
32
+ /** Order by field */
33
+ orderBy?: "createdAt" | "lastUpdatedAt" | "ucdDebt";
34
+ /** Order direction */
35
+ orderDirection?: "asc" | "desc";
36
+ }
37
+ /**
38
+ * Pagination parameters
39
+ */
40
+ export interface PaginationParams {
41
+ /** Page number (0-indexed) */
42
+ page: number;
43
+ /** Number of items per page */
44
+ pageSize: number;
45
+ }
46
+ /**
47
+ * Loan Query configuration
48
+ */
49
+ export interface LoanQueryConfig {
50
+ /** Subgraph client for queries */
51
+ graphClient: DiamondHandsGraphClient;
52
+ /** Bitcoin operations for balance enrichment */
53
+ bitcoinOperations: BitcoinOperations;
54
+ /** Ethereum provider for PKP public key retrieval */
55
+ provider?: Provider;
56
+ /** PositionManagerCoreModule address — used as fallback vault address source for Chipotle loans */
57
+ positionManagerCoreAddress?: string;
58
+ /** Cache for loan query results (keyed by PKP ID) */
59
+ cache?: Cache<LoanData>;
60
+ /** Enable debug logging */
61
+ debug?: boolean;
62
+ /** Default page size for pagination */
63
+ defaultPageSize?: number;
64
+ }
65
+ /**
66
+ * Loan Query Module
67
+ *
68
+ * Handles all loan data queries with caching and balance enrichment
69
+ */
70
+ export declare class LoanQuery {
71
+ private readonly config;
72
+ private readonly defaultPageSize;
73
+ constructor(config: LoanQueryConfig);
74
+ /**
75
+ * Get loan by position ID
76
+ *
77
+ * @param positionId - Position ID
78
+ * @param enrichBalance - Whether to enrich with Bitcoin balance
79
+ * @returns Detailed loan data
80
+ */
81
+ getLoanById(positionId: string, enrichBalance?: boolean): Promise<Result<LoanDataDetail | null, SDKError>>;
82
+ /**
83
+ * Get loan by PKP ID
84
+ *
85
+ * @param pkpId - PKP token ID
86
+ * @param enrichBalance - Whether to enrich with Bitcoin balance
87
+ * @returns Loan data
88
+ */
89
+ getLoanByPkpId(pkpId: string, enrichBalance?: boolean): Promise<Result<LoanDataDetail | null, SDKError>>;
90
+ /**
91
+ * Get loans with filters and pagination
92
+ *
93
+ * @param filters - Query filters
94
+ * @param pagination - Pagination parameters
95
+ * @returns Paginated loans response
96
+ */
97
+ getLoans(filters?: LoanQueryFilters, pagination?: PaginationParams): Promise<Result<PaginatedLoansResponse, SDKError>>;
98
+ /**
99
+ * Get loans with BTC balance data from Bitcoin network
100
+ *
101
+ * Same as getLoans but includes actual Bitcoin balance for each position's vault.
102
+ * Queries BTC balances in parallel for performance.
103
+ *
104
+ * @param filters - Query filters
105
+ * @param pagination - Pagination parameters
106
+ * @returns Paginated loans response with BTC balance data
107
+ */
108
+ getLoansWithBtc(filters?: LoanQueryFilters, pagination?: PaginationParams): Promise<Result<PaginatedLoansResponse, SDKError>>;
109
+ /**
110
+ * Enrich loans with vault addresses derived from PKP public keys
111
+ *
112
+ * @param loans - Array of loans to enrich
113
+ * @returns Enriched loans with vault addresses for all networks
114
+ */
115
+ private enrichLoansWithVaultAddresses;
116
+ /**
117
+ * Map numeric status to string for subgraph queries
118
+ */
119
+ private mapStatusToString;
120
+ /**
121
+ * Map string status to numeric for filtering
122
+ */
123
+ private mapStringToStatus;
124
+ /**
125
+ * Validate if a string is a valid loan status
126
+ */
127
+ private isValidStatus;
128
+ /**
129
+ * Get loans for a borrower
130
+ *
131
+ * @param borrower - Borrower address
132
+ * @param pagination - Pagination parameters
133
+ * @returns Paginated loans for borrower
134
+ */
135
+ getLoansByBorrower(borrower: string, pagination?: PaginationParams, orderBy?: "createdAt" | "lastUpdatedAt" | "ucdDebt", orderDirection?: "asc" | "desc"): Promise<Result<PaginatedLoansResponse, SDKError>>;
136
+ /**
137
+ * Get active loans (status = ACTIVE)
138
+ *
139
+ * @param pagination - Pagination parameters
140
+ * @returns Paginated active loans
141
+ */
142
+ getActiveLoans(pagination?: PaginationParams): Promise<Result<PaginatedLoansResponse, SDKError>>;
143
+ /**
144
+ * Get loans by state/status
145
+ *
146
+ * @param state - Loan state (PENDING_DEPOSIT, PENDING_MINT, ACTIVE, EXPIRED, LIQUIDATABLE, LIQUIDATED, REPAID, CLOSED)
147
+ * @param pagination - Pagination parameters
148
+ * @returns Paginated loans matching the specified state
149
+ */
150
+ getLoansByState(state: string, pagination?: PaginationParams): Promise<Result<PaginatedLoansResponse, SDKError>>;
151
+ /**
152
+ * Enrich a loan with current Bitcoin balance
153
+ *
154
+ * Note: btcAmount field removed - balance is now queried on-chain via lit-actions with signature validation
155
+ * This method is kept for potential future use but no longer sets btcAmount
156
+ */
157
+ private enrichLoanWithBalance;
158
+ /**
159
+ * Get all events for a loan position
160
+ *
161
+ * Retrieves complete event history including:
162
+ * - Payments (full repayments, partial payments, extension fees)
163
+ * - Status updates with reasons
164
+ * - Liquidation event (if liquidated)
165
+ * - UCD mint events
166
+ * - Community fee distributions
167
+ *
168
+ * @param positionId - Position ID to query events for
169
+ * @param filter - Optional filters (date range, event types, etc.)
170
+ * @returns Complete event history for the position
171
+ *
172
+ * @example
173
+ * ```typescript
174
+ * // Get all events
175
+ * const result = await loanQuery.getLoanEvents('0x123...');
176
+ *
177
+ * // Get only payment events
178
+ * const paymentsOnly = await loanQuery.getLoanEvents('0x123...', {
179
+ * eventTypes: ['payment']
180
+ * });
181
+ *
182
+ * // Get events in date range
183
+ * const recent = await loanQuery.getLoanEvents('0x123...', {
184
+ * fromTimestamp: '1640000000',
185
+ * toTimestamp: '1650000000'
186
+ * });
187
+ * ```
188
+ */
189
+ getLoanEvents(positionId: string, filter?: LoanEventsFilter): Promise<Result<LoanEvents, SDKError>>;
190
+ /**
191
+ * Clear loan cache
192
+ *
193
+ * @param pkpId - PKP ID to clear, or undefined to clear all
194
+ */
195
+ clearCache(pkpId?: string): void;
196
+ /**
197
+ * Get cache statistics
198
+ */
199
+ getCacheStats(): import("../cache/cache-manager.module").CacheStats | null;
200
+ }
201
+ /**
202
+ * Factory function to create a LoanQuery instance
203
+ */
204
+ export declare function createLoanQuery(config: LoanQueryConfig): Result<LoanQuery, SDKError>;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Mock Token Manager Module
3
+ *
4
+ * Responsible for:
5
+ * - Managing mock Bitcoin tokens for testing
6
+ * - Minting mock BTC tokens
7
+ * - Approving mock BTC spending
8
+ * - Querying mock BTC balances
9
+ *
10
+ * This module is for testing only and should not be used in production
11
+ */
12
+ import { Result } from '../../types/result';
13
+ import { Satoshis } from '../../types/branded/domain-values';
14
+ import { SDKError } from '../../utils/error-handler';
15
+ import type { ContractManager } from '../contract/contract-manager.module';
16
+ /**
17
+ * Mock Token Manager configuration
18
+ */
19
+ export interface MockTokenManagerConfig {
20
+ /** Contract manager for accessing mock token contracts */
21
+ contractManager: ContractManager;
22
+ /** Network identifier */
23
+ network: string;
24
+ /** Enable debug logging */
25
+ debug?: boolean;
26
+ /** Transaction timeout (ms) */
27
+ transactionTimeoutMs?: number;
28
+ }
29
+ /**
30
+ * Mock token transaction result
31
+ */
32
+ export interface MockTokenTransactionResult {
33
+ /** Transaction hash */
34
+ transactionHash: string;
35
+ /** Block number */
36
+ blockNumber: number;
37
+ /** Gas used */
38
+ gasUsed: string;
39
+ /** Transaction was successful */
40
+ success: boolean;
41
+ }
42
+ /**
43
+ * Mock Token Manager Module
44
+ *
45
+ * Provides utilities for working with mock Bitcoin tokens in test environments
46
+ *
47
+ * ⚠️ WARNING: This module is for testing only. Do not use in production.
48
+ */
49
+ export declare class MockTokenManager {
50
+ private readonly config;
51
+ constructor(config: MockTokenManagerConfig);
52
+ /**
53
+ * Mint mock BTC tokens
54
+ *
55
+ * @param amount - Amount to mint in satoshis
56
+ * @param recipient - Recipient address
57
+ * @returns Transaction result
58
+ */
59
+ mintMockBTC(amount: Satoshis, recipient: string): Promise<Result<MockTokenTransactionResult, SDKError>>;
60
+ /**
61
+ * Approve mock BTC spending
62
+ *
63
+ * @param spender - Spender address
64
+ * @param amount - Amount to approve in satoshis
65
+ * @returns Transaction result
66
+ */
67
+ approveMockBTC(spender: string, amount: Satoshis): Promise<Result<MockTokenTransactionResult, SDKError>>;
68
+ /**
69
+ * Get mock BTC balance
70
+ *
71
+ * @param address - Address to query
72
+ * @returns Balance in satoshis
73
+ */
74
+ getMockBTCBalance(address: string): Promise<Result<Satoshis, SDKError>>;
75
+ /**
76
+ * Check if current network is production (mainnet)
77
+ */
78
+ private isProductionNetwork;
79
+ }
80
+ /**
81
+ * Factory function to create a MockTokenManager instance
82
+ */
83
+ export declare function createMockTokenManager(config: MockTokenManagerConfig): Result<MockTokenManager, SDKError>;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * PKP Manager Module
3
+ *
4
+ * Responsible for:
5
+ * - Creating new PKPs (via service or direct)
6
+ * - Querying PKP data from contracts
7
+ * - Managing PKP lifecycle
8
+ * - Caching PKP data for performance
9
+ *
10
+ * Supports two modes:
11
+ * - Service mode: Uses lit-ops-server for PKP operations
12
+ * - Direct mode: Directly interacts with LIT Protocol
13
+ */
14
+ import type { Wallet } from "ethers";
15
+ import { Result } from "../../types/result";
16
+ import { SDKError } from "../../utils/error-handler";
17
+ import type { Cache } from "../cache/cache-manager.module";
18
+ import type { PKPData, PKPCreationRequest, PKPCreationResult, PKPValidationResult } from "../../interfaces/chunks/pkp-integration.i";
19
+ import type { SDKMode } from "../../interfaces/chunks/config.i";
20
+ /**
21
+ * PKP Manager configuration
22
+ */
23
+ export interface PKPManagerConfig {
24
+ /** Operation mode: service (via lit-ops-server) or direct (LIT Protocol) */
25
+ mode: SDKMode;
26
+ /** LIT network (e.g. chipotle) */
27
+ litNetwork: string;
28
+ /** Service mode: endpoint for lit-ops-server */
29
+ serviceEndpoint?: string;
30
+ /**
31
+ * Service mode: returns `Authorization`-style headers for each request.
32
+ * Called once per request so the underlying session can refresh as
33
+ * needed. Empty object disables the header (server will 401).
34
+ */
35
+ getAuthHeader?: () => Promise<Record<string, string>>;
36
+ /** Direct mode: wallet for PKP operations */
37
+ litOpsWallet?: Wallet;
38
+ /** Optional cache for PKP data */
39
+ cache?: Cache<PKPData>;
40
+ /** Enable debug logging */
41
+ debug?: boolean;
42
+ /** Timeout for service requests (ms) */
43
+ serviceTimeoutMs?: number;
44
+ /** Max retries for failed operations */
45
+ maxRetries?: number;
46
+ }
47
+ /**
48
+ * PKP Manager Module
49
+ *
50
+ * Manages PKP creation, querying, and lifecycle with support for
51
+ * both service mode and direct mode operations.
52
+ */
53
+ export declare class PKPManager {
54
+ private readonly config;
55
+ private readonly serviceTimeoutMs;
56
+ constructor(config: PKPManagerConfig);
57
+ /**
58
+ * Validate PKPManager configuration
59
+ */
60
+ private validateConfig;
61
+ /**
62
+ * Create a new PKP
63
+ *
64
+ * Routes to service mode or direct mode based on configuration.
65
+ *
66
+ * @param request - PKP creation request
67
+ * @returns PKP creation result
68
+ */
69
+ createPKP(request: PKPCreationRequest): Promise<Result<PKPCreationResult, SDKError>>;
70
+ /**
71
+ * Create PKP via lit-ops-server (service mode)
72
+ */
73
+ private createPKPViaService;
74
+ /**
75
+ * Create PKP directly via LIT Protocol (standalone mode)
76
+ *
77
+ * Note: This is a placeholder implementation. In production, this would
78
+ * use the LIT SDK directly to mint a PKP.
79
+ */
80
+ private createPKPDirect;
81
+ /**
82
+ * Get PKP data by token ID
83
+ *
84
+ * Checks cache first, then queries from service/contract if needed.
85
+ *
86
+ * @param tokenId - PKP token ID
87
+ * @returns PKP data or null if not found
88
+ */
89
+ getPKPData(tokenId: string): Promise<Result<PKPData | null, SDKError>>;
90
+ /**
91
+ * Get PKP data from service
92
+ */
93
+ private getPKPDataFromService;
94
+ /**
95
+ * Get PKP data from contract (direct mode)
96
+ *
97
+ * Note: This is a placeholder. In production, would query PKP registry contract.
98
+ */
99
+ private getPKPDataFromContract;
100
+ /**
101
+ * Get PKP public key from token ID
102
+ *
103
+ * Convenience method that extracts just the public key.
104
+ *
105
+ * @param tokenId - PKP token ID
106
+ * @returns PKP public key
107
+ */
108
+ getPKPPublicKey(tokenId: string): Promise<Result<string, SDKError>>;
109
+ /**
110
+ * Validate that a PKP exists and is active
111
+ *
112
+ * @param tokenId - PKP token ID
113
+ * @returns Validation result
114
+ */
115
+ validatePKP(tokenId: string): Promise<Result<PKPValidationResult, SDKError>>;
116
+ /**
117
+ * Clear PKP from cache
118
+ *
119
+ * Useful when PKP data may have changed.
120
+ *
121
+ * @param tokenId - PKP token ID
122
+ */
123
+ clearCache(tokenId: string): void;
124
+ /**
125
+ * Clear all cached PKP data
126
+ */
127
+ clearAllCache(): void;
128
+ /**
129
+ * Get cache statistics
130
+ */
131
+ getCacheStats(): import("../cache/cache-manager.module").CacheStats | null;
132
+ }
133
+ /**
134
+ * Factory function to create a PKPManager instance
135
+ */
136
+ export declare function createPKPManager(config: PKPManagerConfig): Result<PKPManager, SDKError>;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Withdrawal Address Module
3
+ *
4
+ * Self-service management of a connected wallet's approved Bitcoin withdrawal
5
+ * destinations (BitcoinWithdrawalAddressRegistry). A user adds an address —
6
+ * usable only after the registry's time-lock delay (default 24h) — and may
7
+ * remove it immediately. Withdrawals to non-approved (or still-pending)
8
+ * addresses are rejected on-chain; this module also powers the SDK's
9
+ * early-reject so a doomed withdrawal never reaches the Lit Action.
10
+ *
11
+ * Display lists (with the original address strings) come from the subgraph —
12
+ * the contract stores only keccak256(address). This module exposes the
13
+ * authoritative contract reads (isApproved / hashes / timestamps) and the
14
+ * mutating txs.
15
+ */
16
+ import { type TransactionResponse } from "ethers";
17
+ import type { ContractManager } from "../contract/contract-manager.module";
18
+ import { Result } from "../../types/result";
19
+ import { SDKError } from "../../utils/error-handler";
20
+ export interface WithdrawalAddressModuleConfig {
21
+ contractManager: ContractManager;
22
+ debug?: boolean;
23
+ }
24
+ /** A single approved-address entry as read from the contract (no raw string — see subgraph for that). */
25
+ export interface WithdrawalAddressEntry {
26
+ /** keccak256(bytes(normalizedAddress)). */
27
+ addrHash: string;
28
+ /** Unix seconds when the address was added (0 if absent). */
29
+ addedAt: number;
30
+ /** Unix seconds when the address becomes usable (addedAt-at-add-time + delay). */
31
+ usableAt: number;
32
+ /**
33
+ * Authoritative approval from the contract's own `isApprovedByHash` (chain
34
+ * `block.timestamp` + CURRENT delay) — NOT derived from the client clock or
35
+ * the cached `usableAt`, so it stays correct even if the admin changes the
36
+ * delay after this entry was added.
37
+ */
38
+ approved: boolean;
39
+ }
40
+ export declare class WithdrawalAddressModule {
41
+ private readonly config;
42
+ constructor(config: WithdrawalAddressModuleConfig);
43
+ /** Resolve the registry contract, or fail if it isn't configured for this network. */
44
+ private getRegistry;
45
+ /** True iff the registry is wired for this network (enforcement is active). */
46
+ isConfigured(): boolean;
47
+ /** keccak256 of the canonicalized address — matches the on-chain key. */
48
+ static addressHash(btcAddress: string): string;
49
+ /**
50
+ * Add a Bitcoin address to the caller's allowlist. It becomes usable only
51
+ * after the registry's delay elapses. Returns the submitted tx.
52
+ */
53
+ addAddress(btcAddress: string): Promise<Result<TransactionResponse, SDKError>>;
54
+ /** Remove a Bitcoin address from the caller's allowlist (effective immediately). */
55
+ removeAddress(btcAddress: string): Promise<Result<TransactionResponse, SDKError>>;
56
+ /**
57
+ * Authoritative contract read: is `btcAddress` approved (present AND past its
58
+ * delay) for `user`?
59
+ */
60
+ isApproved(user: string, btcAddress: string): Promise<Result<boolean, SDKError>>;
61
+ /**
62
+ * Read the user's allowlist from the contract: hashes + timestamps + derived
63
+ * approval state. NOTE: the raw address strings are NOT on-chain — use the
64
+ * subgraph (WithdrawalAddressBook) to render human-readable addresses.
65
+ */
66
+ getEntries(user: string): Promise<Result<WithdrawalAddressEntry[], SDKError>>;
67
+ /** The current global delay (seconds) before a newly-added address is usable. */
68
+ getAddressDelay(): Promise<Result<number, SDKError>>;
69
+ /**
70
+ * Early-reject guard used by `withdrawBTC`. Resolves to a typed error if the
71
+ * destination is not approved for `borrower`. When the registry is not
72
+ * configured for the network, this is a no-op (the on-chain gate remains the
73
+ * hard guarantee).
74
+ */
75
+ assertApprovedForWithdrawal(borrower: string, btcAddress: string): Promise<Result<void, SDKError>>;
76
+ private txFailure;
77
+ }
78
+ export declare function createWithdrawalAddressModule(config: WithdrawalAddressModuleConfig): WithdrawalAddressModule;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Helpers for `PositionManager.getProtocolPauseStatus()` (Lit Actions / client fast-fail).
3
+ */
4
+ import { type Provider } from 'ethers';
5
+ export type ProtocolPauseStatus = {
6
+ positionManagerPaused: boolean;
7
+ positionManagerLiquidationsPaused: boolean;
8
+ positionManagerCorePaused: boolean;
9
+ loanOperationsPaused: boolean;
10
+ collateralManagerPaused: boolean;
11
+ liquidationManagerPaused: boolean;
12
+ circuitBreakerPaused: boolean;
13
+ ucdControllerPaused: boolean;
14
+ ucdTokenPaused: boolean;
15
+ simplePsmPaused: boolean;
16
+ };
17
+ export declare function fetchProtocolPauseStatus(provider: Provider, positionManagerAddress: string): Promise<ProtocolPauseStatus>;
18
+ export type ProtocolPauseKey = keyof ProtocolPauseStatus;
19
+ export declare function assertProtocolNotPaused(status: ProtocolPauseStatus, requiredKeys: readonly ProtocolPauseKey[]): void;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Node-only entry for the Diamond Hands SDK (PKP mint / server env).
3
+ *
4
+ * Use this subpath when you need {@link loadSDKConfig} with `.env` discovery
5
+ * (`environment.ts`) and optional `PKP_MINT_PRIVATE_KEY` for mint-wallet flows.
6
+ *
7
+ * The main package export (`@gvnrdao/dh-sdk`) re-exports browser-safe config from
8
+ * `environment.browser` — suitable for read-only and user-wallet flows in any runtime.
9
+ * Do **not** put `PKP_MINT_PRIVATE_KEY` in client bundles; import from here only in Node
10
+ * scripts, lit-ops-server, CI, or other trusted server contexts.
11
+ *
12
+ * @see {@link https://github.com/gvnrdao/diamond-hands/blob/main/docs/security/SECRETS-POLICY.md | SECRETS-POLICY.md}
13
+ * @module @gvnrdao/dh-sdk/server
14
+ */
15
+ export { loadSDKConfig, validateSDKEnvironment, getCurrentEnvironment, resolveLitNetworkFromEnv, envLog, } from "./constants/chunks/environment";
16
+ export { loadEncryptedProviderRegistry, getEncryptedPriceProviders, } from "./constants/chunks/encrypted-provider-params";
17
+ export type { SDKConfig, EnvironmentName } from "./constants/chunks/environment";