@gvnrdao/dh-lit-ops 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +197 -0
  2. package/dist/constants/chunks/pkp-data.d.ts +28 -0
  3. package/dist/constants/chunks/pkp-data.d.ts.map +1 -0
  4. package/dist/constants/chunks/pkp-data.js +86 -0
  5. package/dist/constants/chunks/pkp-data.js.map +1 -0
  6. package/dist/constants/index.d.ts +8 -0
  7. package/dist/constants/index.d.ts.map +1 -0
  8. package/dist/constants/index.js +25 -0
  9. package/dist/constants/index.js.map +1 -0
  10. package/dist/index.d.ts +30 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +63 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/interfaces/chunks/authentication.d.ts +29 -0
  15. package/dist/interfaces/chunks/authentication.d.ts.map +1 -0
  16. package/dist/interfaces/chunks/authentication.js +7 -0
  17. package/dist/interfaces/chunks/authentication.js.map +1 -0
  18. package/dist/interfaces/chunks/config.d.ts +52 -0
  19. package/dist/interfaces/chunks/config.d.ts.map +1 -0
  20. package/dist/interfaces/chunks/config.js +7 -0
  21. package/dist/interfaces/chunks/config.js.map +1 -0
  22. package/dist/interfaces/chunks/lit-action-execution.d.ts +27 -0
  23. package/dist/interfaces/chunks/lit-action-execution.d.ts.map +1 -0
  24. package/dist/interfaces/chunks/lit-action-execution.js +7 -0
  25. package/dist/interfaces/chunks/lit-action-execution.js.map +1 -0
  26. package/dist/interfaces/chunks/pkp-operations.d.ts +143 -0
  27. package/dist/interfaces/chunks/pkp-operations.d.ts.map +1 -0
  28. package/dist/interfaces/chunks/pkp-operations.js +3 -0
  29. package/dist/interfaces/chunks/pkp-operations.js.map +1 -0
  30. package/dist/interfaces/index.d.ts +11 -0
  31. package/dist/interfaces/index.d.ts.map +1 -0
  32. package/dist/interfaces/index.js +31 -0
  33. package/dist/interfaces/index.js.map +1 -0
  34. package/dist/modules/action-executor.module.d.ts +34 -0
  35. package/dist/modules/action-executor.module.d.ts.map +1 -0
  36. package/dist/modules/action-executor.module.js +231 -0
  37. package/dist/modules/action-executor.module.js.map +1 -0
  38. package/dist/modules/auth-manager.module.d.ts +24 -0
  39. package/dist/modules/auth-manager.module.d.ts.map +1 -0
  40. package/dist/modules/auth-manager.module.js +103 -0
  41. package/dist/modules/auth-manager.module.js.map +1 -0
  42. package/dist/modules/client-manager.module.d.ts +64 -0
  43. package/dist/modules/client-manager.module.d.ts.map +1 -0
  44. package/dist/modules/client-manager.module.js +213 -0
  45. package/dist/modules/client-manager.module.js.map +1 -0
  46. package/dist/modules/lit-ops.module.d.ts +261 -0
  47. package/dist/modules/lit-ops.module.d.ts.map +1 -0
  48. package/dist/modules/lit-ops.module.js +792 -0
  49. package/dist/modules/lit-ops.module.js.map +1 -0
  50. package/dist/modules/pkp-authorizer.module.d.ts +72 -0
  51. package/dist/modules/pkp-authorizer.module.d.ts.map +1 -0
  52. package/dist/modules/pkp-authorizer.module.js +126 -0
  53. package/dist/modules/pkp-authorizer.module.js.map +1 -0
  54. package/dist/modules/pkp-macros.module.d.ts +188 -0
  55. package/dist/modules/pkp-macros.module.d.ts.map +1 -0
  56. package/dist/modules/pkp-macros.module.js +656 -0
  57. package/dist/modules/pkp-macros.module.js.map +1 -0
  58. package/dist/modules/pkp-manager.module.d.ts +56 -0
  59. package/dist/modules/pkp-manager.module.d.ts.map +1 -0
  60. package/dist/modules/pkp-manager.module.js +304 -0
  61. package/dist/modules/pkp-manager.module.js.map +1 -0
  62. package/dist/modules/pkp-minter.module.d.ts +66 -0
  63. package/dist/modules/pkp-minter.module.d.ts.map +1 -0
  64. package/dist/modules/pkp-minter.module.js +185 -0
  65. package/dist/modules/pkp-minter.module.js.map +1 -0
  66. package/dist/modules/pkp-signer.module.d.ts +56 -0
  67. package/dist/modules/pkp-signer.module.d.ts.map +1 -0
  68. package/dist/modules/pkp-signer.module.js +148 -0
  69. package/dist/modules/pkp-signer.module.js.map +1 -0
  70. package/dist/modules/session-signature-manager.module.d.ts +32 -0
  71. package/dist/modules/session-signature-manager.module.d.ts.map +1 -0
  72. package/dist/modules/session-signature-manager.module.js +123 -0
  73. package/dist/modules/session-signature-manager.module.js.map +1 -0
  74. package/package.json +61 -0
@@ -0,0 +1,792 @@
1
+ "use strict";
2
+ /**
3
+ * LIT-OPS Main Module
4
+ * Diamond Hands Protocol - LIT Protocol Operations
5
+ *
6
+ * Main LitOps class providing decoupled LIT Protocol operations supporting:
7
+ * - Standalone mode: User pays LIT tokens directly
8
+ * - Service mode: Backend service handles LIT token costs
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.LitOps = void 0;
12
+ const dh_lit_actions_1 = require("@gvnrdao/dh-lit-actions");
13
+ const ethers_1 = require("ethers");
14
+ const action_executor_module_1 = require("./action-executor.module");
15
+ const auth_manager_module_1 = require("./auth-manager.module");
16
+ const client_manager_module_1 = require("./client-manager.module");
17
+ const pkp_authorizer_module_1 = require("./pkp-authorizer.module");
18
+ const pkp_macros_module_1 = require("./pkp-macros.module");
19
+ const pkp_manager_module_1 = require("./pkp-manager.module");
20
+ const pkp_minter_module_1 = require("./pkp-minter.module");
21
+ const pkp_signer_module_1 = require("./pkp-signer.module");
22
+ const session_signature_manager_module_1 = require("./session-signature-manager.module");
23
+ class LitOps {
24
+ constructor(config) {
25
+ this.config = {
26
+ domain: "diamond-hands.local",
27
+ sessionExpirationMinutes: 15,
28
+ pkpImmutabilityVerificationDelayMs: 10000, // Default 10000ms (10s) to prevent immutability verification failures on test networks
29
+ ...config,
30
+ };
31
+ // Validate configuration based on mode
32
+ if (this.config.mode === "standalone") {
33
+ if (!this.config.signer) {
34
+ throw new Error("Signer is required for standalone mode");
35
+ }
36
+ if (!this.config.network) {
37
+ throw new Error("Network is required for standalone mode");
38
+ }
39
+ if (this.config.serviceEndpoint) {
40
+ throw new Error("serviceEndpoint must not be provided for standalone mode");
41
+ }
42
+ }
43
+ else if (this.config.mode === "service") {
44
+ if (this.config.signer) {
45
+ throw new Error("Signer must not be provided for service mode");
46
+ }
47
+ if (this.config.network) {
48
+ throw new Error("Network must not be provided for service mode (determined by serviceEndpoint)");
49
+ }
50
+ if (!this.config.serviceEndpoint) {
51
+ throw new Error("serviceEndpoint is required for service mode");
52
+ }
53
+ }
54
+ // Use shared dependencies if provided, otherwise create new singletons
55
+ // Only create network-dependent components for standalone mode
56
+ if (this.config.mode === "standalone") {
57
+ this.clientManager =
58
+ this.config.sharedDependencies?.clientManager ||
59
+ new client_manager_module_1.LitClientManager({
60
+ litNetwork: this.config.network,
61
+ debug: this.config.debug,
62
+ alertWhenUnauthorized: false,
63
+ minNodeCount: 2,
64
+ });
65
+ }
66
+ else {
67
+ // Service mode - create dummy client manager
68
+ this.clientManager =
69
+ this.config.sharedDependencies?.clientManager ||
70
+ {};
71
+ }
72
+ this.pkpManager = new pkp_manager_module_1.PKPManager(this.config.mode, this.config.debug, this.config.serviceEndpoint);
73
+ // Create shared auth manager for all action executors
74
+ this.authManager =
75
+ this.config.sharedDependencies?.authManager ||
76
+ new auth_manager_module_1.LitAuthManager(this.config.debug);
77
+ // Create shared session manager for all signers
78
+ this.sessionManager =
79
+ this.config.sharedDependencies?.sessionManager ||
80
+ new session_signature_manager_module_1.SessionSignatureManager(this.config.debug);
81
+ this.actionExecutor =
82
+ this.config.sharedDependencies?.actionExecutor ||
83
+ new action_executor_module_1.LitActionExecutor(this.config.mode, this.config.debug, this.authManager, this.config.serviceEndpoint);
84
+ // Only create network-dependent PKPSigner for standalone mode
85
+ if (this.config.mode === "standalone") {
86
+ this.pkpSigner =
87
+ this.config.sharedDependencies?.pkpSigner ||
88
+ new pkp_signer_module_1.PKPSigner(this.config.network, this.config.debug, {
89
+ clientManager: this.clientManager,
90
+ sessionManager: this.sessionManager,
91
+ });
92
+ }
93
+ else {
94
+ // Service mode - create dummy PKPSigner
95
+ this.pkpSigner =
96
+ this.config.sharedDependencies?.pkpSigner || {};
97
+ }
98
+ // Create shared PKPMinter with shared dependencies (only for standalone mode)
99
+ if (this.config.mode === "standalone") {
100
+ this.pkpMinter =
101
+ this.config.sharedDependencies?.pkpMinter ||
102
+ new pkp_minter_module_1.PKPMinter({
103
+ signer: this.config.signer,
104
+ network: this.config.network,
105
+ debug: this.config.debug,
106
+ clientManager: this.clientManager,
107
+ });
108
+ // Create shared PKPAuthorizer with shared dependencies
109
+ this.pkpAuthorizer =
110
+ this.config.sharedDependencies?.pkpAuthorizer ||
111
+ new pkp_authorizer_module_1.PKPAuthorizer({
112
+ signer: this.config.signer,
113
+ network: this.config.network,
114
+ debug: this.config.debug,
115
+ clientManager: this.clientManager,
116
+ });
117
+ }
118
+ else {
119
+ // Service mode - create dummy instances
120
+ this.pkpMinter =
121
+ this.config.sharedDependencies?.pkpMinter || {};
122
+ this.pkpAuthorizer =
123
+ this.config.sharedDependencies?.pkpAuthorizer || {};
124
+ }
125
+ // Create PKPMacroUtils with shared dependencies (only for standalone mode)
126
+ if (this.config.mode === "standalone") {
127
+ this.pkpMacroUtils =
128
+ this.config.sharedDependencies?.pkpMacroUtils ||
129
+ new pkp_macros_module_1.PKPMacroUtils(this.config.network, this.config.debug, {
130
+ clientManager: this.clientManager,
131
+ actionExecutor: this.actionExecutor,
132
+ authManager: this.authManager,
133
+ pkpMinter: this.pkpMinter,
134
+ pkpAuthorizer: this.pkpAuthorizer,
135
+ }, this.config.pkpImmutabilityVerificationDelayMs);
136
+ }
137
+ else {
138
+ // Service mode - create dummy PKPMacroUtils
139
+ this.pkpMacroUtils =
140
+ this.config.sharedDependencies?.pkpMacroUtils || {};
141
+ }
142
+ if (this.config.debug) {
143
+ console.log("šŸš€ LitOps initialized:");
144
+ console.log(" Mode:", this.config.mode);
145
+ if (this.config.mode === "standalone") {
146
+ console.log(" Network:", this.config.network);
147
+ console.log(" Signer:", this.config.signer?.address);
148
+ }
149
+ else {
150
+ console.log(" Service Endpoint:", this.config.serviceEndpoint);
151
+ }
152
+ console.log(" Debug:", this.config.debug);
153
+ console.log(" PKP Immutability Verification Delay:", `${this.config.pkpImmutabilityVerificationDelayMs}ms`);
154
+ console.log(" šŸ”§ Shared Dependencies:", {
155
+ clientManager: !!this.config.sharedDependencies?.clientManager,
156
+ pkpManager: !!this.config.sharedDependencies?.pkpManager,
157
+ authManager: !!this.config.sharedDependencies?.authManager,
158
+ sessionManager: !!this.config.sharedDependencies?.sessionManager,
159
+ actionExecutor: !!this.config.sharedDependencies?.actionExecutor,
160
+ pkpSigner: !!this.config.sharedDependencies?.pkpSigner,
161
+ pkpMacroUtils: !!this.config.sharedDependencies?.pkpMacroUtils,
162
+ pkpMinter: !!this.config.sharedDependencies?.pkpMinter,
163
+ pkpAuthorizer: !!this.config.sharedDependencies?.pkpAuthorizer,
164
+ });
165
+ }
166
+ }
167
+ /**
168
+ * Create a new PKP
169
+ */
170
+ async createPKP(signer, litActionCid) {
171
+ const request = {
172
+ signer,
173
+ litActionCid,
174
+ metadata: {
175
+ createdAt: Date.now(),
176
+ mode: this.config.mode,
177
+ },
178
+ };
179
+ return this.pkpManager.createPKP(request);
180
+ }
181
+ /**
182
+ * Validate a PKP
183
+ */
184
+ async validatePKP(pkpId, signer) {
185
+ return this.pkpManager.validatePKP({
186
+ pkpId,
187
+ signer,
188
+ });
189
+ }
190
+ /**
191
+ * Burn a PKP
192
+ */
193
+ async burnPKP(pkpId, signer, reason) {
194
+ return this.pkpManager.burnPKP({
195
+ pkpId,
196
+ signer,
197
+ reason,
198
+ });
199
+ }
200
+ /**
201
+ * Execute a LIT Action from CID
202
+ */
203
+ async executeActionFromCID(cid, pkpPublicKey, params, signer) {
204
+ const litClient = await this.clientManager.getClient({
205
+ litNetwork: this.config.network,
206
+ debug: this.config.debug,
207
+ });
208
+ const request = {
209
+ cid,
210
+ pkpPublicKey,
211
+ params,
212
+ signer,
213
+ };
214
+ return this.actionExecutor.executeAction(request, litClient);
215
+ }
216
+ /**
217
+ * Execute a LIT Action from code
218
+ */
219
+ async executeActionFromCode(code, pkpPublicKey, params, signer) {
220
+ const litClient = await this.clientManager.getClient({
221
+ litNetwork: this.config.network,
222
+ debug: this.config.debug,
223
+ });
224
+ const request = {
225
+ code,
226
+ pkpPublicKey,
227
+ params,
228
+ signer,
229
+ };
230
+ return this.actionExecutor.executeAction(request, litClient);
231
+ }
232
+ /**
233
+ * Sign a message using PKP via LIT Action (Golden Implementation)
234
+ * This is the main PKP signing method that can create PKP if needed
235
+ *
236
+ * If pkpPublicKey is empty, it will:
237
+ * 1. Create a new PKP
238
+ * 2. Authorize the LIT Action
239
+ * 3. Burn the PKP for immutability
240
+ * 4. Sign the message
241
+ *
242
+ * If pkpPublicKey is provided, it will directly sign with existing PKP
243
+ */
244
+ async signMessageWithPKP(message, pkpPublicKey, litActionCid, signer, pkpEthAddress) {
245
+ if (this.config.debug) {
246
+ console.log("\nšŸ”‘ LitOps.signMessageWithPKP called");
247
+ console.log(` Message: "${message}"`);
248
+ console.log(` PKP Public Key: ${pkpPublicKey || "(will create new)"}`);
249
+ console.log(` LIT Action CID: ${litActionCid}`);
250
+ }
251
+ // If no PKP public key provided, create PKP using our macro
252
+ if (!pkpPublicKey || pkpPublicKey.trim() === "") {
253
+ if (this.config.debug) {
254
+ console.log(" šŸ—ļø No PKP provided - creating new PKP with full workflow");
255
+ }
256
+ // Create PKP with authorization and burn for immutability
257
+ const pkpResult = await this.pkpMacroUtils.quickCreatePkpAuthorizeDhActionAndBurn(signer, {
258
+ litActionCid: litActionCid,
259
+ });
260
+ if (this.config.debug) {
261
+ console.log(` āœ… PKP Created: ${pkpResult.tokenId}`);
262
+ console.log(` šŸ”‘ Public Key: ${pkpResult.publicKey}`);
263
+ console.log(` šŸ  Address: ${pkpResult.ethAddress}`);
264
+ }
265
+ // Now sign with the newly created PKP
266
+ pkpPublicKey = pkpResult.publicKey;
267
+ pkpEthAddress = pkpResult.ethAddress;
268
+ }
269
+ // Use the PKPSigner to sign the message
270
+ const request = {
271
+ message,
272
+ pkpPublicKey,
273
+ pkpEthAddress,
274
+ litActionCid,
275
+ signer,
276
+ network: this.config.network,
277
+ debug: this.config.debug,
278
+ };
279
+ return this.pkpSigner.signMessage(request);
280
+ }
281
+ /**
282
+ * Create PKP with full workflow (Create + Authorize + Burn)
283
+ * This method provides the complete PKP creation workflow suitable for production use.
284
+ * Returns all necessary data for subsequent signing operations.
285
+ *
286
+ * @param litActionCid - The LIT Action CID to authorize for this PKP
287
+ * @param signer - The wallet to use for PKP creation and transactions
288
+ * @returns Complete PKP data including tokenId, publicKey, ethAddress, etc.
289
+ */
290
+ async createProductionPKP(litActionCid, signer) {
291
+ if (this.config.debug) {
292
+ console.log("\nšŸ—ļø LitOps.createProductionPKP called");
293
+ console.log(` LIT Action CID: ${litActionCid}`);
294
+ console.log(` Network: ${this.config.network}`);
295
+ }
296
+ // Create PKP with authorization and burn for immutability
297
+ const pkpResult = await this.pkpMacroUtils.quickCreatePkpAuthorizeDhActionAndBurn(signer, {
298
+ litActionCid: litActionCid,
299
+ });
300
+ if (this.config.debug) {
301
+ console.log(" āœ… Production PKP created successfully!");
302
+ console.log(` Token ID: ${pkpResult.tokenId}`);
303
+ console.log(` Public Key: ${pkpResult.publicKey}`);
304
+ console.log(` ETH Address: ${pkpResult.ethAddress}`);
305
+ console.log(` Authorized: ${pkpResult.isPermitted}`);
306
+ console.log(` Immutable: ${pkpResult.burned}`);
307
+ }
308
+ return pkpResult;
309
+ }
310
+ /**
311
+ * Sign message with existing PKP data
312
+ * This method takes the result from createProductionPKP and signs a message.
313
+ * Perfect for two-step workflow: create PKP, then sign multiple messages.
314
+ *
315
+ * @param message - The message to sign
316
+ * @param pkpData - PKP data from createProductionPKP or compatible interface
317
+ * @param litActionCid - The LIT Action CID to use for signing
318
+ * @param signer - The wallet to use for session signatures
319
+ * @returns Signature result with verification data
320
+ */
321
+ async signWithExistingPKP(message, pkpData, litActionCid, signer) {
322
+ if (this.config.debug) {
323
+ console.log("\nšŸ” LitOps.signWithExistingPKP called");
324
+ console.log(` Message: "${message}"`);
325
+ console.log(` PKP Address: ${pkpData.ethAddress}`);
326
+ console.log(` LIT Action CID: ${litActionCid}`);
327
+ console.log(` PKP has ${pkpData.permittedActions.length} authorized actions`);
328
+ }
329
+ // Verify PKP has authorized actions
330
+ if (pkpData.permittedActions.length === 0) {
331
+ throw new Error("PKP has no authorized actions - cannot sign messages");
332
+ }
333
+ if (this.config.debug) {
334
+ console.log(` Using provided LIT Action: ${litActionCid}`);
335
+ }
336
+ // Use the existing PKPSigner with the provided PKP data
337
+ const request = {
338
+ message,
339
+ pkpPublicKey: pkpData.publicKey,
340
+ pkpEthAddress: pkpData.ethAddress,
341
+ litActionCid,
342
+ signer,
343
+ network: this.config.network,
344
+ debug: this.config.debug,
345
+ };
346
+ return this.pkpSigner.signMessage(request);
347
+ }
348
+ /**
349
+ * Get configuration
350
+ */
351
+ getConfig() {
352
+ return { ...this.config };
353
+ }
354
+ /**
355
+ * Get client status
356
+ */
357
+ getStatus() {
358
+ return {
359
+ config: this.getConfig(),
360
+ client: this.clientManager.getStats(),
361
+ };
362
+ }
363
+ /**
364
+ * Validate PKP Security via LIT Action
365
+ *
366
+ * This method executes the pkp-validator LIT Action to validate that a PKP is:
367
+ * - Created (exists on-chain)
368
+ * - Immutable (transferred to burn address)
369
+ * - Has only one authorized action
370
+ * - Authorized for the expected CID
371
+ *
372
+ * @param targetPkpTokenId - The PKP token ID to validate
373
+ * @param expectedCid - The expected CID in hex format (0x...)
374
+ * @param signerPkp - The PKP to use for signing the LIT Action (should be PKP_VALIDATOR_PKP)
375
+ * @param signer - The wallet to use for session signatures
376
+ * @returns PKP validation result with signature verification
377
+ */
378
+ async validatePKPSecurity(targetPkpTokenId, expectedCid, signerPkp, signer) {
379
+ if (this.config.debug) {
380
+ console.log("\nšŸ” LitOps.validatePKPSecurity");
381
+ console.log(` Target PKP: ${targetPkpTokenId}`);
382
+ console.log(` Expected CID (hex): ${expectedCid}`);
383
+ console.log(` Signer PKP: ${signerPkp.tokenId}`);
384
+ }
385
+ try {
386
+ // Get the PKP validator CID
387
+ const pkpValidatorCid = dh_lit_actions_1.DH_LIT_ACTIONS.pkpValidator.cid;
388
+ if (this.config.debug) {
389
+ console.log(` PKP Validator CID: ${pkpValidatorCid}`);
390
+ }
391
+ // Execute PKP Validator LIT Action
392
+ const litResult = await this.executeActionFromCID(pkpValidatorCid, signerPkp.publicKey, {
393
+ targetPkpTokenId,
394
+ expectedCid, // Expected to be in hex format
395
+ message: `PKP validation: ${Date.now()}`,
396
+ }, signer);
397
+ if (this.config.debug) {
398
+ console.log(` LIT Action Success: ${litResult.success}`);
399
+ console.log(` Response: ${litResult.response || "NONE"}`);
400
+ console.log(` Error: ${litResult.error || "NONE"}`);
401
+ }
402
+ // Parse response and verify signature
403
+ if (litResult.success && litResult.response) {
404
+ try {
405
+ // Handle response whether it's a string or object
406
+ const responseData = typeof litResult.response === "string"
407
+ ? JSON.parse(litResult.response)
408
+ : litResult.response;
409
+ // Verify signature if present
410
+ let signatureValid = false;
411
+ let pkpAddress = "";
412
+ let recoveredAddress = "";
413
+ if (litResult.signatures && litResult.signatures.pkpValidation) {
414
+ if (this.config.debug) {
415
+ console.log(" šŸ” Verifying signature authenticity...");
416
+ }
417
+ try {
418
+ // Compute PKP address from public key
419
+ pkpAddress = ethers_1.ethers.utils.computeAddress(`0x${signerPkp.publicKey}`);
420
+ // Recover address from signature - LIT Action signs the keccak256 hash
421
+ const signedMessage = responseData.signedMessage;
422
+ const signature = litResult.signatures.pkpValidation.signature;
423
+ if (signedMessage && signature) {
424
+ // The LIT Action signs the keccak256 hash, not a human-readable message
425
+ const messageHash = ethers_1.ethers.utils.keccak256(ethers_1.ethers.utils.toUtf8Bytes(signedMessage));
426
+ recoveredAddress = ethers_1.ethers.utils.recoverAddress(messageHash, signature);
427
+ signatureValid =
428
+ pkpAddress.toLowerCase() === recoveredAddress.toLowerCase();
429
+ if (this.config.debug) {
430
+ console.log(` PKP Address: ${pkpAddress}`);
431
+ console.log(` Recovered Address: ${recoveredAddress}`);
432
+ console.log(` Signature: ${signature}`);
433
+ console.log(` Signature Valid: ${signatureValid ? "āœ…" : "āŒ"}`);
434
+ }
435
+ }
436
+ else {
437
+ throw new Error("No signed message or signature found for verification");
438
+ }
439
+ }
440
+ catch (verifyError) {
441
+ if (this.config.debug) {
442
+ console.log(` āŒ Signature verification failed: ${verifyError}`);
443
+ }
444
+ throw new Error(`Signature verification failed: ${verifyError instanceof Error
445
+ ? verifyError.message
446
+ : verifyError}`);
447
+ }
448
+ }
449
+ // Return parsed result
450
+ return {
451
+ success: responseData.success || false,
452
+ signature: litResult.signatures?.pkpValidation?.signature,
453
+ error: responseData.error,
454
+ signatureValid,
455
+ pkpAddress,
456
+ recoveredAddress,
457
+ validationResult: responseData.validated
458
+ ? {
459
+ exists: responseData.validated.exists || false,
460
+ isImmutable: responseData.validated.immutable || false,
461
+ hasOnlyOneAction: responseData.validated.singleAction || false,
462
+ matchesExpectedCID: responseData.validated.correctCid || false,
463
+ allValid: responseData.validated.exists &&
464
+ responseData.validated.immutable &&
465
+ responseData.validated.singleAction &&
466
+ responseData.validated.correctCid,
467
+ }
468
+ : undefined,
469
+ };
470
+ }
471
+ catch (parseError) {
472
+ if (this.config.debug) {
473
+ console.log(" Error parsing response:", parseError);
474
+ console.log(" Response type:", typeof litResult.response);
475
+ console.log(" Response value:", litResult.response);
476
+ }
477
+ return {
478
+ success: false,
479
+ error: `Failed to parse LIT Action response: ${parseError}`,
480
+ signatureValid: false,
481
+ };
482
+ }
483
+ }
484
+ // LIT Action execution failed
485
+ return {
486
+ success: false,
487
+ error: litResult.error || "LIT Action execution failed",
488
+ signatureValid: false,
489
+ };
490
+ }
491
+ catch (error) {
492
+ if (this.config.debug) {
493
+ console.error(" āŒ PKP validation failed:", error);
494
+ }
495
+ return {
496
+ success: false,
497
+ error: error instanceof Error ? error.message : "Unknown error",
498
+ signatureValid: false,
499
+ };
500
+ }
501
+ }
502
+ /**
503
+ * Ultimate PKP Macro: Create and Validate PKP to LIT Action
504
+ *
505
+ * This is the ultimate PKP security macro that combines:
506
+ * 1. PKP creation
507
+ * 2. LIT Action authorization
508
+ * 3. PKP immutability (burn to dead address)
509
+ * 4. PKP security validation via pkp-validator LIT Action
510
+ *
511
+ * Returns complete PKP data and cryptographic proof of security.
512
+ *
513
+ * @param litActionCid - The LIT Action CID to authorize for this PKP
514
+ * @param signer - Optional signer (required for standalone mode, not used in service mode)
515
+ * @returns Complete PKP creation and validation result with audit trail
516
+ */
517
+ async createAndValidatePkpToLitAction(litActionCid, signer) {
518
+ const startTime = Date.now();
519
+ const auditSteps = [];
520
+ if (this.config.debug) {
521
+ console.log("\nšŸŽÆ LitOps.createAndValidatePkpToLitAction");
522
+ console.log(" ULTIMATE PKP SECURITY MACRO");
523
+ console.log(` Target LIT Action CID: ${litActionCid}`);
524
+ console.log(` Mode: ${this.config.mode}`);
525
+ }
526
+ // Service mode: Call the service endpoint directly
527
+ if (this.config.mode === "service") {
528
+ if (!this.config.serviceEndpoint) {
529
+ throw new Error("Service endpoint not configured for service mode");
530
+ }
531
+ if (this.config.debug) {
532
+ console.log(` 🌐 Service mode: calling ${this.config.serviceEndpoint}/api/lit/pkp/create-diamond-hands-loan`);
533
+ }
534
+ try {
535
+ const response = await fetch(`${this.config.serviceEndpoint}/api/lit/pkp/create-diamond-hands-loan`, {
536
+ method: "POST",
537
+ headers: {
538
+ "Content-Type": "application/json",
539
+ },
540
+ body: JSON.stringify({
541
+ litActionCid: litActionCid,
542
+ }),
543
+ });
544
+ if (!response.ok) {
545
+ throw new Error(`Service request failed: ${response.status} ${response.statusText}`);
546
+ }
547
+ const result = (await response.json());
548
+ const duration = Date.now() - startTime;
549
+ if (this.config.debug) {
550
+ console.log("āœ… Diamond Hands Loan PKP created via service!");
551
+ console.log(` Duration: ${duration}ms`);
552
+ }
553
+ return {
554
+ success: result.success,
555
+ timestamp: startTime,
556
+ duration,
557
+ targetCid: result.targetCid,
558
+ pkpData: result.pkpData,
559
+ validationResult: result.validationResult,
560
+ auditTrail: result.auditTrail,
561
+ };
562
+ }
563
+ catch (error) {
564
+ const duration = Date.now() - startTime;
565
+ if (this.config.debug) {
566
+ console.error("āŒ Service request failed:", error);
567
+ }
568
+ return {
569
+ success: false,
570
+ error: error instanceof Error ? error.message : String(error),
571
+ timestamp: startTime,
572
+ duration,
573
+ targetCid: litActionCid,
574
+ pkpData: {},
575
+ validationResult: {},
576
+ auditTrail: {
577
+ steps: [
578
+ {
579
+ step: 1,
580
+ description: "Service request failed",
581
+ timestamp: startTime,
582
+ duration,
583
+ success: false,
584
+ data: {
585
+ error: error instanceof Error ? error.message : String(error),
586
+ },
587
+ },
588
+ ],
589
+ totalDuration: duration,
590
+ },
591
+ };
592
+ }
593
+ }
594
+ // Standalone mode validation
595
+ if (this.config.mode === "standalone" && !signer) {
596
+ throw new Error("Signer is required for standalone mode");
597
+ }
598
+ try {
599
+ // Step 1: Create production PKP (create + authorize + burn)
600
+ const step1Start = Date.now();
601
+ if (this.config.debug) {
602
+ console.log("\n Step 1: Creating production PKP...");
603
+ }
604
+ const pkpData = await this.createProductionPKP(litActionCid, signer);
605
+ const step1Duration = Date.now() - step1Start;
606
+ auditSteps.push({
607
+ step: 1,
608
+ description: "Create production PKP (create + authorize + burn)",
609
+ timestamp: step1Start,
610
+ duration: step1Duration,
611
+ success: true,
612
+ data: {
613
+ tokenId: pkpData.tokenId,
614
+ ethAddress: pkpData.ethAddress,
615
+ isPermitted: pkpData.isPermitted,
616
+ burned: pkpData.burned,
617
+ },
618
+ });
619
+ if (this.config.debug) {
620
+ console.log(` āœ… Step 1 completed in ${step1Duration}ms`);
621
+ console.log(` PKP ID: ${pkpData.tokenId}`);
622
+ console.log(` PKP Address: ${pkpData.ethAddress}`);
623
+ }
624
+ // Add delay to prevent PKP immutability verification failures
625
+ // This allows burned PKP state to propagate across LIT Protocol network nodes
626
+ const immutabilityDelayMs = this.config.pkpImmutabilityVerificationDelayMs;
627
+ if (this.config.debug) {
628
+ console.log(`\n ā³ Waiting ${immutabilityDelayMs}ms for PKP immutability verification across network nodes...`);
629
+ }
630
+ await new Promise((resolve) => setTimeout(resolve, immutabilityDelayMs));
631
+ if (this.config.debug) {
632
+ console.log(` āœ… Network propagation delay completed`);
633
+ }
634
+ // Step 2: Validate PKP security using pkp-validator LIT Action
635
+ const step2Start = Date.now();
636
+ if (this.config.debug) {
637
+ console.log("\n Step 2: Validating PKP security...");
638
+ }
639
+ // Use the real PKP validator PKP from dh-lit-actions package
640
+ // Select the appropriate deployment based on network configuration
641
+ let validatorPkp;
642
+ // Determine network and select appropriate deployment based on LitOps config
643
+ const isTestNetwork = this.config.network === "datil-test" ||
644
+ process.env.LIT_NETWORK === "datil-test";
645
+ if (isTestNetwork) {
646
+ // Use test deployments first, then fallback to production
647
+ validatorPkp =
648
+ dh_lit_actions_1.DATIL_TEST_DEPLOYMENTS.pkpValidator.pkp ||
649
+ dh_lit_actions_1.DATIL_DEPLOYMENTS.pkpValidator.pkp;
650
+ if (this.config.debug) {
651
+ console.log(" Using validator PKP for test environment (fallback to production if needed)");
652
+ }
653
+ }
654
+ else {
655
+ // Use production deployments
656
+ validatorPkp = dh_lit_actions_1.DATIL_DEPLOYMENTS.pkpValidator.pkp;
657
+ if (this.config.debug) {
658
+ console.log(" Using production validator PKP");
659
+ }
660
+ }
661
+ if (!validatorPkp) {
662
+ throw new Error("PKP validator PKP not found in dh-lit-actions package");
663
+ }
664
+ let validationResult;
665
+ try {
666
+ // Convert IPFS CID to hex format for validation
667
+ const litActionCidHex = (0, dh_lit_actions_1.cidToHex)(litActionCid);
668
+ if (this.config.debug) {
669
+ console.log(` Converting CID: ${litActionCid} → ${litActionCidHex}`);
670
+ }
671
+ validationResult = await this.validatePKPSecurity(pkpData.tokenId, litActionCidHex, // Pass hex format CID
672
+ validatorPkp, signer);
673
+ // If validation fails, the ultimate macro should fail too
674
+ if (!validationResult.success) {
675
+ throw new Error(`PKP validation failed: ${validationResult.error || "Unknown validation error"}`);
676
+ }
677
+ }
678
+ catch (validationError) {
679
+ // If validation throws an error, the ultimate macro should fail
680
+ throw new Error(`PKP validation error: ${validationError instanceof Error
681
+ ? validationError.message
682
+ : validationError}`);
683
+ }
684
+ const step2Duration = Date.now() - step2Start;
685
+ auditSteps.push({
686
+ step: 2,
687
+ description: "Validate PKP security via pkp-validator LIT Action",
688
+ timestamp: step2Start,
689
+ duration: step2Duration,
690
+ success: validationResult.success,
691
+ data: {
692
+ signatureValid: validationResult.signatureValid,
693
+ allValid: validationResult.validationResult?.allValid,
694
+ signature: validationResult.signature,
695
+ },
696
+ });
697
+ if (this.config.debug) {
698
+ console.log(` āœ… Step 2 completed in ${step2Duration}ms`);
699
+ console.log(` Validation Success: ${validationResult.success}`);
700
+ console.log(` Signature Valid: ${validationResult.signatureValid}`);
701
+ }
702
+ const totalDuration = Date.now() - startTime;
703
+ // Return comprehensive result
704
+ const result = {
705
+ success: true,
706
+ timestamp: startTime,
707
+ duration: totalDuration,
708
+ targetCid: litActionCid,
709
+ pkpData,
710
+ validationResult,
711
+ auditTrail: {
712
+ steps: auditSteps,
713
+ totalDuration,
714
+ },
715
+ };
716
+ if (this.config.debug) {
717
+ console.log(`\nšŸŽ‰ Ultimate macro completed successfully in ${totalDuration}ms`);
718
+ console.log(" āœ… PKP created, authorized, and made immutable");
719
+ console.log(" āœ… PKP security validated with cryptographic proof");
720
+ console.log(" šŸ”’ MAXIMUM SECURITY ACHIEVED!");
721
+ }
722
+ return result;
723
+ }
724
+ catch (error) {
725
+ const totalDuration = Date.now() - startTime;
726
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
727
+ auditSteps.push({
728
+ step: auditSteps.length + 1,
729
+ description: "Ultimate macro failed",
730
+ timestamp: Date.now(),
731
+ duration: 0,
732
+ success: false,
733
+ data: { error: errorMessage },
734
+ });
735
+ if (this.config.debug) {
736
+ console.error(" āŒ Ultimate macro failed:", error);
737
+ }
738
+ return {
739
+ success: false,
740
+ error: errorMessage,
741
+ timestamp: startTime,
742
+ duration: totalDuration,
743
+ targetCid: litActionCid,
744
+ pkpData: {}, // Empty PKP data on failure
745
+ validationResult: {
746
+ success: false,
747
+ error: errorMessage,
748
+ signatureValid: false,
749
+ },
750
+ auditTrail: {
751
+ steps: auditSteps,
752
+ totalDuration,
753
+ },
754
+ };
755
+ }
756
+ }
757
+ /**
758
+ * Production method: Create a new Diamond Hands Loan PKP
759
+ *
760
+ * This is the main method that will be called in production.
761
+ * Creates a new PKP specifically for Diamond Hands loans, using the
762
+ * authorization dummy CID from dh-lit-actions package.
763
+ *
764
+ * @param signer - Optional signer (required for standalone mode, not used in service mode)
765
+ * @returns Complete PKP creation and validation result
766
+ */
767
+ async getNewDiamondHandsLoanPkp(signer) {
768
+ if (this.config.debug) {
769
+ console.log("šŸŽÆ Creating new Diamond Hands Loan PKP");
770
+ console.log(` Using authorization CID: ${dh_lit_actions_1.AUTHORIZATION_DUMMY_CID}`);
771
+ console.log(` Mode: ${this.config.mode}`);
772
+ }
773
+ // In standalone mode, use provided signer or config signer
774
+ // In service mode, signer is not needed (service handles it)
775
+ const effectiveSigner = this.config.mode === "service" ? undefined : signer || this.config.signer;
776
+ if (this.config.mode === "standalone" && !effectiveSigner) {
777
+ throw new Error("Signer is required for standalone mode");
778
+ }
779
+ return this.createAndValidatePkpToLitAction(dh_lit_actions_1.AUTHORIZATION_DUMMY_CID, effectiveSigner);
780
+ }
781
+ /**
782
+ * Cleanup - disconnect all clients
783
+ */
784
+ async disconnect() {
785
+ await this.clientManager.disconnectAll();
786
+ if (this.config.debug) {
787
+ console.log("šŸ”Œ LitOps disconnected");
788
+ }
789
+ }
790
+ }
791
+ exports.LitOps = LitOps;
792
+ //# sourceMappingURL=lit-ops.module.js.map