@elizaos/plugin-tee 1.0.0-beta.0 → 1.0.0-beta.3

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.
package/dist/index.js CHANGED
@@ -1,147 +1,21 @@
1
- import {
2
- secp256k1
3
- } from "./chunk-KJXPCDOM.js";
4
- import {
5
- BaseError,
6
- BytesSizeMismatchError,
7
- FeeCapTooHighError,
8
- Hash,
9
- InvalidAddressError,
10
- InvalidChainIdError,
11
- InvalidLegacyVError,
12
- InvalidSerializableTransactionError,
13
- InvalidStorageKeySizeError,
14
- TipAboveFeeCapError,
15
- aexists,
16
- aoutput,
17
- bytesRegex,
18
- bytesToHex,
19
- checksumAddress,
20
- concat,
21
- concatHex,
22
- createCursor,
23
- createView,
24
- encodeAbiParameters,
25
- hexToBigInt,
26
- hexToBytes,
27
- hexToNumber,
28
- integerRegex,
29
- isAddress,
30
- isHex,
31
- keccak256,
32
- maxUint256,
33
- numberToHex,
34
- rotr,
35
- size,
36
- slice,
37
- stringToHex,
38
- stringify,
39
- toBytes,
40
- toBytes2,
41
- toHex,
42
- trim,
43
- wrapConstructor
44
- } from "./chunk-I5LRTHFY.js";
45
- import "./chunk-PR4QN5HX.js";
46
-
47
1
  // src/index.ts
48
2
  import {
49
- logger as logger5
3
+ logger as logger4
50
4
  } from "@elizaos/core";
51
5
 
52
- // src/services/teeLogService.ts
53
- import path from "node:path";
54
- import {
55
- Service,
56
- ServiceType,
57
- TEEMode as TEEMode2,
58
- TeeType as TeeType2,
59
- logger as logger2
60
- } from "@elizaos/core";
61
-
62
- // src/services/teeLogManager.ts
63
- import {
64
- TeeType
65
- } from "@elizaos/core";
66
- import elliptic from "elliptic";
67
-
68
- // ../../node_modules/uuid/dist/esm/stringify.js
69
- var byteToHex = [];
70
- for (let i = 0; i < 256; ++i) {
71
- byteToHex.push((i + 256).toString(16).slice(1));
72
- }
73
- function unsafeStringify(arr, offset = 0) {
74
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
75
- }
76
-
77
- // ../../node_modules/uuid/dist/esm/rng.js
78
- import { randomFillSync } from "crypto";
79
- var rnds8Pool = new Uint8Array(256);
80
- var poolPtr = rnds8Pool.length;
81
- function rng() {
82
- if (poolPtr > rnds8Pool.length - 16) {
83
- randomFillSync(rnds8Pool);
84
- poolPtr = 0;
85
- }
86
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
87
- }
88
-
89
- // ../../node_modules/uuid/dist/esm/native.js
90
- import { randomUUID } from "crypto";
91
- var native_default = { randomUUID };
6
+ // src/vendors/types.ts
7
+ var TeeVendorNames = {
8
+ PHALA: "phala"
9
+ };
92
10
 
93
- // ../../node_modules/uuid/dist/esm/v4.js
94
- function v4(options, buf, offset) {
95
- if (native_default.randomUUID && !buf && !options) {
96
- return native_default.randomUUID();
97
- }
98
- options = options || {};
99
- const rnds = options.random || (options.rng || rng)();
100
- rnds[6] = rnds[6] & 15 | 64;
101
- rnds[8] = rnds[8] & 63 | 128;
102
- if (buf) {
103
- offset = offset || 0;
104
- for (let i = 0; i < 16; ++i) {
105
- buf[offset + i] = rnds[i];
106
- }
107
- return buf;
108
- }
109
- return unsafeStringify(rnds);
110
- }
111
- var v4_default = v4;
11
+ // src/actions/remoteAttestationAction.ts
12
+ import { logger as logger2 } from "@elizaos/core";
112
13
 
113
14
  // src/providers/remoteAttestationProvider.ts
114
- import { promises as fs } from "node:fs";
115
15
  import { logger } from "@elizaos/core";
116
16
  import { TEEMode } from "@elizaos/core";
117
17
  import { TappdClient } from "@phala/dstack-sdk";
118
18
 
119
- // src/utils.ts
120
- import { createHash } from "node:crypto";
121
- function hexToUint8Array(hex) {
122
- const hexString = hex.trim().replace(/^0x/, "");
123
- if (!hexString) {
124
- throw new Error("Invalid hex string");
125
- }
126
- if (hexString.length % 2 !== 0) {
127
- throw new Error("Invalid hex string");
128
- }
129
- const array = new Uint8Array(hexString.length / 2);
130
- for (let i = 0; i < hexString.length; i += 2) {
131
- const byte = Number.parseInt(hexString.slice(i, i + 2), 16);
132
- if (Number.isNaN(byte)) {
133
- throw new Error("Invalid hex string");
134
- }
135
- array[i / 2] = byte;
136
- }
137
- return array;
138
- }
139
- function calculateSHA256(input) {
140
- const hash = createHash("sha256");
141
- hash.update(input);
142
- return hash.digest();
143
- }
144
-
145
19
  // src/providers/base.ts
146
20
  var DeriveKeyProvider = class {
147
21
  };
@@ -231,412 +105,28 @@ var phalaRemoteAttestationProvider = {
231
105
  }
232
106
  }
233
107
  };
234
- var SgxAttestationProvider = class extends RemoteAttestationProvider {
235
- SGX_QUOTE_MAX_SIZE = 8192 * 4;
236
- SGX_TARGET_INFO_SIZE = 512;
237
- MY_TARGET_INFO_PATH = "/dev/attestation/my_target_info";
238
- TARGET_INFO_PATH = "/dev/attestation/target_info";
239
- USER_REPORT_DATA_PATH = "/dev/attestation/user_report_data";
240
- QUOTE_PATH = "/dev/attestation/quote";
241
- // Remove unnecessary constructor
242
- // constructor() {}
243
- async generateAttestation(reportData) {
244
- const rawUserReport = calculateSHA256(reportData);
245
- try {
246
- await fs.access(this.MY_TARGET_INFO_PATH);
247
- const quote = await this.generateQuoteByGramine(rawUserReport);
248
- const attestation = {
249
- quote,
250
- timestamp: Date.now()
251
- };
252
- return attestation;
253
- } catch (error) {
254
- console.error("Error generating SGX remote attestation:", error);
255
- throw new Error(
256
- `Failed to generate SGX Quote: ${error instanceof Error ? error.message : "Unknown error"}`
257
- );
258
- }
259
- }
260
- async generateQuoteByGramine(rawUserReport) {
261
- if (rawUserReport.length > 64) {
262
- throw new Error("the length of rawUserReport exceeds 64 bytes");
263
- }
264
- const myTargetInfo = await fs.readFile(this.MY_TARGET_INFO_PATH);
265
- if (myTargetInfo.length !== this.SGX_TARGET_INFO_SIZE) {
266
- throw new Error("Invalid my_target_info length");
267
- }
268
- await fs.writeFile(this.TARGET_INFO_PATH, myTargetInfo);
269
- await fs.writeFile(this.USER_REPORT_DATA_PATH, rawUserReport);
270
- const quoteData = await fs.readFile(this.QUOTE_PATH);
271
- if (quoteData.length > this.SGX_QUOTE_MAX_SIZE) {
272
- throw new Error("Invalid quote length");
273
- }
274
- const realLen = quoteData.lastIndexOf(0);
275
- if (realLen === -1) {
276
- throw new Error("quote without EOF");
277
- }
278
- return `0x${quoteData.subarray(0, realLen + 1).toString("hex")}`;
279
- }
280
- };
281
- var sgxAttestationProvider = {
282
- name: "sgx-gramine-remote-attestation",
283
- get: async (runtime, _message) => {
284
- const provider = new SgxAttestationProvider();
285
- const agentId = runtime.agentId;
286
- try {
287
- const attestation = await provider.generateAttestation(agentId);
288
- return {
289
- data: attestation,
290
- values: {
291
- quote: attestation.quote,
292
- timestamp: attestation.timestamp.toString()
293
- },
294
- text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`
295
- };
296
- } catch (error) {
297
- console.error("Error in remote attestation provider:", error);
298
- const errorMessage = `Failed to generate SGX Quote: ${error instanceof Error ? error.message : "Unknown error"}`;
299
- return {
300
- data: null,
301
- values: {},
302
- text: errorMessage
303
- };
304
- }
305
- }
306
- };
307
-
308
- // src/services/teeLogManager.ts
309
- var TeeLogManager = class {
310
- teeLogDAO;
311
- teeType;
312
- teeMode;
313
- // Only used for plugin-tee with TDX dstack
314
- // Map of agentId to its key pair
315
- // These keypairs only store in memory.
316
- // When the agent restarts, we will generate new keypair.
317
- keyPairs = /* @__PURE__ */ new Map();
318
- /**
319
- * Constructor for initializing TeeLog object.
320
- * * @param { TeeLogDAO } teeLogDAO - The data access object for TeeLog.
321
- * @param { TeeType } teeType - The type of Tee.
322
- * @param { TEEMode } teeMode - The mode of Tee.
323
- */
324
- constructor(teeLogDAO, teeType, teeMode) {
325
- this.teeLogDAO = teeLogDAO;
326
- this.teeType = teeType;
327
- this.teeMode = teeMode;
328
- }
329
- /**
330
- * Registers a new agent with the given agent ID and agent name.
331
- *
332
- * @param {string} agentId - The unique identifier for the agent.
333
- * @param {string} agentName - The name of the agent.
334
- * @returns {Promise<boolean>} A promise that resolves to true if the agent is successfully registered.
335
- * @throws {Error} If agentId is empty or null.
336
- */
337
- async registerAgent(agentId, agentName) {
338
- if (!agentId) {
339
- throw new Error("Agent ID is required");
340
- }
341
- const keyPair = this.generateKeyPair();
342
- this.keyPairs.set(agentId, keyPair);
343
- const publicKey = keyPair.getPublic().encode("hex", true);
344
- const attestation = await this.generateAttestation(publicKey);
345
- const new_agent = {
346
- id: v4_default(),
347
- agentId,
348
- agentName: agentName || "",
349
- createdAt: (/* @__PURE__ */ new Date()).getTime(),
350
- publicKey,
351
- attestation
352
- };
353
- return this.teeLogDAO.addAgent(new_agent);
354
- }
355
- /**
356
- * Retrieves all agents from the database.
357
- * @returns {Promise<TeeAgent[]>} A promise that resolves to an array of TeeAgent objects.
358
- */
359
- async getAllAgents() {
360
- return this.teeLogDAO.getAllAgents();
361
- }
362
- /**
363
- * Retrieve an agent from the database by its ID.
364
- * @param {string} agentId - The unique identifier of the agent.
365
- * @returns {Promise<TeeAgent | undefined>} The agent object if found, undefined otherwise.
366
- */
367
- async getAgent(agentId) {
368
- return this.teeLogDAO.getAgent(agentId);
369
- }
370
- /**
371
- * Logs an event with the specified information.
372
- *
373
- * @param {string} agentId - The ID of the agent performing the action.
374
- * @param {string} roomId - The room ID where the event occurred.
375
- * @param {string} entityId - The ID of the entity involved in the event.
376
- * @param {string} type - The type of event being logged.
377
- * @param {string} content - The content of the event being logged.
378
- * @returns {Promise<boolean>} A boolean indicating if the logging was successful.
379
- */
380
- async log(agentId, roomId, entityId, type, content) {
381
- const keyPair = this.keyPairs.get(agentId);
382
- if (!keyPair) {
383
- throw new Error(`Agent ${agentId} not found`);
384
- }
385
- const timestamp = (/* @__PURE__ */ new Date()).getTime();
386
- const messageToSign = `${agentId}|${roomId}|${entityId}|${type}|${content}|${timestamp}`;
387
- const signature = `0x${keyPair.sign(messageToSign).toDER("hex")}`;
388
- return this.teeLogDAO.addLog({
389
- id: v4_default(),
390
- agentId,
391
- roomId,
392
- entityId,
393
- type,
394
- content,
395
- timestamp,
396
- signature
397
- });
398
- }
399
- /**
400
- * Retrieves logs based on the provided query, page number, and page size.
401
- * @param {TeeLogQuery} query - The query object to filter logs.
402
- * @param {number} page - The page number of logs to retrieve.
403
- * @param {number} pageSize - The number of logs per page.
404
- * @returns {Promise<TeePageQuery<TeeLog[]>>} A promise that resolves to a page query of logs.
405
- */
406
- async getLogs(query, page, pageSize) {
407
- return this.teeLogDAO.getPagedLogs(query, page, pageSize);
408
- }
409
- /**
410
- * Generate a new key pair using the secp256k1 elliptic curve algorithm.
411
- *
412
- * @returns {elliptic.ec.KeyPair} The generated key pair.
413
- */
414
- generateKeyPair() {
415
- const ec = new elliptic.ec("secp256k1");
416
- const key = ec.genKeyPair();
417
- return key;
418
- }
419
- /**
420
- * Generates an attestation for the given user report based on the TEE type.
421
- *
422
- * @param {string} userReport The user report to generate the attestation for.
423
- * @returns {Promise<string>} A promise that resolves with the generated attestation as a string.
424
- * @throws {Error} If the TEE type is invalid.
425
- */
426
- async generateAttestation(userReport) {
427
- if (this.teeType === TeeType.SGX_GRAMINE) {
428
- const sgxAttestationProvider2 = new SgxAttestationProvider();
429
- const sgxAttestation = await sgxAttestationProvider2.generateAttestation(userReport);
430
- return JSON.stringify(sgxAttestation);
431
- }
432
- if (this.teeType === TeeType.TDX_DSTACK) {
433
- const tdxAttestationProvider = new PhalaRemoteAttestationProvider(this.teeMode);
434
- const tdxAttestation = await tdxAttestationProvider.generateAttestation(userReport);
435
- return JSON.stringify(tdxAttestation);
436
- }
437
- throw new Error("Invalid TEE type");
438
- }
439
- };
440
108
 
441
- // src/services/teeLogService.ts
442
- var TeeLogService = class _TeeLogService extends Service {
443
- dbPath;
444
- initialized = false;
445
- enableTeeLog = false;
446
- teeType;
447
- teeMode = TEEMode2.OFF;
448
- // Only used for plugin-tee with TDX dstack
449
- teeLogDAO;
450
- teeLogManager;
451
- static serviceType = ServiceType.TEE;
452
- capabilityDescription = "The agent is able to log TEE attestation events and is probably running in a TEE";
453
- /**
454
- * Constructor for creating a new instance of a class.
455
- * @param {IAgentRuntime} runtime - The runtime object to be assigned to the instance.
456
- */
457
- constructor(runtime) {
458
- super();
459
- this.runtime = runtime;
460
- }
461
- /**
462
- * Start the TeeLogService with the given runtime.
463
- *
464
- * @param {IAgentRuntime} runtime - The agent runtime to start the service with
465
- * @returns {Promise<TeeLogService>} - A promise that resolves with the TeeLogService instance
466
- * @throws {Error} - If ENABLE_TEE_LOG is not set, SGX and TDX are configured at the same time, or if the TEE configuration is invalid
467
- */
468
- static async start(runtime) {
469
- const service = new _TeeLogService(runtime);
470
- const enableValues = ["true", "1", "yes", "enable", "enabled", "on"];
471
- const enableTeeLog = runtime.getSetting("ENABLE_TEE_LOG");
472
- if (enableTeeLog === null) {
473
- throw new Error("ENABLE_TEE_LOG is not set.");
474
- }
475
- service.enableTeeLog = enableValues.includes(enableTeeLog.toLowerCase());
476
- if (!service.enableTeeLog) {
477
- logger2.debug("TEE log is not enabled.");
478
- return;
479
- }
480
- const runInSgx = runtime.getSetting("SGX");
481
- const teeMode = runtime.getSetting("TEE_MODE");
482
- const walletSecretSalt = runtime.getSetting("WALLET_SECRET_SALT");
483
- service.teeMode = teeMode ? TEEMode2[teeMode] : TEEMode2.OFF;
484
- const useSgxGramine = runInSgx && enableValues.includes(runInSgx.toLowerCase());
485
- const useTdxDstack = teeMode && teeMode !== TEEMode2.OFF && walletSecretSalt;
486
- if (useSgxGramine && useTdxDstack) {
487
- throw new Error("Cannot configure both SGX and TDX at the same time.");
488
- }
489
- if (useSgxGramine) {
490
- service.teeType = TeeType2.SGX_GRAMINE;
491
- } else if (useTdxDstack) {
492
- service.teeType = TeeType2.TDX_DSTACK;
493
- } else {
494
- throw new Error("Invalid TEE configuration.");
495
- }
496
- const dbPathSetting = runtime.getSetting("TEE_LOG_DB_PATH");
497
- service.dbPath = dbPathSetting || path.resolve("data/tee_log.sqlite");
498
- service.teeLogManager = new TeeLogManager(service.teeLogDAO, service.teeType, service.teeMode);
499
- const isRegistered = await service.teeLogManager.registerAgent(
500
- runtime?.agentId,
501
- runtime?.character?.name
502
- );
503
- if (!isRegistered) {
504
- throw new Error(`Failed to register agent ${runtime.agentId}`);
505
- }
506
- service.initialized = true;
507
- return service;
508
- }
509
- /**
510
- * Stop the TEE service running on the provided runtime.
511
- *
512
- * @param {IAgentRuntime} runtime - The runtime on which the TEE service is running.
513
- * @returns {Promise<void>} - A promise that resolves once the TEE service has stopped.
514
- */
515
- static async stop(runtime) {
516
- const service = runtime.getService(ServiceType.TEE);
517
- if (service) {
518
- await service.stop();
519
- }
520
- }
521
- /**
522
- * Asynchronous method to stop the operation.
523
- * Does nothing.
524
- */
525
- async stop() {
526
- }
527
- /**
528
- * Asynchronously logs the provided information if tee log is enabled.
529
- *
530
- * @param {string} agentId - The ID of the agent requesting the log.
531
- * @param {string} roomId - The ID of the room where the log is taking place.
532
- * @param {string} entityId - The ID of the entity related to the log.
533
- * @param {string} type - The type of log entry.
534
- * @param {string} content - The content of the log entry.
535
- * @returns {Promise<boolean>} A promise that resolves to true if the log is successful, false if tee log is not enabled.
536
- */
537
- async log(agentId, roomId, entityId, type, content) {
538
- if (!this.enableTeeLog) {
539
- return false;
540
- }
541
- return this.teeLogManager.log(agentId, roomId, entityId, type, content);
542
- }
543
- /**
544
- * Asynchronously retrieves all TeeAgents.
545
- *
546
- * @returns {Promise<TeeAgent[]>} A Promise that resolves with an array of TeeAgent objects. If Tee logging is not enabled, an empty array is returned.
547
- */
548
- async getAllAgents() {
549
- if (!this.enableTeeLog) {
550
- return [];
551
- }
552
- return this.teeLogManager.getAllAgents();
109
+ // src/utils.ts
110
+ function hexToUint8Array(hex) {
111
+ const hexString = hex.trim().replace(/^0x/, "");
112
+ if (!hexString) {
113
+ throw new Error("Invalid hex string");
553
114
  }
554
- /**
555
- * Asynchronously retrieves a TeeAgent based on the provided agentId.
556
- *
557
- * @param {string} agentId - The ID of the agent to retrieve.
558
- * @returns {Promise<TeeAgent | undefined>} A Promise that resolves with the retrieved TeeAgent, or undefined if TEE logging is not enabled.
559
- */
560
- async getAgent(agentId) {
561
- if (!this.enableTeeLog) {
562
- return void 0;
563
- }
564
- return this.teeLogManager.getAgent(agentId);
115
+ if (hexString.length % 2 !== 0) {
116
+ throw new Error("Invalid hex string");
565
117
  }
566
- /**
567
- * Retrieves Tee logs based on query, page, and page size.
568
- *
569
- * @param {TeeLogQuery} query - The query parameters to filter the logs.
570
- * @param {number} page - The current page number.
571
- * @param {number} pageSize - The number of logs to fetch per page.
572
- * @returns {Promise<TeePageQuery<TeeLog[]>>} A Promise that resolves to a TeePageQuery object containing an array of TeeLog and pagination information.
573
- */
574
- async getLogs(query, page, pageSize) {
575
- if (!this.enableTeeLog) {
576
- return {
577
- data: [],
578
- total: 0,
579
- page,
580
- pageSize
581
- };
118
+ const array = new Uint8Array(hexString.length / 2);
119
+ for (let i = 0; i < hexString.length; i += 2) {
120
+ const byte = Number.parseInt(hexString.slice(i, i + 2), 16);
121
+ if (Number.isNaN(byte)) {
122
+ throw new Error("Invalid hex string");
582
123
  }
583
- return this.teeLogManager.getLogs(query, page, pageSize);
584
- }
585
- /**
586
- * Asynchronously generates an attestation for the given user report.
587
- *
588
- * @param {string} userReport - The user report to generate attestation for.
589
- * @returns {Promise<string>} A promise that resolves to the generated attestation.
590
- */
591
- async generateAttestation(userReport) {
592
- return this.teeLogManager.generateAttestation(userReport);
593
- }
594
- };
595
-
596
- // src/vendors/types.ts
597
- var TeeVendorNames = {
598
- PHALA: "phala",
599
- SGX_GRAMINE: "sgx_gramine"
600
- };
601
-
602
- // src/vendors/gramine.ts
603
- var GramineVendor = class {
604
- type = TeeVendorNames.SGX_GRAMINE;
605
- /**
606
- * Returns an array of actions.
607
- * @returns {Array} An empty array of actions.
608
- */
609
- getActions() {
610
- return [];
611
- }
612
- /**
613
- * Retrieve the list of providers available.
614
- *
615
- * @returns {Array} An array containing the available providers.
616
- */
617
- getProviders() {
618
- return [sgxAttestationProvider];
619
- }
620
- /**
621
- * Function to get the name of the plugin.
622
- * @returns {string} The name of the plugin.
623
- */
624
- getName() {
625
- return "sgx-gramine-plugin";
626
- }
627
- /**
628
- * Returns the description of the SGX Gramine TEE to Host Eliza Agents.
629
- */
630
- getDescription() {
631
- return "SGX Gramine TEE to Host Eliza Agents";
124
+ array[i / 2] = byte;
632
125
  }
633
- };
634
-
635
- // src/vendors/phala.ts
636
- import { TeeVendors } from "@elizaos/core";
126
+ return array;
127
+ }
637
128
 
638
129
  // src/actions/remoteAttestationAction.ts
639
- import { logger as logger3 } from "@elizaos/core";
640
130
  async function uploadUint8Array(data) {
641
131
  const blob = new Blob([data], { type: "application/octet-stream" });
642
132
  const formData = new FormData();
@@ -662,8 +152,8 @@ var phalaRemoteAttestationAction = {
662
152
  }
663
153
  };
664
154
  const teeMode = runtime.getSetting("TEE_MODE");
665
- logger3.debug(`Tee mode: ${teeMode}`);
666
- logger3.debug(`Attestation message: ${JSON.stringify(attestationMessage)}`);
155
+ logger2.debug(`Tee mode: ${teeMode}`);
156
+ logger2.debug(`Attestation message: ${JSON.stringify(attestationMessage)}`);
667
157
  const provider = new PhalaRemoteAttestationProvider(teeMode);
668
158
  const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));
669
159
  const attestationData = hexToUint8Array(attestation.quote);
@@ -733,1222 +223,11 @@ https://proof.t16z.com/reports/${data.checksum}`,
733
223
  };
734
224
 
735
225
  // src/providers/deriveKeyProvider.ts
736
- import crypto from "node:crypto";
737
- import { logger as logger4 } from "@elizaos/core";
738
- import { TEEMode as TEEMode3 } from "@elizaos/core";
226
+ import { logger as logger3 } from "@elizaos/core";
227
+ import { TEEMode as TEEMode2 } from "@elizaos/core";
739
228
  import { TappdClient as TappdClient2 } from "@phala/dstack-sdk";
740
- import { Keypair } from "@solana/web3.js";
741
-
742
- // ../../node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
743
- function publicKeyToAddress(publicKey) {
744
- const address = keccak256(`0x${publicKey.substring(4)}`).substring(26);
745
- return checksumAddress(`0x${address}`);
746
- }
747
-
748
- // ../../node_modules/viem/_esm/utils/encoding/toRlp.js
749
- function toRlp(bytes, to = "hex") {
750
- const encodable = getEncodable(bytes);
751
- const cursor = createCursor(new Uint8Array(encodable.length));
752
- encodable.encode(cursor);
753
- if (to === "hex")
754
- return bytesToHex(cursor.bytes);
755
- return cursor.bytes;
756
- }
757
- function getEncodable(bytes) {
758
- if (Array.isArray(bytes))
759
- return getEncodableList(bytes.map((x) => getEncodable(x)));
760
- return getEncodableBytes(bytes);
761
- }
762
- function getEncodableList(list) {
763
- const bodyLength = list.reduce((acc, x) => acc + x.length, 0);
764
- const sizeOfBodyLength = getSizeOfLength(bodyLength);
765
- const length = (() => {
766
- if (bodyLength <= 55)
767
- return 1 + bodyLength;
768
- return 1 + sizeOfBodyLength + bodyLength;
769
- })();
770
- return {
771
- length,
772
- encode(cursor) {
773
- if (bodyLength <= 55) {
774
- cursor.pushByte(192 + bodyLength);
775
- } else {
776
- cursor.pushByte(192 + 55 + sizeOfBodyLength);
777
- if (sizeOfBodyLength === 1)
778
- cursor.pushUint8(bodyLength);
779
- else if (sizeOfBodyLength === 2)
780
- cursor.pushUint16(bodyLength);
781
- else if (sizeOfBodyLength === 3)
782
- cursor.pushUint24(bodyLength);
783
- else
784
- cursor.pushUint32(bodyLength);
785
- }
786
- for (const { encode } of list) {
787
- encode(cursor);
788
- }
789
- }
790
- };
791
- }
792
- function getEncodableBytes(bytesOrHex) {
793
- const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex;
794
- const sizeOfBytesLength = getSizeOfLength(bytes.length);
795
- const length = (() => {
796
- if (bytes.length === 1 && bytes[0] < 128)
797
- return 1;
798
- if (bytes.length <= 55)
799
- return 1 + bytes.length;
800
- return 1 + sizeOfBytesLength + bytes.length;
801
- })();
802
- return {
803
- length,
804
- encode(cursor) {
805
- if (bytes.length === 1 && bytes[0] < 128) {
806
- cursor.pushBytes(bytes);
807
- } else if (bytes.length <= 55) {
808
- cursor.pushByte(128 + bytes.length);
809
- cursor.pushBytes(bytes);
810
- } else {
811
- cursor.pushByte(128 + 55 + sizeOfBytesLength);
812
- if (sizeOfBytesLength === 1)
813
- cursor.pushUint8(bytes.length);
814
- else if (sizeOfBytesLength === 2)
815
- cursor.pushUint16(bytes.length);
816
- else if (sizeOfBytesLength === 3)
817
- cursor.pushUint24(bytes.length);
818
- else
819
- cursor.pushUint32(bytes.length);
820
- cursor.pushBytes(bytes);
821
- }
822
- }
823
- };
824
- }
825
- function getSizeOfLength(length) {
826
- if (length < 2 ** 8)
827
- return 1;
828
- if (length < 2 ** 16)
829
- return 2;
830
- if (length < 2 ** 24)
831
- return 3;
832
- if (length < 2 ** 32)
833
- return 4;
834
- throw new BaseError("Length is too large.");
835
- }
836
-
837
- // ../../node_modules/viem/_esm/experimental/eip7702/utils/hashAuthorization.js
838
- function hashAuthorization(parameters) {
839
- const { chainId, contractAddress, nonce, to } = parameters;
840
- const hash = keccak256(concatHex([
841
- "0x05",
842
- toRlp([
843
- chainId ? numberToHex(chainId) : "0x",
844
- contractAddress,
845
- nonce ? numberToHex(nonce) : "0x"
846
- ])
847
- ]));
848
- if (to === "bytes")
849
- return hexToBytes(hash);
850
- return hash;
851
- }
852
-
853
- // ../../node_modules/viem/_esm/utils/blob/blobsToCommitments.js
854
- function blobsToCommitments(parameters) {
855
- const { kzg } = parameters;
856
- const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
857
- const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
858
- const commitments = [];
859
- for (const blob of blobs)
860
- commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));
861
- return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x));
862
- }
863
-
864
- // ../../node_modules/viem/_esm/utils/blob/blobsToProofs.js
865
- function blobsToProofs(parameters) {
866
- const { kzg } = parameters;
867
- const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
868
- const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
869
- const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments;
870
- const proofs = [];
871
- for (let i = 0; i < blobs.length; i++) {
872
- const blob = blobs[i];
873
- const commitment = commitments[i];
874
- proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));
875
- }
876
- return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x));
877
- }
878
-
879
- // ../../node_modules/@noble/hashes/esm/_md.js
880
- function setBigUint64(view, byteOffset, value, isLE) {
881
- if (typeof view.setBigUint64 === "function")
882
- return view.setBigUint64(byteOffset, value, isLE);
883
- const _32n = BigInt(32);
884
- const _u32_max = BigInt(4294967295);
885
- const wh = Number(value >> _32n & _u32_max);
886
- const wl = Number(value & _u32_max);
887
- const h = isLE ? 4 : 0;
888
- const l = isLE ? 0 : 4;
889
- view.setUint32(byteOffset + h, wh, isLE);
890
- view.setUint32(byteOffset + l, wl, isLE);
891
- }
892
- function Chi(a, b, c) {
893
- return a & b ^ ~a & c;
894
- }
895
- function Maj(a, b, c) {
896
- return a & b ^ a & c ^ b & c;
897
- }
898
- var HashMD = class extends Hash {
899
- constructor(blockLen, outputLen, padOffset, isLE) {
900
- super();
901
- this.blockLen = blockLen;
902
- this.outputLen = outputLen;
903
- this.padOffset = padOffset;
904
- this.isLE = isLE;
905
- this.finished = false;
906
- this.length = 0;
907
- this.pos = 0;
908
- this.destroyed = false;
909
- this.buffer = new Uint8Array(blockLen);
910
- this.view = createView(this.buffer);
911
- }
912
- update(data) {
913
- aexists(this);
914
- const { view, buffer, blockLen } = this;
915
- data = toBytes2(data);
916
- const len = data.length;
917
- for (let pos = 0; pos < len; ) {
918
- const take = Math.min(blockLen - this.pos, len - pos);
919
- if (take === blockLen) {
920
- const dataView = createView(data);
921
- for (; blockLen <= len - pos; pos += blockLen)
922
- this.process(dataView, pos);
923
- continue;
924
- }
925
- buffer.set(data.subarray(pos, pos + take), this.pos);
926
- this.pos += take;
927
- pos += take;
928
- if (this.pos === blockLen) {
929
- this.process(view, 0);
930
- this.pos = 0;
931
- }
932
- }
933
- this.length += data.length;
934
- this.roundClean();
935
- return this;
936
- }
937
- digestInto(out) {
938
- aexists(this);
939
- aoutput(out, this);
940
- this.finished = true;
941
- const { buffer, view, blockLen, isLE } = this;
942
- let { pos } = this;
943
- buffer[pos++] = 128;
944
- this.buffer.subarray(pos).fill(0);
945
- if (this.padOffset > blockLen - pos) {
946
- this.process(view, 0);
947
- pos = 0;
948
- }
949
- for (let i = pos; i < blockLen; i++)
950
- buffer[i] = 0;
951
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
952
- this.process(view, 0);
953
- const oview = createView(out);
954
- const len = this.outputLen;
955
- if (len % 4)
956
- throw new Error("_sha2: outputLen should be aligned to 32bit");
957
- const outLen = len / 4;
958
- const state = this.get();
959
- if (outLen > state.length)
960
- throw new Error("_sha2: outputLen bigger than state");
961
- for (let i = 0; i < outLen; i++)
962
- oview.setUint32(4 * i, state[i], isLE);
963
- }
964
- digest() {
965
- const { buffer, outputLen } = this;
966
- this.digestInto(buffer);
967
- const res = buffer.slice(0, outputLen);
968
- this.destroy();
969
- return res;
970
- }
971
- _cloneInto(to) {
972
- to || (to = new this.constructor());
973
- to.set(...this.get());
974
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
975
- to.length = length;
976
- to.pos = pos;
977
- to.finished = finished;
978
- to.destroyed = destroyed;
979
- if (length % blockLen)
980
- to.buffer.set(buffer);
981
- return to;
982
- }
983
- };
984
-
985
- // ../../node_modules/@noble/hashes/esm/sha256.js
986
- var SHA256_K = /* @__PURE__ */ new Uint32Array([
987
- 1116352408,
988
- 1899447441,
989
- 3049323471,
990
- 3921009573,
991
- 961987163,
992
- 1508970993,
993
- 2453635748,
994
- 2870763221,
995
- 3624381080,
996
- 310598401,
997
- 607225278,
998
- 1426881987,
999
- 1925078388,
1000
- 2162078206,
1001
- 2614888103,
1002
- 3248222580,
1003
- 3835390401,
1004
- 4022224774,
1005
- 264347078,
1006
- 604807628,
1007
- 770255983,
1008
- 1249150122,
1009
- 1555081692,
1010
- 1996064986,
1011
- 2554220882,
1012
- 2821834349,
1013
- 2952996808,
1014
- 3210313671,
1015
- 3336571891,
1016
- 3584528711,
1017
- 113926993,
1018
- 338241895,
1019
- 666307205,
1020
- 773529912,
1021
- 1294757372,
1022
- 1396182291,
1023
- 1695183700,
1024
- 1986661051,
1025
- 2177026350,
1026
- 2456956037,
1027
- 2730485921,
1028
- 2820302411,
1029
- 3259730800,
1030
- 3345764771,
1031
- 3516065817,
1032
- 3600352804,
1033
- 4094571909,
1034
- 275423344,
1035
- 430227734,
1036
- 506948616,
1037
- 659060556,
1038
- 883997877,
1039
- 958139571,
1040
- 1322822218,
1041
- 1537002063,
1042
- 1747873779,
1043
- 1955562222,
1044
- 2024104815,
1045
- 2227730452,
1046
- 2361852424,
1047
- 2428436474,
1048
- 2756734187,
1049
- 3204031479,
1050
- 3329325298
1051
- ]);
1052
- var SHA256_IV = /* @__PURE__ */ new Uint32Array([
1053
- 1779033703,
1054
- 3144134277,
1055
- 1013904242,
1056
- 2773480762,
1057
- 1359893119,
1058
- 2600822924,
1059
- 528734635,
1060
- 1541459225
1061
- ]);
1062
- var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1063
- var SHA256 = class extends HashMD {
1064
- constructor() {
1065
- super(64, 32, 8, false);
1066
- this.A = SHA256_IV[0] | 0;
1067
- this.B = SHA256_IV[1] | 0;
1068
- this.C = SHA256_IV[2] | 0;
1069
- this.D = SHA256_IV[3] | 0;
1070
- this.E = SHA256_IV[4] | 0;
1071
- this.F = SHA256_IV[5] | 0;
1072
- this.G = SHA256_IV[6] | 0;
1073
- this.H = SHA256_IV[7] | 0;
1074
- }
1075
- get() {
1076
- const { A, B, C, D, E, F, G, H } = this;
1077
- return [A, B, C, D, E, F, G, H];
1078
- }
1079
- // prettier-ignore
1080
- set(A, B, C, D, E, F, G, H) {
1081
- this.A = A | 0;
1082
- this.B = B | 0;
1083
- this.C = C | 0;
1084
- this.D = D | 0;
1085
- this.E = E | 0;
1086
- this.F = F | 0;
1087
- this.G = G | 0;
1088
- this.H = H | 0;
1089
- }
1090
- process(view, offset) {
1091
- for (let i = 0; i < 16; i++, offset += 4)
1092
- SHA256_W[i] = view.getUint32(offset, false);
1093
- for (let i = 16; i < 64; i++) {
1094
- const W15 = SHA256_W[i - 15];
1095
- const W2 = SHA256_W[i - 2];
1096
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
1097
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
1098
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
1099
- }
1100
- let { A, B, C, D, E, F, G, H } = this;
1101
- for (let i = 0; i < 64; i++) {
1102
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1103
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
1104
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
1105
- const T2 = sigma0 + Maj(A, B, C) | 0;
1106
- H = G;
1107
- G = F;
1108
- F = E;
1109
- E = D + T1 | 0;
1110
- D = C;
1111
- C = B;
1112
- B = A;
1113
- A = T1 + T2 | 0;
1114
- }
1115
- A = A + this.A | 0;
1116
- B = B + this.B | 0;
1117
- C = C + this.C | 0;
1118
- D = D + this.D | 0;
1119
- E = E + this.E | 0;
1120
- F = F + this.F | 0;
1121
- G = G + this.G | 0;
1122
- H = H + this.H | 0;
1123
- this.set(A, B, C, D, E, F, G, H);
1124
- }
1125
- roundClean() {
1126
- SHA256_W.fill(0);
1127
- }
1128
- destroy() {
1129
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
1130
- this.buffer.fill(0);
1131
- }
1132
- };
1133
- var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
1134
-
1135
- // ../../node_modules/viem/_esm/utils/hash/sha256.js
1136
- function sha2562(value, to_) {
1137
- const to = to_ || "hex";
1138
- const bytes = sha256(isHex(value, { strict: false }) ? toBytes(value) : value);
1139
- if (to === "bytes")
1140
- return bytes;
1141
- return toHex(bytes);
1142
- }
1143
-
1144
- // ../../node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js
1145
- function commitmentToVersionedHash(parameters) {
1146
- const { commitment, version = 1 } = parameters;
1147
- const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes");
1148
- const versionedHash = sha2562(commitment, "bytes");
1149
- versionedHash.set([version], 0);
1150
- return to === "bytes" ? versionedHash : bytesToHex(versionedHash);
1151
- }
1152
-
1153
- // ../../node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js
1154
- function commitmentsToVersionedHashes(parameters) {
1155
- const { commitments, version } = parameters;
1156
- const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes");
1157
- const hashes = [];
1158
- for (const commitment of commitments) {
1159
- hashes.push(commitmentToVersionedHash({
1160
- commitment,
1161
- to,
1162
- version
1163
- }));
1164
- }
1165
- return hashes;
1166
- }
1167
-
1168
- // ../../node_modules/viem/_esm/constants/blob.js
1169
- var blobsPerTransaction = 6;
1170
- var bytesPerFieldElement = 32;
1171
- var fieldElementsPerBlob = 4096;
1172
- var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;
1173
- var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80).
1174
- 1 - // zero byte (0x00) appended to each field element.
1175
- 1 * fieldElementsPerBlob * blobsPerTransaction;
1176
-
1177
- // ../../node_modules/viem/_esm/constants/kzg.js
1178
- var versionedHashVersionKzg = 1;
1179
-
1180
- // ../../node_modules/viem/_esm/errors/blob.js
1181
- var BlobSizeTooLargeError = class extends BaseError {
1182
- constructor({ maxSize, size: size2 }) {
1183
- super("Blob size is too large.", {
1184
- metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`],
1185
- name: "BlobSizeTooLargeError"
1186
- });
1187
- }
1188
- };
1189
- var EmptyBlobError = class extends BaseError {
1190
- constructor() {
1191
- super("Blob data must not be empty.", { name: "EmptyBlobError" });
1192
- }
1193
- };
1194
- var InvalidVersionedHashSizeError = class extends BaseError {
1195
- constructor({ hash, size: size2 }) {
1196
- super(`Versioned hash "${hash}" size is invalid.`, {
1197
- metaMessages: ["Expected: 32", `Received: ${size2}`],
1198
- name: "InvalidVersionedHashSizeError"
1199
- });
1200
- }
1201
- };
1202
- var InvalidVersionedHashVersionError = class extends BaseError {
1203
- constructor({ hash, version }) {
1204
- super(`Versioned hash "${hash}" version is invalid.`, {
1205
- metaMessages: [
1206
- `Expected: ${versionedHashVersionKzg}`,
1207
- `Received: ${version}`
1208
- ],
1209
- name: "InvalidVersionedHashVersionError"
1210
- });
1211
- }
1212
- };
1213
-
1214
- // ../../node_modules/viem/_esm/utils/blob/toBlobs.js
1215
- function toBlobs(parameters) {
1216
- const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes");
1217
- const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data;
1218
- const size_ = size(data);
1219
- if (!size_)
1220
- throw new EmptyBlobError();
1221
- if (size_ > maxBytesPerTransaction)
1222
- throw new BlobSizeTooLargeError({
1223
- maxSize: maxBytesPerTransaction,
1224
- size: size_
1225
- });
1226
- const blobs = [];
1227
- let active = true;
1228
- let position = 0;
1229
- while (active) {
1230
- const blob = createCursor(new Uint8Array(bytesPerBlob));
1231
- let size2 = 0;
1232
- while (size2 < fieldElementsPerBlob) {
1233
- const bytes = data.slice(position, position + (bytesPerFieldElement - 1));
1234
- blob.pushByte(0);
1235
- blob.pushBytes(bytes);
1236
- if (bytes.length < 31) {
1237
- blob.pushByte(128);
1238
- active = false;
1239
- break;
1240
- }
1241
- size2++;
1242
- position += 31;
1243
- }
1244
- blobs.push(blob);
1245
- }
1246
- return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes));
1247
- }
1248
-
1249
- // ../../node_modules/viem/_esm/utils/blob/toBlobSidecars.js
1250
- function toBlobSidecars(parameters) {
1251
- const { data, kzg, to } = parameters;
1252
- const blobs = parameters.blobs ?? toBlobs({ data, to });
1253
- const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to });
1254
- const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to });
1255
- const sidecars = [];
1256
- for (let i = 0; i < blobs.length; i++)
1257
- sidecars.push({
1258
- blob: blobs[i],
1259
- commitment: commitments[i],
1260
- proof: proofs[i]
1261
- });
1262
- return sidecars;
1263
- }
1264
-
1265
- // ../../node_modules/viem/_esm/utils/transaction/getTransactionType.js
1266
- function getTransactionType(transaction) {
1267
- if (transaction.type)
1268
- return transaction.type;
1269
- if (typeof transaction.authorizationList !== "undefined")
1270
- return "eip7702";
1271
- if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined")
1272
- return "eip4844";
1273
- if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") {
1274
- return "eip1559";
1275
- }
1276
- if (typeof transaction.gasPrice !== "undefined") {
1277
- if (typeof transaction.accessList !== "undefined")
1278
- return "eip2930";
1279
- return "legacy";
1280
- }
1281
- throw new InvalidSerializableTransactionError({ transaction });
1282
- }
1283
-
1284
- // ../../node_modules/viem/_esm/errors/typedData.js
1285
- var InvalidDomainError = class extends BaseError {
1286
- constructor({ domain }) {
1287
- super(`Invalid domain "${stringify(domain)}".`, {
1288
- metaMessages: ["Must be a valid EIP-712 domain."]
1289
- });
1290
- }
1291
- };
1292
- var InvalidPrimaryTypeError = class extends BaseError {
1293
- constructor({ primaryType, types }) {
1294
- super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
1295
- docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
1296
- metaMessages: ["Check that the primary type is a key in `types`."]
1297
- });
1298
- }
1299
- };
1300
- var InvalidStructTypeError = class extends BaseError {
1301
- constructor({ type }) {
1302
- super(`Struct type "${type}" is invalid.`, {
1303
- metaMessages: ["Struct type must not be a Solidity type."],
1304
- name: "InvalidStructTypeError"
1305
- });
1306
- }
1307
- };
1308
-
1309
- // ../../node_modules/viem/_esm/utils/signature/hashTypedData.js
1310
- function hashTypedData(parameters) {
1311
- const { domain = {}, message, primaryType } = parameters;
1312
- const types = {
1313
- EIP712Domain: getTypesForEIP712Domain({ domain }),
1314
- ...parameters.types
1315
- };
1316
- validateTypedData({
1317
- domain,
1318
- message,
1319
- primaryType,
1320
- types
1321
- });
1322
- const parts = ["0x1901"];
1323
- if (domain)
1324
- parts.push(hashDomain({
1325
- domain,
1326
- types
1327
- }));
1328
- if (primaryType !== "EIP712Domain")
1329
- parts.push(hashStruct({
1330
- data: message,
1331
- primaryType,
1332
- types
1333
- }));
1334
- return keccak256(concat(parts));
1335
- }
1336
- function hashDomain({ domain, types }) {
1337
- return hashStruct({
1338
- data: domain,
1339
- primaryType: "EIP712Domain",
1340
- types
1341
- });
1342
- }
1343
- function hashStruct({ data, primaryType, types }) {
1344
- const encoded = encodeData({
1345
- data,
1346
- primaryType,
1347
- types
1348
- });
1349
- return keccak256(encoded);
1350
- }
1351
- function encodeData({ data, primaryType, types }) {
1352
- const encodedTypes = [{ type: "bytes32" }];
1353
- const encodedValues = [hashType({ primaryType, types })];
1354
- for (const field of types[primaryType]) {
1355
- const [type, value] = encodeField({
1356
- types,
1357
- name: field.name,
1358
- type: field.type,
1359
- value: data[field.name]
1360
- });
1361
- encodedTypes.push(type);
1362
- encodedValues.push(value);
1363
- }
1364
- return encodeAbiParameters(encodedTypes, encodedValues);
1365
- }
1366
- function hashType({ primaryType, types }) {
1367
- const encodedHashType = toHex(encodeType({ primaryType, types }));
1368
- return keccak256(encodedHashType);
1369
- }
1370
- function encodeType({ primaryType, types }) {
1371
- let result = "";
1372
- const unsortedDeps = findTypeDependencies({ primaryType, types });
1373
- unsortedDeps.delete(primaryType);
1374
- const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
1375
- for (const type of deps) {
1376
- result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
1377
- }
1378
- return result;
1379
- }
1380
- function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) {
1381
- const match = primaryType_.match(/^\w*/u);
1382
- const primaryType = match?.[0];
1383
- if (results.has(primaryType) || types[primaryType] === void 0) {
1384
- return results;
1385
- }
1386
- results.add(primaryType);
1387
- for (const field of types[primaryType]) {
1388
- findTypeDependencies({ primaryType: field.type, types }, results);
1389
- }
1390
- return results;
1391
- }
1392
- function encodeField({ types, name, type, value }) {
1393
- if (types[type] !== void 0) {
1394
- return [
1395
- { type: "bytes32" },
1396
- keccak256(encodeData({ data: value, primaryType: type, types }))
1397
- ];
1398
- }
1399
- if (type === "bytes") {
1400
- const prepend = value.length % 2 ? "0" : "";
1401
- value = `0x${prepend + value.slice(2)}`;
1402
- return [{ type: "bytes32" }, keccak256(value)];
1403
- }
1404
- if (type === "string")
1405
- return [{ type: "bytes32" }, keccak256(toHex(value))];
1406
- if (type.lastIndexOf("]") === type.length - 1) {
1407
- const parsedType = type.slice(0, type.lastIndexOf("["));
1408
- const typeValuePairs = value.map((item) => encodeField({
1409
- name,
1410
- type: parsedType,
1411
- types,
1412
- value: item
1413
- }));
1414
- return [
1415
- { type: "bytes32" },
1416
- keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v)))
1417
- ];
1418
- }
1419
- return [{ type }, value];
1420
- }
1421
-
1422
- // ../../node_modules/viem/_esm/utils/typedData.js
1423
- function validateTypedData(parameters) {
1424
- const { domain, message, primaryType, types } = parameters;
1425
- const validateData = (struct, data) => {
1426
- for (const param of struct) {
1427
- const { name, type } = param;
1428
- const value = data[name];
1429
- const integerMatch = type.match(integerRegex);
1430
- if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
1431
- const [_type, base, size_] = integerMatch;
1432
- numberToHex(value, {
1433
- signed: base === "int",
1434
- size: Number.parseInt(size_) / 8
1435
- });
1436
- }
1437
- if (type === "address" && typeof value === "string" && !isAddress(value))
1438
- throw new InvalidAddressError({ address: value });
1439
- const bytesMatch = type.match(bytesRegex);
1440
- if (bytesMatch) {
1441
- const [_type, size_] = bytesMatch;
1442
- if (size_ && size(value) !== Number.parseInt(size_))
1443
- throw new BytesSizeMismatchError({
1444
- expectedSize: Number.parseInt(size_),
1445
- givenSize: size(value)
1446
- });
1447
- }
1448
- const struct2 = types[type];
1449
- if (struct2) {
1450
- validateReference(type);
1451
- validateData(struct2, value);
1452
- }
1453
- }
1454
- };
1455
- if (types.EIP712Domain && domain) {
1456
- if (typeof domain !== "object")
1457
- throw new InvalidDomainError({ domain });
1458
- validateData(types.EIP712Domain, domain);
1459
- }
1460
- if (primaryType !== "EIP712Domain") {
1461
- if (types[primaryType])
1462
- validateData(types[primaryType], message);
1463
- else
1464
- throw new InvalidPrimaryTypeError({ primaryType, types });
1465
- }
1466
- }
1467
- function getTypesForEIP712Domain({ domain }) {
1468
- return [
1469
- typeof domain?.name === "string" && { name: "name", type: "string" },
1470
- domain?.version && { name: "version", type: "string" },
1471
- (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && {
1472
- name: "chainId",
1473
- type: "uint256"
1474
- },
1475
- domain?.verifyingContract && {
1476
- name: "verifyingContract",
1477
- type: "address"
1478
- },
1479
- domain?.salt && { name: "salt", type: "bytes32" }
1480
- ].filter(Boolean);
1481
- }
1482
- function validateReference(type) {
1483
- if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int"))
1484
- throw new InvalidStructTypeError({ type });
1485
- }
1486
-
1487
- // ../../node_modules/viem/_esm/constants/strings.js
1488
- var presignMessagePrefix = "Ethereum Signed Message:\n";
1489
-
1490
- // ../../node_modules/viem/_esm/utils/signature/toPrefixedMessage.js
1491
- function toPrefixedMessage(message_) {
1492
- const message = (() => {
1493
- if (typeof message_ === "string")
1494
- return stringToHex(message_);
1495
- if (typeof message_.raw === "string")
1496
- return message_.raw;
1497
- return bytesToHex(message_.raw);
1498
- })();
1499
- const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`);
1500
- return concat([prefix, message]);
1501
- }
1502
-
1503
- // ../../node_modules/viem/_esm/utils/signature/hashMessage.js
1504
- function hashMessage(message, to_) {
1505
- return keccak256(toPrefixedMessage(message), to_);
1506
- }
1507
-
1508
- // ../../node_modules/viem/_esm/utils/transaction/assertTransaction.js
1509
- function assertTransactionEIP7702(transaction) {
1510
- const { authorizationList } = transaction;
1511
- if (authorizationList) {
1512
- for (const authorization of authorizationList) {
1513
- const { contractAddress, chainId } = authorization;
1514
- if (!isAddress(contractAddress))
1515
- throw new InvalidAddressError({ address: contractAddress });
1516
- if (chainId < 0)
1517
- throw new InvalidChainIdError({ chainId });
1518
- }
1519
- }
1520
- assertTransactionEIP1559(transaction);
1521
- }
1522
- function assertTransactionEIP4844(transaction) {
1523
- const { blobVersionedHashes } = transaction;
1524
- if (blobVersionedHashes) {
1525
- if (blobVersionedHashes.length === 0)
1526
- throw new EmptyBlobError();
1527
- for (const hash of blobVersionedHashes) {
1528
- const size_ = size(hash);
1529
- const version = hexToNumber(slice(hash, 0, 1));
1530
- if (size_ !== 32)
1531
- throw new InvalidVersionedHashSizeError({ hash, size: size_ });
1532
- if (version !== versionedHashVersionKzg)
1533
- throw new InvalidVersionedHashVersionError({
1534
- hash,
1535
- version
1536
- });
1537
- }
1538
- }
1539
- assertTransactionEIP1559(transaction);
1540
- }
1541
- function assertTransactionEIP1559(transaction) {
1542
- const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;
1543
- if (chainId <= 0)
1544
- throw new InvalidChainIdError({ chainId });
1545
- if (to && !isAddress(to))
1546
- throw new InvalidAddressError({ address: to });
1547
- if (maxFeePerGas && maxFeePerGas > maxUint256)
1548
- throw new FeeCapTooHighError({ maxFeePerGas });
1549
- if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
1550
- throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
1551
- }
1552
- function assertTransactionEIP2930(transaction) {
1553
- const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
1554
- if (chainId <= 0)
1555
- throw new InvalidChainIdError({ chainId });
1556
- if (to && !isAddress(to))
1557
- throw new InvalidAddressError({ address: to });
1558
- if (maxPriorityFeePerGas || maxFeePerGas)
1559
- throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");
1560
- if (gasPrice && gasPrice > maxUint256)
1561
- throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
1562
- }
1563
- function assertTransactionLegacy(transaction) {
1564
- const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
1565
- if (to && !isAddress(to))
1566
- throw new InvalidAddressError({ address: to });
1567
- if (typeof chainId !== "undefined" && chainId <= 0)
1568
- throw new InvalidChainIdError({ chainId });
1569
- if (maxPriorityFeePerGas || maxFeePerGas)
1570
- throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");
1571
- if (gasPrice && gasPrice > maxUint256)
1572
- throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
1573
- }
1574
-
1575
- // ../../node_modules/viem/_esm/experimental/eip7702/utils/serializeAuthorizationList.js
1576
- function serializeAuthorizationList(authorizationList) {
1577
- if (!authorizationList || authorizationList.length === 0)
1578
- return [];
1579
- const serializedAuthorizationList = [];
1580
- for (const authorization of authorizationList) {
1581
- const { contractAddress, chainId, nonce, ...signature } = authorization;
1582
- serializedAuthorizationList.push([
1583
- chainId ? toHex(chainId) : "0x",
1584
- contractAddress,
1585
- nonce ? toHex(nonce) : "0x",
1586
- ...toYParitySignatureArray({}, signature)
1587
- ]);
1588
- }
1589
- return serializedAuthorizationList;
1590
- }
1591
-
1592
- // ../../node_modules/viem/_esm/utils/transaction/serializeAccessList.js
1593
- function serializeAccessList(accessList) {
1594
- if (!accessList || accessList.length === 0)
1595
- return [];
1596
- const serializedAccessList = [];
1597
- for (let i = 0; i < accessList.length; i++) {
1598
- const { address, storageKeys } = accessList[i];
1599
- for (let j = 0; j < storageKeys.length; j++) {
1600
- if (storageKeys[j].length - 2 !== 64) {
1601
- throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });
1602
- }
1603
- }
1604
- if (!isAddress(address, { strict: false })) {
1605
- throw new InvalidAddressError({ address });
1606
- }
1607
- serializedAccessList.push([address, storageKeys]);
1608
- }
1609
- return serializedAccessList;
1610
- }
1611
-
1612
- // ../../node_modules/viem/_esm/utils/transaction/serializeTransaction.js
1613
- function serializeTransaction(transaction, signature) {
1614
- const type = getTransactionType(transaction);
1615
- if (type === "eip1559")
1616
- return serializeTransactionEIP1559(transaction, signature);
1617
- if (type === "eip2930")
1618
- return serializeTransactionEIP2930(transaction, signature);
1619
- if (type === "eip4844")
1620
- return serializeTransactionEIP4844(transaction, signature);
1621
- if (type === "eip7702")
1622
- return serializeTransactionEIP7702(transaction, signature);
1623
- return serializeTransactionLegacy(transaction, signature);
1624
- }
1625
- function serializeTransactionEIP7702(transaction, signature) {
1626
- const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
1627
- assertTransactionEIP7702(transaction);
1628
- const serializedAccessList = serializeAccessList(accessList);
1629
- const serializedAuthorizationList = serializeAuthorizationList(authorizationList);
1630
- return concatHex([
1631
- "0x04",
1632
- toRlp([
1633
- toHex(chainId),
1634
- nonce ? toHex(nonce) : "0x",
1635
- maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x",
1636
- maxFeePerGas ? toHex(maxFeePerGas) : "0x",
1637
- gas ? toHex(gas) : "0x",
1638
- to ?? "0x",
1639
- value ? toHex(value) : "0x",
1640
- data ?? "0x",
1641
- serializedAccessList,
1642
- serializedAuthorizationList,
1643
- ...toYParitySignatureArray(transaction, signature)
1644
- ])
1645
- ]);
1646
- }
1647
- function serializeTransactionEIP4844(transaction, signature) {
1648
- const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
1649
- assertTransactionEIP4844(transaction);
1650
- let blobVersionedHashes = transaction.blobVersionedHashes;
1651
- let sidecars = transaction.sidecars;
1652
- if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) {
1653
- const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x));
1654
- const kzg = transaction.kzg;
1655
- const commitments2 = blobsToCommitments({
1656
- blobs: blobs2,
1657
- kzg
1658
- });
1659
- if (typeof blobVersionedHashes === "undefined")
1660
- blobVersionedHashes = commitmentsToVersionedHashes({
1661
- commitments: commitments2
1662
- });
1663
- if (typeof sidecars === "undefined") {
1664
- const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg });
1665
- sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 });
1666
- }
1667
- }
1668
- const serializedAccessList = serializeAccessList(accessList);
1669
- const serializedTransaction = [
1670
- toHex(chainId),
1671
- nonce ? toHex(nonce) : "0x",
1672
- maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x",
1673
- maxFeePerGas ? toHex(maxFeePerGas) : "0x",
1674
- gas ? toHex(gas) : "0x",
1675
- to ?? "0x",
1676
- value ? toHex(value) : "0x",
1677
- data ?? "0x",
1678
- serializedAccessList,
1679
- maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : "0x",
1680
- blobVersionedHashes ?? [],
1681
- ...toYParitySignatureArray(transaction, signature)
1682
- ];
1683
- const blobs = [];
1684
- const commitments = [];
1685
- const proofs = [];
1686
- if (sidecars)
1687
- for (let i = 0; i < sidecars.length; i++) {
1688
- const { blob, commitment, proof } = sidecars[i];
1689
- blobs.push(blob);
1690
- commitments.push(commitment);
1691
- proofs.push(proof);
1692
- }
1693
- return concatHex([
1694
- "0x03",
1695
- sidecars ? (
1696
- // If sidecars are enabled, envelope turns into a "wrapper":
1697
- toRlp([serializedTransaction, blobs, commitments, proofs])
1698
- ) : (
1699
- // If sidecars are disabled, standard envelope is used:
1700
- toRlp(serializedTransaction)
1701
- )
1702
- ]);
1703
- }
1704
- function serializeTransactionEIP1559(transaction, signature) {
1705
- const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
1706
- assertTransactionEIP1559(transaction);
1707
- const serializedAccessList = serializeAccessList(accessList);
1708
- const serializedTransaction = [
1709
- toHex(chainId),
1710
- nonce ? toHex(nonce) : "0x",
1711
- maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x",
1712
- maxFeePerGas ? toHex(maxFeePerGas) : "0x",
1713
- gas ? toHex(gas) : "0x",
1714
- to ?? "0x",
1715
- value ? toHex(value) : "0x",
1716
- data ?? "0x",
1717
- serializedAccessList,
1718
- ...toYParitySignatureArray(transaction, signature)
1719
- ];
1720
- return concatHex([
1721
- "0x02",
1722
- toRlp(serializedTransaction)
1723
- ]);
1724
- }
1725
- function serializeTransactionEIP2930(transaction, signature) {
1726
- const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;
1727
- assertTransactionEIP2930(transaction);
1728
- const serializedAccessList = serializeAccessList(accessList);
1729
- const serializedTransaction = [
1730
- toHex(chainId),
1731
- nonce ? toHex(nonce) : "0x",
1732
- gasPrice ? toHex(gasPrice) : "0x",
1733
- gas ? toHex(gas) : "0x",
1734
- to ?? "0x",
1735
- value ? toHex(value) : "0x",
1736
- data ?? "0x",
1737
- serializedAccessList,
1738
- ...toYParitySignatureArray(transaction, signature)
1739
- ];
1740
- return concatHex([
1741
- "0x01",
1742
- toRlp(serializedTransaction)
1743
- ]);
1744
- }
1745
- function serializeTransactionLegacy(transaction, signature) {
1746
- const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;
1747
- assertTransactionLegacy(transaction);
1748
- let serializedTransaction = [
1749
- nonce ? toHex(nonce) : "0x",
1750
- gasPrice ? toHex(gasPrice) : "0x",
1751
- gas ? toHex(gas) : "0x",
1752
- to ?? "0x",
1753
- value ? toHex(value) : "0x",
1754
- data ?? "0x"
1755
- ];
1756
- if (signature) {
1757
- const v = (() => {
1758
- if (signature.v >= 35n) {
1759
- const inferredChainId = (signature.v - 35n) / 2n;
1760
- if (inferredChainId > 0)
1761
- return signature.v;
1762
- return 27n + (signature.v === 35n ? 0n : 1n);
1763
- }
1764
- if (chainId > 0)
1765
- return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n);
1766
- const v2 = 27n + (signature.v === 27n ? 0n : 1n);
1767
- if (signature.v !== v2)
1768
- throw new InvalidLegacyVError({ v: signature.v });
1769
- return v2;
1770
- })();
1771
- const r = trim(signature.r);
1772
- const s = trim(signature.s);
1773
- serializedTransaction = [
1774
- ...serializedTransaction,
1775
- toHex(v),
1776
- r === "0x00" ? "0x" : r,
1777
- s === "0x00" ? "0x" : s
1778
- ];
1779
- } else if (chainId > 0) {
1780
- serializedTransaction = [
1781
- ...serializedTransaction,
1782
- toHex(chainId),
1783
- "0x",
1784
- "0x"
1785
- ];
1786
- }
1787
- return toRlp(serializedTransaction);
1788
- }
1789
- function toYParitySignatureArray(transaction, signature_) {
1790
- const signature = signature_ ?? transaction;
1791
- const { v, yParity } = signature;
1792
- if (typeof signature.r === "undefined")
1793
- return [];
1794
- if (typeof signature.s === "undefined")
1795
- return [];
1796
- if (typeof v === "undefined" && typeof yParity === "undefined")
1797
- return [];
1798
- const r = trim(signature.r);
1799
- const s = trim(signature.s);
1800
- const yParity_ = (() => {
1801
- if (typeof yParity === "number")
1802
- return yParity ? toHex(1) : "0x";
1803
- if (v === 0n)
1804
- return "0x";
1805
- if (v === 1n)
1806
- return toHex(1);
1807
- return v === 27n ? "0x" : toHex(1);
1808
- })();
1809
- return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s];
1810
- }
1811
-
1812
- // ../../node_modules/viem/_esm/utils/signature/serializeSignature.js
1813
- function serializeSignature({ r, s, to = "hex", v, yParity }) {
1814
- const yParity_ = (() => {
1815
- if (yParity === 0 || yParity === 1)
1816
- return yParity;
1817
- if (v && (v === 27n || v === 28n || v >= 35n))
1818
- return v % 2n === 0n ? 1 : 0;
1819
- throw new Error("Invalid `v` or `yParity` value");
1820
- })();
1821
- const signature = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`;
1822
- if (to === "hex")
1823
- return signature;
1824
- return hexToBytes(signature);
1825
- }
1826
-
1827
- // ../../node_modules/viem/_esm/accounts/toAccount.js
1828
- function toAccount(source) {
1829
- if (typeof source === "string") {
1830
- if (!isAddress(source, { strict: false }))
1831
- throw new InvalidAddressError({ address: source });
1832
- return {
1833
- address: source,
1834
- type: "json-rpc"
1835
- };
1836
- }
1837
- if (!isAddress(source.address, { strict: false }))
1838
- throw new InvalidAddressError({ address: source.address });
1839
- return {
1840
- address: source.address,
1841
- nonceManager: source.nonceManager,
1842
- sign: source.sign,
1843
- experimental_signAuthorization: source.experimental_signAuthorization,
1844
- signMessage: source.signMessage,
1845
- signTransaction: source.signTransaction,
1846
- signTypedData: source.signTypedData,
1847
- source: "custom",
1848
- type: "local"
1849
- };
1850
- }
1851
-
1852
- // ../../node_modules/viem/_esm/accounts/utils/sign.js
1853
- var extraEntropy = false;
1854
- async function sign({ hash, privateKey, to = "object" }) {
1855
- const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), { lowS: true, extraEntropy });
1856
- const signature = {
1857
- r: numberToHex(r, { size: 32 }),
1858
- s: numberToHex(s, { size: 32 }),
1859
- v: recovery ? 28n : 27n,
1860
- yParity: recovery
1861
- };
1862
- return (() => {
1863
- if (to === "bytes" || to === "hex")
1864
- return serializeSignature({ ...signature, to });
1865
- return signature;
1866
- })();
1867
- }
1868
-
1869
- // ../../node_modules/viem/_esm/accounts/utils/signAuthorization.js
1870
- async function experimental_signAuthorization(parameters) {
1871
- const { contractAddress, chainId, nonce, privateKey, to = "object" } = parameters;
1872
- const signature = await sign({
1873
- hash: hashAuthorization({ contractAddress, chainId, nonce }),
1874
- privateKey,
1875
- to
1876
- });
1877
- if (to === "object")
1878
- return {
1879
- contractAddress,
1880
- chainId,
1881
- nonce,
1882
- ...signature
1883
- };
1884
- return signature;
1885
- }
1886
-
1887
- // ../../node_modules/viem/_esm/accounts/utils/signMessage.js
1888
- async function signMessage({ message, privateKey }) {
1889
- return await sign({ hash: hashMessage(message), privateKey, to: "hex" });
1890
- }
1891
-
1892
- // ../../node_modules/viem/_esm/accounts/utils/signTransaction.js
1893
- async function signTransaction(parameters) {
1894
- const { privateKey, transaction, serializer = serializeTransaction } = parameters;
1895
- const signableTransaction = (() => {
1896
- if (transaction.type === "eip4844")
1897
- return {
1898
- ...transaction,
1899
- sidecars: false
1900
- };
1901
- return transaction;
1902
- })();
1903
- const signature = await sign({
1904
- hash: keccak256(serializer(signableTransaction)),
1905
- privateKey
1906
- });
1907
- return serializer(transaction, signature);
1908
- }
1909
-
1910
- // ../../node_modules/viem/_esm/accounts/utils/signTypedData.js
1911
- async function signTypedData(parameters) {
1912
- const { privateKey, ...typedData } = parameters;
1913
- return await sign({
1914
- hash: hashTypedData(typedData),
1915
- privateKey,
1916
- to: "hex"
1917
- });
1918
- }
1919
-
1920
- // ../../node_modules/viem/_esm/accounts/privateKeyToAccount.js
1921
- function privateKeyToAccount(privateKey, options = {}) {
1922
- const { nonceManager } = options;
1923
- const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
1924
- const address = publicKeyToAddress(publicKey);
1925
- const account = toAccount({
1926
- address,
1927
- nonceManager,
1928
- async sign({ hash }) {
1929
- return sign({ hash, privateKey, to: "hex" });
1930
- },
1931
- async experimental_signAuthorization(authorization) {
1932
- return experimental_signAuthorization({ ...authorization, privateKey });
1933
- },
1934
- async signMessage({ message }) {
1935
- return signMessage({ message, privateKey });
1936
- },
1937
- async signTransaction(transaction, { serializer } = {}) {
1938
- return signTransaction({ privateKey, transaction, serializer });
1939
- },
1940
- async signTypedData(typedData) {
1941
- return signTypedData({ ...typedData, privateKey });
1942
- }
1943
- });
1944
- return {
1945
- ...account,
1946
- publicKey,
1947
- source: "privateKey"
1948
- };
1949
- }
1950
-
1951
- // src/providers/deriveKeyProvider.ts
229
+ import { toViemAccount } from "@phala/dstack-sdk/viem";
230
+ import { toKeypair } from "@phala/dstack-sdk/solana";
1952
231
  var PhalaDeriveKeyProvider = class extends DeriveKeyProvider {
1953
232
  client;
1954
233
  raProvider;
@@ -1956,17 +235,17 @@ var PhalaDeriveKeyProvider = class extends DeriveKeyProvider {
1956
235
  super();
1957
236
  let endpoint;
1958
237
  switch (teeMode) {
1959
- case TEEMode3.LOCAL:
238
+ case TEEMode2.LOCAL:
1960
239
  endpoint = "http://localhost:8090";
1961
- logger4.log("TEE: Connecting to local simulator at localhost:8090");
240
+ logger3.log("TEE: Connecting to local simulator at localhost:8090");
1962
241
  break;
1963
- case TEEMode3.DOCKER:
242
+ case TEEMode2.DOCKER:
1964
243
  endpoint = "http://host.docker.internal:8090";
1965
- logger4.log("TEE: Connecting to simulator via Docker at host.docker.internal:8090");
244
+ logger3.log("TEE: Connecting to simulator via Docker at host.docker.internal:8090");
1966
245
  break;
1967
- case TEEMode3.PRODUCTION:
246
+ case TEEMode2.PRODUCTION:
1968
247
  endpoint = void 0;
1969
- logger4.log("TEE: Running in production mode without simulator");
248
+ logger3.log("TEE: Running in production mode without simulator");
1970
249
  break;
1971
250
  default:
1972
251
  throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`);
@@ -1981,9 +260,9 @@ var PhalaDeriveKeyProvider = class extends DeriveKeyProvider {
1981
260
  subject
1982
261
  };
1983
262
  const reportdata = JSON.stringify(deriveKeyData);
1984
- logger4.log("Generating Remote Attestation Quote for Derive Key...");
263
+ logger3.log("Generating Remote Attestation Quote for Derive Key...");
1985
264
  const quote = await this.raProvider.generateAttestation(reportdata);
1986
- logger4.log("Remote Attestation Quote generated successfully!");
265
+ logger3.log("Remote Attestation Quote generated successfully!");
1987
266
  return quote;
1988
267
  }
1989
268
  /**
@@ -1992,17 +271,17 @@ var PhalaDeriveKeyProvider = class extends DeriveKeyProvider {
1992
271
  * @param subject - The subject to derive the key from. This is used for the certificate chain.
1993
272
  * @returns The derived key.
1994
273
  */
1995
- async rawDeriveKey(path2, subject) {
274
+ async rawDeriveKey(path, subject) {
1996
275
  try {
1997
- if (!path2 || !subject) {
1998
- logger4.error("Path and Subject are required for key derivation");
276
+ if (!path || !subject) {
277
+ logger3.error("Path and Subject are required for key derivation");
1999
278
  }
2000
- logger4.log("Deriving Raw Key in TEE...");
2001
- const derivedKey = await this.client.deriveKey(path2, subject);
2002
- logger4.log("Raw Key Derived Successfully!");
279
+ logger3.log("Deriving Raw Key in TEE...");
280
+ const derivedKey = await this.client.deriveKey(path, subject);
281
+ logger3.log("Raw Key Derived Successfully!");
2003
282
  return derivedKey;
2004
283
  } catch (error) {
2005
- logger4.error("Error deriving raw key:", error);
284
+ logger3.error("Error deriving raw key:", error);
2006
285
  throw error;
2007
286
  }
2008
287
  }
@@ -2013,27 +292,22 @@ var PhalaDeriveKeyProvider = class extends DeriveKeyProvider {
2013
292
  * @param agentId - The agent ID to generate an attestation for.
2014
293
  * @returns An object containing the derived keypair and attestation.
2015
294
  */
2016
- async deriveEd25519Keypair(path2, subject, agentId) {
295
+ async deriveEd25519Keypair(path, subject, agentId) {
2017
296
  try {
2018
- if (!path2 || !subject) {
2019
- logger4.error("Path and Subject are required for key derivation");
297
+ if (!path || !subject) {
298
+ logger3.error("Path and Subject are required for key derivation");
2020
299
  }
2021
- logger4.log("Deriving Key in TEE...");
2022
- const derivedKey = await this.client.deriveKey(path2, subject);
2023
- const uint8ArrayDerivedKey = derivedKey.asUint8Array();
2024
- const hash = crypto.createHash("sha256");
2025
- hash.update(uint8ArrayDerivedKey);
2026
- const seed = hash.digest();
2027
- const seedArray = new Uint8Array(seed);
2028
- const keypair = Keypair.fromSeed(seedArray.slice(0, 32));
300
+ logger3.log("Deriving Key in TEE...");
301
+ const derivedKey = await this.client.deriveKey(path, subject);
302
+ const keypair = toKeypair(derivedKey);
2029
303
  const attestation = await this.generateDeriveKeyAttestation(
2030
304
  agentId,
2031
305
  keypair.publicKey.toBase58()
2032
306
  );
2033
- logger4.log("Key Derived Successfully!");
307
+ logger3.log("Key Derived Successfully!");
2034
308
  return { keypair, attestation };
2035
309
  } catch (error) {
2036
- logger4.error("Error deriving key:", error);
310
+ logger3.error("Error deriving key:", error);
2037
311
  throw error;
2038
312
  }
2039
313
  }
@@ -2044,20 +318,19 @@ var PhalaDeriveKeyProvider = class extends DeriveKeyProvider {
2044
318
  * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.
2045
319
  * @returns An object containing the derived keypair and attestation.
2046
320
  */
2047
- async deriveEcdsaKeypair(path2, subject, agentId) {
321
+ async deriveEcdsaKeypair(path, subject, agentId) {
2048
322
  try {
2049
- if (!path2 || !subject) {
2050
- logger4.error("Path and Subject are required for key derivation");
323
+ if (!path || !subject) {
324
+ logger3.error("Path and Subject are required for key derivation");
2051
325
  }
2052
- logger4.log("Deriving ECDSA Key in TEE...");
2053
- const deriveKeyResponse = await this.client.deriveKey(path2, subject);
2054
- const hex = keccak256(deriveKeyResponse.asUint8Array());
2055
- const keypair = privateKeyToAccount(hex);
326
+ logger3.log("Deriving ECDSA Key in TEE...");
327
+ const deriveKeyResponse = await this.client.deriveKey(path, subject);
328
+ const keypair = toViemAccount(deriveKeyResponse);
2056
329
  const attestation = await this.generateDeriveKeyAttestation(agentId, keypair.address);
2057
- logger4.log("ECDSA Key Derived Successfully!");
330
+ logger3.log("ECDSA Key Derived Successfully!");
2058
331
  return { keypair, attestation };
2059
332
  } catch (error) {
2060
- logger4.error("Error deriving ecdsa key:", error);
333
+ logger3.error("Error deriving ecdsa key:", error);
2061
334
  throw error;
2062
335
  }
2063
336
  }
@@ -2070,7 +343,7 @@ var phalaDeriveKeyProvider = {
2070
343
  const agentId = runtime.agentId;
2071
344
  try {
2072
345
  if (!runtime.getSetting("WALLET_SECRET_SALT")) {
2073
- logger4.error("Wallet secret salt is not configured in settings");
346
+ logger3.error("Wallet secret salt is not configured in settings");
2074
347
  return {
2075
348
  data: null,
2076
349
  values: {},
@@ -2097,7 +370,7 @@ EVM Address: ${values.evm_address}`;
2097
370
  text
2098
371
  };
2099
372
  } catch (error) {
2100
- logger4.error("Error creating PublicKey:", error);
373
+ logger3.error("Error creating PublicKey:", error);
2101
374
  return {
2102
375
  data: null,
2103
376
  values: {},
@@ -2105,7 +378,7 @@ EVM Address: ${values.evm_address}`;
2105
378
  };
2106
379
  }
2107
380
  } catch (error) {
2108
- logger4.error("Error in derive key provider:", error.message);
381
+ logger3.error("Error in derive key provider:", error.message);
2109
382
  return {
2110
383
  data: null,
2111
384
  values: {},
@@ -2117,7 +390,7 @@ EVM Address: ${values.evm_address}`;
2117
390
 
2118
391
  // src/vendors/phala.ts
2119
392
  var PhalaVendor = class {
2120
- type = TeeVendors.PHALA;
393
+ type = TeeVendorNames.PHALA;
2121
394
  /**
2122
395
  * Returns an array of actions.
2123
396
  *
@@ -2152,8 +425,7 @@ var PhalaVendor = class {
2152
425
 
2153
426
  // src/vendors/index.ts
2154
427
  var vendors = {
2155
- [TeeVendorNames.PHALA]: new PhalaVendor(),
2156
- [TeeVendorNames.SGX_GRAMINE]: new GramineVendor()
428
+ [TeeVendorNames.PHALA]: new PhalaVendor()
2157
429
  };
2158
430
  var getVendor = (type) => {
2159
431
  const vendor = vendors[type];
@@ -2167,26 +439,18 @@ var getVendor = (type) => {
2167
439
  async function initializeTEE(config, runtime) {
2168
440
  if (config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR")) {
2169
441
  const vendor = config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR");
2170
- logger5.info(`Initializing TEE with vendor: ${vendor}`);
442
+ logger4.info(`Initializing TEE with vendor: ${vendor}`);
2171
443
  let plugin;
2172
444
  switch (vendor) {
2173
445
  case "phala":
2174
446
  plugin = teePlugin({
2175
- vendor: TeeVendorNames.PHALA,
2176
- vendorConfig: {
2177
- apiKey: runtime.getSetting("TEE_API_KEY")
2178
- }
2179
- });
2180
- break;
2181
- case "sgx-gramine":
2182
- plugin = teePlugin({
2183
- vendor: TeeVendorNames.SGX_GRAMINE
447
+ vendor: TeeVendorNames.PHALA
2184
448
  });
2185
449
  break;
2186
450
  default:
2187
451
  throw new Error(`Invalid TEE vendor: ${vendor}`);
2188
452
  }
2189
- logger5.info(`Pushing plugin: ${plugin.name}`);
453
+ logger4.info(`Pushing plugin: ${plugin.name}`);
2190
454
  runtime.plugins.push(plugin);
2191
455
  }
2192
456
  }
@@ -2208,13 +472,12 @@ var teePlugin = (config) => {
2208
472
  actions: vendor.getActions(),
2209
473
  evaluators: [],
2210
474
  providers: vendor.getProviders(),
2211
- services: [TeeLogService]
475
+ services: []
2212
476
  };
2213
477
  };
2214
478
  export {
2215
479
  PhalaDeriveKeyProvider,
2216
480
  PhalaRemoteAttestationProvider,
2217
- TeeLogService,
2218
481
  teePlugin
2219
482
  };
2220
483
  //# sourceMappingURL=index.js.map