@elizaos/plugin-tee 1.0.0-alpha.58 → 1.0.0-alpha.59

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
@@ -53,7 +53,7 @@ import {
53
53
  import path from "node:path";
54
54
  import {
55
55
  Service,
56
- ServiceTypes,
56
+ ServiceType,
57
57
  TEEMode as TEEMode2,
58
58
  TeeType as TeeType2
59
59
  } from "@elizaos/core";
@@ -671,7 +671,7 @@ var TeeLogService = class _TeeLogService extends Service {
671
671
  // Only used for plugin-tee with TDX dstack
672
672
  teeLogDAO;
673
673
  teeLogManager;
674
- static serviceType = ServiceTypes.TEE;
674
+ static serviceType = ServiceType.TEE;
675
675
  capabilityDescription = "The agent is able to log TEE attestation events and is probably running in a TEE";
676
676
  /**
677
677
  * Constructor for creating a new instance of a class.
@@ -742,7 +742,7 @@ var TeeLogService = class _TeeLogService extends Service {
742
742
  * @returns {Promise<void>} - A promise that resolves once the TEE service has stopped.
743
743
  */
744
744
  static async stop(runtime) {
745
- const service = runtime.getService(ServiceTypes.TEE);
745
+ const service = runtime.getService(ServiceType.TEE);
746
746
  if (service) {
747
747
  await service.stop();
748
748
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/services/teeLogService.ts","../src/types.ts","../src/adapters/sqliteTables.ts","../src/adapters/sqliteDAO.ts","../src/services/teeLogManager.ts","../../../node_modules/uuid/dist/esm/stringify.js","../../../node_modules/uuid/dist/esm/rng.js","../../../node_modules/uuid/dist/esm/native.js","../../../node_modules/uuid/dist/esm/v4.js","../src/providers/remoteAttestationProvider.ts","../src/utils.ts","../src/providers/base.ts","../src/vendors/types.ts","../src/vendors/gramine.ts","../src/vendors/phala.ts","../src/actions/remoteAttestationAction.ts","../src/providers/deriveKeyProvider.ts","../../../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../../../node_modules/viem/utils/encoding/toRlp.ts","../../../node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../../../node_modules/viem/utils/blob/blobsToCommitments.ts","../../../node_modules/viem/utils/blob/blobsToProofs.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/utils/hash/sha256.ts","../../../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../../../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../../../node_modules/viem/constants/blob.ts","../../../node_modules/viem/constants/kzg.ts","../../../node_modules/viem/errors/blob.ts","../../../node_modules/viem/utils/blob/toBlobs.ts","../../../node_modules/viem/utils/blob/toBlobSidecars.ts","../../../node_modules/viem/utils/transaction/getTransactionType.ts","../../../node_modules/viem/errors/typedData.ts","../../../node_modules/viem/utils/signature/hashTypedData.ts","../../../node_modules/viem/utils/typedData.ts","../../../node_modules/viem/constants/strings.ts","../../../node_modules/viem/utils/signature/toPrefixedMessage.ts","../../../node_modules/viem/utils/signature/hashMessage.ts","../../../node_modules/viem/utils/transaction/assertTransaction.ts","../../../node_modules/viem/experimental/eip7702/utils/serializeAuthorizationList.ts","../../../node_modules/viem/utils/transaction/serializeAccessList.ts","../../../node_modules/viem/utils/transaction/serializeTransaction.ts","../../../node_modules/viem/utils/signature/serializeSignature.ts","../../../node_modules/viem/accounts/toAccount.ts","../../../node_modules/viem/accounts/utils/sign.ts","../../../node_modules/viem/accounts/utils/signAuthorization.ts","../../../node_modules/viem/accounts/utils/signMessage.ts","../../../node_modules/viem/accounts/utils/signTransaction.ts","../../../node_modules/viem/accounts/utils/signTypedData.ts","../../../node_modules/viem/accounts/privateKeyToAccount.ts","../src/vendors/index.ts"],"sourcesContent":["import {\n\ttype IAgentRuntime,\n\ttype Plugin,\n\ttype TeePluginConfig,\n\ttype TeeVendorConfig,\n\tlogger,\n} from \"@elizaos/core\";\nimport { TeeLogService } from \"./services/teeLogService\";\nimport { TeeVendorNames, getVendor } from \"./vendors\";\n\nexport { PhalaDeriveKeyProvider } from \"./providers/deriveKeyProvider\";\nexport { PhalaRemoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nexport { TeeLogService };\nexport type { TeeVendorConfig };\n\n/**\n * Asynchronously initializes the Trusted Execution Environment (TEE) based on the provided configuration and runtime settings.\n * @param {Record<string, string>} config - The configuration object containing TEE vendor information.\n * @param {IAgentRuntime} runtime - The runtime object with TEE related settings.\n * @returns {Promise<void>} - A promise that resolves once the TEE is initialized.\n */\nasync function initializeTEE(\n\tconfig: Record<string, string>,\n\truntime: IAgentRuntime,\n) {\n\tif (config.TEE_VENDOR || runtime.getSetting(\"TEE_VENDOR\")) {\n\t\tconst vendor = config.TEE_VENDOR || runtime.getSetting(\"TEE_VENDOR\");\n\t\tlogger.info(`Initializing TEE with vendor: ${vendor}`);\n\t\tlet plugin: Plugin;\n\t\tswitch (vendor) {\n\t\t\tcase \"phala\":\n\t\t\t\tplugin = teePlugin({\n\t\t\t\t\tvendor: TeeVendorNames.PHALA,\n\t\t\t\t\tvendorConfig: {\n\t\t\t\t\t\tapiKey: runtime.getSetting(\"TEE_API_KEY\"),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"sgx-gramine\":\n\t\t\t\tplugin = teePlugin({\n\t\t\t\t\tvendor: TeeVendorNames.SGX_GRAMINE,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Invalid TEE vendor: ${vendor}`);\n\t\t}\n\t\tlogger.info(`Pushing plugin: ${plugin.name}`);\n\t\truntime.plugins.push(plugin);\n\t}\n}\n\n/**\n * A function that creates a TEE (Trusted Execution Environment) plugin based on the provided configuration.\n * @param { TeePluginConfig } [config] - Optional configuration for the TEE plugin.\n * @returns { Plugin } - The TEE plugin containing initialization, description, actions, evaluators, providers, and services.\n */\nexport const teePlugin = (config?: TeePluginConfig): Plugin => {\n\tconst vendorType = config?.vendor || TeeVendorNames.PHALA;\n\tconst vendor = getVendor(vendorType);\n\treturn {\n\t\tname: vendor.getName(),\n\t\tinit: async (config: Record<string, string>, runtime: IAgentRuntime) => {\n\t\t\treturn await initializeTEE(\n\t\t\t\t{\n\t\t\t\t\t...config,\n\t\t\t\t\tvendor: vendorType,\n\t\t\t\t},\n\t\t\t\truntime,\n\t\t\t);\n\t\t},\n\t\tdescription: vendor.getDescription(),\n\t\tactions: vendor.getActions(),\n\t\tevaluators: [],\n\t\tproviders: vendor.getProviders(),\n\t\tservices: [TeeLogService],\n\t};\n};\n","import path from \"node:path\";\nimport {\n\ttype IAgentRuntime,\n\ttype ITeeLogService,\n\tService,\n\ttype ServiceType,\n\tServiceTypes,\n\tTEEMode,\n\ttype TeeAgent,\n\ttype TeeLog,\n\ttype TeeLogDAO,\n\ttype TeeLogQuery,\n\ttype TeePageQuery,\n\tTeeType,\n} from \"@elizaos/core\";\nimport Database from \"better-sqlite3\";\nimport { SqliteTeeLogDAO } from \"../adapters/sqliteDAO\";\nimport { TeeLogManager } from \"./teeLogManager\";\n\n/**\n * Represents a TeeLogService class that extends Service and implements ITeeLogService\n * This service is responsible for logging TEE attestation events\n */\nexport class TeeLogService extends Service implements ITeeLogService {\n\tprivate dbPath: string;\n\n\tprivate initialized = false;\n\tprivate enableTeeLog = false;\n\tprivate teeType: TeeType;\n\tprivate teeMode: TEEMode = TEEMode.OFF; // Only used for plugin-tee with TDX dstack\n\n\tprivate teeLogDAO: TeeLogDAO<Database.Database>;\n\tprivate teeLogManager: TeeLogManager;\n\n\tstatic serviceType: ServiceType = ServiceTypes.TEE;\n\tcapabilityDescription =\n\t\t\"The agent is able to log TEE attestation events and is probably running in a TEE\";\n\n\t/**\n\t * Constructor for creating a new instance of a class.\n\t * @param {IAgentRuntime} runtime - The runtime object to be assigned to the instance.\n\t */\n\tconstructor(runtime: IAgentRuntime) {\n\t\tsuper();\n\t\tthis.runtime = runtime;\n\t}\n\n\t/**\n\t * Start the TeeLogService with the given runtime.\n\t *\n\t * @param {IAgentRuntime} runtime - The agent runtime to start the service with\n\t * @returns {Promise<TeeLogService>} - A promise that resolves with the TeeLogService instance\n\t * @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\n\t */\n\tstatic async start(runtime: IAgentRuntime): Promise<TeeLogService> {\n\t\tconst service = new TeeLogService(runtime);\n\n\t\tconst enableValues = [\"true\", \"1\", \"yes\", \"enable\", \"enabled\", \"on\"];\n\n\t\tconst enableTeeLog = runtime.getSetting(\"ENABLE_TEE_LOG\") as string;\n\t\tif (enableTeeLog === null) {\n\t\t\tthrow new Error(\"ENABLE_TEE_LOG is not set.\");\n\t\t}\n\t\tservice.enableTeeLog = enableValues.includes(enableTeeLog.toLowerCase());\n\t\tif (!service.enableTeeLog) {\n\t\t\tconsole.log(\"TEE log is not enabled.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst runInSgx = runtime.getSetting(\"SGX\") as string;\n\t\tconst teeMode = runtime.getSetting(\"TEE_MODE\") as string;\n\t\tconst walletSecretSalt = runtime.getSetting(\"WALLET_SECRET_SALT\");\n\n\t\tservice.teeMode = teeMode\n\t\t\t? TEEMode[teeMode as keyof typeof TEEMode]\n\t\t\t: TEEMode.OFF;\n\n\t\tconst useSgxGramine =\n\t\t\trunInSgx && enableValues.includes(runInSgx.toLowerCase());\n\t\tconst useTdxDstack = teeMode && teeMode !== TEEMode.OFF && walletSecretSalt;\n\n\t\tif (useSgxGramine && useTdxDstack) {\n\t\t\tthrow new Error(\"Cannot configure both SGX and TDX at the same time.\");\n\t\t}\n\t\tif (useSgxGramine) {\n\t\t\tservice.teeType = TeeType.SGX_GRAMINE;\n\t\t} else if (useTdxDstack) {\n\t\t\tservice.teeType = TeeType.TDX_DSTACK;\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid TEE configuration.\");\n\t\t}\n\n\t\tconst dbPathSetting = runtime.getSetting(\"TEE_LOG_DB_PATH\") as string;\n\t\tservice.dbPath = dbPathSetting || path.resolve(\"data/tee_log.sqlite\");\n\n\t\tconst db = new Database(service.dbPath);\n\t\tservice.teeLogDAO = new SqliteTeeLogDAO(db);\n\t\tservice.teeLogManager = new TeeLogManager(\n\t\t\tservice.teeLogDAO,\n\t\t\tservice.teeType,\n\t\t\tservice.teeMode,\n\t\t);\n\n\t\tconst isRegistered = await service.teeLogManager.registerAgent(\n\t\t\truntime?.agentId,\n\t\t\truntime?.character?.name,\n\t\t);\n\t\tif (!isRegistered) {\n\t\t\tthrow new Error(`Failed to register agent ${runtime.agentId}`);\n\t\t}\n\n\t\tservice.initialized = true;\n\t\treturn service;\n\t}\n\n\t/**\n\t * Stop the TEE service running on the provided runtime.\n\t *\n\t * @param {IAgentRuntime} runtime - The runtime on which the TEE service is running.\n\t * @returns {Promise<void>} - A promise that resolves once the TEE service has stopped.\n\t */\n\tstatic async stop(runtime: IAgentRuntime) {\n\t\tconst service = runtime.getService(ServiceTypes.TEE);\n\t\tif (service) {\n\t\t\tawait service.stop();\n\t\t}\n\t}\n\n\t/**\n\t * Asynchronous method to stop the operation.\n\t * Does nothing.\n\t */\n\tasync stop() {\n\t\t// do nothing\n\t}\n\n\t/**\n\t * Asynchronously logs the provided information if tee log is enabled.\n\t *\n\t * @param {string} agentId - The ID of the agent requesting the log.\n\t * @param {string} roomId - The ID of the room where the log is taking place.\n\t * @param {string} entityId - The ID of the entity related to the log.\n\t * @param {string} type - The type of log entry.\n\t * @param {string} content - The content of the log entry.\n\t * @returns {Promise<boolean>} A promise that resolves to true if the log is successful, false if tee log is not enabled.\n\t */\n\tasync log(\n\t\tagentId: string,\n\t\troomId: string,\n\t\tentityId: string,\n\t\ttype: string,\n\t\tcontent: string,\n\t): Promise<boolean> {\n\t\tif (!this.enableTeeLog) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn this.teeLogManager.log(agentId, roomId, entityId, type, content);\n\t}\n\n\t/**\n\t * Asynchronously retrieves all TeeAgents.\n\t *\n\t * @returns {Promise<TeeAgent[]>} A Promise that resolves with an array of TeeAgent objects. If Tee logging is not enabled, an empty array is returned.\n\t */\n\tasync getAllAgents(): Promise<TeeAgent[]> {\n\t\tif (!this.enableTeeLog) {\n\t\t\treturn [];\n\t\t}\n\n\t\treturn this.teeLogManager.getAllAgents();\n\t}\n\n\t/**\n\t * Asynchronously retrieves a TeeAgent based on the provided agentId.\n\t *\n\t * @param {string} agentId - The ID of the agent to retrieve.\n\t * @returns {Promise<TeeAgent | undefined>} A Promise that resolves with the retrieved TeeAgent, or undefined if TEE logging is not enabled.\n\t */\n\tasync getAgent(agentId: string): Promise<TeeAgent | undefined> {\n\t\tif (!this.enableTeeLog) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn this.teeLogManager.getAgent(agentId);\n\t}\n\n\t/**\n\t * Retrieves Tee logs based on query, page, and page size.\n\t *\n\t * @param {TeeLogQuery} query - The query parameters to filter the logs.\n\t * @param {number} page - The current page number.\n\t * @param {number} pageSize - The number of logs to fetch per page.\n\t * @returns {Promise<TeePageQuery<TeeLog[]>>} A Promise that resolves to a TeePageQuery object containing an array of TeeLog and pagination information.\n\t */\n\tasync getLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>> {\n\t\tif (!this.enableTeeLog) {\n\t\t\treturn {\n\t\t\t\tdata: [],\n\t\t\t\ttotal: 0,\n\t\t\t\tpage: page,\n\t\t\t\tpageSize: pageSize,\n\t\t\t};\n\t\t}\n\n\t\treturn this.teeLogManager.getLogs(query, page, pageSize);\n\t}\n\n\t/**\n\t * Asynchronously generates an attestation for the given user report.\n\t *\n\t * @param {string} userReport - The user report to generate attestation for.\n\t * @returns {Promise<string>} A promise that resolves to the generated attestation.\n\t */\n\tasync generateAttestation(userReport: string): Promise<string> {\n\t\treturn this.teeLogManager.generateAttestation(userReport);\n\t}\n}\n\nexport default TeeLogService;\n","/**\n * Enum representing different types of Tee.\n * @enum {string}\n * @readonly\n */\n\nexport enum TeeType {\n\tSGX_GRAMINE = \"sgx_gramine\",\n\tTDX_DSTACK = \"tdx_dstack\",\n}\n\n// Represents a log entry in the TeeLog table, containing details about agent activities.\n/**\n * Interface representing a log entry for a tee.\n * @typedef {Object} TeeLog\n * @property {string} id - The unique identifier for the log entry.\n * @property {string} agentId - The identifier of the agent who created the log entry.\n * @property {string} roomId - The identifier of the room where the log entry was created.\n * @property {string} entityId - The identifier of the entity associated with the log entry.\n * @property {string} type - The type of the log entry.\n * @property {string} content - The content of the log entry.\n * @property {number} timestamp - The timestamp when the log entry was created.\n * @property {string} signature - The signature of the log entry.\n */\n\nexport interface TeeLog {\n\tid: string;\n\tagentId: string;\n\troomId: string;\n\tentityId: string;\n\ttype: string;\n\tcontent: string;\n\ttimestamp: number;\n\tsignature: string;\n}\n\n/**\n * Interface for defining query parameters for fetching TeeLog data.\n * @property {string} [agentId] - The ID of the agent associated with the log.\n * @property {string} [roomId] - The ID of the room associated with the log.\n * @property {string} [entityId] - The ID of the entity associated with the log.\n * @property {string} [type] - The type of log.\n * @property {string} [containsContent] - The content that the log must contain.\n * @property {number} [startTimestamp] - The starting timestamp for filtering logs.\n * @property {number} [endTimestamp] - The ending timestamp for filtering logs.\n */\nexport interface TeeLogQuery {\n\tagentId?: string;\n\troomId?: string;\n\tentityId?: string;\n\ttype?: string;\n\tcontainsContent?: string;\n\tstartTimestamp?: number;\n\tendTimestamp?: number;\n}\n\n// Represents an agent in the TeeAgent table, containing details about the agent.\n/**\n * Interface for representing a TeeAgent.\n * @interface\n * @property {string} id - Primary key\n * @property {string} agentId - Allow duplicate agentId. This is to support the case where the same agentId is registered multiple times. Each time the agent restarts, a new keypair and attestation will be generated.\n * @property {string} agentName - The name of the agent.\n * @property {number} createdAt - The timestamp when the agent was created.\n * @property {string} publicKey - The public key of the agent.\n * @property {string} attestation - The attestation of the agent.\n */\n\nexport interface TeeAgent {\n\tid: string; // Primary key\n\t// Allow duplicate agentId.\n\t// This is to support the case where the same agentId is registered multiple times.\n\t// Each time the agent restarts, we will generate a new keypair and attestation.\n\tagentId: string;\n\tagentName: string;\n\tcreatedAt: number;\n\tpublicKey: string;\n\tattestation: string;\n}\n\n/**\n * Interface for defining the structure of a paginated query result.\n * @template Result The type of data contained in the query result.\n * @property {number} page The current page number.\n * @property {number} pageSize The number of items per page.\n * @property {number} [total] The total number of items in the query result (optional).\n * @property {Result} [data] The data contained in the query result (optional).\n */\nexport interface TeePageQuery<Result> {\n\tpage: number;\n\tpageSize: number;\n\ttotal?: number;\n\tdata?: Result;\n}\n\n/**\n * Represents a Data Access Object for managing Tee logs and agents.\n * @template DB - Type of the database connection or client\n */\nexport abstract class TeeLogDAO<DB> {\n\tdb: DB;\n\n\tabstract initialize(): Promise<void>;\n\n\tabstract addLog(log: TeeLog): Promise<boolean>;\n\n\tabstract getPagedLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>>;\n\n\tabstract addAgent(agent: TeeAgent): Promise<boolean>;\n\n\tabstract getAgent(agentId: string): Promise<TeeAgent>;\n\n\tabstract getAllAgents(): Promise<TeeAgent[]>;\n}\n","/**\n * Defines the SQL script to create SQLite tables for the 'tee_logs' and 'tee_agents' tables.\n *\n * @constant\n * @type {string}\n */\nexport const sqliteTables = `\nBEGIN TRANSACTION;\n\n-- Table: tee_logs\nCREATE TABLE IF NOT EXISTS \"tee_logs\" (\n \"id\" TEXT PRIMARY KEY,\n \"agentId\" TEXT NOT NULL,\n \"roomId\" TEXT NOT NULL,\n \"entityId\" TEXT NOT NULL,\n \"type\" TEXT NOT NULL,\n \"content\" TEXT NOT NULL,\n \"timestamp\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n \"signature\" TEXT NOT NULL\n);\n\n-- Table: tee_agents\nCREATE TABLE IF NOT EXISTS \"tee_agents\" (\n \"id\" TEXT PRIMARY KEY,\n \"agentId\" TEXT NOT NULL,\n \"agentName\" TEXT NOT NULL,\n \"createdAt\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n \"publicKey\" TEXT NOT NULL,\n \"attestation\" TEXT NOT NULL\n);\n\nCOMMIT;`;\n","import type { Database } from \"better-sqlite3\";\nimport {\n\ttype TeeAgent,\n\ttype TeeLog,\n\tTeeLogDAO,\n\ttype TeeLogQuery,\n\ttype TeePageQuery,\n} from \"../types\";\nimport { sqliteTables } from \"./sqliteTables\";\n\n/**\n * Represents a data access object for interacting with SQLite database to perform operations related to TeeLog and TeeAgent.\n * @extends TeeLogDAO\n */\nexport class SqliteTeeLogDAO extends TeeLogDAO<Database> {\n\t/**\n\t * Constructor for creating a new instance of the class.\n\t * @param {Database} db - The database object to be used by the instance\n\t */\n\tconstructor(db: Database) {\n\t\tsuper();\n\t\tthis.db = db;\n\t}\n\n\t/**\n\t * Asynchronously initializes the database by executing the provided SQLite table creation SQL.\n\t * @returns A Promise that resolves to void once the initialization is complete.\n\t */\n\tasync initialize(): Promise<void> {\n\t\tthis.db.exec(sqliteTables);\n\t}\n\n\t/**\n\t * Add a log to the database.\n\t *\n\t * @param {TeeLog} log - The log object to be added.\n\t * @returns {Promise<boolean>} - Indicates if the log was successfully added or not.\n\t */\n\tasync addLog(log: TeeLog): Promise<boolean> {\n\t\tconst stmt = this.db.prepare(\n\t\t\t\"INSERT INTO tee_logs (id, agentId, roomId, entityId, type, content, timestamp, signature) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\",\n\t\t);\n\t\ttry {\n\t\t\tstmt.run(\n\t\t\t\tlog.id,\n\t\t\t\tlog.agentId,\n\t\t\t\tlog.roomId,\n\t\t\t\tlog.entityId,\n\t\t\t\tlog.type,\n\t\t\t\tlog.content,\n\t\t\t\tlog.timestamp,\n\t\t\t\tlog.signature,\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error adding log to database\", error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Retrieves paged logs based on the provided query criteria.\n\t *\n\t * @param {TeeLogQuery} query - The query criteria to filter the logs.\n\t * @param {number} page - The page number to retrieve.\n\t * @param {number} pageSize - The number of logs per page.\n\t * @returns {Promise<TeePageQuery<TeeLog[]>>} The paged logs data along with page information.\n\t */\n\tasync getPagedLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>> {\n\t\tconst currentPage = page < 1 ? 1 : page;\n\t\tconst offset = (currentPage - 1) * pageSize;\n\t\tconst limit = pageSize;\n\n\t\tconst whereConditions = [];\n\t\tconst params = [];\n\n\t\tif (query.agentId && query.agentId !== \"\") {\n\t\t\twhereConditions.push(\"agentId = ?\");\n\t\t\tparams.push(query.agentId);\n\t\t}\n\t\tif (query.roomId && query.roomId !== \"\") {\n\t\t\twhereConditions.push(\"roomId = ?\");\n\t\t\tparams.push(query.roomId);\n\t\t}\n\t\tif (query.entityId && query.entityId !== \"\") {\n\t\t\twhereConditions.push(\"entityId = ?\");\n\t\t\tparams.push(query.entityId);\n\t\t}\n\t\tif (query.type && query.type !== \"\") {\n\t\t\twhereConditions.push(\"type = ?\");\n\t\t\tparams.push(query.type);\n\t\t}\n\t\tif (query.containsContent && query.containsContent !== \"\") {\n\t\t\twhereConditions.push(\"content LIKE ?\");\n\t\t\tparams.push(`%${query.containsContent}%`);\n\t\t}\n\t\tif (query.startTimestamp) {\n\t\t\twhereConditions.push(\"timestamp >= ?\");\n\t\t\tparams.push(query.startTimestamp);\n\t\t}\n\t\tif (query.endTimestamp) {\n\t\t\twhereConditions.push(\"timestamp <= ?\");\n\t\t\tparams.push(query.endTimestamp);\n\t\t}\n\n\t\tconst whereClause =\n\t\t\twhereConditions.length > 0\n\t\t\t\t? `WHERE ${whereConditions.join(\" AND \")}`\n\t\t\t\t: \"\";\n\n\t\ttry {\n\t\t\tconst total_stmt = this.db.prepare(\n\t\t\t\t`SELECT COUNT(*) as total FROM tee_logs ${whereClause}`,\n\t\t\t);\n\t\t\tconst total = total_stmt.get(params).total;\n\n\t\t\tconst logs_stmt = this.db.prepare(\n\t\t\t\t`SELECT * FROM tee_logs ${whereClause} ORDER BY timestamp ASC LIMIT ? OFFSET ?`,\n\t\t\t);\n\t\t\tconst logs = logs_stmt.all(...params, limit, offset);\n\n\t\t\treturn {\n\t\t\t\tpage: currentPage,\n\t\t\t\tpageSize,\n\t\t\t\ttotal,\n\t\t\t\tdata: logs,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error getting paged logs from database\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Add an agent to the database.\n\t *\n\t * @param {TeeAgent} agent - The TeeAgent object to be added.\n\t * @returns {Promise<boolean>} - A Promise that resolves to true if the agent was successfully added, and false otherwise.\n\t */\n\tasync addAgent(agent: TeeAgent): Promise<boolean> {\n\t\tconst stmt = this.db.prepare(\n\t\t\t\"INSERT INTO tee_agents (id, agentId, agentName, createdAt, publicKey, attestation) VALUES (?, ?, ?, ?, ?, ?)\",\n\t\t);\n\t\ttry {\n\t\t\tstmt.run(\n\t\t\t\tagent.id,\n\t\t\t\tagent.agentId,\n\t\t\t\tagent.agentName,\n\t\t\t\tagent.createdAt,\n\t\t\t\tagent.publicKey,\n\t\t\t\tagent.attestation,\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error adding agent to database\", error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Retrieves a TeeAgent from the database based on the provided agentId.\n\t *\n\t * @param {string} agentId - The unique identifier of the agent to retrieve.\n\t * @returns {Promise<TeeAgent | null>} A promise that resolves with the retrieved TeeAgent, or null if not found.\n\t */\n\tasync getAgent(agentId: string): Promise<TeeAgent | null> {\n\t\tconst stmt = this.db.prepare(\n\t\t\t\"SELECT * FROM tee_agents WHERE agentId = ? ORDER BY createdAt DESC LIMIT 1\",\n\t\t);\n\t\ttry {\n\t\t\treturn stmt.get(agentId);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error getting agent from database\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Retrieves all agents from the database.\n\t *\n\t * @returns {Promise<TeeAgent[]>} All agents\n\t */\n\tasync getAllAgents(): Promise<TeeAgent[]> {\n\t\tconst stmt = this.db.prepare(\"SELECT * FROM tee_agents\");\n\t\ttry {\n\t\t\treturn stmt.all();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error getting all agents from database\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n","import {\n\ttype TEEMode,\n\ttype TeeAgent,\n\ttype TeeLog,\n\ttype TeeLogDAO,\n\ttype TeeLogQuery,\n\ttype TeePageQuery,\n\tTeeType,\n} from \"@elizaos/core\";\nimport elliptic from \"elliptic\";\nimport { v4 } from \"uuid\";\nimport { SgxAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { PhalaRemoteAttestationProvider as TdxAttestationProvider } from \"../providers/remoteAttestationProvider\";\n\n/**\n * Manage TeeLog related operations including agent registration, logging, and retrieval.\n */\nexport class TeeLogManager {\n\tprivate teeLogDAO: TeeLogDAO;\n\tprivate teeType: TeeType;\n\tprivate teeMode: TEEMode; // Only used for plugin-tee with TDX dstack\n\n\t// Map of agentId to its key pair\n\t// These keypairs only store in memory.\n\t// When the agent restarts, we will generate new keypair.\n\tprivate keyPairs: Map<string, elliptic.ec.KeyPair> = new Map();\n\n\t/**\n\t * Constructor for initializing TeeLog object.\n\t * * @param { TeeLogDAO } teeLogDAO - The data access object for TeeLog.\n\t * @param { TeeType } teeType - The type of Tee.\n\t * @param { TEEMode } teeMode - The mode of Tee.\n\t */\n\tconstructor(teeLogDAO: TeeLogDAO, teeType: TeeType, teeMode: TEEMode) {\n\t\tthis.teeLogDAO = teeLogDAO;\n\t\tthis.teeType = teeType;\n\t\tthis.teeMode = teeMode;\n\t}\n\n\t/**\n\t * Registers a new agent with the given agent ID and agent name.\n\t *\n\t * @param {string} agentId - The unique identifier for the agent.\n\t * @param {string} agentName - The name of the agent.\n\t * @returns {Promise<boolean>} A promise that resolves to true if the agent is successfully registered.\n\t * @throws {Error} If agentId is empty or null.\n\t */\n\tpublic async registerAgent(\n\t\tagentId: string,\n\t\tagentName: string,\n\t): Promise<boolean> {\n\t\tif (!agentId) {\n\t\t\tthrow new Error(\"Agent ID is required\");\n\t\t}\n\n\t\tconst keyPair = this.generateKeyPair();\n\t\tthis.keyPairs.set(agentId, keyPair);\n\n\t\tconst publicKey = keyPair.getPublic().encode(\"hex\", true);\n\t\tconst attestation = await this.generateAttestation(publicKey);\n\n\t\tconst new_agent = {\n\t\t\tid: v4(),\n\t\t\tagentId,\n\t\t\tagentName: agentName || \"\",\n\t\t\tcreatedAt: new Date().getTime(),\n\t\t\tpublicKey,\n\t\t\tattestation,\n\t\t};\n\n\t\tconsole.log(\"registerAgent new_agent\", new_agent);\n\n\t\treturn this.teeLogDAO.addAgent(new_agent);\n\t}\n\n\t/**\n\t * Retrieves all agents from the database.\n\t * @returns {Promise<TeeAgent[]>} A promise that resolves to an array of TeeAgent objects.\n\t */\n\tpublic async getAllAgents(): Promise<TeeAgent[]> {\n\t\treturn this.teeLogDAO.getAllAgents();\n\t}\n\n\t/**\n\t * Retrieve an agent from the database by its ID.\n\t * @param {string} agentId - The unique identifier of the agent.\n\t * @returns {Promise<TeeAgent | undefined>} The agent object if found, undefined otherwise.\n\t */\n\tpublic async getAgent(agentId: string): Promise<TeeAgent | undefined> {\n\t\treturn this.teeLogDAO.getAgent(agentId);\n\t}\n\n\t/**\n\t * Logs an event with the specified information.\n\t *\n\t * @param {string} agentId - The ID of the agent performing the action.\n\t * @param {string} roomId - The room ID where the event occurred.\n\t * @param {string} entityId - The ID of the entity involved in the event.\n\t * @param {string} type - The type of event being logged.\n\t * @param {string} content - The content of the event being logged.\n\t * @returns {Promise<boolean>} A boolean indicating if the logging was successful.\n\t */\n\tpublic async log(\n\t\tagentId: string,\n\t\troomId: string,\n\t\tentityId: string,\n\t\ttype: string,\n\t\tcontent: string,\n\t): Promise<boolean> {\n\t\tconst keyPair = this.keyPairs.get(agentId);\n\t\tif (!keyPair) {\n\t\t\tthrow new Error(`Agent ${agentId} not found`);\n\t\t}\n\n\t\tconst timestamp = new Date().getTime();\n\n\t\t// Join the information into a single string\n\t\tconst messageToSign = `${agentId}|${roomId}|${entityId}|${type}|${content}|${timestamp}`;\n\n\t\t// Sign the joined message\n\t\tconst signature = `0x${keyPair.sign(messageToSign).toDER(\"hex\")}`;\n\n\t\treturn this.teeLogDAO.addLog({\n\t\t\tid: v4(),\n\t\t\tagentId,\n\t\t\troomId,\n\t\t\tentityId,\n\t\t\ttype,\n\t\t\tcontent,\n\t\t\ttimestamp,\n\t\t\tsignature,\n\t\t});\n\t}\n\n\t/**\n\t * Retrieves logs based on the provided query, page number, and page size.\n\t * @param {TeeLogQuery} query - The query object to filter logs.\n\t * @param {number} page - The page number of logs to retrieve.\n\t * @param {number} pageSize - The number of logs per page.\n\t * @returns {Promise<TeePageQuery<TeeLog[]>>} A promise that resolves to a page query of logs.\n\t */\n\tpublic async getLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>> {\n\t\treturn this.teeLogDAO.getPagedLogs(query, page, pageSize);\n\t}\n\n\t/**\n\t * Generate a new key pair using the secp256k1 elliptic curve algorithm.\n\t *\n\t * @returns {elliptic.ec.KeyPair} The generated key pair.\n\t */\n\tpublic generateKeyPair(): elliptic.ec.KeyPair {\n\t\tconst ec = new elliptic.ec(\"secp256k1\");\n\t\tconst key = ec.genKeyPair();\n\t\treturn key;\n\t}\n\n\t/**\n\t * Generates an attestation for the given user report based on the TEE type.\n\t *\n\t * @param {string} userReport The user report to generate the attestation for.\n\t * @returns {Promise<string>} A promise that resolves with the generated attestation as a string.\n\t * @throws {Error} If the TEE type is invalid.\n\t */\n\tpublic async generateAttestation(userReport: string): Promise<string> {\n\t\tif (this.teeType === TeeType.SGX_GRAMINE) {\n\t\t\tconst sgxAttestationProvider = new SgxAttestationProvider();\n\t\t\tconst sgxAttestation =\n\t\t\t\tawait sgxAttestationProvider.generateAttestation(userReport);\n\t\t\treturn JSON.stringify(sgxAttestation);\n\t\t}\n\t\tif (this.teeType === TeeType.TDX_DSTACK) {\n\t\t\tconst tdxAttestationProvider = new TdxAttestationProvider(this.teeMode);\n\t\t\tconst tdxAttestation =\n\t\t\t\tawait tdxAttestationProvider.generateAttestation(userReport);\n\t\t\treturn JSON.stringify(tdxAttestation);\n\t\t}\n\t\tthrow new Error(\"Invalid TEE type\");\n\t}\n}\n","import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n","import { randomFillSync } from 'crypto';\nconst rnds8Pool = new Uint8Array(256);\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, (poolPtr += 16));\n}\n","import { randomUUID } from 'crypto';\nexport default { randomUUID };\n","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random || (options.rng || rng)();\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n","import { promises as fs } from \"node:fs\"; // Fix: Use node: protocol\nimport {\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype State,\n\tlogger,\n} from \"@elizaos/core\";\nimport {\n\ttype RemoteAttestationMessage,\n\ttype RemoteAttestationQuote,\n\tTEEMode,\n} from \"@elizaos/core\";\nimport type { SgxAttestation } from \"@elizaos/core\";\nimport {\n\tTappdClient,\n\ttype TdxQuoteHashAlgorithms,\n\ttype TdxQuoteResponse,\n} from \"@phala/dstack-sdk\";\nimport { calculateSHA256 } from \"../utils\";\nimport { RemoteAttestationProvider } from \"./base\";\n\n// Define the ProviderResult interface if not already imported\n/**\n * Interface for the result returned by a provider.\n * @typedef {Object} ProviderResult\n * @property {any} data - The data returned by the provider.\n * @property {Record<string, string>} values - The values returned by the provider.\n * @property {string} text - The text returned by the provider.\n */\ninterface ProviderResult {\n\tdata?: any;\n\tvalues?: Record<string, string>;\n\ttext?: string;\n}\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaRemoteAttestationProvider();\n * ```\n */\n/**\n * PhalaRemoteAttestationProvider class that extends RemoteAttestationProvider\n * @extends RemoteAttestationProvider\n */\nclass PhalaRemoteAttestationProvider extends RemoteAttestationProvider {\n\tprivate client: TappdClient;\n\n\tconstructor(teeMode?: string) {\n\t\tsuper();\n\t\tlet endpoint: string | undefined;\n\n\t\t// Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n\t\tswitch (teeMode) {\n\t\t\tcase TEEMode.LOCAL:\n\t\t\t\tendpoint = \"http://localhost:8090\";\n\t\t\t\tlogger.log(\"TEE: Connecting to local simulator at localhost:8090\");\n\t\t\t\tbreak;\n\t\t\tcase TEEMode.DOCKER:\n\t\t\t\tendpoint = \"http://host.docker.internal:8090\";\n\t\t\t\tlogger.log(\n\t\t\t\t\t\"TEE: Connecting to simulator via Docker at host.docker.internal:8090\",\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase TEEMode.PRODUCTION:\n\t\t\t\tendpoint = undefined;\n\t\t\t\tlogger.log(\"TEE: Running in production mode without simulator\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`,\n\t\t\t\t);\n\t\t}\n\n\t\tthis.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n\t}\n\n\tasync generateAttestation(\n\t\treportData: string,\n\t\thashAlgorithm?: TdxQuoteHashAlgorithms,\n\t): Promise<RemoteAttestationQuote> {\n\t\ttry {\n\t\t\tlogger.log(\"Generating attestation for: \", reportData);\n\t\t\tconst tdxQuote: TdxQuoteResponse = await this.client.tdxQuote(\n\t\t\t\treportData,\n\t\t\t\thashAlgorithm,\n\t\t\t);\n\t\t\tconst rtmrs = tdxQuote.replayRtmrs();\n\t\t\tlogger.log(\n\t\t\t\t`rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`,\n\t\t\t);\n\t\t\tconst quote: RemoteAttestationQuote = {\n\t\t\t\tquote: tdxQuote.quote,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\tlogger.log(\"Remote attestation quote: \", quote);\n\t\t\treturn quote;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error generating remote attestation:\", error);\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to generate TDX Quote: ${\n\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// Keep the original provider for backwards compatibility\nconst phalaRemoteAttestationProvider: Provider = {\n\tname: \"phala-remote-attestation\",\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst teeMode = runtime.getSetting(\"TEE_MODE\");\n\t\tconst provider = new PhalaRemoteAttestationProvider(teeMode);\n\t\tconst agentId = runtime.agentId;\n\n\t\ttry {\n\t\t\tconst attestationMessage: RemoteAttestationMessage = {\n\t\t\t\tagentId: agentId,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tmessage: {\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: message.content.text,\n\t\t\t\t},\n\t\t\t};\n\t\t\tlogger.log(\n\t\t\t\t\"Generating attestation for: \",\n\t\t\t\tJSON.stringify(attestationMessage),\n\t\t\t);\n\t\t\tconst attestation = await provider.generateAttestation(\n\t\t\t\tJSON.stringify(attestationMessage),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\ttext: `Your Agent's remote attestation is: ${JSON.stringify(\n\t\t\t\t\tattestation,\n\t\t\t\t)}`,\n\t\t\t\tdata: {\n\t\t\t\t\tattestation,\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\tquote: attestation.quote,\n\t\t\t\t\ttimestamp: attestation.timestamp.toString(),\n\t\t\t\t},\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error in remote attestation provider:\", error);\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to generate TDX Quote: ${\n\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t}`,\n\t\t\t);\n\t\t}\n\t},\n};\n\n/**\n * SGX Gramine TEE Provider\n * @example\n * ```ts\n * const provider = new SgxAttestationProvider();\n * ```\n */\nclass SgxAttestationProvider extends RemoteAttestationProvider {\n\tprivate readonly SGX_QUOTE_MAX_SIZE: number = 8192 * 4;\n\tprivate readonly SGX_TARGET_INFO_SIZE: number = 512;\n\n\tprivate readonly MY_TARGET_INFO_PATH: string =\n\t\t\"/dev/attestation/my_target_info\";\n\tprivate readonly TARGET_INFO_PATH: string = \"/dev/attestation/target_info\";\n\tprivate readonly USER_REPORT_DATA_PATH: string =\n\t\t\"/dev/attestation/user_report_data\";\n\tprivate readonly QUOTE_PATH: string = \"/dev/attestation/quote\";\n\n\t// Remove unnecessary constructor\n\t// constructor() {}\n\n\tasync generateAttestation(reportData: string): Promise<SgxAttestation> {\n\t\t// Hash the report data to generate the raw user report.\n\t\t// The resulting hash value is 32 bytes long.\n\t\t// Ensure that the length of the raw user report does not exceed 64 bytes.\n\t\tconst rawUserReport = calculateSHA256(reportData);\n\n\t\ttry {\n\t\t\t// Check if the gramine attestation device file exists\n\t\t\tawait fs.access(this.MY_TARGET_INFO_PATH);\n\n\t\t\tconst quote = await this.generateQuoteByGramine(rawUserReport);\n\t\t\tconst attestation: SgxAttestation = {\n\t\t\t\tquote: quote,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\t// console.log(\"SGX remote attestation: \", attestation);\n\t\t\treturn attestation;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error generating SGX remote attestation:\", error);\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to generate SGX Quote: ${\n\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync generateQuoteByGramine(rawUserReport: Buffer): Promise<string> {\n\t\tif (rawUserReport.length > 64) {\n\t\t\tthrow new Error(\"the length of rawUserReport exceeds 64 bytes\");\n\t\t}\n\n\t\tconst myTargetInfo = await fs.readFile(this.MY_TARGET_INFO_PATH);\n\t\tif (myTargetInfo.length !== this.SGX_TARGET_INFO_SIZE) {\n\t\t\tthrow new Error(\"Invalid my_target_info length\");\n\t\t}\n\n\t\tawait fs.writeFile(this.TARGET_INFO_PATH, myTargetInfo);\n\t\tawait fs.writeFile(this.USER_REPORT_DATA_PATH, rawUserReport);\n\n\t\t// Read quote\n\t\tconst quoteData = await fs.readFile(this.QUOTE_PATH);\n\t\tif (quoteData.length > this.SGX_QUOTE_MAX_SIZE) {\n\t\t\tthrow new Error(\"Invalid quote length\");\n\t\t}\n\n\t\tconst realLen = quoteData.lastIndexOf(0);\n\t\tif (realLen === -1) {\n\t\t\tthrow new Error(\"quote without EOF\");\n\t\t}\n\n\t\t//return '0x' + quoteData.subarray(0, realLen + 1).toString('hex');\n\t\treturn `0x${quoteData.subarray(0, realLen + 1).toString(\"hex\")}`; // Fix: Use template literal\n\t}\n}\n\nconst sgxAttestationProvider: Provider = {\n\tname: \"sgx-gramine-remote-attestation\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\t_message: Memory,\n\t): Promise<ProviderResult> => {\n\t\tconst provider = new SgxAttestationProvider();\n\t\tconst agentId = runtime.agentId;\n\n\t\ttry {\n\t\t\t// console.log(\"Generating attestation for agent: \", agentId);\n\t\t\tconst attestation = await provider.generateAttestation(agentId);\n\n\t\t\treturn {\n\t\t\t\tdata: attestation,\n\t\t\t\tvalues: {\n\t\t\t\t\tquote: attestation.quote,\n\t\t\t\t\ttimestamp: attestation.timestamp.toString(),\n\t\t\t\t},\n\t\t\t\ttext: `Your Agent's remote attestation is: ${JSON.stringify(\n\t\t\t\t\tattestation,\n\t\t\t\t)}`,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error in remote attestation provider:\", error);\n\t\t\tconst errorMessage = `Failed to generate SGX Quote: ${\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t}`;\n\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\tvalues: {},\n\t\t\t\ttext: errorMessage,\n\t\t\t};\n\t\t}\n\t},\n};\n\nexport {\n\tphalaRemoteAttestationProvider,\n\tPhalaRemoteAttestationProvider,\n\tsgxAttestationProvider,\n\tSgxAttestationProvider,\n};\n","import { createHash } from \"node:crypto\";\n\n/**\n * Converts a hexadecimal string to a Uint8Array.\n *\n * @param {string} hex - The hexadecimal string to convert.\n * @returns {Uint8Array} - The resulting Uint8Array.\n * @throws {Error} - If the input hex string is invalid.\n */\nexport function hexToUint8Array(hex: string) {\n\tconst hexString = hex.trim().replace(/^0x/, \"\");\n\tif (!hexString) {\n\t\tthrow new Error(\"Invalid hex string\");\n\t}\n\tif (hexString.length % 2 !== 0) {\n\t\tthrow new Error(\"Invalid hex string\");\n\t}\n\n\tconst array = new Uint8Array(hexString.length / 2);\n\tfor (let i = 0; i < hexString.length; i += 2) {\n\t\tconst byte = Number.parseInt(hexString.slice(i, i + 2), 16);\n\t\tif (Number.isNaN(byte)) {\n\t\t\tthrow new Error(\"Invalid hex string\");\n\t\t}\n\t\tarray[i / 2] = byte;\n\t}\n\treturn array;\n}\n\n// Function to calculate SHA-256 and return a Buffer (32 bytes)\n/**\n * Calculates the SHA256 hash of the input string.\n *\n * @param {string} input - The input string to calculate the hash from.\n * @returns {Buffer} - The calculated SHA256 hash as a Buffer object.\n */\nexport function calculateSHA256(input: string): Buffer {\n\tconst hash = createHash(\"sha256\");\n\thash.update(input);\n\treturn hash.digest();\n}\n","import type { RemoteAttestationQuote } from \"@elizaos/core\";\nimport type { TdxQuoteHashAlgorithms } from \"@phala/dstack-sdk\";\n\n/**\n * Abstract class for deriving keys from the TEE.\n * You can implement your own logic for deriving keys from the TEE.\n * @example\n * ```ts\n * class MyDeriveKeyProvider extends DeriveKeyProvider {\n * private client: TappdClient;\n *\n * constructor(endpoint: string) {\n * super();\n * this.client = new TappdClient();\n * }\n *\n * async rawDeriveKey(path: string, subject: string): Promise<any> {\n * return this.client.deriveKey(path, subject);\n * }\n * }\n * ```\n */\n/**\n * Abstract class representing a key provider for deriving keys.\n */\nexport abstract class DeriveKeyProvider {}\n\n/**\n * Abstract class for remote attestation provider.\n */\nexport abstract class RemoteAttestationProvider {\n\tabstract generateAttestation(\n\t\treportData: string,\n\t\thashAlgorithm?: TdxQuoteHashAlgorithms,\n\t): Promise<RemoteAttestationQuote>;\n}\n","import type { Action, Provider } from \"@elizaos/core\";\n\nexport const TeeVendorNames = {\n\tPHALA: \"phala\",\n\tSGX_GRAMINE: \"sgx_gramine\",\n} as const;\n\n/**\n * Type representing the name of a Tee vendor.\n * It can either be one of the keys of TeeVendorNames or a string.\n */\nexport type TeeVendorName =\n\t| (typeof TeeVendorNames)[keyof typeof TeeVendorNames]\n\t| string;\n\n/**\n * Interface for a TeeVendor, representing a vendor that sells tees.\n * @interface\n */\n\nexport interface TeeVendor {\n\ttype: TeeVendorName;\n\tgetActions(): Action[];\n\tgetProviders(): Provider[];\n\tgetName(): string;\n\tgetDescription(): string;\n}\n","import { sgxAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport type { TeeVendor } from \"./types\";\nimport { TeeVendorNames } from \"./types\";\n\n/**\n * Vendor class for SGX Gramine TEE.\n * @implements {TeeVendor}\n */\n\nexport class GramineVendor implements TeeVendor {\n\ttype = TeeVendorNames.SGX_GRAMINE;\n\n\t/**\n\t * Returns an array of actions.\n\t * @returns {Array} An empty array of actions.\n\t */\n\tgetActions() {\n\t\treturn [];\n\t}\n\n\t/**\n\t * Retrieve the list of providers available.\n\t *\n\t * @returns {Array} An array containing the available providers.\n\t */\n\tgetProviders() {\n\t\treturn [sgxAttestationProvider];\n\t}\n\n\t/**\n\t * Function to get the name of the plugin.\n\t * @returns {string} The name of the plugin.\n\t */\n\tgetName() {\n\t\treturn \"sgx-gramine-plugin\";\n\t}\n\n\t/**\n\t * Returns the description of the SGX Gramine TEE to Host Eliza Agents.\n\t */\n\tgetDescription() {\n\t\treturn \"SGX Gramine TEE to Host Eliza Agents\";\n\t}\n}\n","import { TeeVendors } from \"@elizaos/core\";\nimport { phalaRemoteAttestationAction as remoteAttestationAction } from \"../actions/remoteAttestationAction\";\nimport { phalaDeriveKeyProvider as deriveKeyProvider } from \"../providers/deriveKeyProvider\";\nimport { phalaRemoteAttestationProvider as remoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport type { TeeVendor } from \"./types\";\n\n/**\n * A class representing a vendor for Phala TEE.\n * * @implements { TeeVendor }\n * @type {TeeVendors.PHALA}\n *//**\n * Get the actions for the PhalaVendor.\n * * @returns { Array } An array of actions.\n *//**\n * Get the providers for the PhalaVendor.\n * * @returns { Array } An array of providers.\n *//**\n * Get the name of the PhalaVendor.\n * * @returns { string } The name of the vendor.\n *//**\n * Get the description of the PhalaVendor.\n * * @returns { string } The description of the vendor.\n */\nexport class PhalaVendor implements TeeVendor {\n\ttype = TeeVendors.PHALA;\n\n\t/**\n\t * Returns an array of actions.\n\t *\n\t * @returns {Array} An array containing the remote attestation action.\n\t */\n\tgetActions() {\n\t\treturn [remoteAttestationAction];\n\t}\n\t/**\n\t * Retrieve the list of providers.\n\t *\n\t * @returns {Array<Function>} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider.\n\t */\n\tgetProviders() {\n\t\treturn [deriveKeyProvider, remoteAttestationProvider];\n\t}\n\n\t/**\n\t * Returns the name of the plugin.\n\t * @returns {string} The name of the plugin.\n\t */\n\tgetName() {\n\t\treturn \"phala-tee-plugin\";\n\t}\n\n\t/**\n\t * Get the description of the function\n\t * @returns {string} The description of the function\n\t */\n\tgetDescription() {\n\t\treturn \"Phala TEE Cloud to Host Eliza Agents\";\n\t}\n}\n","import type {\n\tHandlerCallback,\n\tIAgentRuntime,\n\tMemory,\n\tRemoteAttestationMessage,\n\tState,\n} from \"@elizaos/core\";\nimport { logger } from \"@elizaos/core\";\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { hexToUint8Array } from \"../utils\";\n\n/**\n * Asynchronously uploads a Uint8Array as a binary file to a specified URL.\n *\n * @param {Uint8Array} data - The Uint8Array data to be uploaded as a binary file.\n * @returns {Promise<Response>} A Promise that resolves once the upload is complete, returning a Response object.\n */\nasync function uploadUint8Array(data: Uint8Array) {\n\tconst blob = new Blob([data], { type: \"application/octet-stream\" });\n\tconst formData = new FormData();\n\tformData.append(\"file\", blob, \"quote.bin\");\n\n\treturn await fetch(\"https://proof.t16z.com/api/upload\", {\n\t\tmethod: \"POST\",\n\t\tbody: formData as BodyInit,\n\t});\n}\n\n/**\n * Represents an action for remote attestation.\n *\n * This action is used to generate a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE).\n *\n * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array<Array<Object>>}}\n */\nexport const phalaRemoteAttestationAction = {\n\tname: \"REMOTE_ATTESTATION\",\n\tsimiles: [\"REMOTE_ATTESTATION\", \"TEE_REMOTE_ATTESTATION\", \"TEE_ATTESTATION\"],\n\tdescription:\n\t\t\"Generate a remote attestation to prove that the agent is running in a TEE\",\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\t_state: State,\n\t\t_options: { [key: string]: unknown },\n\t\tcallback: HandlerCallback,\n\t) => {\n\t\ttry {\n\t\t\t// Attestation will be generated based on the message info\n\t\t\tconst attestationMessage: RemoteAttestationMessage = {\n\t\t\t\tagentId: runtime.agentId,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tmessage: {\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: message.content.text,\n\t\t\t\t},\n\t\t\t};\n\t\t\t// Get the remote attestation of the agentId\n\t\t\tconst teeMode = runtime.getSetting(\"TEE_MODE\");\n\t\t\tlogger.debug(`Tee mode: ${teeMode}`);\n\t\t\tlogger.debug(\n\t\t\t\t`Attestation message: ${JSON.stringify(attestationMessage)}`,\n\t\t\t);\n\t\t\tconst provider = new RemoteAttestationProvider(teeMode);\n\n\t\t\tconst attestation = await provider.generateAttestation(\n\t\t\t\tJSON.stringify(attestationMessage),\n\t\t\t);\n\t\t\tconst attestationData = hexToUint8Array(attestation.quote);\n\t\t\tconst response = await uploadUint8Array(attestationData);\n\t\t\tconst data = await response.json();\n\n\t\t\tcallback({\n\t\t\t\ttext: `Here's my 🧾 RA Quote 🫡\nhttps://proof.t16z.com/reports/${data.checksum}`,\n\t\t\t\tactions: [\"NONE\"],\n\t\t\t});\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Failed to fetch remote attestation: \", error);\n\t\t\treturn false;\n\t\t}\n\t},\n\tvalidate: async (_runtime: IAgentRuntime) => {\n\t\treturn true;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"If you are running in a TEE, generate a remote attestation\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{agentName}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Of course, one second...\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{agentName}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{agentName}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Oh, dear...lemme find that for you\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t],\n};\n\n/**\n * Marlin Remote Attestation action.\n *\n * This action allows generating a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE).\n *\n * @type {{\n * name: string,\n * similes: string[],\n * description: string,\n * handler: (runtime: IAgentRuntime, _message: Memory, _state: State, _options: Record<string, unknown>, callback: HandlerCallback) => Promise<boolean>,\n * validate: (runtime: IAgentRuntime) => Promise<boolean>,\n * examples: { name: string, content: { text: string, actions: string[] } }[][]\n * }}\n */\nexport const marlinRemoteAttestationAction = {\n\tname: \"REMOTE_ATTESTATION\",\n\tsimiles: [\"REMOTE_ATTESTATION\", \"TEE_REMOTE_ATTESTATION\", \"TEE_ATTESTATION\"],\n\tdescription:\n\t\t\"Generate a remote attestation to prove that the agent is running in a TEE\",\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\t_message: Memory,\n\t\t_state: State,\n\t\t_options: Record<string, unknown>, // Replaced any with Record<string, unknown>\n\t\tcallback: HandlerCallback,\n\t) => {\n\t\ttry {\n\t\t\tconst endpoint =\n\t\t\t\truntime.getSetting(\"TEE_MARLIN_ATTESTATION_ENDPOINT\") ??\n\t\t\t\t\"http://127.0.0.1:1350\";\n\t\t\tconst response = await fetch(`${endpoint}/attestation/hex`);\n\t\t\tcallback({\n\t\t\t\ttext: `Here you go - ${await response.text()}`,\n\t\t\t\tactions: [\"NONE\"],\n\t\t\t});\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Failed to fetch remote attestation: \", error);\n\t\t\treturn false;\n\t\t}\n\t},\n\tvalidate: async (_runtime: IAgentRuntime) => {\n\t\treturn true;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"user\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Attest yourself\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"user\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Generate a remote attestation\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t],\n};\n","import crypto from \"node:crypto\";\nimport {\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype State,\n\tlogger,\n} from \"@elizaos/core\";\nimport {\n\ttype DeriveKeyAttestationData,\n\ttype RemoteAttestationQuote,\n\tTEEMode,\n} from \"@elizaos/core\";\nimport { type DeriveKeyResponse, TappdClient } from \"@phala/dstack-sdk\";\nimport { Keypair } from \"@solana/web3.js\";\nimport { type PrivateKeyAccount, keccak256 } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { DeriveKeyProvider } from \"./base\";\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from \"./remoteAttestationProvider\";\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaDeriveKeyProvider(runtime.getSetting('TEE_MODE'));\n * ```\n */\n/**\n * A class representing a key provider for deriving keys in the Phala TEE environment.\n * Extends the DeriveKeyProvider class.\n */\nclass PhalaDeriveKeyProvider extends DeriveKeyProvider {\n\tprivate client: TappdClient;\n\tprivate raProvider: RemoteAttestationProvider;\n\n\tconstructor(teeMode?: string) {\n\t\tsuper();\n\t\tlet endpoint: string | undefined;\n\n\t\t// Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n\t\tswitch (teeMode) {\n\t\t\tcase TEEMode.LOCAL:\n\t\t\t\tendpoint = \"http://localhost:8090\";\n\t\t\t\tlogger.log(\"TEE: Connecting to local simulator at localhost:8090\");\n\t\t\t\tbreak;\n\t\t\tcase TEEMode.DOCKER:\n\t\t\t\tendpoint = \"http://host.docker.internal:8090\";\n\t\t\t\tlogger.log(\n\t\t\t\t\t\"TEE: Connecting to simulator via Docker at host.docker.internal:8090\",\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase TEEMode.PRODUCTION:\n\t\t\t\tendpoint = undefined;\n\t\t\t\tlogger.log(\"TEE: Running in production mode without simulator\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`,\n\t\t\t\t);\n\t\t}\n\n\t\tthis.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n\t\tthis.raProvider = new RemoteAttestationProvider(teeMode);\n\t}\n\n\tprivate async generateDeriveKeyAttestation(\n\t\tagentId: string,\n\t\tpublicKey: string,\n\t\tsubject?: string,\n\t): Promise<RemoteAttestationQuote> {\n\t\tconst deriveKeyData: DeriveKeyAttestationData = {\n\t\t\tagentId,\n\t\t\tpublicKey,\n\t\t\tsubject,\n\t\t};\n\t\tconst reportdata = JSON.stringify(deriveKeyData);\n\t\tlogger.log(\"Generating Remote Attestation Quote for Derive Key...\");\n\t\tconst quote = await this.raProvider.generateAttestation(reportdata);\n\t\tlogger.log(\"Remote Attestation Quote generated successfully!\");\n\t\treturn quote;\n\t}\n\n\t/**\n\t * Derives a raw key from the given path and subject.\n\t * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n\t * @param subject - The subject to derive the key from. This is used for the certificate chain.\n\t * @returns The derived key.\n\t */\n\tasync rawDeriveKey(\n\t\tpath: string,\n\t\tsubject: string,\n\t): Promise<DeriveKeyResponse> {\n\t\ttry {\n\t\t\tif (!path || !subject) {\n\t\t\t\tlogger.error(\"Path and Subject are required for key derivation\");\n\t\t\t}\n\n\t\t\tlogger.log(\"Deriving Raw Key in TEE...\");\n\t\t\tconst derivedKey = await this.client.deriveKey(path, subject);\n\n\t\t\tlogger.log(\"Raw Key Derived Successfully!\");\n\t\t\treturn derivedKey;\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error deriving raw key:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Derives an Ed25519 keypair from the given path and subject.\n\t * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n\t * @param subject - The subject to derive the key from. This is used for the certificate chain.\n\t * @param agentId - The agent ID to generate an attestation for.\n\t * @returns An object containing the derived keypair and attestation.\n\t */\n\tasync deriveEd25519Keypair(\n\t\tpath: string,\n\t\tsubject: string,\n\t\tagentId: string,\n\t): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n\t\ttry {\n\t\t\tif (!path || !subject) {\n\t\t\t\tlogger.error(\"Path and Subject are required for key derivation\");\n\t\t\t}\n\n\t\t\tlogger.log(\"Deriving Key in TEE...\");\n\t\t\tconst derivedKey = await this.client.deriveKey(path, subject);\n\t\t\tconst uint8ArrayDerivedKey = derivedKey.asUint8Array();\n\n\t\t\tconst hash = crypto.createHash(\"sha256\");\n\t\t\thash.update(uint8ArrayDerivedKey);\n\t\t\tconst seed = hash.digest();\n\t\t\tconst seedArray = new Uint8Array(seed);\n\t\t\tconst keypair = Keypair.fromSeed(seedArray.slice(0, 32));\n\n\t\t\t// Generate an attestation for the derived key data for public to verify\n\t\t\tconst attestation = await this.generateDeriveKeyAttestation(\n\t\t\t\tagentId,\n\t\t\t\tkeypair.publicKey.toBase58(),\n\t\t\t);\n\t\t\tlogger.log(\"Key Derived Successfully!\");\n\n\t\t\treturn { keypair, attestation };\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error deriving key:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Derives an ECDSA keypair from the given path and subject.\n\t * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n\t * @param subject - The subject to derive the key from. This is used for the certificate chain.\n\t * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.\n\t * @returns An object containing the derived keypair and attestation.\n\t */\n\tasync deriveEcdsaKeypair(\n\t\tpath: string,\n\t\tsubject: string,\n\t\tagentId: string,\n\t): Promise<{\n\t\tkeypair: PrivateKeyAccount;\n\t\tattestation: RemoteAttestationQuote;\n\t}> {\n\t\ttry {\n\t\t\tif (!path || !subject) {\n\t\t\t\tlogger.error(\"Path and Subject are required for key derivation\");\n\t\t\t}\n\n\t\t\tlogger.log(\"Deriving ECDSA Key in TEE...\");\n\t\t\tconst deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey(\n\t\t\t\tpath,\n\t\t\t\tsubject,\n\t\t\t);\n\t\t\tconst hex = keccak256(deriveKeyResponse.asUint8Array());\n\t\t\tconst keypair: PrivateKeyAccount = privateKeyToAccount(hex);\n\n\t\t\t// Generate an attestation for the derived key data for public to verify\n\t\t\tconst attestation = await this.generateDeriveKeyAttestation(\n\t\t\t\tagentId,\n\t\t\t\tkeypair.address,\n\t\t\t);\n\t\t\tlogger.log(\"ECDSA Key Derived Successfully!\");\n\n\t\t\treturn { keypair, attestation };\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error deriving ecdsa key:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\n// Define the ProviderResult interface if not already imported\ninterface ProviderResult {\n\tdata?: any;\n\tvalues?: Record<string, string>;\n\ttext?: string;\n}\n\nconst phalaDeriveKeyProvider: Provider = {\n\tname: \"phala-derive-key\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\t_message?: Memory,\n\t): Promise<ProviderResult> => {\n\t\tconst teeMode = runtime.getSetting(\"TEE_MODE\");\n\t\tconst provider = new PhalaDeriveKeyProvider(teeMode);\n\t\tconst agentId = runtime.agentId;\n\t\ttry {\n\t\t\t// Validate wallet configuration\n\t\t\tif (!runtime.getSetting(\"WALLET_SECRET_SALT\")) {\n\t\t\t\tlogger.error(\"Wallet secret salt is not configured in settings\");\n\t\t\t\treturn {\n\t\t\t\t\tdata: null,\n\t\t\t\t\tvalues: {},\n\t\t\t\t\ttext: \"Wallet secret salt is not configured in settings\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst secretSalt =\n\t\t\t\t\truntime.getSetting(\"WALLET_SECRET_SALT\") || \"secret_salt\";\n\t\t\t\tconst solanaKeypair = await provider.deriveEd25519Keypair(\n\t\t\t\t\tsecretSalt,\n\t\t\t\t\t\"solana\",\n\t\t\t\t\tagentId,\n\t\t\t\t);\n\t\t\t\tconst evmKeypair = await provider.deriveEcdsaKeypair(\n\t\t\t\t\tsecretSalt,\n\t\t\t\t\t\"evm\",\n\t\t\t\t\tagentId,\n\t\t\t\t);\n\n\t\t\t\t// Original data structure\n\t\t\t\tconst walletData = {\n\t\t\t\t\tsolana: solanaKeypair.keypair.publicKey,\n\t\t\t\t\tevm: evmKeypair.keypair.address,\n\t\t\t\t};\n\n\t\t\t\t// Values for template injection\n\t\t\t\tconst values = {\n\t\t\t\t\tsolana_public_key: solanaKeypair.keypair.publicKey.toString(),\n\t\t\t\t\tevm_address: evmKeypair.keypair.address,\n\t\t\t\t};\n\n\t\t\t\t// Text representation\n\t\t\t\tconst text = `Solana Public Key: ${values.solana_public_key}\\nEVM Address: ${values.evm_address}`;\n\n\t\t\t\treturn {\n\t\t\t\t\tdata: walletData,\n\t\t\t\t\tvalues: values,\n\t\t\t\t\ttext: text,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Error creating PublicKey:\", error);\n\t\t\t\treturn {\n\t\t\t\t\tdata: null,\n\t\t\t\t\tvalues: {},\n\t\t\t\t\ttext: `Error creating PublicKey: ${\n\t\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t\t}`,\n\t\t\t\t};\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in derive key provider:\", error.message);\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\tvalues: {},\n\t\t\t\ttext: `Failed to fetch derive key information: ${\n\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t}`,\n\t\t\t};\n\t\t}\n\t},\n};\n\n/**\n * SGX Gramine TEE Provider\n * @example\n * ```ts\n * const provider = new SgxGramineDeriveKeyProvider();\n * ```\n */\nclass SgxGramineDeriveKeyProvider extends DeriveKeyProvider {}\n\nconst sgxGramineDeriveKeyProvider: Provider = {\n\tname: \"sgx-gramine-derive-key\",\n\tget: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message?: Memory,\n\t): Promise<ProviderResult> => {\n\t\treturn {\n\t\t\tdata: { provider: \"sgx-gramine\" },\n\t\t\tvalues: { provider_name: \"SGX Gramine\" },\n\t\t\ttext: \"SGX Gramine Derive Key Provider\",\n\t\t};\n\t},\n};\n\nexport {\n\tphalaDeriveKeyProvider,\n\tPhalaDeriveKeyProvider,\n\tsgxGramineDeriveKeyProvider,\n\tSgxGramineDeriveKeyProvider,\n};\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n | ChecksumAddressErrorType\n | Keccak256ErrorType\n | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n return checksumAddress(`0x${address}`) as Address\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray<T> = T | readonly RecursiveArray<T>[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n | CreateCursorErrorType\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\nexport function toRlp<to extends To = 'hex'>(\n bytes: RecursiveArray<ByteArray> | RecursiveArray<Hex>,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType<to> {\n const encodable = getEncodable(bytes)\n const cursor = createCursor(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType<to>\n return cursor.bytes as ToRlpReturnType<to>\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp<to extends To = 'bytes'>(\n bytes: RecursiveArray<ByteArray>,\n to: to | To | undefined = 'bytes',\n): ToRlpReturnType<to> {\n return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp<to extends To = 'hex'>(\n hex: RecursiveArray<Hex>,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType<to> {\n return toRlp(hex, to)\n}\n\nfunction getEncodable(\n bytes: RecursiveArray<ByteArray> | RecursiveArray<Hex>,\n): Encodable {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)))\n return getEncodableBytes(bytes as any)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n const sizeOfBodyLength = getSizeOfLength(bodyLength)\n const length = (() => {\n if (bodyLength <= 55) return 1 + bodyLength\n return 1 + sizeOfBodyLength + bodyLength\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength)\n } else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n else cursor.pushUint32(bodyLength)\n }\n for (const { encode } of list) {\n encode(cursor)\n }\n },\n }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n const sizeOfBytesLength = getSizeOfLength(bytes.length)\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80) return 1\n if (bytes.length <= 55) return 1 + bytes.length\n return 1 + sizeOfBytesLength + bytes.length\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes)\n } else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length)\n cursor.pushBytes(bytes)\n } else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n else cursor.pushUint32(bytes.length)\n cursor.pushBytes(bytes)\n }\n },\n }\n}\n\nfunction getSizeOfLength(length: number) {\n if (length < 2 ** 8) return 1\n if (length < 2 ** 16) return 2\n if (length < 2 ** 24) return 3\n if (length < 2 ** 32) return 4\n throw new BaseError('Length is too large.')\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../../types/misc.js'\nimport {\n type ConcatHexErrorType,\n concatHex,\n} from '../../../utils/data/concat.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../../utils/encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../../../utils/encoding/toRlp.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../../utils/hash/keccak256.js'\nimport type { Authorization } from '../types/authorization.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters<to extends To> = Authorization & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n}\n\nexport type HashAuthorizationReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization<to extends To = 'hex'>(\n parameters: HashAuthorizationParameters<to>,\n): HashAuthorizationReturnType<to> {\n const { chainId, contractAddress, nonce, to } = parameters\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n contractAddress,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType<to>\n return hash as HashAuthorizationReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick<Kzg, 'blobToKzgCommitment'>\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters<blobs, to>,\n): BlobsToCommitmentsReturnType<to> {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick<Kzg, 'computeBlobKzgProof'>\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters<blobs, commitments, to>,\n): blobsToProofsReturnType<to> {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType<to>\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { aexists, aoutput } from './_assert.js';\nimport { type Input, Hash, createView, toBytes } from './utils.js';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.js';\nimport { type CHash, rotr, wrapConstructor } from './utils.js';\n\n/** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n/**\n * Temporary buffer, not used to store anything between runs.\n * Named this way because it matches specification.\n */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n SHA256_W.fill(0);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n\n/**\n * Constants taken from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf.\n */\nclass SHA224 extends SHA256 {\n protected A = 0xc1059ed8 | 0;\n protected B = 0x367cd507 | 0;\n protected C = 0x3070dd17 | 0;\n protected D = 0xf70e5939 | 0;\n protected E = 0xffc00b31 | 0;\n protected F = 0x68581511 | 0;\n protected G = 0x64f98fa7 | 0;\n protected H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/** SHA2-256 hash function */\nexport const sha256: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/** SHA2-224 hash function */\nexport const sha224: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Sha256Hash<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256<to extends To = 'hex'>(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash<to> {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash<to>\n return toHex(bytes) as Sha256Hash<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters<commitment, to>,\n): CommitmentToVersionedHashReturnType<to> {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters<commitments, to>,\n): CommitmentsToVersionedHashesReturnType<to> {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6\n\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32\n\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096\n\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob\n\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction =\n bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\nexport const versionedHashVersionKzg = 1\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters<data, to>): ToBlobsReturnType<to> {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType<to extends To> =\n | (to extends 'bytes' ? BlobSidecars<ByteArray> : never)\n | (to extends 'hex' ? BlobSidecars<Hex> : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters<data, blobs, to>,\n): ToBlobSidecarsReturnType<to> {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType<to>\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestGeneric,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n} from '../../types/transaction.js'\nimport type { Assign, ExactPartial, IsNever, OneOf } from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends LegacyProperties ? 'legacy' : never)\n | (transaction extends EIP1559Properties ? 'eip1559' : never)\n | (transaction extends EIP2930Properties ? 'eip2930' : never)\n | (transaction extends EIP4844Properties ? 'eip4844' : never)\n | (transaction extends EIP7702Properties ? 'eip7702' : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract<transaction['type'], string>\n : never),\n> = IsNever<keyof transaction> extends true\n ? string\n : IsNever<result> extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType<transaction> {\n if (transaction.type)\n return transaction.type as GetTransactionType<transaction>\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign<BaseProperties, FeeValuesLegacy>\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n ExactPartial<LegacyProperties>,\n {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n ExactPartial<EIP1559Properties>,\n ExactPartial<FeeValuesEIP4844> &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n ExactPartial<EIP1559Properties>,\n {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import type { TypedData } from 'abitype'\n\nimport { stringify } from '../utils/stringify.js'\nimport { BaseError } from './base.js'\n\nexport type InvalidDomainErrorType = InvalidDomainError & {\n name: 'InvalidDomainError'\n}\nexport class InvalidDomainError extends BaseError {\n constructor({ domain }: { domain: unknown }) {\n super(`Invalid domain \"${stringify(domain)}\".`, {\n metaMessages: ['Must be a valid EIP-712 domain.'],\n })\n }\n}\n\nexport type InvalidPrimaryTypeErrorType = InvalidPrimaryTypeError & {\n name: 'InvalidPrimaryTypeError'\n}\nexport class InvalidPrimaryTypeError extends BaseError {\n constructor({\n primaryType,\n types,\n }: { primaryType: string; types: TypedData | Record<string, unknown> }) {\n super(\n `Invalid primary type \\`${primaryType}\\` must be one of \\`${JSON.stringify(Object.keys(types))}\\`.`,\n {\n docsPath: '/api/glossary/Errors#typeddatainvalidprimarytypeerror',\n metaMessages: ['Check that the primary type is a key in `types`.'],\n },\n )\n }\n}\n\nexport type InvalidStructTypeErrorType = InvalidStructTypeError & {\n name: 'InvalidStructTypeError'\n}\nexport class InvalidStructTypeError extends BaseError {\n constructor({ type }: { type: string }) {\n super(`Struct type \"${type}\" is invalid.`, {\n metaMessages: ['Struct type must not be a Solidity type.'],\n name: 'InvalidStructTypeError',\n })\n }\n}\n","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData, TypedDataDomain } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from '../abi/encodeAbiParameters.js'\nimport { concat } from '../data/concat.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n type ValidateTypedDataErrorType,\n getTypesForEIP712Domain,\n validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n name: string\n type: string\n}\n\nexport type HashTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition<typedData, primaryType>\n\nexport type HashTypedDataReturnType = Hex\n\nexport type HashTypedDataErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | HashStructErrorType\n | ValidateTypedDataErrorType\n | ErrorType\n\nexport function hashTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: HashTypedDataParameters<typedData, primaryType>,\n): HashTypedDataReturnType {\n const {\n domain = {},\n message,\n primaryType,\n } = parameters as HashTypedDataParameters\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\n }\n\n // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n // as we can't statically check this with TypeScript.\n validateTypedData({\n domain,\n message,\n primaryType,\n types,\n })\n\n const parts: Hex[] = ['0x1901']\n if (domain)\n parts.push(\n hashDomain({\n domain,\n types: types as Record<string, MessageTypeProperty[]>,\n }),\n )\n\n if (primaryType !== 'EIP712Domain')\n parts.push(\n hashStruct({\n data: message,\n primaryType,\n types: types as Record<string, MessageTypeProperty[]>,\n }),\n )\n\n return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain({\n domain,\n types,\n}: {\n domain: TypedDataDomain\n types: Record<string, MessageTypeProperty[]>\n}) {\n return hashStruct({\n data: domain,\n primaryType: 'EIP712Domain',\n types,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct({\n data,\n primaryType,\n types,\n}: {\n data: Record<string, unknown>\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encoded = encodeData({\n data,\n primaryType,\n types,\n })\n return keccak256(encoded)\n}\n\ntype EncodeDataErrorType =\n | EncodeAbiParametersErrorType\n | EncodeFieldErrorType\n | HashTypeErrorType\n | ErrorType\n\nfunction encodeData({\n data,\n primaryType,\n types,\n}: {\n data: Record<string, unknown>\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encodedTypes: AbiParameter[] = [{ type: 'bytes32' }]\n const encodedValues: unknown[] = [hashType({ primaryType, types })]\n\n for (const field of types[primaryType]) {\n const [type, value] = encodeField({\n types,\n name: field.name,\n type: field.type,\n value: data[field.name],\n })\n encodedTypes.push(type)\n encodedValues.push(value)\n }\n\n return encodeAbiParameters(encodedTypes, encodedValues)\n}\n\ntype HashTypeErrorType =\n | ToHexErrorType\n | EncodeTypeErrorType\n | Keccak256ErrorType\n | ErrorType\n\nfunction hashType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encodedHashType = toHex(encodeType({ primaryType, types }))\n return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nexport function encodeType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n let result = ''\n const unsortedDeps = findTypeDependencies({ primaryType, types })\n unsortedDeps.delete(primaryType)\n\n const deps = [primaryType, ...Array.from(unsortedDeps).sort()]\n for (const type of deps) {\n result += `${type}(${types[type]\n .map(({ name, type: t }) => `${t} ${name}`)\n .join(',')})`\n }\n\n return result\n}\n\ntype FindTypeDependenciesErrorType = ErrorType\n\nfunction findTypeDependencies(\n {\n primaryType: primaryType_,\n types,\n }: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n },\n results: Set<string> = new Set(),\n): Set<string> {\n const match = primaryType_.match(/^\\w*/u)\n const primaryType = match?.[0]!\n if (results.has(primaryType) || types[primaryType] === undefined) {\n return results\n }\n\n results.add(primaryType)\n\n for (const field of types[primaryType]) {\n findTypeDependencies({ primaryType: field.type, types }, results)\n }\n return results\n}\n\ntype EncodeFieldErrorType =\n | Keccak256ErrorType\n | EncodeAbiParametersErrorType\n | ToHexErrorType\n | ErrorType\n\nfunction encodeField({\n types,\n name,\n type,\n value,\n}: {\n types: Record<string, readonly MessageTypeProperty[]>\n name: string\n type: string\n value: any\n}): [type: AbiParameter, value: any] {\n if (types[type] !== undefined) {\n return [\n { type: 'bytes32' },\n keccak256(encodeData({ data: value, primaryType: type, types })),\n ]\n }\n\n if (type === 'bytes') {\n const prepend = value.length % 2 ? '0' : ''\n value = `0x${prepend + value.slice(2)}`\n return [{ type: 'bytes32' }, keccak256(value)]\n }\n\n if (type === 'string') return [{ type: 'bytes32' }, keccak256(toHex(value))]\n\n if (type.lastIndexOf(']') === type.length - 1) {\n const parsedType = type.slice(0, type.lastIndexOf('['))\n const typeValuePairs = (value as [AbiParameter, any][]).map((item) =>\n encodeField({\n name,\n type: parsedType,\n types,\n value: item,\n }),\n )\n return [\n { type: 'bytes32' },\n keccak256(\n encodeAbiParameters(\n typeValuePairs.map(([t]) => t),\n typeValuePairs.map(([, v]) => v),\n ),\n ),\n ]\n }\n\n return [{ type }, value]\n}\n","import type { TypedData, TypedDataDomain, TypedDataParameter } from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport {\n InvalidDomainError,\n InvalidPrimaryTypeError,\n InvalidStructTypeError,\n} from '../errors/typedData.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.js'\nimport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nimport { type SizeErrorType, size } from './data/size.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\nimport { bytesRegex, integerRegex } from './regex.js'\nimport {\n type HashDomainErrorType,\n hashDomain,\n} from './signature/hashTypedData.js'\nimport { stringify } from './stringify.js'\n\nexport type SerializeTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function serializeTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition<typedData, primaryType>) {\n const {\n domain: domain_,\n message: message_,\n primaryType,\n types,\n } = parameters as unknown as TypedDataDefinition\n\n const normalizeData = (\n struct: readonly TypedDataParameter[],\n data_: Record<string, unknown>,\n ) => {\n const data = { ...data_ }\n for (const param of struct) {\n const { name, type } = param\n if (type === 'address') data[name] = (data[name] as string).toLowerCase()\n }\n return data\n }\n\n const domain = (() => {\n if (!types.EIP712Domain) return {}\n if (!domain_) return {}\n return normalizeData(types.EIP712Domain, domain_)\n })()\n\n const message = (() => {\n if (primaryType === 'EIP712Domain') return undefined\n return normalizeData(types[primaryType], message_)\n })()\n\n return stringify({ domain, message, primaryType, types })\n}\n\nexport type ValidateTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function validateTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition<typedData, primaryType>) {\n const { domain, message, primaryType, types } =\n parameters as unknown as TypedDataDefinition\n\n const validateData = (\n struct: readonly TypedDataParameter[],\n data: Record<string, unknown>,\n ) => {\n for (const param of struct) {\n const { name, type } = param\n const value = data[name]\n\n const integerMatch = type.match(integerRegex)\n if (\n integerMatch &&\n (typeof value === 'number' || typeof value === 'bigint')\n ) {\n const [_type, base, size_] = integerMatch\n // If number cannot be cast to a sized hex value, it is out of range\n // and will throw.\n numberToHex(value, {\n signed: base === 'int',\n size: Number.parseInt(size_) / 8,\n })\n }\n\n if (type === 'address' && typeof value === 'string' && !isAddress(value))\n throw new InvalidAddressError({ address: value })\n\n const bytesMatch = type.match(bytesRegex)\n if (bytesMatch) {\n const [_type, size_] = bytesMatch\n if (size_ && size(value as Hex) !== Number.parseInt(size_))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_),\n givenSize: size(value as Hex),\n })\n }\n\n const struct = types[type]\n if (struct) {\n validateReference(type)\n validateData(struct, value as Record<string, unknown>)\n }\n }\n }\n\n // Validate domain types.\n if (types.EIP712Domain && domain) {\n if (typeof domain !== 'object') throw new InvalidDomainError({ domain })\n validateData(types.EIP712Domain, domain)\n }\n\n // Validate message types.\n if (primaryType !== 'EIP712Domain') {\n if (types[primaryType]) validateData(types[primaryType], message)\n else throw new InvalidPrimaryTypeError({ primaryType, types })\n }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n domain,\n}: { domain?: TypedDataDomain | undefined }): TypedDataParameter[] {\n return [\n typeof domain?.name === 'string' && { name: 'name', type: 'string' },\n domain?.version && { name: 'version', type: 'string' },\n (typeof domain?.chainId === 'number' ||\n typeof domain?.chainId === 'bigint') && {\n name: 'chainId',\n type: 'uint256',\n },\n domain?.verifyingContract && {\n name: 'verifyingContract',\n type: 'address',\n },\n domain?.salt && { name: 'salt', type: 'bytes32' },\n ].filter(Boolean) as TypedDataParameter[]\n}\n\nexport type DomainSeparatorErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | ErrorType\n\nexport function domainSeparator({ domain }: { domain: TypedDataDomain }): Hex {\n return hashDomain({\n domain,\n types: {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n },\n })\n}\n\n/** @internal */\nfunction validateReference(type: string) {\n // Struct type must not be a Solidity type.\n if (\n type === 'address' ||\n type === 'bool' ||\n type === 'string' ||\n type.startsWith('bytes') ||\n type.startsWith('uint') ||\n type.startsWith('int')\n )\n throw new InvalidStructTypeError({ type })\n}\n","export const presignMessagePrefix = '\\x19Ethereum Signed Message:\\n'\n","import { presignMessagePrefix } from '../../constants/strings.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { size } from '../data/size.js'\nimport {\n type BytesToHexErrorType,\n type StringToHexErrorType,\n bytesToHex,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type ToPrefixedMessageErrorType =\n | ConcatErrorType\n | StringToHexErrorType\n | BytesToHexErrorType\n | ErrorType\n\nexport function toPrefixedMessage(message_: SignableMessage): Hex {\n const message = (() => {\n if (typeof message_ === 'string') return stringToHex(message_)\n if (typeof message_.raw === 'string') return message_.raw\n return bytesToHex(message_.raw)\n })()\n const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`)\n return concat([prefix, message])\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { toPrefixedMessage } from './toPrefixedMessage.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessageReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType = Keccak256ErrorType | ErrorType\n\nexport function hashMessage<to extends To = 'hex'>(\n message: SignableMessage,\n to_?: to | undefined,\n): HashMessageReturnType<to> {\n return keccak256(toPrefixedMessage(message), to_)\n}\n","import { versionedHashVersionKzg } from '../../constants/kzg.js'\nimport { maxUint256 } from '../../constants/number.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n EmptyBlobError,\n type EmptyBlobErrorType,\n InvalidVersionedHashSizeError,\n type InvalidVersionedHashSizeErrorType,\n InvalidVersionedHashVersionError,\n type InvalidVersionedHashVersionErrorType,\n} from '../../errors/blob.js'\nimport {\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from '../../errors/chain.js'\nimport {\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { size } from '../data/size.js'\nimport { slice } from '../data/slice.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nexport type AssertTransactionEIP7702ErrorType =\n | AssertTransactionEIP1559ErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | ErrorType\n\nexport function assertTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n) {\n const { authorizationList } = transaction\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { contractAddress, chainId } = authorization\n if (!isAddress(contractAddress))\n throw new InvalidAddressError({ address: contractAddress })\n if (chainId < 0) throw new InvalidChainIdError({ chainId })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP4844ErrorType =\n | AssertTransactionEIP1559ErrorType\n | EmptyBlobErrorType\n | InvalidVersionedHashSizeErrorType\n | InvalidVersionedHashVersionErrorType\n | ErrorType\n\nexport function assertTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n) {\n const { blobVersionedHashes } = transaction\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0) throw new EmptyBlobError()\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash)\n const version = hexToNumber(slice(hash, 0, 1))\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ })\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP1559ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n\nexport type AssertTransactionEIP2930ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n\nexport type AssertTransactionLegacyErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport { toHex } from '../../../utils/encoding/toHex.js'\nimport { toYParitySignatureArray } from '../../../utils/transaction/serializeTransaction.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../types/authorization.js'\n\nexport type SerializeAuthorizationListReturnType = SerializedAuthorizationList\n\nexport type SerializeAuthorizationListErrorType = ErrorType\n\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(\n authorizationList?: AuthorizationList<number, true> | undefined,\n): SerializeAuthorizationListReturnType {\n if (!authorizationList || authorizationList.length === 0) return []\n\n const serializedAuthorizationList = []\n for (const authorization of authorizationList) {\n const { contractAddress, chainId, nonce, ...signature } = authorization\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ])\n }\n\n return serializedAuthorizationList as {} as SerializeAuthorizationListReturnType\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { AccessList } from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport type { RecursiveArray } from '../encoding/toRlp.js'\n\nexport type SerializeAccessListErrorType =\n | InvalidStorageKeySizeErrorType\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(\n accessList?: AccessList | undefined,\n): RecursiveArray<Hex> {\n if (!accessList || accessList.length === 0) return []\n\n const serializedAccessList = []\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i]\n\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] })\n }\n }\n\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address })\n }\n\n serializedAccessList.push([address, storageKeys])\n }\n return serializedAccessList\n}\n","import {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ByteArray,\n Hex,\n Signature,\n SignatureLegacy,\n} from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from '../blob/blobsToCommitments.js'\nimport {\n blobsToProofs,\n type blobsToProofsErrorType,\n} from '../blob/blobsToProofs.js'\nimport {\n type CommitmentsToVersionedHashesErrorType,\n commitmentsToVersionedHashes,\n} from '../blob/commitmentsToVersionedHashes.js'\nimport {\n type ToBlobSidecarsErrorType,\n toBlobSidecars,\n} from '../blob/toBlobSidecars.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport { type ToHexErrorType, bytesToHex, toHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../../experimental/eip7702/utils/serializeAuthorizationList.js'\nimport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionEIP4844ErrorType,\n type AssertTransactionEIP7702ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionEIP4844,\n assertTransactionEIP7702,\n assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './getTransactionType.js'\nimport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n transaction extends TransactionSerializable = TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType<transaction>,\n> = TransactionSerialized<_transactionType>\n\nexport type SerializeTransactionFn<\n transaction extends TransactionSerializableGeneric = TransactionSerializable,\n ///\n _transactionType extends TransactionType = never,\n> = typeof serializeTransaction<\n OneOf<TransactionSerializable | transaction>,\n _transactionType\n>\n\nexport type SerializeTransactionErrorType =\n | GetTransactionTypeErrorType\n | SerializeTransactionEIP1559ErrorType\n | SerializeTransactionEIP2930ErrorType\n | SerializeTransactionEIP4844ErrorType\n | SerializeTransactionEIP7702ErrorType\n | SerializeTransactionLegacyErrorType\n | ErrorType\n\nexport function serializeTransaction<\n const transaction extends TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType<transaction>,\n>(\n transaction: transaction,\n signature?: Signature | undefined,\n): SerializedTransactionReturnType<transaction, _transactionType> {\n const type = getTransactionType(transaction) as GetTransactionType\n\n if (type === 'eip1559')\n return serializeTransactionEIP1559(\n transaction as TransactionSerializableEIP1559,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip2930')\n return serializeTransactionEIP2930(\n transaction as TransactionSerializableEIP2930,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip4844')\n return serializeTransactionEIP4844(\n transaction as TransactionSerializableEIP4844,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip7702')\n return serializeTransactionEIP7702(\n transaction as TransactionSerializableEIP7702,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n return serializeTransactionLegacy(\n transaction as TransactionSerializableLegacy,\n signature as SignatureLegacy,\n ) as SerializedTransactionReturnType<transaction>\n}\n\ntype SerializeTransactionEIP7702ErrorType =\n | AssertTransactionEIP7702ErrorType\n | SerializeAuthorizationListErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n signature?: Signature | undefined,\n): TransactionSerializedEIP7702 {\n const {\n authorizationList,\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP7702(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n const serializedAuthorizationList =\n serializeAuthorizationList(authorizationList)\n\n return concatHex([\n '0x04',\n toRlp([\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]) as TransactionSerializedEIP7702\n}\n\ntype SerializeTransactionEIP4844ErrorType =\n | AssertTransactionEIP4844ErrorType\n | BlobsToCommitmentsErrorType\n | CommitmentsToVersionedHashesErrorType\n | blobsToProofsErrorType\n | ToBlobSidecarsErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n signature?: Signature | undefined,\n): TransactionSerializedEIP4844 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP4844(transaction)\n\n let blobVersionedHashes = transaction.blobVersionedHashes\n let sidecars = transaction.sidecars\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (\n transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')\n ) {\n const blobs = (\n typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : (transaction.blobs as ByteArray[]).map((x) => bytesToHex(x))\n ) as Hex[]\n const kzg = transaction.kzg!\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n })\n\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n })\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n sidecars = toBlobSidecars({ blobs, commitments, proofs })\n }\n }\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ] as const\n\n const blobs: Hex[] = []\n const commitments: Hex[] = []\n const proofs: Hex[] = []\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i]\n blobs.push(blob)\n commitments.push(commitment)\n proofs.push(proof)\n }\n\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP4844\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n | AssertTransactionEIP1559ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n signature?: Signature | undefined,\n): TransactionSerializedEIP1559 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP1559(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n | AssertTransactionEIP2930ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n signature?: Signature | undefined,\n): TransactionSerializedEIP2930 {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } =\n transaction\n\n assertTransactionEIP2930(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | ErrorType\n\nfunction serializeTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n signature?: SignatureLegacy | undefined,\n): TransactionSerializedLegacy {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n assertTransactionLegacy(transaction)\n\n let serializedTransaction = [\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n ]\n\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n\n if (inferredChainId > 0) return signature.v\n return 27n + (signature.v === 35n ? 0n : 1n)\n }\n\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\n\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n)\n if (signature.v !== v) throw new InvalidLegacyVError({ v: signature.v })\n return v\n })()\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n serializedTransaction = [\n ...serializedTransaction,\n toHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n toHex(chainId),\n '0x',\n '0x',\n ]\n }\n\n return toRlp(serializedTransaction) as TransactionSerializedLegacy\n}\n\nexport function toYParitySignatureArray(\n transaction: TransactionSerializableGeneric,\n signature_?: Signature | undefined,\n) {\n const signature = signature_ ?? transaction\n const { v, yParity } = signature\n\n if (typeof signature.r === 'undefined') return []\n if (typeof signature.s === 'undefined') return []\n if (typeof v === 'undefined' && typeof yParity === 'undefined') return []\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n const yParity_ = (() => {\n if (typeof yParity === 'number') return yParity ? toHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return toHex(1)\n\n return v === 27n ? '0x' : toHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type HexToBigIntErrorType, hexToBigInt } from '../encoding/fromHex.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\nimport type { ToHexErrorType } from '../encoding/toHex.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeSignatureParameters<to extends To = 'hex'> = Signature & {\n to?: to | To | undefined\n}\n\nexport type SerializeSignatureReturnType<to extends To = 'hex'> =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeSignatureErrorType =\n | HexToBigIntErrorType\n | ToHexErrorType\n | ErrorType\n\n/**\n * @description Converts a signature into hex format.\n *\n * @param signature The signature to convert.\n * @returns The signature in hex format.\n *\n * @example\n * serializeSignature({\n * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n * yParity: 1\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function serializeSignature<to extends To = 'hex'>({\n r,\n s,\n to = 'hex',\n v,\n yParity,\n}: SerializeSignatureParameters<to>): SerializeSignatureReturnType<to> {\n const yParity_ = (() => {\n if (yParity === 0 || yParity === 1) return yParity\n if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0\n throw new Error('Invalid `v` or `yParity` value')\n })()\n const signature = `0x${new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).toCompactHex()}${yParity_ === 0 ? '1b' : '1c'}` as const\n\n if (to === 'hex') return signature as SerializeSignatureReturnType<to>\n return hexToBytes(signature) as SerializeSignatureReturnType<to>\n}\n","// TODO(v3): Rename to `toLocalAccount` + add `source` property to define source (privateKey, mnemonic, hdKey, etc).\n\nimport type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n AccountSource,\n CustomSource,\n JsonRpcAccount,\n LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType<accountSource extends AccountSource> =\n | (accountSource extends Address ? JsonRpcAccount : never)\n | (accountSource extends CustomSource ? LocalAccount : never)\n\nexport type ToAccountErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a custom signing implementation.\n *\n * @returns A Local Account.\n */\nexport function toAccount<accountSource extends AccountSource>(\n source: accountSource,\n): GetAccountReturnType<accountSource> {\n if (typeof source === 'string') {\n if (!isAddress(source, { strict: false }))\n throw new InvalidAddressError({ address: source })\n return {\n address: source,\n type: 'json-rpc',\n } as GetAccountReturnType<accountSource>\n }\n\n if (!isAddress(source.address, { strict: false }))\n throw new InvalidAddressError({ address: source.address })\n return {\n address: source.address,\n nonceManager: source.nonceManager,\n sign: source.sign,\n experimental_signAuthorization: source.experimental_signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType<accountSource>\n}\n","// TODO(v3): Convert to sync.\n\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignParameters<to extends To = 'object'> = {\n hash: Hex\n privateKey: Hex\n to?: to | To | undefined\n}\n\nexport type SignReturnType<to extends To = 'object'> =\n | (to extends 'object' ? Signature : never)\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type SignErrorType = NumberToHexErrorType | ErrorType\n\nlet extraEntropy: Hex | boolean = false\n\n/**\n * Sets extra entropy for signing functions.\n */\nexport function setSignEntropy(entropy: true | Hex) {\n if (!entropy) throw new Error('must be a `true` or a hex value.')\n extraEntropy = entropy\n}\n\n/**\n * @description Signs a hash with a given private key.\n *\n * @param hash The hash to sign.\n * @param privateKey The private key to sign with.\n *\n * @returns The signature.\n */\nexport async function sign<to extends To = 'object'>({\n hash,\n privateKey,\n to = 'object',\n}: SignParameters<to>): Promise<SignReturnType<to>> {\n const { r, s, recovery } = secp256k1.sign(\n hash.slice(2),\n privateKey.slice(2),\n { lowS: true, extraEntropy },\n )\n const signature = {\n r: numberToHex(r, { size: 32 }),\n s: numberToHex(s, { size: 32 }),\n v: recovery ? 28n : 27n,\n yParity: recovery,\n }\n return (() => {\n if (to === 'bytes' || to === 'hex')\n return serializeSignature({ ...signature, to })\n return signature\n })() as SignReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n SignedAuthorization,\n} from '../../experimental/eip7702/types/authorization.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../experimental/eip7702/utils/hashAuthorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n sign,\n} from './sign.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignAuthorizationParameters<to extends To = 'object'> =\n Authorization & {\n /** The private key to sign with. */\n privateKey: Hex\n to?: SignParameters<to>['to'] | undefined\n }\n\nexport type SignAuthorizationReturnType<to extends To = 'object'> = Prettify<\n to extends 'object' ? SignedAuthorization : SignReturnType<to>\n>\n\nexport type SignAuthorizationErrorType =\n | SignErrorType\n | HashAuthorizationErrorType\n | ErrorType\n\n/**\n * Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport async function experimental_signAuthorization<to extends To = 'object'>(\n parameters: SignAuthorizationParameters<to>,\n): Promise<SignAuthorizationReturnType<to>> {\n const {\n contractAddress,\n chainId,\n nonce,\n privateKey,\n to = 'object',\n } = parameters\n const signature = await sign({\n hash: hashAuthorization({ contractAddress, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n contractAddress,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport {\n type HashMessageErrorType,\n hashMessage,\n} from '../../utils/signature/hashMessage.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignMessageParameters = {\n /** The message to sign. */\n message: SignableMessage\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n | SignErrorType\n | HashMessageErrorType\n | ErrorType\n\n/**\n * @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signMessage({\n message,\n privateKey,\n}: SignMessageParameters): Promise<SignMessageReturnType> {\n return await sign({ hash: hashMessage(message), privateKey, to: 'hex' })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerialized,\n} from '../../types/transaction.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport {\n type SerializeTransactionFn,\n serializeTransaction,\n} from '../../utils/transaction/serializeTransaction.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTransactionParameters<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n> = {\n privateKey: Hex\n transaction: transaction\n serializer?: serializer | undefined\n}\n\nexport type SignTransactionReturnType<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n> = TransactionSerialized<GetTransactionType<transaction>>\n\nexport type SignTransactionErrorType =\n | Keccak256ErrorType\n | SignErrorType\n | ErrorType\n\nexport async function signTransaction<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n>(\n parameters: SignTransactionParameters<serializer, transaction>,\n): Promise<SignTransactionReturnType<serializer, transaction>> {\n const {\n privateKey,\n transaction,\n serializer = serializeTransaction,\n } = parameters\n\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === 'eip4844')\n return {\n ...transaction,\n sidecars: false,\n }\n return transaction\n })()\n\n const signature = await sign({\n hash: keccak256(serializer(signableTransaction)),\n privateKey,\n })\n return serializer(transaction, signature) as SignTransactionReturnType<\n serializer,\n transaction\n >\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition<typedData, primaryType> & {\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n | HashTypedDataErrorType\n | SignErrorType\n | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: SignTypedDataParameters<typedData, primaryType>,\n): Promise<SignTypedDataReturnType> {\n const { privateKey, ...typedData } =\n parameters as unknown as SignTypedDataParameters\n return await sign({\n hash: hashTypedData(typedData),\n privateKey,\n to: 'hex',\n })\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type { NonceManager } from '../utils/nonceManager.js'\nimport { type ToAccountErrorType, toAccount } from './toAccount.js'\nimport type { PrivateKeyAccount } from './types.js'\nimport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nimport { type SignErrorType, sign } from './utils/sign.js'\nimport { experimental_signAuthorization } from './utils/signAuthorization.js'\nimport { type SignMessageErrorType, signMessage } from './utils/signMessage.js'\nimport {\n type SignTransactionErrorType,\n signTransaction,\n} from './utils/signTransaction.js'\nimport {\n type SignTypedDataErrorType,\n signTypedData,\n} from './utils/signTypedData.js'\n\nexport type PrivateKeyToAccountOptions = {\n nonceManager?: NonceManager | undefined\n}\n\nexport type PrivateKeyToAccountErrorType =\n | ToAccountErrorType\n | ToHexErrorType\n | PublicKeyToAddressErrorType\n | SignErrorType\n | SignMessageErrorType\n | SignTransactionErrorType\n | SignTypedDataErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a private key.\n *\n * @returns A Private Key Account.\n */\nexport function privateKeyToAccount(\n privateKey: Hex,\n options: PrivateKeyToAccountOptions = {},\n): PrivateKeyAccount {\n const { nonceManager } = options\n const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n const address = publicKeyToAddress(publicKey)\n\n const account = toAccount({\n address,\n nonceManager,\n async sign({ hash }) {\n return sign({ hash, privateKey, to: 'hex' })\n },\n async experimental_signAuthorization(authorization) {\n return experimental_signAuthorization({ ...authorization, privateKey })\n },\n async signMessage({ message }) {\n return signMessage({ message, privateKey })\n },\n async signTransaction(transaction, { serializer } = {}) {\n return signTransaction({ privateKey, transaction, serializer })\n },\n async signTypedData(typedData) {\n return signTypedData({ ...typedData, privateKey } as any)\n },\n })\n\n return {\n ...account,\n publicKey,\n source: 'privateKey',\n } as PrivateKeyAccount\n}\n","import { GramineVendor } from \"./gramine\";\nimport { PhalaVendor } from \"./phala\";\nimport type { TeeVendor } from \"./types\";\nimport { type TeeVendorName, TeeVendorNames } from \"./types\";\n\nconst vendors: Record<TeeVendorName, TeeVendor> = {\n\t[TeeVendorNames.PHALA]: new PhalaVendor(),\n\t[TeeVendorNames.SGX_GRAMINE]: new GramineVendor(),\n};\n\nexport const getVendor = (type: TeeVendorName): TeeVendor => {\n\tconst vendor = vendors[type];\n\tif (!vendor) {\n\t\tthrow new Error(`Unsupported TEE vendor type: ${type}`);\n\t}\n\treturn vendor;\n};\n\nexport * from \"./types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EAKC,UAAAA;AAAA,OACM;;;ACNP,OAAO,UAAU;AACjB;AAAA,EAGC;AAAA,EAEA;AAAA,EACA,WAAAC;AAAA,EAMA,WAAAC;AAAA,OACM;AACP,OAAO,cAAc;;;ACoFd,IAAe,YAAf,MAA6B;AAAA,EACnC;AAiBD;;;AC/GO,IAAM,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQrB,IAAM,kBAAN,cAA8B,UAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKxD,YAAY,IAAc;AACzB,UAAM;AACN,SAAK,KAAK;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,aAA4B;AACjC,SAAK,GAAG,KAAK,YAAY;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,OAAO,KAA+B;AAC3C,UAAM,OAAO,KAAK,GAAG;AAAA,MACpB;AAAA,IACD;AACA,QAAI;AACH,WAAK;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ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B,MAAM,OAAOC,SAAgC,YAA2B;AACvE,aAAO,MAAM;AAAA,QACZ;AAAA,UACC,GAAGA;AAAA,UACH,QAAQ;AAAA,QACT;AAAA,QACA;AAAA,MACD;AAAA,IACD;AAAA,IACA,aAAa,OAAO,eAAe;AAAA,IACnC,SAAS,OAAO,WAAW;AAAA,IAC3B,YAAY,CAAC;AAAA,IACb,WAAW,OAAO,aAAa;AAAA,IAC/B,UAAU,CAAC,aAAa;AAAA,EACzB;AACD;","names":["logger","TEEMode","TeeType","sgxAttestationProvider","TEEMode","TeeType","logger","logger","logger","TEEMode","TappdClient","toBytes","sha256","sha256","size","size","struct","blobs","commitments","proofs","v","TEEMode","logger","TappdClient","path","logger","config"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/services/teeLogService.ts","../src/types.ts","../src/adapters/sqliteTables.ts","../src/adapters/sqliteDAO.ts","../src/services/teeLogManager.ts","../../../node_modules/uuid/dist/esm/stringify.js","../../../node_modules/uuid/dist/esm/rng.js","../../../node_modules/uuid/dist/esm/native.js","../../../node_modules/uuid/dist/esm/v4.js","../src/providers/remoteAttestationProvider.ts","../src/utils.ts","../src/providers/base.ts","../src/vendors/types.ts","../src/vendors/gramine.ts","../src/vendors/phala.ts","../src/actions/remoteAttestationAction.ts","../src/providers/deriveKeyProvider.ts","../../../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../../../node_modules/viem/utils/encoding/toRlp.ts","../../../node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../../../node_modules/viem/utils/blob/blobsToCommitments.ts","../../../node_modules/viem/utils/blob/blobsToProofs.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/utils/hash/sha256.ts","../../../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../../../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../../../node_modules/viem/constants/blob.ts","../../../node_modules/viem/constants/kzg.ts","../../../node_modules/viem/errors/blob.ts","../../../node_modules/viem/utils/blob/toBlobs.ts","../../../node_modules/viem/utils/blob/toBlobSidecars.ts","../../../node_modules/viem/utils/transaction/getTransactionType.ts","../../../node_modules/viem/errors/typedData.ts","../../../node_modules/viem/utils/signature/hashTypedData.ts","../../../node_modules/viem/utils/typedData.ts","../../../node_modules/viem/constants/strings.ts","../../../node_modules/viem/utils/signature/toPrefixedMessage.ts","../../../node_modules/viem/utils/signature/hashMessage.ts","../../../node_modules/viem/utils/transaction/assertTransaction.ts","../../../node_modules/viem/experimental/eip7702/utils/serializeAuthorizationList.ts","../../../node_modules/viem/utils/transaction/serializeAccessList.ts","../../../node_modules/viem/utils/transaction/serializeTransaction.ts","../../../node_modules/viem/utils/signature/serializeSignature.ts","../../../node_modules/viem/accounts/toAccount.ts","../../../node_modules/viem/accounts/utils/sign.ts","../../../node_modules/viem/accounts/utils/signAuthorization.ts","../../../node_modules/viem/accounts/utils/signMessage.ts","../../../node_modules/viem/accounts/utils/signTransaction.ts","../../../node_modules/viem/accounts/utils/signTypedData.ts","../../../node_modules/viem/accounts/privateKeyToAccount.ts","../src/vendors/index.ts"],"sourcesContent":["import {\n\ttype IAgentRuntime,\n\ttype Plugin,\n\ttype TeePluginConfig,\n\ttype TeeVendorConfig,\n\tlogger,\n} from \"@elizaos/core\";\nimport { TeeLogService } from \"./services/teeLogService\";\nimport { TeeVendorNames, getVendor } from \"./vendors\";\n\nexport { PhalaDeriveKeyProvider } from \"./providers/deriveKeyProvider\";\nexport { PhalaRemoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nexport { TeeLogService };\nexport type { TeeVendorConfig };\n\n/**\n * Asynchronously initializes the Trusted Execution Environment (TEE) based on the provided configuration and runtime settings.\n * @param {Record<string, string>} config - The configuration object containing TEE vendor information.\n * @param {IAgentRuntime} runtime - The runtime object with TEE related settings.\n * @returns {Promise<void>} - A promise that resolves once the TEE is initialized.\n */\nasync function initializeTEE(\n\tconfig: Record<string, string>,\n\truntime: IAgentRuntime,\n) {\n\tif (config.TEE_VENDOR || runtime.getSetting(\"TEE_VENDOR\")) {\n\t\tconst vendor = config.TEE_VENDOR || runtime.getSetting(\"TEE_VENDOR\");\n\t\tlogger.info(`Initializing TEE with vendor: ${vendor}`);\n\t\tlet plugin: Plugin;\n\t\tswitch (vendor) {\n\t\t\tcase \"phala\":\n\t\t\t\tplugin = teePlugin({\n\t\t\t\t\tvendor: TeeVendorNames.PHALA,\n\t\t\t\t\tvendorConfig: {\n\t\t\t\t\t\tapiKey: runtime.getSetting(\"TEE_API_KEY\"),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"sgx-gramine\":\n\t\t\t\tplugin = teePlugin({\n\t\t\t\t\tvendor: TeeVendorNames.SGX_GRAMINE,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Invalid TEE vendor: ${vendor}`);\n\t\t}\n\t\tlogger.info(`Pushing plugin: ${plugin.name}`);\n\t\truntime.plugins.push(plugin);\n\t}\n}\n\n/**\n * A function that creates a TEE (Trusted Execution Environment) plugin based on the provided configuration.\n * @param { TeePluginConfig } [config] - Optional configuration for the TEE plugin.\n * @returns { Plugin } - The TEE plugin containing initialization, description, actions, evaluators, providers, and services.\n */\nexport const teePlugin = (config?: TeePluginConfig): Plugin => {\n\tconst vendorType = config?.vendor || TeeVendorNames.PHALA;\n\tconst vendor = getVendor(vendorType);\n\treturn {\n\t\tname: vendor.getName(),\n\t\tinit: async (config: Record<string, string>, runtime: IAgentRuntime) => {\n\t\t\treturn await initializeTEE(\n\t\t\t\t{\n\t\t\t\t\t...config,\n\t\t\t\t\tvendor: vendorType,\n\t\t\t\t},\n\t\t\t\truntime,\n\t\t\t);\n\t\t},\n\t\tdescription: vendor.getDescription(),\n\t\tactions: vendor.getActions(),\n\t\tevaluators: [],\n\t\tproviders: vendor.getProviders(),\n\t\tservices: [TeeLogService],\n\t};\n};\n","import path from \"node:path\";\nimport {\n\ttype IAgentRuntime,\n\ttype ITeeLogService,\n\tService,\n\ttype ServiceTypeName,\n\tServiceType,\n\tTEEMode,\n\ttype TeeAgent,\n\ttype TeeLog,\n\ttype TeeLogDAO,\n\ttype TeeLogQuery,\n\ttype TeePageQuery,\n\tTeeType,\n} from \"@elizaos/core\";\nimport Database from \"better-sqlite3\";\nimport { SqliteTeeLogDAO } from \"../adapters/sqliteDAO\";\nimport { TeeLogManager } from \"./teeLogManager\";\n\n/**\n * Represents a TeeLogService class that extends Service and implements ITeeLogService\n * This service is responsible for logging TEE attestation events\n */\nexport class TeeLogService extends Service implements ITeeLogService {\n\tprivate dbPath: string;\n\n\tprivate initialized = false;\n\tprivate enableTeeLog = false;\n\tprivate teeType: TeeType;\n\tprivate teeMode: TEEMode = TEEMode.OFF; // Only used for plugin-tee with TDX dstack\n\n\tprivate teeLogDAO: TeeLogDAO<Database.Database>;\n\tprivate teeLogManager: TeeLogManager;\n\n\tstatic serviceType: ServiceTypeName = ServiceType.TEE;\n\tcapabilityDescription =\n\t\t\"The agent is able to log TEE attestation events and is probably running in a TEE\";\n\n\t/**\n\t * Constructor for creating a new instance of a class.\n\t * @param {IAgentRuntime} runtime - The runtime object to be assigned to the instance.\n\t */\n\tconstructor(runtime: IAgentRuntime) {\n\t\tsuper();\n\t\tthis.runtime = runtime;\n\t}\n\n\t/**\n\t * Start the TeeLogService with the given runtime.\n\t *\n\t * @param {IAgentRuntime} runtime - The agent runtime to start the service with\n\t * @returns {Promise<TeeLogService>} - A promise that resolves with the TeeLogService instance\n\t * @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\n\t */\n\tstatic async start(runtime: IAgentRuntime): Promise<TeeLogService> {\n\t\tconst service = new TeeLogService(runtime);\n\n\t\tconst enableValues = [\"true\", \"1\", \"yes\", \"enable\", \"enabled\", \"on\"];\n\n\t\tconst enableTeeLog = runtime.getSetting(\"ENABLE_TEE_LOG\") as string;\n\t\tif (enableTeeLog === null) {\n\t\t\tthrow new Error(\"ENABLE_TEE_LOG is not set.\");\n\t\t}\n\t\tservice.enableTeeLog = enableValues.includes(enableTeeLog.toLowerCase());\n\t\tif (!service.enableTeeLog) {\n\t\t\tconsole.log(\"TEE log is not enabled.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst runInSgx = runtime.getSetting(\"SGX\") as string;\n\t\tconst teeMode = runtime.getSetting(\"TEE_MODE\") as string;\n\t\tconst walletSecretSalt = runtime.getSetting(\"WALLET_SECRET_SALT\");\n\n\t\tservice.teeMode = teeMode\n\t\t\t? TEEMode[teeMode as keyof typeof TEEMode]\n\t\t\t: TEEMode.OFF;\n\n\t\tconst useSgxGramine =\n\t\t\trunInSgx && enableValues.includes(runInSgx.toLowerCase());\n\t\tconst useTdxDstack = teeMode && teeMode !== TEEMode.OFF && walletSecretSalt;\n\n\t\tif (useSgxGramine && useTdxDstack) {\n\t\t\tthrow new Error(\"Cannot configure both SGX and TDX at the same time.\");\n\t\t}\n\t\tif (useSgxGramine) {\n\t\t\tservice.teeType = TeeType.SGX_GRAMINE;\n\t\t} else if (useTdxDstack) {\n\t\t\tservice.teeType = TeeType.TDX_DSTACK;\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid TEE configuration.\");\n\t\t}\n\n\t\tconst dbPathSetting = runtime.getSetting(\"TEE_LOG_DB_PATH\") as string;\n\t\tservice.dbPath = dbPathSetting || path.resolve(\"data/tee_log.sqlite\");\n\n\t\tconst db = new Database(service.dbPath);\n\t\tservice.teeLogDAO = new SqliteTeeLogDAO(db);\n\t\tservice.teeLogManager = new TeeLogManager(\n\t\t\tservice.teeLogDAO,\n\t\t\tservice.teeType,\n\t\t\tservice.teeMode,\n\t\t);\n\n\t\tconst isRegistered = await service.teeLogManager.registerAgent(\n\t\t\truntime?.agentId,\n\t\t\truntime?.character?.name,\n\t\t);\n\t\tif (!isRegistered) {\n\t\t\tthrow new Error(`Failed to register agent ${runtime.agentId}`);\n\t\t}\n\n\t\tservice.initialized = true;\n\t\treturn service;\n\t}\n\n\t/**\n\t * Stop the TEE service running on the provided runtime.\n\t *\n\t * @param {IAgentRuntime} runtime - The runtime on which the TEE service is running.\n\t * @returns {Promise<void>} - A promise that resolves once the TEE service has stopped.\n\t */\n\tstatic async stop(runtime: IAgentRuntime) {\n\t\tconst service = runtime.getService(ServiceType.TEE);\n\t\tif (service) {\n\t\t\tawait service.stop();\n\t\t}\n\t}\n\n\t/**\n\t * Asynchronous method to stop the operation.\n\t * Does nothing.\n\t */\n\tasync stop() {\n\t\t// do nothing\n\t}\n\n\t/**\n\t * Asynchronously logs the provided information if tee log is enabled.\n\t *\n\t * @param {string} agentId - The ID of the agent requesting the log.\n\t * @param {string} roomId - The ID of the room where the log is taking place.\n\t * @param {string} entityId - The ID of the entity related to the log.\n\t * @param {string} type - The type of log entry.\n\t * @param {string} content - The content of the log entry.\n\t * @returns {Promise<boolean>} A promise that resolves to true if the log is successful, false if tee log is not enabled.\n\t */\n\tasync log(\n\t\tagentId: string,\n\t\troomId: string,\n\t\tentityId: string,\n\t\ttype: string,\n\t\tcontent: string,\n\t): Promise<boolean> {\n\t\tif (!this.enableTeeLog) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn this.teeLogManager.log(agentId, roomId, entityId, type, content);\n\t}\n\n\t/**\n\t * Asynchronously retrieves all TeeAgents.\n\t *\n\t * @returns {Promise<TeeAgent[]>} A Promise that resolves with an array of TeeAgent objects. If Tee logging is not enabled, an empty array is returned.\n\t */\n\tasync getAllAgents(): Promise<TeeAgent[]> {\n\t\tif (!this.enableTeeLog) {\n\t\t\treturn [];\n\t\t}\n\n\t\treturn this.teeLogManager.getAllAgents();\n\t}\n\n\t/**\n\t * Asynchronously retrieves a TeeAgent based on the provided agentId.\n\t *\n\t * @param {string} agentId - The ID of the agent to retrieve.\n\t * @returns {Promise<TeeAgent | undefined>} A Promise that resolves with the retrieved TeeAgent, or undefined if TEE logging is not enabled.\n\t */\n\tasync getAgent(agentId: string): Promise<TeeAgent | undefined> {\n\t\tif (!this.enableTeeLog) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn this.teeLogManager.getAgent(agentId);\n\t}\n\n\t/**\n\t * Retrieves Tee logs based on query, page, and page size.\n\t *\n\t * @param {TeeLogQuery} query - The query parameters to filter the logs.\n\t * @param {number} page - The current page number.\n\t * @param {number} pageSize - The number of logs to fetch per page.\n\t * @returns {Promise<TeePageQuery<TeeLog[]>>} A Promise that resolves to a TeePageQuery object containing an array of TeeLog and pagination information.\n\t */\n\tasync getLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>> {\n\t\tif (!this.enableTeeLog) {\n\t\t\treturn {\n\t\t\t\tdata: [],\n\t\t\t\ttotal: 0,\n\t\t\t\tpage: page,\n\t\t\t\tpageSize: pageSize,\n\t\t\t};\n\t\t}\n\n\t\treturn this.teeLogManager.getLogs(query, page, pageSize);\n\t}\n\n\t/**\n\t * Asynchronously generates an attestation for the given user report.\n\t *\n\t * @param {string} userReport - The user report to generate attestation for.\n\t * @returns {Promise<string>} A promise that resolves to the generated attestation.\n\t */\n\tasync generateAttestation(userReport: string): Promise<string> {\n\t\treturn this.teeLogManager.generateAttestation(userReport);\n\t}\n}\n\nexport default TeeLogService;\n","/**\n * Enum representing different types of Tee.\n * @enum {string}\n * @readonly\n */\n\nexport enum TeeType {\n\tSGX_GRAMINE = \"sgx_gramine\",\n\tTDX_DSTACK = \"tdx_dstack\",\n}\n\n// Represents a log entry in the TeeLog table, containing details about agent activities.\n/**\n * Interface representing a log entry for a tee.\n * @typedef {Object} TeeLog\n * @property {string} id - The unique identifier for the log entry.\n * @property {string} agentId - The identifier of the agent who created the log entry.\n * @property {string} roomId - The identifier of the room where the log entry was created.\n * @property {string} entityId - The identifier of the entity associated with the log entry.\n * @property {string} type - The type of the log entry.\n * @property {string} content - The content of the log entry.\n * @property {number} timestamp - The timestamp when the log entry was created.\n * @property {string} signature - The signature of the log entry.\n */\n\nexport interface TeeLog {\n\tid: string;\n\tagentId: string;\n\troomId: string;\n\tentityId: string;\n\ttype: string;\n\tcontent: string;\n\ttimestamp: number;\n\tsignature: string;\n}\n\n/**\n * Interface for defining query parameters for fetching TeeLog data.\n * @property {string} [agentId] - The ID of the agent associated with the log.\n * @property {string} [roomId] - The ID of the room associated with the log.\n * @property {string} [entityId] - The ID of the entity associated with the log.\n * @property {string} [type] - The type of log.\n * @property {string} [containsContent] - The content that the log must contain.\n * @property {number} [startTimestamp] - The starting timestamp for filtering logs.\n * @property {number} [endTimestamp] - The ending timestamp for filtering logs.\n */\nexport interface TeeLogQuery {\n\tagentId?: string;\n\troomId?: string;\n\tentityId?: string;\n\ttype?: string;\n\tcontainsContent?: string;\n\tstartTimestamp?: number;\n\tendTimestamp?: number;\n}\n\n// Represents an agent in the TeeAgent table, containing details about the agent.\n/**\n * Interface for representing a TeeAgent.\n * @interface\n * @property {string} id - Primary key\n * @property {string} agentId - Allow duplicate agentId. This is to support the case where the same agentId is registered multiple times. Each time the agent restarts, a new keypair and attestation will be generated.\n * @property {string} agentName - The name of the agent.\n * @property {number} createdAt - The timestamp when the agent was created.\n * @property {string} publicKey - The public key of the agent.\n * @property {string} attestation - The attestation of the agent.\n */\n\nexport interface TeeAgent {\n\tid: string; // Primary key\n\t// Allow duplicate agentId.\n\t// This is to support the case where the same agentId is registered multiple times.\n\t// Each time the agent restarts, we will generate a new keypair and attestation.\n\tagentId: string;\n\tagentName: string;\n\tcreatedAt: number;\n\tpublicKey: string;\n\tattestation: string;\n}\n\n/**\n * Interface for defining the structure of a paginated query result.\n * @template Result The type of data contained in the query result.\n * @property {number} page The current page number.\n * @property {number} pageSize The number of items per page.\n * @property {number} [total] The total number of items in the query result (optional).\n * @property {Result} [data] The data contained in the query result (optional).\n */\nexport interface TeePageQuery<Result> {\n\tpage: number;\n\tpageSize: number;\n\ttotal?: number;\n\tdata?: Result;\n}\n\n/**\n * Represents a Data Access Object for managing Tee logs and agents.\n * @template DB - Type of the database connection or client\n */\nexport abstract class TeeLogDAO<DB> {\n\tdb: DB;\n\n\tabstract initialize(): Promise<void>;\n\n\tabstract addLog(log: TeeLog): Promise<boolean>;\n\n\tabstract getPagedLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>>;\n\n\tabstract addAgent(agent: TeeAgent): Promise<boolean>;\n\n\tabstract getAgent(agentId: string): Promise<TeeAgent>;\n\n\tabstract getAllAgents(): Promise<TeeAgent[]>;\n}\n","/**\n * Defines the SQL script to create SQLite tables for the 'tee_logs' and 'tee_agents' tables.\n *\n * @constant\n * @type {string}\n */\nexport const sqliteTables = `\nBEGIN TRANSACTION;\n\n-- Table: tee_logs\nCREATE TABLE IF NOT EXISTS \"tee_logs\" (\n \"id\" TEXT PRIMARY KEY,\n \"agentId\" TEXT NOT NULL,\n \"roomId\" TEXT NOT NULL,\n \"entityId\" TEXT NOT NULL,\n \"type\" TEXT NOT NULL,\n \"content\" TEXT NOT NULL,\n \"timestamp\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n \"signature\" TEXT NOT NULL\n);\n\n-- Table: tee_agents\nCREATE TABLE IF NOT EXISTS \"tee_agents\" (\n \"id\" TEXT PRIMARY KEY,\n \"agentId\" TEXT NOT NULL,\n \"agentName\" TEXT NOT NULL,\n \"createdAt\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n \"publicKey\" TEXT NOT NULL,\n \"attestation\" TEXT NOT NULL\n);\n\nCOMMIT;`;\n","import type { Database } from \"better-sqlite3\";\nimport {\n\ttype TeeAgent,\n\ttype TeeLog,\n\tTeeLogDAO,\n\ttype TeeLogQuery,\n\ttype TeePageQuery,\n} from \"../types\";\nimport { sqliteTables } from \"./sqliteTables\";\n\n/**\n * Represents a data access object for interacting with SQLite database to perform operations related to TeeLog and TeeAgent.\n * @extends TeeLogDAO\n */\nexport class SqliteTeeLogDAO extends TeeLogDAO<Database> {\n\t/**\n\t * Constructor for creating a new instance of the class.\n\t * @param {Database} db - The database object to be used by the instance\n\t */\n\tconstructor(db: Database) {\n\t\tsuper();\n\t\tthis.db = db;\n\t}\n\n\t/**\n\t * Asynchronously initializes the database by executing the provided SQLite table creation SQL.\n\t * @returns A Promise that resolves to void once the initialization is complete.\n\t */\n\tasync initialize(): Promise<void> {\n\t\tthis.db.exec(sqliteTables);\n\t}\n\n\t/**\n\t * Add a log to the database.\n\t *\n\t * @param {TeeLog} log - The log object to be added.\n\t * @returns {Promise<boolean>} - Indicates if the log was successfully added or not.\n\t */\n\tasync addLog(log: TeeLog): Promise<boolean> {\n\t\tconst stmt = this.db.prepare(\n\t\t\t\"INSERT INTO tee_logs (id, agentId, roomId, entityId, type, content, timestamp, signature) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\",\n\t\t);\n\t\ttry {\n\t\t\tstmt.run(\n\t\t\t\tlog.id,\n\t\t\t\tlog.agentId,\n\t\t\t\tlog.roomId,\n\t\t\t\tlog.entityId,\n\t\t\t\tlog.type,\n\t\t\t\tlog.content,\n\t\t\t\tlog.timestamp,\n\t\t\t\tlog.signature,\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error adding log to database\", error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Retrieves paged logs based on the provided query criteria.\n\t *\n\t * @param {TeeLogQuery} query - The query criteria to filter the logs.\n\t * @param {number} page - The page number to retrieve.\n\t * @param {number} pageSize - The number of logs per page.\n\t * @returns {Promise<TeePageQuery<TeeLog[]>>} The paged logs data along with page information.\n\t */\n\tasync getPagedLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>> {\n\t\tconst currentPage = page < 1 ? 1 : page;\n\t\tconst offset = (currentPage - 1) * pageSize;\n\t\tconst limit = pageSize;\n\n\t\tconst whereConditions = [];\n\t\tconst params = [];\n\n\t\tif (query.agentId && query.agentId !== \"\") {\n\t\t\twhereConditions.push(\"agentId = ?\");\n\t\t\tparams.push(query.agentId);\n\t\t}\n\t\tif (query.roomId && query.roomId !== \"\") {\n\t\t\twhereConditions.push(\"roomId = ?\");\n\t\t\tparams.push(query.roomId);\n\t\t}\n\t\tif (query.entityId && query.entityId !== \"\") {\n\t\t\twhereConditions.push(\"entityId = ?\");\n\t\t\tparams.push(query.entityId);\n\t\t}\n\t\tif (query.type && query.type !== \"\") {\n\t\t\twhereConditions.push(\"type = ?\");\n\t\t\tparams.push(query.type);\n\t\t}\n\t\tif (query.containsContent && query.containsContent !== \"\") {\n\t\t\twhereConditions.push(\"content LIKE ?\");\n\t\t\tparams.push(`%${query.containsContent}%`);\n\t\t}\n\t\tif (query.startTimestamp) {\n\t\t\twhereConditions.push(\"timestamp >= ?\");\n\t\t\tparams.push(query.startTimestamp);\n\t\t}\n\t\tif (query.endTimestamp) {\n\t\t\twhereConditions.push(\"timestamp <= ?\");\n\t\t\tparams.push(query.endTimestamp);\n\t\t}\n\n\t\tconst whereClause =\n\t\t\twhereConditions.length > 0\n\t\t\t\t? `WHERE ${whereConditions.join(\" AND \")}`\n\t\t\t\t: \"\";\n\n\t\ttry {\n\t\t\tconst total_stmt = this.db.prepare(\n\t\t\t\t`SELECT COUNT(*) as total FROM tee_logs ${whereClause}`,\n\t\t\t);\n\t\t\tconst total = total_stmt.get(params).total;\n\n\t\t\tconst logs_stmt = this.db.prepare(\n\t\t\t\t`SELECT * FROM tee_logs ${whereClause} ORDER BY timestamp ASC LIMIT ? OFFSET ?`,\n\t\t\t);\n\t\t\tconst logs = logs_stmt.all(...params, limit, offset);\n\n\t\t\treturn {\n\t\t\t\tpage: currentPage,\n\t\t\t\tpageSize,\n\t\t\t\ttotal,\n\t\t\t\tdata: logs,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error getting paged logs from database\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Add an agent to the database.\n\t *\n\t * @param {TeeAgent} agent - The TeeAgent object to be added.\n\t * @returns {Promise<boolean>} - A Promise that resolves to true if the agent was successfully added, and false otherwise.\n\t */\n\tasync addAgent(agent: TeeAgent): Promise<boolean> {\n\t\tconst stmt = this.db.prepare(\n\t\t\t\"INSERT INTO tee_agents (id, agentId, agentName, createdAt, publicKey, attestation) VALUES (?, ?, ?, ?, ?, ?)\",\n\t\t);\n\t\ttry {\n\t\t\tstmt.run(\n\t\t\t\tagent.id,\n\t\t\t\tagent.agentId,\n\t\t\t\tagent.agentName,\n\t\t\t\tagent.createdAt,\n\t\t\t\tagent.publicKey,\n\t\t\t\tagent.attestation,\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error adding agent to database\", error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Retrieves a TeeAgent from the database based on the provided agentId.\n\t *\n\t * @param {string} agentId - The unique identifier of the agent to retrieve.\n\t * @returns {Promise<TeeAgent | null>} A promise that resolves with the retrieved TeeAgent, or null if not found.\n\t */\n\tasync getAgent(agentId: string): Promise<TeeAgent | null> {\n\t\tconst stmt = this.db.prepare(\n\t\t\t\"SELECT * FROM tee_agents WHERE agentId = ? ORDER BY createdAt DESC LIMIT 1\",\n\t\t);\n\t\ttry {\n\t\t\treturn stmt.get(agentId);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error getting agent from database\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Retrieves all agents from the database.\n\t *\n\t * @returns {Promise<TeeAgent[]>} All agents\n\t */\n\tasync getAllAgents(): Promise<TeeAgent[]> {\n\t\tconst stmt = this.db.prepare(\"SELECT * FROM tee_agents\");\n\t\ttry {\n\t\t\treturn stmt.all();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error getting all agents from database\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n","import {\n\ttype TEEMode,\n\ttype TeeAgent,\n\ttype TeeLog,\n\ttype TeeLogDAO,\n\ttype TeeLogQuery,\n\ttype TeePageQuery,\n\tTeeType,\n} from \"@elizaos/core\";\nimport elliptic from \"elliptic\";\nimport { v4 } from \"uuid\";\nimport { SgxAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { PhalaRemoteAttestationProvider as TdxAttestationProvider } from \"../providers/remoteAttestationProvider\";\n\n/**\n * Manage TeeLog related operations including agent registration, logging, and retrieval.\n */\nexport class TeeLogManager {\n\tprivate teeLogDAO: TeeLogDAO;\n\tprivate teeType: TeeType;\n\tprivate teeMode: TEEMode; // Only used for plugin-tee with TDX dstack\n\n\t// Map of agentId to its key pair\n\t// These keypairs only store in memory.\n\t// When the agent restarts, we will generate new keypair.\n\tprivate keyPairs: Map<string, elliptic.ec.KeyPair> = new Map();\n\n\t/**\n\t * Constructor for initializing TeeLog object.\n\t * * @param { TeeLogDAO } teeLogDAO - The data access object for TeeLog.\n\t * @param { TeeType } teeType - The type of Tee.\n\t * @param { TEEMode } teeMode - The mode of Tee.\n\t */\n\tconstructor(teeLogDAO: TeeLogDAO, teeType: TeeType, teeMode: TEEMode) {\n\t\tthis.teeLogDAO = teeLogDAO;\n\t\tthis.teeType = teeType;\n\t\tthis.teeMode = teeMode;\n\t}\n\n\t/**\n\t * Registers a new agent with the given agent ID and agent name.\n\t *\n\t * @param {string} agentId - The unique identifier for the agent.\n\t * @param {string} agentName - The name of the agent.\n\t * @returns {Promise<boolean>} A promise that resolves to true if the agent is successfully registered.\n\t * @throws {Error} If agentId is empty or null.\n\t */\n\tpublic async registerAgent(\n\t\tagentId: string,\n\t\tagentName: string,\n\t): Promise<boolean> {\n\t\tif (!agentId) {\n\t\t\tthrow new Error(\"Agent ID is required\");\n\t\t}\n\n\t\tconst keyPair = this.generateKeyPair();\n\t\tthis.keyPairs.set(agentId, keyPair);\n\n\t\tconst publicKey = keyPair.getPublic().encode(\"hex\", true);\n\t\tconst attestation = await this.generateAttestation(publicKey);\n\n\t\tconst new_agent = {\n\t\t\tid: v4(),\n\t\t\tagentId,\n\t\t\tagentName: agentName || \"\",\n\t\t\tcreatedAt: new Date().getTime(),\n\t\t\tpublicKey,\n\t\t\tattestation,\n\t\t};\n\n\t\tconsole.log(\"registerAgent new_agent\", new_agent);\n\n\t\treturn this.teeLogDAO.addAgent(new_agent);\n\t}\n\n\t/**\n\t * Retrieves all agents from the database.\n\t * @returns {Promise<TeeAgent[]>} A promise that resolves to an array of TeeAgent objects.\n\t */\n\tpublic async getAllAgents(): Promise<TeeAgent[]> {\n\t\treturn this.teeLogDAO.getAllAgents();\n\t}\n\n\t/**\n\t * Retrieve an agent from the database by its ID.\n\t * @param {string} agentId - The unique identifier of the agent.\n\t * @returns {Promise<TeeAgent | undefined>} The agent object if found, undefined otherwise.\n\t */\n\tpublic async getAgent(agentId: string): Promise<TeeAgent | undefined> {\n\t\treturn this.teeLogDAO.getAgent(agentId);\n\t}\n\n\t/**\n\t * Logs an event with the specified information.\n\t *\n\t * @param {string} agentId - The ID of the agent performing the action.\n\t * @param {string} roomId - The room ID where the event occurred.\n\t * @param {string} entityId - The ID of the entity involved in the event.\n\t * @param {string} type - The type of event being logged.\n\t * @param {string} content - The content of the event being logged.\n\t * @returns {Promise<boolean>} A boolean indicating if the logging was successful.\n\t */\n\tpublic async log(\n\t\tagentId: string,\n\t\troomId: string,\n\t\tentityId: string,\n\t\ttype: string,\n\t\tcontent: string,\n\t): Promise<boolean> {\n\t\tconst keyPair = this.keyPairs.get(agentId);\n\t\tif (!keyPair) {\n\t\t\tthrow new Error(`Agent ${agentId} not found`);\n\t\t}\n\n\t\tconst timestamp = new Date().getTime();\n\n\t\t// Join the information into a single string\n\t\tconst messageToSign = `${agentId}|${roomId}|${entityId}|${type}|${content}|${timestamp}`;\n\n\t\t// Sign the joined message\n\t\tconst signature = `0x${keyPair.sign(messageToSign).toDER(\"hex\")}`;\n\n\t\treturn this.teeLogDAO.addLog({\n\t\t\tid: v4(),\n\t\t\tagentId,\n\t\t\troomId,\n\t\t\tentityId,\n\t\t\ttype,\n\t\t\tcontent,\n\t\t\ttimestamp,\n\t\t\tsignature,\n\t\t});\n\t}\n\n\t/**\n\t * Retrieves logs based on the provided query, page number, and page size.\n\t * @param {TeeLogQuery} query - The query object to filter logs.\n\t * @param {number} page - The page number of logs to retrieve.\n\t * @param {number} pageSize - The number of logs per page.\n\t * @returns {Promise<TeePageQuery<TeeLog[]>>} A promise that resolves to a page query of logs.\n\t */\n\tpublic async getLogs(\n\t\tquery: TeeLogQuery,\n\t\tpage: number,\n\t\tpageSize: number,\n\t): Promise<TeePageQuery<TeeLog[]>> {\n\t\treturn this.teeLogDAO.getPagedLogs(query, page, pageSize);\n\t}\n\n\t/**\n\t * Generate a new key pair using the secp256k1 elliptic curve algorithm.\n\t *\n\t * @returns {elliptic.ec.KeyPair} The generated key pair.\n\t */\n\tpublic generateKeyPair(): elliptic.ec.KeyPair {\n\t\tconst ec = new elliptic.ec(\"secp256k1\");\n\t\tconst key = ec.genKeyPair();\n\t\treturn key;\n\t}\n\n\t/**\n\t * Generates an attestation for the given user report based on the TEE type.\n\t *\n\t * @param {string} userReport The user report to generate the attestation for.\n\t * @returns {Promise<string>} A promise that resolves with the generated attestation as a string.\n\t * @throws {Error} If the TEE type is invalid.\n\t */\n\tpublic async generateAttestation(userReport: string): Promise<string> {\n\t\tif (this.teeType === TeeType.SGX_GRAMINE) {\n\t\t\tconst sgxAttestationProvider = new SgxAttestationProvider();\n\t\t\tconst sgxAttestation =\n\t\t\t\tawait sgxAttestationProvider.generateAttestation(userReport);\n\t\t\treturn JSON.stringify(sgxAttestation);\n\t\t}\n\t\tif (this.teeType === TeeType.TDX_DSTACK) {\n\t\t\tconst tdxAttestationProvider = new TdxAttestationProvider(this.teeMode);\n\t\t\tconst tdxAttestation =\n\t\t\t\tawait tdxAttestationProvider.generateAttestation(userReport);\n\t\t\treturn JSON.stringify(tdxAttestation);\n\t\t}\n\t\tthrow new Error(\"Invalid TEE type\");\n\t}\n}\n","import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n","import { randomFillSync } from 'crypto';\nconst rnds8Pool = new Uint8Array(256);\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, (poolPtr += 16));\n}\n","import { randomUUID } from 'crypto';\nexport default { randomUUID };\n","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random || (options.rng || rng)();\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n","import { promises as fs } from \"node:fs\"; // Fix: Use node: protocol\nimport {\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype State,\n\tlogger,\n} from \"@elizaos/core\";\nimport {\n\ttype RemoteAttestationMessage,\n\ttype RemoteAttestationQuote,\n\tTEEMode,\n} from \"@elizaos/core\";\nimport type { SgxAttestation } from \"@elizaos/core\";\nimport {\n\tTappdClient,\n\ttype TdxQuoteHashAlgorithms,\n\ttype TdxQuoteResponse,\n} from \"@phala/dstack-sdk\";\nimport { calculateSHA256 } from \"../utils\";\nimport { RemoteAttestationProvider } from \"./base\";\n\n// Define the ProviderResult interface if not already imported\n/**\n * Interface for the result returned by a provider.\n * @typedef {Object} ProviderResult\n * @property {any} data - The data returned by the provider.\n * @property {Record<string, string>} values - The values returned by the provider.\n * @property {string} text - The text returned by the provider.\n */\ninterface ProviderResult {\n\tdata?: any;\n\tvalues?: Record<string, string>;\n\ttext?: string;\n}\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaRemoteAttestationProvider();\n * ```\n */\n/**\n * PhalaRemoteAttestationProvider class that extends RemoteAttestationProvider\n * @extends RemoteAttestationProvider\n */\nclass PhalaRemoteAttestationProvider extends RemoteAttestationProvider {\n\tprivate client: TappdClient;\n\n\tconstructor(teeMode?: string) {\n\t\tsuper();\n\t\tlet endpoint: string | undefined;\n\n\t\t// Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n\t\tswitch (teeMode) {\n\t\t\tcase TEEMode.LOCAL:\n\t\t\t\tendpoint = \"http://localhost:8090\";\n\t\t\t\tlogger.log(\"TEE: Connecting to local simulator at localhost:8090\");\n\t\t\t\tbreak;\n\t\t\tcase TEEMode.DOCKER:\n\t\t\t\tendpoint = \"http://host.docker.internal:8090\";\n\t\t\t\tlogger.log(\n\t\t\t\t\t\"TEE: Connecting to simulator via Docker at host.docker.internal:8090\",\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase TEEMode.PRODUCTION:\n\t\t\t\tendpoint = undefined;\n\t\t\t\tlogger.log(\"TEE: Running in production mode without simulator\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`,\n\t\t\t\t);\n\t\t}\n\n\t\tthis.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n\t}\n\n\tasync generateAttestation(\n\t\treportData: string,\n\t\thashAlgorithm?: TdxQuoteHashAlgorithms,\n\t): Promise<RemoteAttestationQuote> {\n\t\ttry {\n\t\t\tlogger.log(\"Generating attestation for: \", reportData);\n\t\t\tconst tdxQuote: TdxQuoteResponse = await this.client.tdxQuote(\n\t\t\t\treportData,\n\t\t\t\thashAlgorithm,\n\t\t\t);\n\t\t\tconst rtmrs = tdxQuote.replayRtmrs();\n\t\t\tlogger.log(\n\t\t\t\t`rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`,\n\t\t\t);\n\t\t\tconst quote: RemoteAttestationQuote = {\n\t\t\t\tquote: tdxQuote.quote,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\tlogger.log(\"Remote attestation quote: \", quote);\n\t\t\treturn quote;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error generating remote attestation:\", error);\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to generate TDX Quote: ${\n\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// Keep the original provider for backwards compatibility\nconst phalaRemoteAttestationProvider: Provider = {\n\tname: \"phala-remote-attestation\",\n\tget: async (runtime: IAgentRuntime, message: Memory) => {\n\t\tconst teeMode = runtime.getSetting(\"TEE_MODE\");\n\t\tconst provider = new PhalaRemoteAttestationProvider(teeMode);\n\t\tconst agentId = runtime.agentId;\n\n\t\ttry {\n\t\t\tconst attestationMessage: RemoteAttestationMessage = {\n\t\t\t\tagentId: agentId,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tmessage: {\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: message.content.text,\n\t\t\t\t},\n\t\t\t};\n\t\t\tlogger.log(\n\t\t\t\t\"Generating attestation for: \",\n\t\t\t\tJSON.stringify(attestationMessage),\n\t\t\t);\n\t\t\tconst attestation = await provider.generateAttestation(\n\t\t\t\tJSON.stringify(attestationMessage),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\ttext: `Your Agent's remote attestation is: ${JSON.stringify(\n\t\t\t\t\tattestation,\n\t\t\t\t)}`,\n\t\t\t\tdata: {\n\t\t\t\t\tattestation,\n\t\t\t\t},\n\t\t\t\tvalues: {\n\t\t\t\t\tquote: attestation.quote,\n\t\t\t\t\ttimestamp: attestation.timestamp.toString(),\n\t\t\t\t},\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error in remote attestation provider:\", error);\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to generate TDX Quote: ${\n\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t}`,\n\t\t\t);\n\t\t}\n\t},\n};\n\n/**\n * SGX Gramine TEE Provider\n * @example\n * ```ts\n * const provider = new SgxAttestationProvider();\n * ```\n */\nclass SgxAttestationProvider extends RemoteAttestationProvider {\n\tprivate readonly SGX_QUOTE_MAX_SIZE: number = 8192 * 4;\n\tprivate readonly SGX_TARGET_INFO_SIZE: number = 512;\n\n\tprivate readonly MY_TARGET_INFO_PATH: string =\n\t\t\"/dev/attestation/my_target_info\";\n\tprivate readonly TARGET_INFO_PATH: string = \"/dev/attestation/target_info\";\n\tprivate readonly USER_REPORT_DATA_PATH: string =\n\t\t\"/dev/attestation/user_report_data\";\n\tprivate readonly QUOTE_PATH: string = \"/dev/attestation/quote\";\n\n\t// Remove unnecessary constructor\n\t// constructor() {}\n\n\tasync generateAttestation(reportData: string): Promise<SgxAttestation> {\n\t\t// Hash the report data to generate the raw user report.\n\t\t// The resulting hash value is 32 bytes long.\n\t\t// Ensure that the length of the raw user report does not exceed 64 bytes.\n\t\tconst rawUserReport = calculateSHA256(reportData);\n\n\t\ttry {\n\t\t\t// Check if the gramine attestation device file exists\n\t\t\tawait fs.access(this.MY_TARGET_INFO_PATH);\n\n\t\t\tconst quote = await this.generateQuoteByGramine(rawUserReport);\n\t\t\tconst attestation: SgxAttestation = {\n\t\t\t\tquote: quote,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\t// console.log(\"SGX remote attestation: \", attestation);\n\t\t\treturn attestation;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error generating SGX remote attestation:\", error);\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to generate SGX Quote: ${\n\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync generateQuoteByGramine(rawUserReport: Buffer): Promise<string> {\n\t\tif (rawUserReport.length > 64) {\n\t\t\tthrow new Error(\"the length of rawUserReport exceeds 64 bytes\");\n\t\t}\n\n\t\tconst myTargetInfo = await fs.readFile(this.MY_TARGET_INFO_PATH);\n\t\tif (myTargetInfo.length !== this.SGX_TARGET_INFO_SIZE) {\n\t\t\tthrow new Error(\"Invalid my_target_info length\");\n\t\t}\n\n\t\tawait fs.writeFile(this.TARGET_INFO_PATH, myTargetInfo);\n\t\tawait fs.writeFile(this.USER_REPORT_DATA_PATH, rawUserReport);\n\n\t\t// Read quote\n\t\tconst quoteData = await fs.readFile(this.QUOTE_PATH);\n\t\tif (quoteData.length > this.SGX_QUOTE_MAX_SIZE) {\n\t\t\tthrow new Error(\"Invalid quote length\");\n\t\t}\n\n\t\tconst realLen = quoteData.lastIndexOf(0);\n\t\tif (realLen === -1) {\n\t\t\tthrow new Error(\"quote without EOF\");\n\t\t}\n\n\t\t//return '0x' + quoteData.subarray(0, realLen + 1).toString('hex');\n\t\treturn `0x${quoteData.subarray(0, realLen + 1).toString(\"hex\")}`; // Fix: Use template literal\n\t}\n}\n\nconst sgxAttestationProvider: Provider = {\n\tname: \"sgx-gramine-remote-attestation\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\t_message: Memory,\n\t): Promise<ProviderResult> => {\n\t\tconst provider = new SgxAttestationProvider();\n\t\tconst agentId = runtime.agentId;\n\n\t\ttry {\n\t\t\t// console.log(\"Generating attestation for agent: \", agentId);\n\t\t\tconst attestation = await provider.generateAttestation(agentId);\n\n\t\t\treturn {\n\t\t\t\tdata: attestation,\n\t\t\t\tvalues: {\n\t\t\t\t\tquote: attestation.quote,\n\t\t\t\t\ttimestamp: attestation.timestamp.toString(),\n\t\t\t\t},\n\t\t\t\ttext: `Your Agent's remote attestation is: ${JSON.stringify(\n\t\t\t\t\tattestation,\n\t\t\t\t)}`,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error in remote attestation provider:\", error);\n\t\t\tconst errorMessage = `Failed to generate SGX Quote: ${\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t}`;\n\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\tvalues: {},\n\t\t\t\ttext: errorMessage,\n\t\t\t};\n\t\t}\n\t},\n};\n\nexport {\n\tphalaRemoteAttestationProvider,\n\tPhalaRemoteAttestationProvider,\n\tsgxAttestationProvider,\n\tSgxAttestationProvider,\n};\n","import { createHash } from \"node:crypto\";\n\n/**\n * Converts a hexadecimal string to a Uint8Array.\n *\n * @param {string} hex - The hexadecimal string to convert.\n * @returns {Uint8Array} - The resulting Uint8Array.\n * @throws {Error} - If the input hex string is invalid.\n */\nexport function hexToUint8Array(hex: string) {\n\tconst hexString = hex.trim().replace(/^0x/, \"\");\n\tif (!hexString) {\n\t\tthrow new Error(\"Invalid hex string\");\n\t}\n\tif (hexString.length % 2 !== 0) {\n\t\tthrow new Error(\"Invalid hex string\");\n\t}\n\n\tconst array = new Uint8Array(hexString.length / 2);\n\tfor (let i = 0; i < hexString.length; i += 2) {\n\t\tconst byte = Number.parseInt(hexString.slice(i, i + 2), 16);\n\t\tif (Number.isNaN(byte)) {\n\t\t\tthrow new Error(\"Invalid hex string\");\n\t\t}\n\t\tarray[i / 2] = byte;\n\t}\n\treturn array;\n}\n\n// Function to calculate SHA-256 and return a Buffer (32 bytes)\n/**\n * Calculates the SHA256 hash of the input string.\n *\n * @param {string} input - The input string to calculate the hash from.\n * @returns {Buffer} - The calculated SHA256 hash as a Buffer object.\n */\nexport function calculateSHA256(input: string): Buffer {\n\tconst hash = createHash(\"sha256\");\n\thash.update(input);\n\treturn hash.digest();\n}\n","import type { RemoteAttestationQuote } from \"@elizaos/core\";\nimport type { TdxQuoteHashAlgorithms } from \"@phala/dstack-sdk\";\n\n/**\n * Abstract class for deriving keys from the TEE.\n * You can implement your own logic for deriving keys from the TEE.\n * @example\n * ```ts\n * class MyDeriveKeyProvider extends DeriveKeyProvider {\n * private client: TappdClient;\n *\n * constructor(endpoint: string) {\n * super();\n * this.client = new TappdClient();\n * }\n *\n * async rawDeriveKey(path: string, subject: string): Promise<any> {\n * return this.client.deriveKey(path, subject);\n * }\n * }\n * ```\n */\n/**\n * Abstract class representing a key provider for deriving keys.\n */\nexport abstract class DeriveKeyProvider {}\n\n/**\n * Abstract class for remote attestation provider.\n */\nexport abstract class RemoteAttestationProvider {\n\tabstract generateAttestation(\n\t\treportData: string,\n\t\thashAlgorithm?: TdxQuoteHashAlgorithms,\n\t): Promise<RemoteAttestationQuote>;\n}\n","import type { Action, Provider } from \"@elizaos/core\";\n\nexport const TeeVendorNames = {\n\tPHALA: \"phala\",\n\tSGX_GRAMINE: \"sgx_gramine\",\n} as const;\n\n/**\n * Type representing the name of a Tee vendor.\n * It can either be one of the keys of TeeVendorNames or a string.\n */\nexport type TeeVendorName =\n\t| (typeof TeeVendorNames)[keyof typeof TeeVendorNames]\n\t| string;\n\n/**\n * Interface for a TeeVendor, representing a vendor that sells tees.\n * @interface\n */\n\nexport interface TeeVendor {\n\ttype: TeeVendorName;\n\tgetActions(): Action[];\n\tgetProviders(): Provider[];\n\tgetName(): string;\n\tgetDescription(): string;\n}\n","import { sgxAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport type { TeeVendor } from \"./types\";\nimport { TeeVendorNames } from \"./types\";\n\n/**\n * Vendor class for SGX Gramine TEE.\n * @implements {TeeVendor}\n */\n\nexport class GramineVendor implements TeeVendor {\n\ttype = TeeVendorNames.SGX_GRAMINE;\n\n\t/**\n\t * Returns an array of actions.\n\t * @returns {Array} An empty array of actions.\n\t */\n\tgetActions() {\n\t\treturn [];\n\t}\n\n\t/**\n\t * Retrieve the list of providers available.\n\t *\n\t * @returns {Array} An array containing the available providers.\n\t */\n\tgetProviders() {\n\t\treturn [sgxAttestationProvider];\n\t}\n\n\t/**\n\t * Function to get the name of the plugin.\n\t * @returns {string} The name of the plugin.\n\t */\n\tgetName() {\n\t\treturn \"sgx-gramine-plugin\";\n\t}\n\n\t/**\n\t * Returns the description of the SGX Gramine TEE to Host Eliza Agents.\n\t */\n\tgetDescription() {\n\t\treturn \"SGX Gramine TEE to Host Eliza Agents\";\n\t}\n}\n","import { TeeVendors } from \"@elizaos/core\";\nimport { phalaRemoteAttestationAction as remoteAttestationAction } from \"../actions/remoteAttestationAction\";\nimport { phalaDeriveKeyProvider as deriveKeyProvider } from \"../providers/deriveKeyProvider\";\nimport { phalaRemoteAttestationProvider as remoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport type { TeeVendor } from \"./types\";\n\n/**\n * A class representing a vendor for Phala TEE.\n * * @implements { TeeVendor }\n * @type {TeeVendors.PHALA}\n *//**\n * Get the actions for the PhalaVendor.\n * * @returns { Array } An array of actions.\n *//**\n * Get the providers for the PhalaVendor.\n * * @returns { Array } An array of providers.\n *//**\n * Get the name of the PhalaVendor.\n * * @returns { string } The name of the vendor.\n *//**\n * Get the description of the PhalaVendor.\n * * @returns { string } The description of the vendor.\n */\nexport class PhalaVendor implements TeeVendor {\n\ttype = TeeVendors.PHALA;\n\n\t/**\n\t * Returns an array of actions.\n\t *\n\t * @returns {Array} An array containing the remote attestation action.\n\t */\n\tgetActions() {\n\t\treturn [remoteAttestationAction];\n\t}\n\t/**\n\t * Retrieve the list of providers.\n\t *\n\t * @returns {Array<Function>} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider.\n\t */\n\tgetProviders() {\n\t\treturn [deriveKeyProvider, remoteAttestationProvider];\n\t}\n\n\t/**\n\t * Returns the name of the plugin.\n\t * @returns {string} The name of the plugin.\n\t */\n\tgetName() {\n\t\treturn \"phala-tee-plugin\";\n\t}\n\n\t/**\n\t * Get the description of the function\n\t * @returns {string} The description of the function\n\t */\n\tgetDescription() {\n\t\treturn \"Phala TEE Cloud to Host Eliza Agents\";\n\t}\n}\n","import type {\n\tHandlerCallback,\n\tIAgentRuntime,\n\tMemory,\n\tRemoteAttestationMessage,\n\tState,\n} from \"@elizaos/core\";\nimport { logger } from \"@elizaos/core\";\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { hexToUint8Array } from \"../utils\";\n\n/**\n * Asynchronously uploads a Uint8Array as a binary file to a specified URL.\n *\n * @param {Uint8Array} data - The Uint8Array data to be uploaded as a binary file.\n * @returns {Promise<Response>} A Promise that resolves once the upload is complete, returning a Response object.\n */\nasync function uploadUint8Array(data: Uint8Array) {\n\tconst blob = new Blob([data], { type: \"application/octet-stream\" });\n\tconst formData = new FormData();\n\tformData.append(\"file\", blob, \"quote.bin\");\n\n\treturn await fetch(\"https://proof.t16z.com/api/upload\", {\n\t\tmethod: \"POST\",\n\t\tbody: formData as BodyInit,\n\t});\n}\n\n/**\n * Represents an action for remote attestation.\n *\n * This action is used to generate a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE).\n *\n * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array<Array<Object>>}}\n */\nexport const phalaRemoteAttestationAction = {\n\tname: \"REMOTE_ATTESTATION\",\n\tsimiles: [\"REMOTE_ATTESTATION\", \"TEE_REMOTE_ATTESTATION\", \"TEE_ATTESTATION\"],\n\tdescription:\n\t\t\"Generate a remote attestation to prove that the agent is running in a TEE\",\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\t_state: State,\n\t\t_options: { [key: string]: unknown },\n\t\tcallback: HandlerCallback,\n\t) => {\n\t\ttry {\n\t\t\t// Attestation will be generated based on the message info\n\t\t\tconst attestationMessage: RemoteAttestationMessage = {\n\t\t\t\tagentId: runtime.agentId,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tmessage: {\n\t\t\t\t\tentityId: message.entityId,\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcontent: message.content.text,\n\t\t\t\t},\n\t\t\t};\n\t\t\t// Get the remote attestation of the agentId\n\t\t\tconst teeMode = runtime.getSetting(\"TEE_MODE\");\n\t\t\tlogger.debug(`Tee mode: ${teeMode}`);\n\t\t\tlogger.debug(\n\t\t\t\t`Attestation message: ${JSON.stringify(attestationMessage)}`,\n\t\t\t);\n\t\t\tconst provider = new RemoteAttestationProvider(teeMode);\n\n\t\t\tconst attestation = await provider.generateAttestation(\n\t\t\t\tJSON.stringify(attestationMessage),\n\t\t\t);\n\t\t\tconst attestationData = hexToUint8Array(attestation.quote);\n\t\t\tconst response = await uploadUint8Array(attestationData);\n\t\t\tconst data = await response.json();\n\n\t\t\tcallback({\n\t\t\t\ttext: `Here's my 🧾 RA Quote 🫡\nhttps://proof.t16z.com/reports/${data.checksum}`,\n\t\t\t\tactions: [\"NONE\"],\n\t\t\t});\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Failed to fetch remote attestation: \", error);\n\t\t\treturn false;\n\t\t}\n\t},\n\tvalidate: async (_runtime: IAgentRuntime) => {\n\t\treturn true;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"If you are running in a TEE, generate a remote attestation\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{agentName}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Of course, one second...\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{agentName}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{agentName}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Oh, dear...lemme find that for you\",\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t],\n};\n\n/**\n * Marlin Remote Attestation action.\n *\n * This action allows generating a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE).\n *\n * @type {{\n * name: string,\n * similes: string[],\n * description: string,\n * handler: (runtime: IAgentRuntime, _message: Memory, _state: State, _options: Record<string, unknown>, callback: HandlerCallback) => Promise<boolean>,\n * validate: (runtime: IAgentRuntime) => Promise<boolean>,\n * examples: { name: string, content: { text: string, actions: string[] } }[][]\n * }}\n */\nexport const marlinRemoteAttestationAction = {\n\tname: \"REMOTE_ATTESTATION\",\n\tsimiles: [\"REMOTE_ATTESTATION\", \"TEE_REMOTE_ATTESTATION\", \"TEE_ATTESTATION\"],\n\tdescription:\n\t\t\"Generate a remote attestation to prove that the agent is running in a TEE\",\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\t_message: Memory,\n\t\t_state: State,\n\t\t_options: Record<string, unknown>, // Replaced any with Record<string, unknown>\n\t\tcallback: HandlerCallback,\n\t) => {\n\t\ttry {\n\t\t\tconst endpoint =\n\t\t\t\truntime.getSetting(\"TEE_MARLIN_ATTESTATION_ENDPOINT\") ??\n\t\t\t\t\"http://127.0.0.1:1350\";\n\t\t\tconst response = await fetch(`${endpoint}/attestation/hex`);\n\t\t\tcallback({\n\t\t\t\ttext: `Here you go - ${await response.text()}`,\n\t\t\t\tactions: [\"NONE\"],\n\t\t\t});\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Failed to fetch remote attestation: \", error);\n\t\t\treturn false;\n\t\t}\n\t},\n\tvalidate: async (_runtime: IAgentRuntime) => {\n\t\treturn true;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"user\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Attest yourself\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"user\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Generate a remote attestation\",\n\t\t\t\t\tactions: [\"REMOTE_ATTESTATION\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t],\n};\n","import crypto from \"node:crypto\";\nimport {\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype Provider,\n\ttype State,\n\tlogger,\n} from \"@elizaos/core\";\nimport {\n\ttype DeriveKeyAttestationData,\n\ttype RemoteAttestationQuote,\n\tTEEMode,\n} from \"@elizaos/core\";\nimport { type DeriveKeyResponse, TappdClient } from \"@phala/dstack-sdk\";\nimport { Keypair } from \"@solana/web3.js\";\nimport { type PrivateKeyAccount, keccak256 } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { DeriveKeyProvider } from \"./base\";\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from \"./remoteAttestationProvider\";\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaDeriveKeyProvider(runtime.getSetting('TEE_MODE'));\n * ```\n */\n/**\n * A class representing a key provider for deriving keys in the Phala TEE environment.\n * Extends the DeriveKeyProvider class.\n */\nclass PhalaDeriveKeyProvider extends DeriveKeyProvider {\n\tprivate client: TappdClient;\n\tprivate raProvider: RemoteAttestationProvider;\n\n\tconstructor(teeMode?: string) {\n\t\tsuper();\n\t\tlet endpoint: string | undefined;\n\n\t\t// Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n\t\tswitch (teeMode) {\n\t\t\tcase TEEMode.LOCAL:\n\t\t\t\tendpoint = \"http://localhost:8090\";\n\t\t\t\tlogger.log(\"TEE: Connecting to local simulator at localhost:8090\");\n\t\t\t\tbreak;\n\t\t\tcase TEEMode.DOCKER:\n\t\t\t\tendpoint = \"http://host.docker.internal:8090\";\n\t\t\t\tlogger.log(\n\t\t\t\t\t\"TEE: Connecting to simulator via Docker at host.docker.internal:8090\",\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase TEEMode.PRODUCTION:\n\t\t\t\tendpoint = undefined;\n\t\t\t\tlogger.log(\"TEE: Running in production mode without simulator\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`,\n\t\t\t\t);\n\t\t}\n\n\t\tthis.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n\t\tthis.raProvider = new RemoteAttestationProvider(teeMode);\n\t}\n\n\tprivate async generateDeriveKeyAttestation(\n\t\tagentId: string,\n\t\tpublicKey: string,\n\t\tsubject?: string,\n\t): Promise<RemoteAttestationQuote> {\n\t\tconst deriveKeyData: DeriveKeyAttestationData = {\n\t\t\tagentId,\n\t\t\tpublicKey,\n\t\t\tsubject,\n\t\t};\n\t\tconst reportdata = JSON.stringify(deriveKeyData);\n\t\tlogger.log(\"Generating Remote Attestation Quote for Derive Key...\");\n\t\tconst quote = await this.raProvider.generateAttestation(reportdata);\n\t\tlogger.log(\"Remote Attestation Quote generated successfully!\");\n\t\treturn quote;\n\t}\n\n\t/**\n\t * Derives a raw key from the given path and subject.\n\t * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n\t * @param subject - The subject to derive the key from. This is used for the certificate chain.\n\t * @returns The derived key.\n\t */\n\tasync rawDeriveKey(\n\t\tpath: string,\n\t\tsubject: string,\n\t): Promise<DeriveKeyResponse> {\n\t\ttry {\n\t\t\tif (!path || !subject) {\n\t\t\t\tlogger.error(\"Path and Subject are required for key derivation\");\n\t\t\t}\n\n\t\t\tlogger.log(\"Deriving Raw Key in TEE...\");\n\t\t\tconst derivedKey = await this.client.deriveKey(path, subject);\n\n\t\t\tlogger.log(\"Raw Key Derived Successfully!\");\n\t\t\treturn derivedKey;\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error deriving raw key:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Derives an Ed25519 keypair from the given path and subject.\n\t * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n\t * @param subject - The subject to derive the key from. This is used for the certificate chain.\n\t * @param agentId - The agent ID to generate an attestation for.\n\t * @returns An object containing the derived keypair and attestation.\n\t */\n\tasync deriveEd25519Keypair(\n\t\tpath: string,\n\t\tsubject: string,\n\t\tagentId: string,\n\t): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n\t\ttry {\n\t\t\tif (!path || !subject) {\n\t\t\t\tlogger.error(\"Path and Subject are required for key derivation\");\n\t\t\t}\n\n\t\t\tlogger.log(\"Deriving Key in TEE...\");\n\t\t\tconst derivedKey = await this.client.deriveKey(path, subject);\n\t\t\tconst uint8ArrayDerivedKey = derivedKey.asUint8Array();\n\n\t\t\tconst hash = crypto.createHash(\"sha256\");\n\t\t\thash.update(uint8ArrayDerivedKey);\n\t\t\tconst seed = hash.digest();\n\t\t\tconst seedArray = new Uint8Array(seed);\n\t\t\tconst keypair = Keypair.fromSeed(seedArray.slice(0, 32));\n\n\t\t\t// Generate an attestation for the derived key data for public to verify\n\t\t\tconst attestation = await this.generateDeriveKeyAttestation(\n\t\t\t\tagentId,\n\t\t\t\tkeypair.publicKey.toBase58(),\n\t\t\t);\n\t\t\tlogger.log(\"Key Derived Successfully!\");\n\n\t\t\treturn { keypair, attestation };\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error deriving key:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Derives an ECDSA keypair from the given path and subject.\n\t * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n\t * @param subject - The subject to derive the key from. This is used for the certificate chain.\n\t * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.\n\t * @returns An object containing the derived keypair and attestation.\n\t */\n\tasync deriveEcdsaKeypair(\n\t\tpath: string,\n\t\tsubject: string,\n\t\tagentId: string,\n\t): Promise<{\n\t\tkeypair: PrivateKeyAccount;\n\t\tattestation: RemoteAttestationQuote;\n\t}> {\n\t\ttry {\n\t\t\tif (!path || !subject) {\n\t\t\t\tlogger.error(\"Path and Subject are required for key derivation\");\n\t\t\t}\n\n\t\t\tlogger.log(\"Deriving ECDSA Key in TEE...\");\n\t\t\tconst deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey(\n\t\t\t\tpath,\n\t\t\t\tsubject,\n\t\t\t);\n\t\t\tconst hex = keccak256(deriveKeyResponse.asUint8Array());\n\t\t\tconst keypair: PrivateKeyAccount = privateKeyToAccount(hex);\n\n\t\t\t// Generate an attestation for the derived key data for public to verify\n\t\t\tconst attestation = await this.generateDeriveKeyAttestation(\n\t\t\t\tagentId,\n\t\t\t\tkeypair.address,\n\t\t\t);\n\t\t\tlogger.log(\"ECDSA Key Derived Successfully!\");\n\n\t\t\treturn { keypair, attestation };\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error deriving ecdsa key:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\n// Define the ProviderResult interface if not already imported\ninterface ProviderResult {\n\tdata?: any;\n\tvalues?: Record<string, string>;\n\ttext?: string;\n}\n\nconst phalaDeriveKeyProvider: Provider = {\n\tname: \"phala-derive-key\",\n\tget: async (\n\t\truntime: IAgentRuntime,\n\t\t_message?: Memory,\n\t): Promise<ProviderResult> => {\n\t\tconst teeMode = runtime.getSetting(\"TEE_MODE\");\n\t\tconst provider = new PhalaDeriveKeyProvider(teeMode);\n\t\tconst agentId = runtime.agentId;\n\t\ttry {\n\t\t\t// Validate wallet configuration\n\t\t\tif (!runtime.getSetting(\"WALLET_SECRET_SALT\")) {\n\t\t\t\tlogger.error(\"Wallet secret salt is not configured in settings\");\n\t\t\t\treturn {\n\t\t\t\t\tdata: null,\n\t\t\t\t\tvalues: {},\n\t\t\t\t\ttext: \"Wallet secret salt is not configured in settings\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst secretSalt =\n\t\t\t\t\truntime.getSetting(\"WALLET_SECRET_SALT\") || \"secret_salt\";\n\t\t\t\tconst solanaKeypair = await provider.deriveEd25519Keypair(\n\t\t\t\t\tsecretSalt,\n\t\t\t\t\t\"solana\",\n\t\t\t\t\tagentId,\n\t\t\t\t);\n\t\t\t\tconst evmKeypair = await provider.deriveEcdsaKeypair(\n\t\t\t\t\tsecretSalt,\n\t\t\t\t\t\"evm\",\n\t\t\t\t\tagentId,\n\t\t\t\t);\n\n\t\t\t\t// Original data structure\n\t\t\t\tconst walletData = {\n\t\t\t\t\tsolana: solanaKeypair.keypair.publicKey,\n\t\t\t\t\tevm: evmKeypair.keypair.address,\n\t\t\t\t};\n\n\t\t\t\t// Values for template injection\n\t\t\t\tconst values = {\n\t\t\t\t\tsolana_public_key: solanaKeypair.keypair.publicKey.toString(),\n\t\t\t\t\tevm_address: evmKeypair.keypair.address,\n\t\t\t\t};\n\n\t\t\t\t// Text representation\n\t\t\t\tconst text = `Solana Public Key: ${values.solana_public_key}\\nEVM Address: ${values.evm_address}`;\n\n\t\t\t\treturn {\n\t\t\t\t\tdata: walletData,\n\t\t\t\t\tvalues: values,\n\t\t\t\t\ttext: text,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Error creating PublicKey:\", error);\n\t\t\t\treturn {\n\t\t\t\t\tdata: null,\n\t\t\t\t\tvalues: {},\n\t\t\t\t\ttext: `Error creating PublicKey: ${\n\t\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t\t}`,\n\t\t\t\t};\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in derive key provider:\", error.message);\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\tvalues: {},\n\t\t\t\ttext: `Failed to fetch derive key information: ${\n\t\t\t\t\terror instanceof Error ? error.message : \"Unknown error\"\n\t\t\t\t}`,\n\t\t\t};\n\t\t}\n\t},\n};\n\n/**\n * SGX Gramine TEE Provider\n * @example\n * ```ts\n * const provider = new SgxGramineDeriveKeyProvider();\n * ```\n */\nclass SgxGramineDeriveKeyProvider extends DeriveKeyProvider {}\n\nconst sgxGramineDeriveKeyProvider: Provider = {\n\tname: \"sgx-gramine-derive-key\",\n\tget: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message?: Memory,\n\t): Promise<ProviderResult> => {\n\t\treturn {\n\t\t\tdata: { provider: \"sgx-gramine\" },\n\t\t\tvalues: { provider_name: \"SGX Gramine\" },\n\t\t\ttext: \"SGX Gramine Derive Key Provider\",\n\t\t};\n\t},\n};\n\nexport {\n\tphalaDeriveKeyProvider,\n\tPhalaDeriveKeyProvider,\n\tsgxGramineDeriveKeyProvider,\n\tSgxGramineDeriveKeyProvider,\n};\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n | ChecksumAddressErrorType\n | Keccak256ErrorType\n | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n return checksumAddress(`0x${address}`) as Address\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray<T> = T | readonly RecursiveArray<T>[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n | CreateCursorErrorType\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\nexport function toRlp<to extends To = 'hex'>(\n bytes: RecursiveArray<ByteArray> | RecursiveArray<Hex>,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType<to> {\n const encodable = getEncodable(bytes)\n const cursor = createCursor(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType<to>\n return cursor.bytes as ToRlpReturnType<to>\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp<to extends To = 'bytes'>(\n bytes: RecursiveArray<ByteArray>,\n to: to | To | undefined = 'bytes',\n): ToRlpReturnType<to> {\n return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp<to extends To = 'hex'>(\n hex: RecursiveArray<Hex>,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType<to> {\n return toRlp(hex, to)\n}\n\nfunction getEncodable(\n bytes: RecursiveArray<ByteArray> | RecursiveArray<Hex>,\n): Encodable {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)))\n return getEncodableBytes(bytes as any)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n const sizeOfBodyLength = getSizeOfLength(bodyLength)\n const length = (() => {\n if (bodyLength <= 55) return 1 + bodyLength\n return 1 + sizeOfBodyLength + bodyLength\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength)\n } else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n else cursor.pushUint32(bodyLength)\n }\n for (const { encode } of list) {\n encode(cursor)\n }\n },\n }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n const sizeOfBytesLength = getSizeOfLength(bytes.length)\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80) return 1\n if (bytes.length <= 55) return 1 + bytes.length\n return 1 + sizeOfBytesLength + bytes.length\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes)\n } else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length)\n cursor.pushBytes(bytes)\n } else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n else cursor.pushUint32(bytes.length)\n cursor.pushBytes(bytes)\n }\n },\n }\n}\n\nfunction getSizeOfLength(length: number) {\n if (length < 2 ** 8) return 1\n if (length < 2 ** 16) return 2\n if (length < 2 ** 24) return 3\n if (length < 2 ** 32) return 4\n throw new BaseError('Length is too large.')\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../../types/misc.js'\nimport {\n type ConcatHexErrorType,\n concatHex,\n} from '../../../utils/data/concat.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../../utils/encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../../../utils/encoding/toRlp.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../../utils/hash/keccak256.js'\nimport type { Authorization } from '../types/authorization.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters<to extends To> = Authorization & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n}\n\nexport type HashAuthorizationReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization<to extends To = 'hex'>(\n parameters: HashAuthorizationParameters<to>,\n): HashAuthorizationReturnType<to> {\n const { chainId, contractAddress, nonce, to } = parameters\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n contractAddress,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType<to>\n return hash as HashAuthorizationReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick<Kzg, 'blobToKzgCommitment'>\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters<blobs, to>,\n): BlobsToCommitmentsReturnType<to> {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick<Kzg, 'computeBlobKzgProof'>\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters<blobs, commitments, to>,\n): blobsToProofsReturnType<to> {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType<to>\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { aexists, aoutput } from './_assert.js';\nimport { type Input, Hash, createView, toBytes } from './utils.js';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.js';\nimport { type CHash, rotr, wrapConstructor } from './utils.js';\n\n/** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n/**\n * Temporary buffer, not used to store anything between runs.\n * Named this way because it matches specification.\n */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n SHA256_W.fill(0);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n\n/**\n * Constants taken from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf.\n */\nclass SHA224 extends SHA256 {\n protected A = 0xc1059ed8 | 0;\n protected B = 0x367cd507 | 0;\n protected C = 0x3070dd17 | 0;\n protected D = 0xf70e5939 | 0;\n protected E = 0xffc00b31 | 0;\n protected F = 0x68581511 | 0;\n protected G = 0x64f98fa7 | 0;\n protected H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/** SHA2-256 hash function */\nexport const sha256: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/** SHA2-224 hash function */\nexport const sha224: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Sha256Hash<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256<to extends To = 'hex'>(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash<to> {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash<to>\n return toHex(bytes) as Sha256Hash<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters<commitment, to>,\n): CommitmentToVersionedHashReturnType<to> {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters<commitments, to>,\n): CommitmentsToVersionedHashesReturnType<to> {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6\n\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32\n\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096\n\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob\n\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction =\n bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\nexport const versionedHashVersionKzg = 1\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters<data, to>): ToBlobsReturnType<to> {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType<to extends To> =\n | (to extends 'bytes' ? BlobSidecars<ByteArray> : never)\n | (to extends 'hex' ? BlobSidecars<Hex> : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters<data, blobs, to>,\n): ToBlobSidecarsReturnType<to> {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType<to>\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestGeneric,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n} from '../../types/transaction.js'\nimport type { Assign, ExactPartial, IsNever, OneOf } from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends LegacyProperties ? 'legacy' : never)\n | (transaction extends EIP1559Properties ? 'eip1559' : never)\n | (transaction extends EIP2930Properties ? 'eip2930' : never)\n | (transaction extends EIP4844Properties ? 'eip4844' : never)\n | (transaction extends EIP7702Properties ? 'eip7702' : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract<transaction['type'], string>\n : never),\n> = IsNever<keyof transaction> extends true\n ? string\n : IsNever<result> extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType<transaction> {\n if (transaction.type)\n return transaction.type as GetTransactionType<transaction>\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign<BaseProperties, FeeValuesLegacy>\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n ExactPartial<LegacyProperties>,\n {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n ExactPartial<EIP1559Properties>,\n ExactPartial<FeeValuesEIP4844> &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n ExactPartial<EIP1559Properties>,\n {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import type { TypedData } from 'abitype'\n\nimport { stringify } from '../utils/stringify.js'\nimport { BaseError } from './base.js'\n\nexport type InvalidDomainErrorType = InvalidDomainError & {\n name: 'InvalidDomainError'\n}\nexport class InvalidDomainError extends BaseError {\n constructor({ domain }: { domain: unknown }) {\n super(`Invalid domain \"${stringify(domain)}\".`, {\n metaMessages: ['Must be a valid EIP-712 domain.'],\n })\n }\n}\n\nexport type InvalidPrimaryTypeErrorType = InvalidPrimaryTypeError & {\n name: 'InvalidPrimaryTypeError'\n}\nexport class InvalidPrimaryTypeError extends BaseError {\n constructor({\n primaryType,\n types,\n }: { primaryType: string; types: TypedData | Record<string, unknown> }) {\n super(\n `Invalid primary type \\`${primaryType}\\` must be one of \\`${JSON.stringify(Object.keys(types))}\\`.`,\n {\n docsPath: '/api/glossary/Errors#typeddatainvalidprimarytypeerror',\n metaMessages: ['Check that the primary type is a key in `types`.'],\n },\n )\n }\n}\n\nexport type InvalidStructTypeErrorType = InvalidStructTypeError & {\n name: 'InvalidStructTypeError'\n}\nexport class InvalidStructTypeError extends BaseError {\n constructor({ type }: { type: string }) {\n super(`Struct type \"${type}\" is invalid.`, {\n metaMessages: ['Struct type must not be a Solidity type.'],\n name: 'InvalidStructTypeError',\n })\n }\n}\n","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData, TypedDataDomain } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from '../abi/encodeAbiParameters.js'\nimport { concat } from '../data/concat.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n type ValidateTypedDataErrorType,\n getTypesForEIP712Domain,\n validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n name: string\n type: string\n}\n\nexport type HashTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition<typedData, primaryType>\n\nexport type HashTypedDataReturnType = Hex\n\nexport type HashTypedDataErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | HashStructErrorType\n | ValidateTypedDataErrorType\n | ErrorType\n\nexport function hashTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: HashTypedDataParameters<typedData, primaryType>,\n): HashTypedDataReturnType {\n const {\n domain = {},\n message,\n primaryType,\n } = parameters as HashTypedDataParameters\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\n }\n\n // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n // as we can't statically check this with TypeScript.\n validateTypedData({\n domain,\n message,\n primaryType,\n types,\n })\n\n const parts: Hex[] = ['0x1901']\n if (domain)\n parts.push(\n hashDomain({\n domain,\n types: types as Record<string, MessageTypeProperty[]>,\n }),\n )\n\n if (primaryType !== 'EIP712Domain')\n parts.push(\n hashStruct({\n data: message,\n primaryType,\n types: types as Record<string, MessageTypeProperty[]>,\n }),\n )\n\n return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain({\n domain,\n types,\n}: {\n domain: TypedDataDomain\n types: Record<string, MessageTypeProperty[]>\n}) {\n return hashStruct({\n data: domain,\n primaryType: 'EIP712Domain',\n types,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct({\n data,\n primaryType,\n types,\n}: {\n data: Record<string, unknown>\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encoded = encodeData({\n data,\n primaryType,\n types,\n })\n return keccak256(encoded)\n}\n\ntype EncodeDataErrorType =\n | EncodeAbiParametersErrorType\n | EncodeFieldErrorType\n | HashTypeErrorType\n | ErrorType\n\nfunction encodeData({\n data,\n primaryType,\n types,\n}: {\n data: Record<string, unknown>\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encodedTypes: AbiParameter[] = [{ type: 'bytes32' }]\n const encodedValues: unknown[] = [hashType({ primaryType, types })]\n\n for (const field of types[primaryType]) {\n const [type, value] = encodeField({\n types,\n name: field.name,\n type: field.type,\n value: data[field.name],\n })\n encodedTypes.push(type)\n encodedValues.push(value)\n }\n\n return encodeAbiParameters(encodedTypes, encodedValues)\n}\n\ntype HashTypeErrorType =\n | ToHexErrorType\n | EncodeTypeErrorType\n | Keccak256ErrorType\n | ErrorType\n\nfunction hashType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encodedHashType = toHex(encodeType({ primaryType, types }))\n return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nexport function encodeType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n let result = ''\n const unsortedDeps = findTypeDependencies({ primaryType, types })\n unsortedDeps.delete(primaryType)\n\n const deps = [primaryType, ...Array.from(unsortedDeps).sort()]\n for (const type of deps) {\n result += `${type}(${types[type]\n .map(({ name, type: t }) => `${t} ${name}`)\n .join(',')})`\n }\n\n return result\n}\n\ntype FindTypeDependenciesErrorType = ErrorType\n\nfunction findTypeDependencies(\n {\n primaryType: primaryType_,\n types,\n }: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n },\n results: Set<string> = new Set(),\n): Set<string> {\n const match = primaryType_.match(/^\\w*/u)\n const primaryType = match?.[0]!\n if (results.has(primaryType) || types[primaryType] === undefined) {\n return results\n }\n\n results.add(primaryType)\n\n for (const field of types[primaryType]) {\n findTypeDependencies({ primaryType: field.type, types }, results)\n }\n return results\n}\n\ntype EncodeFieldErrorType =\n | Keccak256ErrorType\n | EncodeAbiParametersErrorType\n | ToHexErrorType\n | ErrorType\n\nfunction encodeField({\n types,\n name,\n type,\n value,\n}: {\n types: Record<string, readonly MessageTypeProperty[]>\n name: string\n type: string\n value: any\n}): [type: AbiParameter, value: any] {\n if (types[type] !== undefined) {\n return [\n { type: 'bytes32' },\n keccak256(encodeData({ data: value, primaryType: type, types })),\n ]\n }\n\n if (type === 'bytes') {\n const prepend = value.length % 2 ? '0' : ''\n value = `0x${prepend + value.slice(2)}`\n return [{ type: 'bytes32' }, keccak256(value)]\n }\n\n if (type === 'string') return [{ type: 'bytes32' }, keccak256(toHex(value))]\n\n if (type.lastIndexOf(']') === type.length - 1) {\n const parsedType = type.slice(0, type.lastIndexOf('['))\n const typeValuePairs = (value as [AbiParameter, any][]).map((item) =>\n encodeField({\n name,\n type: parsedType,\n types,\n value: item,\n }),\n )\n return [\n { type: 'bytes32' },\n keccak256(\n encodeAbiParameters(\n typeValuePairs.map(([t]) => t),\n typeValuePairs.map(([, v]) => v),\n ),\n ),\n ]\n }\n\n return [{ type }, value]\n}\n","import type { TypedData, TypedDataDomain, TypedDataParameter } from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport {\n InvalidDomainError,\n InvalidPrimaryTypeError,\n InvalidStructTypeError,\n} from '../errors/typedData.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.js'\nimport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nimport { type SizeErrorType, size } from './data/size.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\nimport { bytesRegex, integerRegex } from './regex.js'\nimport {\n type HashDomainErrorType,\n hashDomain,\n} from './signature/hashTypedData.js'\nimport { stringify } from './stringify.js'\n\nexport type SerializeTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function serializeTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition<typedData, primaryType>) {\n const {\n domain: domain_,\n message: message_,\n primaryType,\n types,\n } = parameters as unknown as TypedDataDefinition\n\n const normalizeData = (\n struct: readonly TypedDataParameter[],\n data_: Record<string, unknown>,\n ) => {\n const data = { ...data_ }\n for (const param of struct) {\n const { name, type } = param\n if (type === 'address') data[name] = (data[name] as string).toLowerCase()\n }\n return data\n }\n\n const domain = (() => {\n if (!types.EIP712Domain) return {}\n if (!domain_) return {}\n return normalizeData(types.EIP712Domain, domain_)\n })()\n\n const message = (() => {\n if (primaryType === 'EIP712Domain') return undefined\n return normalizeData(types[primaryType], message_)\n })()\n\n return stringify({ domain, message, primaryType, types })\n}\n\nexport type ValidateTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function validateTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition<typedData, primaryType>) {\n const { domain, message, primaryType, types } =\n parameters as unknown as TypedDataDefinition\n\n const validateData = (\n struct: readonly TypedDataParameter[],\n data: Record<string, unknown>,\n ) => {\n for (const param of struct) {\n const { name, type } = param\n const value = data[name]\n\n const integerMatch = type.match(integerRegex)\n if (\n integerMatch &&\n (typeof value === 'number' || typeof value === 'bigint')\n ) {\n const [_type, base, size_] = integerMatch\n // If number cannot be cast to a sized hex value, it is out of range\n // and will throw.\n numberToHex(value, {\n signed: base === 'int',\n size: Number.parseInt(size_) / 8,\n })\n }\n\n if (type === 'address' && typeof value === 'string' && !isAddress(value))\n throw new InvalidAddressError({ address: value })\n\n const bytesMatch = type.match(bytesRegex)\n if (bytesMatch) {\n const [_type, size_] = bytesMatch\n if (size_ && size(value as Hex) !== Number.parseInt(size_))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_),\n givenSize: size(value as Hex),\n })\n }\n\n const struct = types[type]\n if (struct) {\n validateReference(type)\n validateData(struct, value as Record<string, unknown>)\n }\n }\n }\n\n // Validate domain types.\n if (types.EIP712Domain && domain) {\n if (typeof domain !== 'object') throw new InvalidDomainError({ domain })\n validateData(types.EIP712Domain, domain)\n }\n\n // Validate message types.\n if (primaryType !== 'EIP712Domain') {\n if (types[primaryType]) validateData(types[primaryType], message)\n else throw new InvalidPrimaryTypeError({ primaryType, types })\n }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n domain,\n}: { domain?: TypedDataDomain | undefined }): TypedDataParameter[] {\n return [\n typeof domain?.name === 'string' && { name: 'name', type: 'string' },\n domain?.version && { name: 'version', type: 'string' },\n (typeof domain?.chainId === 'number' ||\n typeof domain?.chainId === 'bigint') && {\n name: 'chainId',\n type: 'uint256',\n },\n domain?.verifyingContract && {\n name: 'verifyingContract',\n type: 'address',\n },\n domain?.salt && { name: 'salt', type: 'bytes32' },\n ].filter(Boolean) as TypedDataParameter[]\n}\n\nexport type DomainSeparatorErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | ErrorType\n\nexport function domainSeparator({ domain }: { domain: TypedDataDomain }): Hex {\n return hashDomain({\n domain,\n types: {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n },\n })\n}\n\n/** @internal */\nfunction validateReference(type: string) {\n // Struct type must not be a Solidity type.\n if (\n type === 'address' ||\n type === 'bool' ||\n type === 'string' ||\n type.startsWith('bytes') ||\n type.startsWith('uint') ||\n type.startsWith('int')\n )\n throw new InvalidStructTypeError({ type })\n}\n","export const presignMessagePrefix = '\\x19Ethereum Signed Message:\\n'\n","import { presignMessagePrefix } from '../../constants/strings.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { size } from '../data/size.js'\nimport {\n type BytesToHexErrorType,\n type StringToHexErrorType,\n bytesToHex,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type ToPrefixedMessageErrorType =\n | ConcatErrorType\n | StringToHexErrorType\n | BytesToHexErrorType\n | ErrorType\n\nexport function toPrefixedMessage(message_: SignableMessage): Hex {\n const message = (() => {\n if (typeof message_ === 'string') return stringToHex(message_)\n if (typeof message_.raw === 'string') return message_.raw\n return bytesToHex(message_.raw)\n })()\n const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`)\n return concat([prefix, message])\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { toPrefixedMessage } from './toPrefixedMessage.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessageReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType = Keccak256ErrorType | ErrorType\n\nexport function hashMessage<to extends To = 'hex'>(\n message: SignableMessage,\n to_?: to | undefined,\n): HashMessageReturnType<to> {\n return keccak256(toPrefixedMessage(message), to_)\n}\n","import { versionedHashVersionKzg } from '../../constants/kzg.js'\nimport { maxUint256 } from '../../constants/number.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n EmptyBlobError,\n type EmptyBlobErrorType,\n InvalidVersionedHashSizeError,\n type InvalidVersionedHashSizeErrorType,\n InvalidVersionedHashVersionError,\n type InvalidVersionedHashVersionErrorType,\n} from '../../errors/blob.js'\nimport {\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from '../../errors/chain.js'\nimport {\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { size } from '../data/size.js'\nimport { slice } from '../data/slice.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nexport type AssertTransactionEIP7702ErrorType =\n | AssertTransactionEIP1559ErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | ErrorType\n\nexport function assertTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n) {\n const { authorizationList } = transaction\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { contractAddress, chainId } = authorization\n if (!isAddress(contractAddress))\n throw new InvalidAddressError({ address: contractAddress })\n if (chainId < 0) throw new InvalidChainIdError({ chainId })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP4844ErrorType =\n | AssertTransactionEIP1559ErrorType\n | EmptyBlobErrorType\n | InvalidVersionedHashSizeErrorType\n | InvalidVersionedHashVersionErrorType\n | ErrorType\n\nexport function assertTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n) {\n const { blobVersionedHashes } = transaction\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0) throw new EmptyBlobError()\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash)\n const version = hexToNumber(slice(hash, 0, 1))\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ })\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP1559ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n\nexport type AssertTransactionEIP2930ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n\nexport type AssertTransactionLegacyErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport { toHex } from '../../../utils/encoding/toHex.js'\nimport { toYParitySignatureArray } from '../../../utils/transaction/serializeTransaction.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../types/authorization.js'\n\nexport type SerializeAuthorizationListReturnType = SerializedAuthorizationList\n\nexport type SerializeAuthorizationListErrorType = ErrorType\n\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(\n authorizationList?: AuthorizationList<number, true> | undefined,\n): SerializeAuthorizationListReturnType {\n if (!authorizationList || authorizationList.length === 0) return []\n\n const serializedAuthorizationList = []\n for (const authorization of authorizationList) {\n const { contractAddress, chainId, nonce, ...signature } = authorization\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ])\n }\n\n return serializedAuthorizationList as {} as SerializeAuthorizationListReturnType\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { AccessList } from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport type { RecursiveArray } from '../encoding/toRlp.js'\n\nexport type SerializeAccessListErrorType =\n | InvalidStorageKeySizeErrorType\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(\n accessList?: AccessList | undefined,\n): RecursiveArray<Hex> {\n if (!accessList || accessList.length === 0) return []\n\n const serializedAccessList = []\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i]\n\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] })\n }\n }\n\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address })\n }\n\n serializedAccessList.push([address, storageKeys])\n }\n return serializedAccessList\n}\n","import {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ByteArray,\n Hex,\n Signature,\n SignatureLegacy,\n} from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from '../blob/blobsToCommitments.js'\nimport {\n blobsToProofs,\n type blobsToProofsErrorType,\n} from '../blob/blobsToProofs.js'\nimport {\n type CommitmentsToVersionedHashesErrorType,\n commitmentsToVersionedHashes,\n} from '../blob/commitmentsToVersionedHashes.js'\nimport {\n type ToBlobSidecarsErrorType,\n toBlobSidecars,\n} from '../blob/toBlobSidecars.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport { type ToHexErrorType, bytesToHex, toHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../../experimental/eip7702/utils/serializeAuthorizationList.js'\nimport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionEIP4844ErrorType,\n type AssertTransactionEIP7702ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionEIP4844,\n assertTransactionEIP7702,\n assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './getTransactionType.js'\nimport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n transaction extends TransactionSerializable = TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType<transaction>,\n> = TransactionSerialized<_transactionType>\n\nexport type SerializeTransactionFn<\n transaction extends TransactionSerializableGeneric = TransactionSerializable,\n ///\n _transactionType extends TransactionType = never,\n> = typeof serializeTransaction<\n OneOf<TransactionSerializable | transaction>,\n _transactionType\n>\n\nexport type SerializeTransactionErrorType =\n | GetTransactionTypeErrorType\n | SerializeTransactionEIP1559ErrorType\n | SerializeTransactionEIP2930ErrorType\n | SerializeTransactionEIP4844ErrorType\n | SerializeTransactionEIP7702ErrorType\n | SerializeTransactionLegacyErrorType\n | ErrorType\n\nexport function serializeTransaction<\n const transaction extends TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType<transaction>,\n>(\n transaction: transaction,\n signature?: Signature | undefined,\n): SerializedTransactionReturnType<transaction, _transactionType> {\n const type = getTransactionType(transaction) as GetTransactionType\n\n if (type === 'eip1559')\n return serializeTransactionEIP1559(\n transaction as TransactionSerializableEIP1559,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip2930')\n return serializeTransactionEIP2930(\n transaction as TransactionSerializableEIP2930,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip4844')\n return serializeTransactionEIP4844(\n transaction as TransactionSerializableEIP4844,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip7702')\n return serializeTransactionEIP7702(\n transaction as TransactionSerializableEIP7702,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n return serializeTransactionLegacy(\n transaction as TransactionSerializableLegacy,\n signature as SignatureLegacy,\n ) as SerializedTransactionReturnType<transaction>\n}\n\ntype SerializeTransactionEIP7702ErrorType =\n | AssertTransactionEIP7702ErrorType\n | SerializeAuthorizationListErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n signature?: Signature | undefined,\n): TransactionSerializedEIP7702 {\n const {\n authorizationList,\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP7702(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n const serializedAuthorizationList =\n serializeAuthorizationList(authorizationList)\n\n return concatHex([\n '0x04',\n toRlp([\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]) as TransactionSerializedEIP7702\n}\n\ntype SerializeTransactionEIP4844ErrorType =\n | AssertTransactionEIP4844ErrorType\n | BlobsToCommitmentsErrorType\n | CommitmentsToVersionedHashesErrorType\n | blobsToProofsErrorType\n | ToBlobSidecarsErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n signature?: Signature | undefined,\n): TransactionSerializedEIP4844 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP4844(transaction)\n\n let blobVersionedHashes = transaction.blobVersionedHashes\n let sidecars = transaction.sidecars\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (\n transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')\n ) {\n const blobs = (\n typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : (transaction.blobs as ByteArray[]).map((x) => bytesToHex(x))\n ) as Hex[]\n const kzg = transaction.kzg!\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n })\n\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n })\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n sidecars = toBlobSidecars({ blobs, commitments, proofs })\n }\n }\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ] as const\n\n const blobs: Hex[] = []\n const commitments: Hex[] = []\n const proofs: Hex[] = []\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i]\n blobs.push(blob)\n commitments.push(commitment)\n proofs.push(proof)\n }\n\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP4844\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n | AssertTransactionEIP1559ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n signature?: Signature | undefined,\n): TransactionSerializedEIP1559 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP1559(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n | AssertTransactionEIP2930ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n signature?: Signature | undefined,\n): TransactionSerializedEIP2930 {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } =\n transaction\n\n assertTransactionEIP2930(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | ErrorType\n\nfunction serializeTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n signature?: SignatureLegacy | undefined,\n): TransactionSerializedLegacy {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n assertTransactionLegacy(transaction)\n\n let serializedTransaction = [\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n ]\n\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n\n if (inferredChainId > 0) return signature.v\n return 27n + (signature.v === 35n ? 0n : 1n)\n }\n\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\n\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n)\n if (signature.v !== v) throw new InvalidLegacyVError({ v: signature.v })\n return v\n })()\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n serializedTransaction = [\n ...serializedTransaction,\n toHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n toHex(chainId),\n '0x',\n '0x',\n ]\n }\n\n return toRlp(serializedTransaction) as TransactionSerializedLegacy\n}\n\nexport function toYParitySignatureArray(\n transaction: TransactionSerializableGeneric,\n signature_?: Signature | undefined,\n) {\n const signature = signature_ ?? transaction\n const { v, yParity } = signature\n\n if (typeof signature.r === 'undefined') return []\n if (typeof signature.s === 'undefined') return []\n if (typeof v === 'undefined' && typeof yParity === 'undefined') return []\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n const yParity_ = (() => {\n if (typeof yParity === 'number') return yParity ? toHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return toHex(1)\n\n return v === 27n ? '0x' : toHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type HexToBigIntErrorType, hexToBigInt } from '../encoding/fromHex.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\nimport type { ToHexErrorType } from '../encoding/toHex.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeSignatureParameters<to extends To = 'hex'> = Signature & {\n to?: to | To | undefined\n}\n\nexport type SerializeSignatureReturnType<to extends To = 'hex'> =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeSignatureErrorType =\n | HexToBigIntErrorType\n | ToHexErrorType\n | ErrorType\n\n/**\n * @description Converts a signature into hex format.\n *\n * @param signature The signature to convert.\n * @returns The signature in hex format.\n *\n * @example\n * serializeSignature({\n * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n * yParity: 1\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function serializeSignature<to extends To = 'hex'>({\n r,\n s,\n to = 'hex',\n v,\n yParity,\n}: SerializeSignatureParameters<to>): SerializeSignatureReturnType<to> {\n const yParity_ = (() => {\n if (yParity === 0 || yParity === 1) return yParity\n if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0\n throw new Error('Invalid `v` or `yParity` value')\n })()\n const signature = `0x${new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).toCompactHex()}${yParity_ === 0 ? '1b' : '1c'}` as const\n\n if (to === 'hex') return signature as SerializeSignatureReturnType<to>\n return hexToBytes(signature) as SerializeSignatureReturnType<to>\n}\n","// TODO(v3): Rename to `toLocalAccount` + add `source` property to define source (privateKey, mnemonic, hdKey, etc).\n\nimport type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n AccountSource,\n CustomSource,\n JsonRpcAccount,\n LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType<accountSource extends AccountSource> =\n | (accountSource extends Address ? JsonRpcAccount : never)\n | (accountSource extends CustomSource ? LocalAccount : never)\n\nexport type ToAccountErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a custom signing implementation.\n *\n * @returns A Local Account.\n */\nexport function toAccount<accountSource extends AccountSource>(\n source: accountSource,\n): GetAccountReturnType<accountSource> {\n if (typeof source === 'string') {\n if (!isAddress(source, { strict: false }))\n throw new InvalidAddressError({ address: source })\n return {\n address: source,\n type: 'json-rpc',\n } as GetAccountReturnType<accountSource>\n }\n\n if (!isAddress(source.address, { strict: false }))\n throw new InvalidAddressError({ address: source.address })\n return {\n address: source.address,\n nonceManager: source.nonceManager,\n sign: source.sign,\n experimental_signAuthorization: source.experimental_signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType<accountSource>\n}\n","// TODO(v3): Convert to sync.\n\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignParameters<to extends To = 'object'> = {\n hash: Hex\n privateKey: Hex\n to?: to | To | undefined\n}\n\nexport type SignReturnType<to extends To = 'object'> =\n | (to extends 'object' ? Signature : never)\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type SignErrorType = NumberToHexErrorType | ErrorType\n\nlet extraEntropy: Hex | boolean = false\n\n/**\n * Sets extra entropy for signing functions.\n */\nexport function setSignEntropy(entropy: true | Hex) {\n if (!entropy) throw new Error('must be a `true` or a hex value.')\n extraEntropy = entropy\n}\n\n/**\n * @description Signs a hash with a given private key.\n *\n * @param hash The hash to sign.\n * @param privateKey The private key to sign with.\n *\n * @returns The signature.\n */\nexport async function sign<to extends To = 'object'>({\n hash,\n privateKey,\n to = 'object',\n}: SignParameters<to>): Promise<SignReturnType<to>> {\n const { r, s, recovery } = secp256k1.sign(\n hash.slice(2),\n privateKey.slice(2),\n { lowS: true, extraEntropy },\n )\n const signature = {\n r: numberToHex(r, { size: 32 }),\n s: numberToHex(s, { size: 32 }),\n v: recovery ? 28n : 27n,\n yParity: recovery,\n }\n return (() => {\n if (to === 'bytes' || to === 'hex')\n return serializeSignature({ ...signature, to })\n return signature\n })() as SignReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n SignedAuthorization,\n} from '../../experimental/eip7702/types/authorization.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../experimental/eip7702/utils/hashAuthorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n sign,\n} from './sign.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignAuthorizationParameters<to extends To = 'object'> =\n Authorization & {\n /** The private key to sign with. */\n privateKey: Hex\n to?: SignParameters<to>['to'] | undefined\n }\n\nexport type SignAuthorizationReturnType<to extends To = 'object'> = Prettify<\n to extends 'object' ? SignedAuthorization : SignReturnType<to>\n>\n\nexport type SignAuthorizationErrorType =\n | SignErrorType\n | HashAuthorizationErrorType\n | ErrorType\n\n/**\n * Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport async function experimental_signAuthorization<to extends To = 'object'>(\n parameters: SignAuthorizationParameters<to>,\n): Promise<SignAuthorizationReturnType<to>> {\n const {\n contractAddress,\n chainId,\n nonce,\n privateKey,\n to = 'object',\n } = parameters\n const signature = await sign({\n hash: hashAuthorization({ contractAddress, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n contractAddress,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport {\n type HashMessageErrorType,\n hashMessage,\n} from '../../utils/signature/hashMessage.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignMessageParameters = {\n /** The message to sign. */\n message: SignableMessage\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n | SignErrorType\n | HashMessageErrorType\n | ErrorType\n\n/**\n * @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signMessage({\n message,\n privateKey,\n}: SignMessageParameters): Promise<SignMessageReturnType> {\n return await sign({ hash: hashMessage(message), privateKey, to: 'hex' })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerialized,\n} from '../../types/transaction.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport {\n type SerializeTransactionFn,\n serializeTransaction,\n} from '../../utils/transaction/serializeTransaction.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTransactionParameters<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n> = {\n privateKey: Hex\n transaction: transaction\n serializer?: serializer | undefined\n}\n\nexport type SignTransactionReturnType<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n> = TransactionSerialized<GetTransactionType<transaction>>\n\nexport type SignTransactionErrorType =\n | Keccak256ErrorType\n | SignErrorType\n | ErrorType\n\nexport async function signTransaction<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n>(\n parameters: SignTransactionParameters<serializer, transaction>,\n): Promise<SignTransactionReturnType<serializer, transaction>> {\n const {\n privateKey,\n transaction,\n serializer = serializeTransaction,\n } = parameters\n\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === 'eip4844')\n return {\n ...transaction,\n sidecars: false,\n }\n return transaction\n })()\n\n const signature = await sign({\n hash: keccak256(serializer(signableTransaction)),\n privateKey,\n })\n return serializer(transaction, signature) as SignTransactionReturnType<\n serializer,\n transaction\n >\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition<typedData, primaryType> & {\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n | HashTypedDataErrorType\n | SignErrorType\n | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: SignTypedDataParameters<typedData, primaryType>,\n): Promise<SignTypedDataReturnType> {\n const { privateKey, ...typedData } =\n parameters as unknown as SignTypedDataParameters\n return await sign({\n hash: hashTypedData(typedData),\n privateKey,\n to: 'hex',\n })\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type { NonceManager } from '../utils/nonceManager.js'\nimport { type ToAccountErrorType, toAccount } from './toAccount.js'\nimport type { PrivateKeyAccount } from './types.js'\nimport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nimport { type SignErrorType, sign } from './utils/sign.js'\nimport { experimental_signAuthorization } from './utils/signAuthorization.js'\nimport { type SignMessageErrorType, signMessage } from './utils/signMessage.js'\nimport {\n type SignTransactionErrorType,\n signTransaction,\n} from './utils/signTransaction.js'\nimport {\n type SignTypedDataErrorType,\n signTypedData,\n} from './utils/signTypedData.js'\n\nexport type PrivateKeyToAccountOptions = {\n nonceManager?: NonceManager | undefined\n}\n\nexport type PrivateKeyToAccountErrorType =\n | ToAccountErrorType\n | ToHexErrorType\n | PublicKeyToAddressErrorType\n | SignErrorType\n | SignMessageErrorType\n | SignTransactionErrorType\n | SignTypedDataErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a private key.\n *\n * @returns A Private Key Account.\n */\nexport function privateKeyToAccount(\n privateKey: Hex,\n options: PrivateKeyToAccountOptions = {},\n): PrivateKeyAccount {\n const { nonceManager } = options\n const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n const address = publicKeyToAddress(publicKey)\n\n const account = toAccount({\n address,\n nonceManager,\n async sign({ hash }) {\n return sign({ hash, privateKey, to: 'hex' })\n },\n async experimental_signAuthorization(authorization) {\n return experimental_signAuthorization({ ...authorization, privateKey })\n },\n async signMessage({ message }) {\n return signMessage({ message, privateKey })\n },\n async signTransaction(transaction, { serializer } = {}) {\n return signTransaction({ privateKey, transaction, serializer })\n },\n async signTypedData(typedData) {\n return signTypedData({ ...typedData, privateKey } as any)\n },\n })\n\n return {\n ...account,\n publicKey,\n source: 'privateKey',\n } as PrivateKeyAccount\n}\n","import { GramineVendor } from \"./gramine\";\nimport { PhalaVendor } from \"./phala\";\nimport type { TeeVendor } from \"./types\";\nimport { type TeeVendorName, TeeVendorNames } from \"./types\";\n\nconst vendors: Record<TeeVendorName, TeeVendor> = {\n\t[TeeVendorNames.PHALA]: new PhalaVendor(),\n\t[TeeVendorNames.SGX_GRAMINE]: new GramineVendor(),\n};\n\nexport const getVendor = (type: TeeVendorName): TeeVendor => {\n\tconst vendor = vendors[type];\n\tif (!vendor) {\n\t\tthrow new Error(`Unsupported TEE vendor type: ${type}`);\n\t}\n\treturn vendor;\n};\n\nexport * from \"./types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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eeType","logger","logger","logger","TEEMode","TappdClient","toBytes","sha256","sha256","size","size","struct","blobs","commitments","proofs","v","TEEMode","logger","TappdClient","path","logger","config"]}
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@elizaos/plugin-tee",
3
- "version": "1.0.0-alpha.58",
3
+ "version": "1.0.0-alpha.59",
4
4
  "main": "dist/index.js",
5
5
  "type": "module",
6
6
  "types": "dist/index.d.ts",
7
7
  "dependencies": {
8
- "@elizaos/core": "^1.0.0-alpha.58",
8
+ "@elizaos/core": "^1.0.0-alpha.59",
9
9
  "@phala/dstack-sdk": "^0.1.7",
10
10
  "@solana/web3.js": "^1.98.0",
11
11
  "better-sqlite3": "11.8.1",
@@ -24,5 +24,5 @@
24
24
  "publishConfig": {
25
25
  "access": "public"
26
26
  },
27
- "gitHead": "b8410813a402c96a74f1a63a0d72be15305cf19c"
27
+ "gitHead": "e450585943baaa522b53b236a7cb0268b72b3901"
28
28
  }